Cache guessed IP addresses.
[oddments/ddns.git] / src / ddns / system.py
CommitLineData
f22ab085 1#!/usr/bin/python
3fdcb9d1
MT
2###############################################################################
3# #
4# ddns - A dynamic DNS client for IPFire #
5# Copyright (C) 2012 IPFire development team #
6# #
7# This program is free software: you can redistribute it and/or modify #
8# it under the terms of the GNU General Public License as published by #
9# the Free Software Foundation, either version 3 of the License, or #
10# (at your option) any later version. #
11# #
12# This program is distributed in the hope that it will be useful, #
13# but WITHOUT ANY WARRANTY; without even the implied warranty of #
14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
15# GNU General Public License for more details. #
16# #
17# You should have received a copy of the GNU General Public License #
18# along with this program. If not, see <http://www.gnu.org/licenses/>. #
19# #
20###############################################################################
f22ab085 21
d4c5c0d5 22import base64
f22ab085 23import re
6cecd141 24import socket
adb124d0 25import urllib
f22ab085
MT
26import urllib2
27
28from __version__ import CLIENT_VERSION
7a909224 29from .errors import *
f22ab085
MT
30from i18n import _
31
32# Initialize the logger.
33import logging
34logger = logging.getLogger("ddns.system")
35logger.propagate = 1
36
37class DDNSSystem(object):
38 """
39 The DDNSSystem class adds a layer of abstraction
40 between the ddns software and the system.
41 """
42
43 # The default useragent.
44 USER_AGENT = "IPFireDDNSUpdater/%s" % CLIENT_VERSION
45
46 def __init__(self, core):
47 # Connection to the core of the program.
48 self.core = core
49
91a8ff83
MT
50 # Address cache.
51 self.__addresses = {}
52
2780b6bb
MT
53 # Find out on which distribution we are running.
54 self.distro = self._get_distro_identifier()
55 logger.debug(_("Running on distribution: %s") % self.distro)
56
f22ab085
MT
57 @property
58 def proxy(self):
59 proxy = self.core.settings.get("proxy")
60
61 # Strip http:// at the beginning.
fd898828 62 if proxy and proxy.startswith("http://"):
f22ab085
MT
63 proxy = proxy[7:]
64
65 return proxy
66
7f75b957
MT
67 def get_local_ipv6_address(self):
68 return # XXX TODO
69
70 def get_local_ipv4_address(self):
71 if self.distro == "ipfire-2":
72 try:
73 with open("/var/ipfire/red/local-ipaddress") as f:
74 return f.readline()
75
76 except IOError, e:
77 # File not found
78 if e.errno == 2:
79 return
80
81 raise
82
83 return # XXX TODO
84
46c23a71 85 def _guess_external_ip_address(self, url, timeout=10):
30270391
MT
86 """
87 Sends a request to an external web server
88 to determine the current default IP address.
89 """
7a909224 90 try:
46c23a71 91 response = self.send_request(url, timeout=timeout)
7a909224
MT
92
93 # If the server could not be reached, we will return nothing.
94 except DDNSNetworkError:
95 return
30270391
MT
96
97 if not response.code == 200:
98 return
99
100 match = re.search(r"^Your IP address is: (.*)$", response.read())
101 if match is None:
102 return
103
104 return match.group(1)
105
46c23a71 106 def guess_external_ipv6_address(self):
f22ab085
MT
107 """
108 Sends a request to the internet to determine
46c23a71 109 the public IPv6 address.
f22ab085 110 """
46c23a71 111 return self._guess_external_ip_address("http://checkip6.dns.lightningwirelabs.com")
f22ab085 112
46c23a71
MT
113 def guess_external_ipv4_address(self):
114 """
115 Sends a request to the internet to determine
116 the public IPv4 address.
117 """
118 return self._guess_external_ip_address("http://checkip4.dns.lightningwirelabs.com")
f22ab085 119
d4c5c0d5 120 def send_request(self, url, method="GET", data=None, username=None, password=None, timeout=30):
adb124d0
MT
121 assert method in ("GET", "POST")
122
123 # Add all arguments in the data dict to the URL and escape them properly.
124 if method == "GET" and data:
125 query_args = self._format_query_args(data)
126 data = None
127
4c1b0d25
SS
128 if "?" in url:
129 url = "%s&%s" % (url, query_args)
130 else:
131 url = "%s?%s" % (url, query_args)
adb124d0
MT
132
133 logger.debug("Sending request (%s): %s" % (method, url))
f22ab085
MT
134 if data:
135 logger.debug(" data: %s" % data)
136
137 req = urllib2.Request(url, data=data)
138
d4c5c0d5
SS
139 if username and password:
140 basic_auth_header = self._make_basic_auth_header(username, password)
d4c5c0d5
SS
141 req.add_header("Authorization", "Basic %s" % basic_auth_header)
142
f22ab085
MT
143 # Set the user agent.
144 req.add_header("User-Agent", self.USER_AGENT)
145
146 # All requests should not be cached anywhere.
147 req.add_header("Pragma", "no-cache")
148
149 # Set the upstream proxy if needed.
150 if self.proxy:
151 logger.debug("Using proxy: %s" % self.proxy)
152
153 # Configure the proxy for this request.
154 req.set_proxy(self.proxy, "http")
155
adb124d0
MT
156 assert req.get_method() == method
157
f22ab085
MT
158 logger.debug(_("Request header:"))
159 for k, v in req.headers.items():
160 logger.debug(" %s: %s" % (k, v))
161
162 try:
7a909224 163 resp = urllib2.urlopen(req, timeout=timeout)
f22ab085
MT
164
165 # Log response header.
09c496c5 166 logger.debug(_("Response header (Status Code %s):") % resp.code)
f22ab085
MT
167 for k, v in resp.info().items():
168 logger.debug(" %s: %s" % (k, v))
169
170 # Return the entire response object.
171 return resp
172
7a909224 173 except urllib2.HTTPError, e:
536e87d1
MT
174 # 400 - Bad request
175 if e.code == 400:
176 raise DDNSRequestError(e.reason)
177
178 # 401 - Authorization Required
179 # 403 - Forbidden
180 elif e.code in (401, 403):
181 raise DDNSAuthenticationError(e.reason)
182
183 # 500 - Internal Server Error
184 elif e.code == 500:
185 raise DDNSInternalServerError(e.reason)
186
7a909224 187 # 503 - Service Unavailable
536e87d1
MT
188 elif e.code == 503:
189 raise DDNSServiceUnavailableError(e.reason)
7a909224
MT
190
191 # Raise all other unhandled exceptions.
192 raise
193
f22ab085 194 except urllib2.URLError, e:
7a909224
MT
195 if e.reason:
196 # Network Unreachable (e.g. no IPv6 access)
197 if e.reason.errno == 101:
198 raise DDNSNetworkUnreachableError
199 elif e.reason.errno == 111:
200 raise DDNSConnectionRefusedError
201
202 # Raise all other unhandled exceptions.
f22ab085
MT
203 raise
204
7a909224
MT
205 except socket.timeout, e:
206 logger.debug(_("Connection timeout"))
207
208 raise DDNSConnectionTimeoutError
209
adb124d0
MT
210 def _format_query_args(self, data):
211 args = []
212
213 for k, v in data.items():
214 arg = "%s=%s" % (k, urllib.quote(v))
215 args.append(arg)
216
217 return "&".join(args)
218
d4c5c0d5
SS
219 def _make_basic_auth_header(self, username, password):
220 authstring = "%s:%s" % (username, password)
221
222 # Encode authorization data in base64.
223 authstring = base64.encodestring(authstring)
224
225 # Remove any newline characters.
226 authstring = authstring.replace("\n", "")
227
228 return authstring
229
f22ab085 230 def get_address(self, proto):
91a8ff83
MT
231 """
232 Returns the current IP address for
233 the given IP protocol.
234 """
235 try:
236 return self.__addresses[proto]
237
238 # IP is currently unknown and needs to be retrieved.
239 except KeyError:
240 self.__addresses[proto] = address = \
241 self._get_address(proto)
242
243 return address
244
245 def _get_address(self, proto):
f22ab085
MT
246 assert proto in ("ipv6", "ipv4")
247
afca6b38
MT
248 # IPFire 2 does not support IPv6.
249 if self.distro == "ipfire-2" and proto == "ipv6":
250 return
251
30270391
MT
252 # Check if the external IP address should be guessed from
253 # a remote server.
254 guess_ip = self.core.settings.get("guess_external_ip", "true")
255
256 # If the external IP address should be used, we just do
257 # that.
258 if guess_ip in ("true", "yes", "1"):
259 if proto == "ipv6":
260 return self.guess_external_ipv6_address()
f22ab085 261
30270391 262 elif proto == "ipv4":
f22ab085
MT
263 return self.guess_external_ipv4_address()
264
7f75b957
MT
265 # Get the local IP addresses.
266 else:
267 if proto == "ipv6":
268 return self.get_local_ipv6_address()
269 elif proto == "ipv4":
270 return self.get_local_ipv4_address()
6cecd141
MT
271
272 def resolve(self, hostname, proto=None):
273 addresses = []
274
275 if proto is None:
276 family = 0
277 elif proto == "ipv6":
278 family = socket.AF_INET6
279 elif proto == "ipv4":
280 family = socket.AF_INET
281 else:
282 raise ValueError("Protocol not supported: %s" % proto)
283
284 # Resolve the host address.
73f2bc0b
MT
285 try:
286 response = socket.getaddrinfo(hostname, None, family)
287 except socket.gaierror, e:
288 # Name or service not known
289 if e.errno == -2:
290 return []
291
aac65fab
MT
292 # No record for requested family available (e.g. no AAAA)
293 elif e.errno == -5:
294 return []
295
73f2bc0b 296 raise
6cecd141
MT
297
298 # Handle responses.
299 for family, socktype, proto, canonname, sockaddr in response:
300 # IPv6
301 if family == socket.AF_INET6:
302 address, port, flow_info, scope_id = sockaddr
303
304 # Only use the global scope.
305 if not scope_id == 0:
306 continue
307
308 # IPv4
309 elif family == socket.AF_INET:
310 address, port = sockaddr
311
312 # Ignore everything else...
313 else:
314 continue
315
316 # Add to repsonse list if not already in there.
317 if not address in addresses:
318 addresses.append(address)
319
320 return addresses
2780b6bb
MT
321
322 def _get_distro_identifier(self):
323 """
324 Returns a unique identifier for the distribution
325 we are running on.
326 """
327 os_release = self.__parse_os_release()
328 if os_release:
329 return os_release
330
331 system_release = self.__parse_system_release()
332 if system_release:
333 return system_release
334
335 # If nothing else could be found, we return
336 # just "unknown".
337 return "unknown"
338
339 def __parse_os_release(self):
340 """
341 Tries to parse /etc/os-release and
342 returns a unique distribution identifier
343 if the file exists.
344 """
345 try:
346 f = open("/etc/os-release", "r")
347 except IOError, e:
348 # File not found
349 if e.errno == 2:
350 return
351
352 raise
353
354 os_release = {}
355 with f:
356 for line in f.readlines():
357 m = re.match(r"^([A-Z\_]+)=(.*)$", line)
358 if m is None:
359 continue
360
361 os_release[m.group(1)] = m.group(2)
362
363 try:
364 return "%(ID)s-%(VERSION_ID)s" % os_release
365 except KeyError:
366 return
367
368 def __parse_system_release(self):
369 """
370 Tries to parse /etc/system-release and
371 returns a unique distribution identifier
372 if the file exists.
373 """
374 try:
375 f = open("/etc/system-release", "r")
376 except IOError, e:
377 # File not found
378 if e.errno == 2:
379 return
380
381 raise
382
383 with f:
384 # Read first line
385 line = f.readline()
386
387 # Check for IPFire systems
388 m = re.match(r"^IPFire (\d).(\d+)", line)
389 if m:
390 return "ipfire-%s" % m.group(1)