]> git.ipfire.org Git - ddns.git/blob - src/ddns/system.py
Handle HTTP errors as early as possible.
[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 # 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
54 @property
55 def proxy(self):
56 proxy = self.core.settings.get("proxy")
57
58 # Strip http:// at the beginning.
59 if proxy and proxy.startswith("http://"):
60 proxy = proxy[7:]
61
62 return proxy
63
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
82 def _guess_external_ip_address(self, url, timeout=10):
83 """
84 Sends a request to an external web server
85 to determine the current default IP address.
86 """
87 try:
88 response = self.send_request(url, timeout=timeout)
89
90 # If the server could not be reached, we will return nothing.
91 except DDNSNetworkError:
92 return
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
103 def guess_external_ipv6_address(self):
104 """
105 Sends a request to the internet to determine
106 the public IPv6 address.
107 """
108 return self._guess_external_ip_address("http://checkip6.dns.lightningwirelabs.com")
109
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")
116
117 def send_request(self, url, method="GET", data=None, username=None, password=None, timeout=30):
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
125 if "?" in url:
126 url = "%s&%s" % (url, query_args)
127 else:
128 url = "%s?%s" % (url, query_args)
129
130 logger.debug("Sending request (%s): %s" % (method, url))
131 if data:
132 logger.debug(" data: %s" % data)
133
134 req = urllib2.Request(url, data=data)
135
136 if username and password:
137 basic_auth_header = self._make_basic_auth_header(username, password)
138 req.add_header("Authorization", "Basic %s" % basic_auth_header)
139
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
153 assert req.get_method() == method
154
155 logger.debug(_("Request header:"))
156 for k, v in req.headers.items():
157 logger.debug(" %s: %s" % (k, v))
158
159 try:
160 resp = urllib2.urlopen(req, timeout=timeout)
161
162 # Log response header.
163 logger.debug(_("Response header (Status Code %s):") % resp.code)
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
170 except urllib2.HTTPError, e:
171 # 400 - Bad request
172 if e.code == 400:
173 raise DDNSRequestError(e.reason)
174
175 # 401 - Authorization Required
176 # 403 - Forbidden
177 elif e.code in (401, 403):
178 raise DDNSAuthenticationError(e.reason)
179
180 # 500 - Internal Server Error
181 elif e.code == 500:
182 raise DDNSInternalServerError(e.reason)
183
184 # 503 - Service Unavailable
185 elif e.code == 503:
186 raise DDNSServiceUnavailableError(e.reason)
187
188 # Raise all other unhandled exceptions.
189 raise
190
191 except urllib2.URLError, e:
192 if e.reason:
193 # Network Unreachable (e.g. no IPv6 access)
194 if e.reason.errno == 101:
195 raise DDNSNetworkUnreachableError
196 elif e.reason.errno == 111:
197 raise DDNSConnectionRefusedError
198
199 # Raise all other unhandled exceptions.
200 raise
201
202 except socket.timeout, e:
203 logger.debug(_("Connection timeout"))
204
205 raise DDNSConnectionTimeoutError
206
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
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
227 def get_address(self, proto):
228 assert proto in ("ipv6", "ipv4")
229
230 # IPFire 2 does not support IPv6.
231 if self.distro == "ipfire-2" and proto == "ipv6":
232 return
233
234 # Check if the external IP address should be guessed from
235 # a remote server.
236 guess_ip = self.core.settings.get("guess_external_ip", "true")
237
238 # If the external IP address should be used, we just do
239 # that.
240 if guess_ip in ("true", "yes", "1"):
241 if proto == "ipv6":
242 return self.guess_external_ipv6_address()
243
244 elif proto == "ipv4":
245 return self.guess_external_ipv4_address()
246
247 # Get the local IP addresses.
248 else:
249 if proto == "ipv6":
250 return self.get_local_ipv6_address()
251 elif proto == "ipv4":
252 return self.get_local_ipv4_address()
253
254 def resolve(self, hostname, proto=None):
255 addresses = []
256
257 if proto is None:
258 family = 0
259 elif proto == "ipv6":
260 family = socket.AF_INET6
261 elif proto == "ipv4":
262 family = socket.AF_INET
263 else:
264 raise ValueError("Protocol not supported: %s" % proto)
265
266 # Resolve the host address.
267 try:
268 response = socket.getaddrinfo(hostname, None, family)
269 except socket.gaierror, e:
270 # Name or service not known
271 if e.errno == -2:
272 return []
273
274 # No record for requested family available (e.g. no AAAA)
275 elif e.errno == -5:
276 return []
277
278 raise
279
280 # Handle responses.
281 for family, socktype, proto, canonname, sockaddr in response:
282 # IPv6
283 if family == socket.AF_INET6:
284 address, port, flow_info, scope_id = sockaddr
285
286 # Only use the global scope.
287 if not scope_id == 0:
288 continue
289
290 # IPv4
291 elif family == socket.AF_INET:
292 address, port = sockaddr
293
294 # Ignore everything else...
295 else:
296 continue
297
298 # Add to repsonse list if not already in there.
299 if not address in addresses:
300 addresses.append(address)
301
302 return addresses
303
304 def _get_distro_identifier(self):
305 """
306 Returns a unique identifier for the distribution
307 we are running on.
308 """
309 os_release = self.__parse_os_release()
310 if os_release:
311 return os_release
312
313 system_release = self.__parse_system_release()
314 if system_release:
315 return system_release
316
317 # If nothing else could be found, we return
318 # just "unknown".
319 return "unknown"
320
321 def __parse_os_release(self):
322 """
323 Tries to parse /etc/os-release and
324 returns a unique distribution identifier
325 if the file exists.
326 """
327 try:
328 f = open("/etc/os-release", "r")
329 except IOError, e:
330 # File not found
331 if e.errno == 2:
332 return
333
334 raise
335
336 os_release = {}
337 with f:
338 for line in f.readlines():
339 m = re.match(r"^([A-Z\_]+)=(.*)$", line)
340 if m is None:
341 continue
342
343 os_release[m.group(1)] = m.group(2)
344
345 try:
346 return "%(ID)s-%(VERSION_ID)s" % os_release
347 except KeyError:
348 return
349
350 def __parse_system_release(self):
351 """
352 Tries to parse /etc/system-release and
353 returns a unique distribution identifier
354 if the file exists.
355 """
356 try:
357 f = open("/etc/system-release", "r")
358 except IOError, e:
359 # File not found
360 if e.errno == 2:
361 return
362
363 raise
364
365 with f:
366 # Read first line
367 line = f.readline()
368
369 # Check for IPFire systems
370 m = re.match(r"^IPFire (\d).(\d+)", line)
371 if m:
372 return "ipfire-%s" % m.group(1)