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