]> git.ipfire.org Git - ddns.git/blame - src/ddns/system.py
Use HTTPS for checkip{6,4}.dns.lightningwirelabs.com
[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
a6094ef6 24import ssl
6cecd141 25import socket
adb124d0 26import urllib
f22ab085
MT
27import urllib2
28
29from __version__ import CLIENT_VERSION
7a909224 30from .errors import *
f22ab085
MT
31from i18n import _
32
33# Initialize the logger.
34import logging
35logger = logging.getLogger("ddns.system")
36logger.propagate = 1
37
38class DDNSSystem(object):
39 """
40 The DDNSSystem class adds a layer of abstraction
41 between the ddns software and the system.
42 """
43
44 # The default useragent.
45 USER_AGENT = "IPFireDDNSUpdater/%s" % CLIENT_VERSION
46
47 def __init__(self, core):
48 # Connection to the core of the program.
49 self.core = core
50
91a8ff83
MT
51 # Address cache.
52 self.__addresses = {}
53
2780b6bb
MT
54 # Find out on which distribution we are running.
55 self.distro = self._get_distro_identifier()
56 logger.debug(_("Running on distribution: %s") % self.distro)
57
f22ab085
MT
58 @property
59 def proxy(self):
60 proxy = self.core.settings.get("proxy")
61
62 # Strip http:// at the beginning.
fd898828 63 if proxy and proxy.startswith("http://"):
f22ab085
MT
64 proxy = proxy[7:]
65
66 return proxy
67
eba7100b 68 def get_local_ip_address(self, proto):
12dc74a8
MT
69 ip_address = self._get_local_ip_address(proto)
70
71 # Check if the IP address is usable and only return it then
72 if self._is_usable_ip_address(proto, ip_address):
73 return ip_address
74
75 def _get_local_ip_address(self, proto):
eba7100b
MT
76 # Legacy code for IPFire 2.
77 if self.distro == "ipfire-2" and proto == "ipv4":
7f75b957
MT
78 try:
79 with open("/var/ipfire/red/local-ipaddress") as f:
80 return f.readline()
81
82 except IOError, e:
83 # File not found
84 if e.errno == 2:
85 return
86
87 raise
88
eba7100b
MT
89 # XXX TODO
90 raise NotImplementedError
7f75b957 91
46c23a71 92 def _guess_external_ip_address(self, url, timeout=10):
30270391
MT
93 """
94 Sends a request to an external web server
95 to determine the current default IP address.
96 """
7a909224 97 try:
46c23a71 98 response = self.send_request(url, timeout=timeout)
7a909224
MT
99
100 # If the server could not be reached, we will return nothing.
101 except DDNSNetworkError:
102 return
30270391
MT
103
104 if not response.code == 200:
105 return
106
107 match = re.search(r"^Your IP address is: (.*)$", response.read())
108 if match is None:
109 return
110
111 return match.group(1)
112
022003bc
MT
113 def guess_external_ip_address(self, family, **kwargs):
114 if family == "ipv6":
60e54d71 115 url = "https://checkip6.dns.lightningwirelabs.com"
022003bc 116 elif family == "ipv4":
60e54d71 117 url = "https://checkip4.dns.lightningwirelabs.com"
022003bc
MT
118 else:
119 raise ValueError("unknown address family")
f22ab085 120
022003bc 121 return self._guess_external_ip_address(url, **kwargs)
f22ab085 122
d4c5c0d5 123 def send_request(self, url, method="GET", data=None, username=None, password=None, timeout=30):
adb124d0
MT
124 assert method in ("GET", "POST")
125
126 # Add all arguments in the data dict to the URL and escape them properly.
127 if method == "GET" and data:
128 query_args = self._format_query_args(data)
129 data = None
130
4c1b0d25
SS
131 if "?" in url:
132 url = "%s&%s" % (url, query_args)
133 else:
134 url = "%s?%s" % (url, query_args)
adb124d0
MT
135
136 logger.debug("Sending request (%s): %s" % (method, url))
f22ab085
MT
137 if data:
138 logger.debug(" data: %s" % data)
139
140 req = urllib2.Request(url, data=data)
141
d4c5c0d5
SS
142 if username and password:
143 basic_auth_header = self._make_basic_auth_header(username, password)
d4c5c0d5
SS
144 req.add_header("Authorization", "Basic %s" % basic_auth_header)
145
f22ab085
MT
146 # Set the user agent.
147 req.add_header("User-Agent", self.USER_AGENT)
148
149 # All requests should not be cached anywhere.
150 req.add_header("Pragma", "no-cache")
151
152 # Set the upstream proxy if needed.
153 if self.proxy:
154 logger.debug("Using proxy: %s" % self.proxy)
155
156 # Configure the proxy for this request.
157 req.set_proxy(self.proxy, "http")
158
adb124d0
MT
159 assert req.get_method() == method
160
f22ab085
MT
161 logger.debug(_("Request header:"))
162 for k, v in req.headers.items():
163 logger.debug(" %s: %s" % (k, v))
164
165 try:
7a909224 166 resp = urllib2.urlopen(req, timeout=timeout)
f22ab085
MT
167
168 # Log response header.
09c496c5 169 logger.debug(_("Response header (Status Code %s):") % resp.code)
f22ab085
MT
170 for k, v in resp.info().items():
171 logger.debug(" %s: %s" % (k, v))
172
173 # Return the entire response object.
174 return resp
175
7a909224 176 except urllib2.HTTPError, e:
3bc79bff
MT
177 # Log response header.
178 logger.debug(_("Response header (Status Code %s):") % e.code)
179 for k, v in e.hdrs.items():
180 logger.debug(" %s: %s" % (k, v))
181
536e87d1
MT
182 # 400 - Bad request
183 if e.code == 400:
184 raise DDNSRequestError(e.reason)
185
186 # 401 - Authorization Required
187 # 403 - Forbidden
188 elif e.code in (401, 403):
189 raise DDNSAuthenticationError(e.reason)
190
ff43fa70
MT
191 # 404 - Not found
192 # Either the provider has changed the API, or
193 # there is an error on the server
194 elif e.code == 404:
195 raise DDNSNotFound(e.reason)
196
f1c73c2c
DW
197 # 429 - Too Many Requests
198 elif e.code == 429:
199 raise DDNSTooManyRequests(e.reason)
200
536e87d1
MT
201 # 500 - Internal Server Error
202 elif e.code == 500:
203 raise DDNSInternalServerError(e.reason)
204
7a909224 205 # 503 - Service Unavailable
536e87d1
MT
206 elif e.code == 503:
207 raise DDNSServiceUnavailableError(e.reason)
7a909224
MT
208
209 # Raise all other unhandled exceptions.
210 raise
211
f22ab085 212 except urllib2.URLError, e:
7a909224 213 if e.reason:
a6094ef6
MT
214 # Handle SSL errors
215 if isinstance(e.reason, ssl.SSLError):
216 e = e.reason
217
218 if e.reason == "CERTIFICATE_VERIFY_FAILED":
219 raise DDNSCertificateError
220
221 # Raise all other SSL errors
222 raise DDNSSSLError(e.reason)
223
694d8485
MT
224 # Name or service not known
225 if e.reason.errno == -2:
226 raise DDNSResolveError
227
7a909224
MT
228 # Network Unreachable (e.g. no IPv6 access)
229 if e.reason.errno == 101:
230 raise DDNSNetworkUnreachableError
a96ab398
MT
231
232 # Connection Refused
7a909224
MT
233 elif e.reason.errno == 111:
234 raise DDNSConnectionRefusedError
235
5d98b003
MT
236 # No route to host
237 elif e.reason.errno == 113:
238 raise DDNSNoRouteToHostError(req.host)
239
7a909224 240 # Raise all other unhandled exceptions.
f22ab085
MT
241 raise
242
7a909224
MT
243 except socket.timeout, e:
244 logger.debug(_("Connection timeout"))
245
246 raise DDNSConnectionTimeoutError
247
adb124d0
MT
248 def _format_query_args(self, data):
249 args = []
250
251 for k, v in data.items():
252 arg = "%s=%s" % (k, urllib.quote(v))
253 args.append(arg)
254
255 return "&".join(args)
256
d4c5c0d5
SS
257 def _make_basic_auth_header(self, username, password):
258 authstring = "%s:%s" % (username, password)
259
260 # Encode authorization data in base64.
261 authstring = base64.encodestring(authstring)
262
263 # Remove any newline characters.
264 authstring = authstring.replace("\n", "")
265
266 return authstring
267
f22ab085 268 def get_address(self, proto):
91a8ff83
MT
269 """
270 Returns the current IP address for
271 the given IP protocol.
272 """
273 try:
274 return self.__addresses[proto]
275
276 # IP is currently unknown and needs to be retrieved.
277 except KeyError:
278 self.__addresses[proto] = address = \
279 self._get_address(proto)
280
281 return address
282
283 def _get_address(self, proto):
f22ab085
MT
284 assert proto in ("ipv6", "ipv4")
285
afca6b38
MT
286 # IPFire 2 does not support IPv6.
287 if self.distro == "ipfire-2" and proto == "ipv6":
288 return
289
30270391
MT
290 # Check if the external IP address should be guessed from
291 # a remote server.
292 guess_ip = self.core.settings.get("guess_external_ip", "true")
3a061b71 293 guess_ip = guess_ip in ("true", "yes", "1")
30270391 294
3a061b71 295 # Get the local IP address.
12dc74a8
MT
296 local_ip_address = None
297
298 if not guess_ip:
299 try:
300 local_ip_address = self.get_local_ip_address(proto)
301 except NotImplementedError:
302 logger.warning(_("Falling back to check the IP address with help of a public server"))
3a061b71 303
12dc74a8
MT
304 # If no local IP address could be determined, we will fall back to the guess
305 # it with help of an external server...
306 if not local_ip_address:
3a061b71
MT
307 local_ip_address = self.guess_external_ip_address(proto)
308
309 return local_ip_address
310
311 def _is_usable_ip_address(self, proto, address):
312 """
313 Returns True is the local IP address is usable
314 for dynamic DNS (i.e. is not a RFC1918 address or similar).
315 """
316 if proto == "ipv4":
317 # This is not the most perfect solution to match
318 # these addresses, but instead of pulling in an entire
319 # library to handle the IP addresses better, we match
320 # with regular expressions instead.
321 matches = (
322 # RFC1918 address space
323 r"^10\.\d+\.\d+\.\d+$",
324 r"^192\.168\.\d+\.\d+$",
325 r"^172\.(1[6-9]|2[0-9]|31)\.\d+\.\d+$",
326
327 # Dual Stack Lite address space
580f98e8 328 r"^100\.(6[4-9]|[7-9][0-9]|1[01][0-9]|12[0-7])\.\d+\.\d+$",
3a061b71
MT
329 )
330
331 for match in matches:
332 m = re.match(match, address)
333 if m is None:
334 continue
335
336 # Found a match. IP address is not usable.
337 return False
338
339 # In all other cases, return OK.
340 return True
6cecd141
MT
341
342 def resolve(self, hostname, proto=None):
343 addresses = []
344
345 if proto is None:
346 family = 0
347 elif proto == "ipv6":
348 family = socket.AF_INET6
349 elif proto == "ipv4":
350 family = socket.AF_INET
351 else:
352 raise ValueError("Protocol not supported: %s" % proto)
353
354 # Resolve the host address.
73f2bc0b
MT
355 try:
356 response = socket.getaddrinfo(hostname, None, family)
357 except socket.gaierror, e:
358 # Name or service not known
359 if e.errno == -2:
360 return []
361
694d8485
MT
362 # Temporary failure in name resolution
363 elif e.errno == -3:
364 raise DDNSResolveError(hostname)
365
aac65fab
MT
366 # No record for requested family available (e.g. no AAAA)
367 elif e.errno == -5:
368 return []
369
73f2bc0b 370 raise
6cecd141
MT
371
372 # Handle responses.
373 for family, socktype, proto, canonname, sockaddr in response:
374 # IPv6
375 if family == socket.AF_INET6:
376 address, port, flow_info, scope_id = sockaddr
377
378 # Only use the global scope.
379 if not scope_id == 0:
380 continue
381
382 # IPv4
383 elif family == socket.AF_INET:
384 address, port = sockaddr
385
386 # Ignore everything else...
387 else:
388 continue
389
390 # Add to repsonse list if not already in there.
391 if not address in addresses:
392 addresses.append(address)
393
394 return addresses
2780b6bb
MT
395
396 def _get_distro_identifier(self):
397 """
398 Returns a unique identifier for the distribution
399 we are running on.
400 """
401 os_release = self.__parse_os_release()
402 if os_release:
403 return os_release
404
405 system_release = self.__parse_system_release()
406 if system_release:
407 return system_release
408
409 # If nothing else could be found, we return
410 # just "unknown".
411 return "unknown"
412
413 def __parse_os_release(self):
414 """
415 Tries to parse /etc/os-release and
416 returns a unique distribution identifier
417 if the file exists.
418 """
419 try:
420 f = open("/etc/os-release", "r")
421 except IOError, e:
422 # File not found
423 if e.errno == 2:
424 return
425
426 raise
427
428 os_release = {}
429 with f:
430 for line in f.readlines():
431 m = re.match(r"^([A-Z\_]+)=(.*)$", line)
432 if m is None:
433 continue
434
435 os_release[m.group(1)] = m.group(2)
436
437 try:
438 return "%(ID)s-%(VERSION_ID)s" % os_release
439 except KeyError:
440 return
441
442 def __parse_system_release(self):
443 """
444 Tries to parse /etc/system-release and
445 returns a unique distribution identifier
446 if the file exists.
447 """
448 try:
449 f = open("/etc/system-release", "r")
450 except IOError, e:
451 # File not found
452 if e.errno == 2:
453 return
454
455 raise
456
457 with f:
458 # Read first line
459 line = f.readline()
460
461 # Check for IPFire systems
462 m = re.match(r"^IPFire (\d).(\d+)", line)
463 if m:
464 return "ipfire-%s" % m.group(1)