]> git.ipfire.org Git - oddments/ddns.git/blame - src/ddns/system.py
regex: Add trailing $ which was missing.
[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
eba7100b
MT
67 def get_local_ip_address(self, proto):
68 # Legacy code for IPFire 2.
69 if self.distro == "ipfire-2" and proto == "ipv4":
7f75b957
MT
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
eba7100b
MT
81 # XXX TODO
82 raise NotImplementedError
7f75b957 83
46c23a71 84 def _guess_external_ip_address(self, url, timeout=10):
30270391
MT
85 """
86 Sends a request to an external web server
87 to determine the current default IP address.
88 """
7a909224 89 try:
46c23a71 90 response = self.send_request(url, timeout=timeout)
7a909224
MT
91
92 # If the server could not be reached, we will return nothing.
93 except DDNSNetworkError:
94 return
30270391
MT
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
022003bc
MT
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")
f22ab085 112
022003bc 113 return self._guess_external_ip_address(url, **kwargs)
f22ab085 114
d4c5c0d5 115 def send_request(self, url, method="GET", data=None, username=None, password=None, timeout=30):
adb124d0
MT
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
4c1b0d25
SS
123 if "?" in url:
124 url = "%s&%s" % (url, query_args)
125 else:
126 url = "%s?%s" % (url, query_args)
adb124d0
MT
127
128 logger.debug("Sending request (%s): %s" % (method, url))
f22ab085
MT
129 if data:
130 logger.debug(" data: %s" % data)
131
132 req = urllib2.Request(url, data=data)
133
d4c5c0d5
SS
134 if username and password:
135 basic_auth_header = self._make_basic_auth_header(username, password)
d4c5c0d5
SS
136 req.add_header("Authorization", "Basic %s" % basic_auth_header)
137
f22ab085
MT
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
adb124d0
MT
151 assert req.get_method() == method
152
f22ab085
MT
153 logger.debug(_("Request header:"))
154 for k, v in req.headers.items():
155 logger.debug(" %s: %s" % (k, v))
156
157 try:
7a909224 158 resp = urllib2.urlopen(req, timeout=timeout)
f22ab085
MT
159
160 # Log response header.
09c496c5 161 logger.debug(_("Response header (Status Code %s):") % resp.code)
f22ab085
MT
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
7a909224 168 except urllib2.HTTPError, e:
536e87d1
MT
169 # 400 - Bad request
170 if e.code == 400:
171 raise DDNSRequestError(e.reason)
172
173 # 401 - Authorization Required
174 # 403 - Forbidden
175 elif e.code in (401, 403):
176 raise DDNSAuthenticationError(e.reason)
177
178 # 500 - Internal Server Error
179 elif e.code == 500:
180 raise DDNSInternalServerError(e.reason)
181
7a909224 182 # 503 - Service Unavailable
536e87d1
MT
183 elif e.code == 503:
184 raise DDNSServiceUnavailableError(e.reason)
7a909224
MT
185
186 # Raise all other unhandled exceptions.
187 raise
188
f22ab085 189 except urllib2.URLError, e:
7a909224
MT
190 if e.reason:
191 # Network Unreachable (e.g. no IPv6 access)
192 if e.reason.errno == 101:
193 raise DDNSNetworkUnreachableError
a96ab398
MT
194
195 # Connection Refused
7a909224
MT
196 elif e.reason.errno == 111:
197 raise DDNSConnectionRefusedError
198
199 # Raise all other unhandled exceptions.
f22ab085
MT
200 raise
201
7a909224
MT
202 except socket.timeout, e:
203 logger.debug(_("Connection timeout"))
204
205 raise DDNSConnectionTimeoutError
206
adb124d0
MT
207 def _format_query_args(self, data):
208 args = []
209
210 for k, v in data.items():
211 arg = "%s=%s" % (k, urllib.quote(v))
212 args.append(arg)
213
214 return "&".join(args)
215
d4c5c0d5
SS
216 def _make_basic_auth_header(self, username, password):
217 authstring = "%s:%s" % (username, password)
218
219 # Encode authorization data in base64.
220 authstring = base64.encodestring(authstring)
221
222 # Remove any newline characters.
223 authstring = authstring.replace("\n", "")
224
225 return authstring
226
f22ab085 227 def get_address(self, proto):
91a8ff83
MT
228 """
229 Returns the current IP address for
230 the given IP protocol.
231 """
232 try:
233 return self.__addresses[proto]
234
235 # IP is currently unknown and needs to be retrieved.
236 except KeyError:
237 self.__addresses[proto] = address = \
238 self._get_address(proto)
239
240 return address
241
242 def _get_address(self, proto):
f22ab085
MT
243 assert proto in ("ipv6", "ipv4")
244
afca6b38
MT
245 # IPFire 2 does not support IPv6.
246 if self.distro == "ipfire-2" and proto == "ipv6":
247 return
248
30270391
MT
249 # Check if the external IP address should be guessed from
250 # a remote server.
251 guess_ip = self.core.settings.get("guess_external_ip", "true")
3a061b71 252 guess_ip = guess_ip in ("true", "yes", "1")
30270391 253
3a061b71
MT
254 # If the external IP address should be used, we just do that.
255 if guess_ip:
022003bc 256 return self.guess_external_ip_address(proto)
f22ab085 257
3a061b71
MT
258 # Get the local IP address.
259 local_ip_address = self.get_local_ip_address(proto)
260
261 # If the local IP address is not usable, we must guess
262 # the correct IP address...
263 if not self._is_usable_ip_address(proto, local_ip_address):
264 local_ip_address = self.guess_external_ip_address(proto)
265
266 return local_ip_address
267
268 def _is_usable_ip_address(self, proto, address):
269 """
270 Returns True is the local IP address is usable
271 for dynamic DNS (i.e. is not a RFC1918 address or similar).
272 """
273 if proto == "ipv4":
274 # This is not the most perfect solution to match
275 # these addresses, but instead of pulling in an entire
276 # library to handle the IP addresses better, we match
277 # with regular expressions instead.
278 matches = (
279 # RFC1918 address space
280 r"^10\.\d+\.\d+\.\d+$",
281 r"^192\.168\.\d+\.\d+$",
282 r"^172\.(1[6-9]|2[0-9]|31)\.\d+\.\d+$",
283
284 # Dual Stack Lite address space
580f98e8 285 r"^100\.(6[4-9]|[7-9][0-9]|1[01][0-9]|12[0-7])\.\d+\.\d+$",
3a061b71
MT
286 )
287
288 for match in matches:
289 m = re.match(match, address)
290 if m is None:
291 continue
292
293 # Found a match. IP address is not usable.
294 return False
295
296 # In all other cases, return OK.
297 return True
6cecd141
MT
298
299 def resolve(self, hostname, proto=None):
300 addresses = []
301
302 if proto is None:
303 family = 0
304 elif proto == "ipv6":
305 family = socket.AF_INET6
306 elif proto == "ipv4":
307 family = socket.AF_INET
308 else:
309 raise ValueError("Protocol not supported: %s" % proto)
310
311 # Resolve the host address.
73f2bc0b
MT
312 try:
313 response = socket.getaddrinfo(hostname, None, family)
314 except socket.gaierror, e:
315 # Name or service not known
316 if e.errno == -2:
317 return []
318
aac65fab
MT
319 # No record for requested family available (e.g. no AAAA)
320 elif e.errno == -5:
321 return []
322
73f2bc0b 323 raise
6cecd141
MT
324
325 # Handle responses.
326 for family, socktype, proto, canonname, sockaddr in response:
327 # IPv6
328 if family == socket.AF_INET6:
329 address, port, flow_info, scope_id = sockaddr
330
331 # Only use the global scope.
332 if not scope_id == 0:
333 continue
334
335 # IPv4
336 elif family == socket.AF_INET:
337 address, port = sockaddr
338
339 # Ignore everything else...
340 else:
341 continue
342
343 # Add to repsonse list if not already in there.
344 if not address in addresses:
345 addresses.append(address)
346
347 return addresses
2780b6bb
MT
348
349 def _get_distro_identifier(self):
350 """
351 Returns a unique identifier for the distribution
352 we are running on.
353 """
354 os_release = self.__parse_os_release()
355 if os_release:
356 return os_release
357
358 system_release = self.__parse_system_release()
359 if system_release:
360 return system_release
361
362 # If nothing else could be found, we return
363 # just "unknown".
364 return "unknown"
365
366 def __parse_os_release(self):
367 """
368 Tries to parse /etc/os-release and
369 returns a unique distribution identifier
370 if the file exists.
371 """
372 try:
373 f = open("/etc/os-release", "r")
374 except IOError, e:
375 # File not found
376 if e.errno == 2:
377 return
378
379 raise
380
381 os_release = {}
382 with f:
383 for line in f.readlines():
384 m = re.match(r"^([A-Z\_]+)=(.*)$", line)
385 if m is None:
386 continue
387
388 os_release[m.group(1)] = m.group(2)
389
390 try:
391 return "%(ID)s-%(VERSION_ID)s" % os_release
392 except KeyError:
393 return
394
395 def __parse_system_release(self):
396 """
397 Tries to parse /etc/system-release and
398 returns a unique distribution identifier
399 if the file exists.
400 """
401 try:
402 f = open("/etc/system-release", "r")
403 except IOError, e:
404 # File not found
405 if e.errno == 2:
406 return
407
408 raise
409
410 with f:
411 # Read first line
412 line = f.readline()
413
414 # Check for IPFire systems
415 m = re.match(r"^IPFire (\d).(\d+)", line)
416 if m:
417 return "ipfire-%s" % m.group(1)