Show much prettier and more useful error messages.
[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
2780b6bb
MT
50 # Find out on which distribution we are running.
51 self.distro = self._get_distro_identifier()
52 logger.debug(_("Running on distribution: %s") % self.distro)
53
f22ab085
MT
54 @property
55 def proxy(self):
56 proxy = self.core.settings.get("proxy")
57
58 # Strip http:// at the beginning.
fd898828 59 if proxy and proxy.startswith("http://"):
f22ab085
MT
60 proxy = proxy[7:]
61
62 return proxy
63
7f75b957
MT
64 def get_local_ipv6_address(self):
65 return # XXX TODO
66
67 def get_local_ipv4_address(self):
68 if self.distro == "ipfire-2":
69 try:
70 with open("/var/ipfire/red/local-ipaddress") as f:
71 return f.readline()
72
73 except IOError, e:
74 # File not found
75 if e.errno == 2:
76 return
77
78 raise
79
80 return # XXX TODO
81
46c23a71 82 def _guess_external_ip_address(self, url, timeout=10):
30270391
MT
83 """
84 Sends a request to an external web server
85 to determine the current default IP address.
86 """
7a909224 87 try:
46c23a71 88 response = self.send_request(url, timeout=timeout)
7a909224
MT
89
90 # If the server could not be reached, we will return nothing.
91 except DDNSNetworkError:
92 return
30270391
MT
93
94 if not response.code == 200:
95 return
96
97 match = re.search(r"^Your IP address is: (.*)$", response.read())
98 if match is None:
99 return
100
101 return match.group(1)
102
46c23a71 103 def guess_external_ipv6_address(self):
f22ab085
MT
104 """
105 Sends a request to the internet to determine
46c23a71 106 the public IPv6 address.
f22ab085 107 """
46c23a71 108 return self._guess_external_ip_address("http://checkip6.dns.lightningwirelabs.com")
f22ab085 109
46c23a71
MT
110 def guess_external_ipv4_address(self):
111 """
112 Sends a request to the internet to determine
113 the public IPv4 address.
114 """
115 return self._guess_external_ip_address("http://checkip4.dns.lightningwirelabs.com")
f22ab085 116
d4c5c0d5 117 def send_request(self, url, method="GET", data=None, username=None, password=None, timeout=30):
adb124d0
MT
118 assert method in ("GET", "POST")
119
120 # Add all arguments in the data dict to the URL and escape them properly.
121 if method == "GET" and data:
122 query_args = self._format_query_args(data)
123 data = None
124
4c1b0d25
SS
125 if "?" in url:
126 url = "%s&%s" % (url, query_args)
127 else:
128 url = "%s?%s" % (url, query_args)
adb124d0
MT
129
130 logger.debug("Sending request (%s): %s" % (method, url))
f22ab085
MT
131 if data:
132 logger.debug(" data: %s" % data)
133
134 req = urllib2.Request(url, data=data)
135
d4c5c0d5
SS
136 if username and password:
137 basic_auth_header = self._make_basic_auth_header(username, password)
d4c5c0d5
SS
138 req.add_header("Authorization", "Basic %s" % basic_auth_header)
139
f22ab085
MT
140 # Set the user agent.
141 req.add_header("User-Agent", self.USER_AGENT)
142
143 # All requests should not be cached anywhere.
144 req.add_header("Pragma", "no-cache")
145
146 # Set the upstream proxy if needed.
147 if self.proxy:
148 logger.debug("Using proxy: %s" % self.proxy)
149
150 # Configure the proxy for this request.
151 req.set_proxy(self.proxy, "http")
152
adb124d0
MT
153 assert req.get_method() == method
154
f22ab085
MT
155 logger.debug(_("Request header:"))
156 for k, v in req.headers.items():
157 logger.debug(" %s: %s" % (k, v))
158
159 try:
7a909224 160 resp = urllib2.urlopen(req, timeout=timeout)
f22ab085
MT
161
162 # Log response header.
09c496c5 163 logger.debug(_("Response header (Status Code %s):") % resp.code)
f22ab085
MT
164 for k, v in resp.info().items():
165 logger.debug(" %s: %s" % (k, v))
166
167 # Return the entire response object.
168 return resp
169
7a909224
MT
170 except urllib2.HTTPError, e:
171 # 503 - Service Unavailable
172 if e.code == 503:
173 raise DDNSServiceUnavailableError
174
175 # Raise all other unhandled exceptions.
176 raise
177
f22ab085 178 except urllib2.URLError, e:
7a909224
MT
179 if e.reason:
180 # Network Unreachable (e.g. no IPv6 access)
181 if e.reason.errno == 101:
182 raise DDNSNetworkUnreachableError
183 elif e.reason.errno == 111:
184 raise DDNSConnectionRefusedError
185
186 # Raise all other unhandled exceptions.
f22ab085
MT
187 raise
188
7a909224
MT
189 except socket.timeout, e:
190 logger.debug(_("Connection timeout"))
191
192 raise DDNSConnectionTimeoutError
193
adb124d0
MT
194 def _format_query_args(self, data):
195 args = []
196
197 for k, v in data.items():
198 arg = "%s=%s" % (k, urllib.quote(v))
199 args.append(arg)
200
201 return "&".join(args)
202
d4c5c0d5
SS
203 def _make_basic_auth_header(self, username, password):
204 authstring = "%s:%s" % (username, password)
205
206 # Encode authorization data in base64.
207 authstring = base64.encodestring(authstring)
208
209 # Remove any newline characters.
210 authstring = authstring.replace("\n", "")
211
212 return authstring
213
f22ab085
MT
214 def get_address(self, proto):
215 assert proto in ("ipv6", "ipv4")
216
afca6b38
MT
217 # IPFire 2 does not support IPv6.
218 if self.distro == "ipfire-2" and proto == "ipv6":
219 return
220
30270391
MT
221 # Check if the external IP address should be guessed from
222 # a remote server.
223 guess_ip = self.core.settings.get("guess_external_ip", "true")
224
225 # If the external IP address should be used, we just do
226 # that.
227 if guess_ip in ("true", "yes", "1"):
228 if proto == "ipv6":
229 return self.guess_external_ipv6_address()
f22ab085 230
30270391 231 elif proto == "ipv4":
f22ab085
MT
232 return self.guess_external_ipv4_address()
233
7f75b957
MT
234 # Get the local IP addresses.
235 else:
236 if proto == "ipv6":
237 return self.get_local_ipv6_address()
238 elif proto == "ipv4":
239 return self.get_local_ipv4_address()
6cecd141
MT
240
241 def resolve(self, hostname, proto=None):
242 addresses = []
243
244 if proto is None:
245 family = 0
246 elif proto == "ipv6":
247 family = socket.AF_INET6
248 elif proto == "ipv4":
249 family = socket.AF_INET
250 else:
251 raise ValueError("Protocol not supported: %s" % proto)
252
253 # Resolve the host address.
73f2bc0b
MT
254 try:
255 response = socket.getaddrinfo(hostname, None, family)
256 except socket.gaierror, e:
257 # Name or service not known
258 if e.errno == -2:
259 return []
260
aac65fab
MT
261 # No record for requested family available (e.g. no AAAA)
262 elif e.errno == -5:
263 return []
264
73f2bc0b 265 raise
6cecd141
MT
266
267 # Handle responses.
268 for family, socktype, proto, canonname, sockaddr in response:
269 # IPv6
270 if family == socket.AF_INET6:
271 address, port, flow_info, scope_id = sockaddr
272
273 # Only use the global scope.
274 if not scope_id == 0:
275 continue
276
277 # IPv4
278 elif family == socket.AF_INET:
279 address, port = sockaddr
280
281 # Ignore everything else...
282 else:
283 continue
284
285 # Add to repsonse list if not already in there.
286 if not address in addresses:
287 addresses.append(address)
288
289 return addresses
2780b6bb
MT
290
291 def _get_distro_identifier(self):
292 """
293 Returns a unique identifier for the distribution
294 we are running on.
295 """
296 os_release = self.__parse_os_release()
297 if os_release:
298 return os_release
299
300 system_release = self.__parse_system_release()
301 if system_release:
302 return system_release
303
304 # If nothing else could be found, we return
305 # just "unknown".
306 return "unknown"
307
308 def __parse_os_release(self):
309 """
310 Tries to parse /etc/os-release and
311 returns a unique distribution identifier
312 if the file exists.
313 """
314 try:
315 f = open("/etc/os-release", "r")
316 except IOError, e:
317 # File not found
318 if e.errno == 2:
319 return
320
321 raise
322
323 os_release = {}
324 with f:
325 for line in f.readlines():
326 m = re.match(r"^([A-Z\_]+)=(.*)$", line)
327 if m is None:
328 continue
329
330 os_release[m.group(1)] = m.group(2)
331
332 try:
333 return "%(ID)s-%(VERSION_ID)s" % os_release
334 except KeyError:
335 return
336
337 def __parse_system_release(self):
338 """
339 Tries to parse /etc/system-release and
340 returns a unique distribution identifier
341 if the file exists.
342 """
343 try:
344 f = open("/etc/system-release", "r")
345 except IOError, e:
346 # File not found
347 if e.errno == 2:
348 return
349
350 raise
351
352 with f:
353 # Read first line
354 line = f.readline()
355
356 # Check for IPFire systems
357 m = re.match(r"^IPFire (\d).(\d+)", line)
358 if m:
359 return "ipfire-%s" % m.group(1)