]>
Commit | Line | Data |
---|---|---|
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 | 22 | import base64 |
f22ab085 | 23 | import re |
6cecd141 | 24 | import socket |
adb124d0 | 25 | import urllib |
f22ab085 MT |
26 | import urllib2 |
27 | ||
28 | from __version__ import CLIENT_VERSION | |
7a909224 | 29 | from .errors import * |
f22ab085 MT |
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 | ||
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 | 170 | except urllib2.HTTPError, e: |
536e87d1 MT |
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 | ||
7a909224 | 184 | # 503 - Service Unavailable |
536e87d1 MT |
185 | elif e.code == 503: |
186 | raise DDNSServiceUnavailableError(e.reason) | |
7a909224 MT |
187 | |
188 | # Raise all other unhandled exceptions. | |
189 | raise | |
190 | ||
f22ab085 | 191 | except urllib2.URLError, e: |
7a909224 MT |
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. | |
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 MT |
227 | def get_address(self, proto): |
228 | assert proto in ("ipv6", "ipv4") | |
229 | ||
afca6b38 MT |
230 | # IPFire 2 does not support IPv6. |
231 | if self.distro == "ipfire-2" and proto == "ipv6": | |
232 | return | |
233 | ||
30270391 MT |
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() | |
f22ab085 | 243 | |
30270391 | 244 | elif proto == "ipv4": |
f22ab085 MT |
245 | return self.guess_external_ipv4_address() |
246 | ||
7f75b957 MT |
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() | |
6cecd141 MT |
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. | |
73f2bc0b MT |
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 | ||
aac65fab MT |
274 | # No record for requested family available (e.g. no AAAA) |
275 | elif e.errno == -5: | |
276 | return [] | |
277 | ||
73f2bc0b | 278 | raise |
6cecd141 MT |
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 | |
2780b6bb MT |
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) |