]> git.ipfire.org Git - people/stevee/ddns.git/blame - src/ddns/system.py
Simplify IP address guessing code.
[people/stevee/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
7f75b957
MT
67 def get_local_ipv6_address(self):
68 return # XXX TODO
69
70 def get_local_ipv4_address(self):
71 if self.distro == "ipfire-2":
72 try:
73 with open("/var/ipfire/red/local-ipaddress") as f:
74 return f.readline()
75
76 except IOError, e:
77 # File not found
78 if e.errno == 2:
79 return
80
81 raise
82
83 return # XXX TODO
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:
536e87d1
MT
170 # 400 - Bad request
171 if e.code == 400:
172 raise DDNSRequestError(e.reason)
173
174 # 401 - Authorization Required
175 # 403 - Forbidden
176 elif e.code in (401, 403):
177 raise DDNSAuthenticationError(e.reason)
178
179 # 500 - Internal Server Error
180 elif e.code == 500:
181 raise DDNSInternalServerError(e.reason)
182
7a909224 183 # 503 - Service Unavailable
536e87d1
MT
184 elif e.code == 503:
185 raise DDNSServiceUnavailableError(e.reason)
7a909224
MT
186
187 # Raise all other unhandled exceptions.
188 raise
189
f22ab085 190 except urllib2.URLError, e:
7a909224
MT
191 if e.reason:
192 # Network Unreachable (e.g. no IPv6 access)
193 if e.reason.errno == 101:
194 raise DDNSNetworkUnreachableError
195 elif e.reason.errno == 111:
196 raise DDNSConnectionRefusedError
197
198 # Raise all other unhandled exceptions.
f22ab085
MT
199 raise
200
7a909224
MT
201 except socket.timeout, e:
202 logger.debug(_("Connection timeout"))
203
204 raise DDNSConnectionTimeoutError
205
adb124d0
MT
206 def _format_query_args(self, data):
207 args = []
208
209 for k, v in data.items():
210 arg = "%s=%s" % (k, urllib.quote(v))
211 args.append(arg)
212
213 return "&".join(args)
214
d4c5c0d5
SS
215 def _make_basic_auth_header(self, username, password):
216 authstring = "%s:%s" % (username, password)
217
218 # Encode authorization data in base64.
219 authstring = base64.encodestring(authstring)
220
221 # Remove any newline characters.
222 authstring = authstring.replace("\n", "")
223
224 return authstring
225
f22ab085 226 def get_address(self, proto):
91a8ff83
MT
227 """
228 Returns the current IP address for
229 the given IP protocol.
230 """
231 try:
232 return self.__addresses[proto]
233
234 # IP is currently unknown and needs to be retrieved.
235 except KeyError:
236 self.__addresses[proto] = address = \
237 self._get_address(proto)
238
239 return address
240
241 def _get_address(self, proto):
f22ab085
MT
242 assert proto in ("ipv6", "ipv4")
243
afca6b38
MT
244 # IPFire 2 does not support IPv6.
245 if self.distro == "ipfire-2" and proto == "ipv6":
246 return
247
30270391
MT
248 # Check if the external IP address should be guessed from
249 # a remote server.
250 guess_ip = self.core.settings.get("guess_external_ip", "true")
251
252 # If the external IP address should be used, we just do
253 # that.
254 if guess_ip in ("true", "yes", "1"):
022003bc 255 return self.guess_external_ip_address(proto)
f22ab085 256
7f75b957
MT
257 # Get the local IP addresses.
258 else:
259 if proto == "ipv6":
260 return self.get_local_ipv6_address()
261 elif proto == "ipv4":
262 return self.get_local_ipv4_address()
6cecd141
MT
263
264 def resolve(self, hostname, proto=None):
265 addresses = []
266
267 if proto is None:
268 family = 0
269 elif proto == "ipv6":
270 family = socket.AF_INET6
271 elif proto == "ipv4":
272 family = socket.AF_INET
273 else:
274 raise ValueError("Protocol not supported: %s" % proto)
275
276 # Resolve the host address.
73f2bc0b
MT
277 try:
278 response = socket.getaddrinfo(hostname, None, family)
279 except socket.gaierror, e:
280 # Name or service not known
281 if e.errno == -2:
282 return []
283
aac65fab
MT
284 # No record for requested family available (e.g. no AAAA)
285 elif e.errno == -5:
286 return []
287
73f2bc0b 288 raise
6cecd141
MT
289
290 # Handle responses.
291 for family, socktype, proto, canonname, sockaddr in response:
292 # IPv6
293 if family == socket.AF_INET6:
294 address, port, flow_info, scope_id = sockaddr
295
296 # Only use the global scope.
297 if not scope_id == 0:
298 continue
299
300 # IPv4
301 elif family == socket.AF_INET:
302 address, port = sockaddr
303
304 # Ignore everything else...
305 else:
306 continue
307
308 # Add to repsonse list if not already in there.
309 if not address in addresses:
310 addresses.append(address)
311
312 return addresses
2780b6bb
MT
313
314 def _get_distro_identifier(self):
315 """
316 Returns a unique identifier for the distribution
317 we are running on.
318 """
319 os_release = self.__parse_os_release()
320 if os_release:
321 return os_release
322
323 system_release = self.__parse_system_release()
324 if system_release:
325 return system_release
326
327 # If nothing else could be found, we return
328 # just "unknown".
329 return "unknown"
330
331 def __parse_os_release(self):
332 """
333 Tries to parse /etc/os-release and
334 returns a unique distribution identifier
335 if the file exists.
336 """
337 try:
338 f = open("/etc/os-release", "r")
339 except IOError, e:
340 # File not found
341 if e.errno == 2:
342 return
343
344 raise
345
346 os_release = {}
347 with f:
348 for line in f.readlines():
349 m = re.match(r"^([A-Z\_]+)=(.*)$", line)
350 if m is None:
351 continue
352
353 os_release[m.group(1)] = m.group(2)
354
355 try:
356 return "%(ID)s-%(VERSION_ID)s" % os_release
357 except KeyError:
358 return
359
360 def __parse_system_release(self):
361 """
362 Tries to parse /etc/system-release and
363 returns a unique distribution identifier
364 if the file exists.
365 """
366 try:
367 f = open("/etc/system-release", "r")
368 except IOError, e:
369 # File not found
370 if e.errno == 2:
371 return
372
373 raise
374
375 with f:
376 # Read first line
377 line = f.readline()
378
379 # Check for IPFire systems
380 m = re.match(r"^IPFire (\d).(\d+)", line)
381 if m:
382 return "ipfire-%s" % m.group(1)