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