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