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