2 ###############################################################################
4 # ddns - A dynamic DNS client for IPFire #
5 # Copyright (C) 2012 IPFire development team #
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. #
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. #
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/>. #
20 ###############################################################################
29 from __version__
import CLIENT_VERSION
33 # Initialize the logger.
35 logger
= logging
.getLogger("ddns.system")
38 class DDNSSystem(object):
40 The DDNSSystem class adds a layer of abstraction
41 between the ddns software and the system.
44 # The default useragent.
45 USER_AGENT
= "IPFireDDNSUpdater/%s" % CLIENT_VERSION
47 def __init__(self
, core
):
48 # Connection to the core of the program.
54 # Find out on which distribution we are running.
55 self
.distro
= self
._get
_distro
_identifier
()
56 logger
.debug(_("Running on distribution: %s") % self
.distro
)
60 proxy
= self
.core
.settings
.get("proxy")
62 # Strip http:// at the beginning.
63 if proxy
and proxy
.startswith("http://"):
68 def get_local_ip_address(self
, proto
):
69 ip_address
= self
._get
_local
_ip
_address
(proto
)
71 # Check if the IP address is usable and only return it then
72 if self
._is
_usable
_ip
_address
(proto
, ip_address
):
75 def _get_local_ip_address(self
, proto
):
76 # Legacy code for IPFire 2.
77 if self
.distro
== "ipfire-2" and proto
== "ipv4":
79 with
open("/var/ipfire/red/local-ipaddress") as f
:
90 raise NotImplementedError
92 def _guess_external_ip_address(self
, url
, timeout
=10):
94 Sends a request to an external web server
95 to determine the current default IP address.
98 response
= self
.send_request(url
, timeout
=timeout
)
100 # If the server could not be reached, we will return nothing.
101 except DDNSNetworkError
:
104 if not response
.code
== 200:
107 match
= re
.search(r
"^Your IP address is: (.*)$", response
.read())
111 return match
.group(1)
113 def guess_external_ip_address(self
, family
, **kwargs
):
115 url
= "https://checkip6.dns.lightningwirelabs.com"
116 elif family
== "ipv4":
117 url
= "https://checkip4.dns.lightningwirelabs.com"
119 raise ValueError("unknown address family")
121 return self
._guess
_external
_ip
_address
(url
, **kwargs
)
123 def send_request(self
, url
, method
="GET", data
=None, username
=None, password
=None, timeout
=30):
124 assert method
in ("GET", "POST")
126 # Add all arguments in the data dict to the URL and escape them properly.
127 if method
== "GET" and data
:
128 query_args
= self
._format
_query
_args
(data
)
132 url
= "%s&%s" % (url
, query_args
)
134 url
= "%s?%s" % (url
, query_args
)
136 logger
.debug("Sending request (%s): %s" % (method
, url
))
138 logger
.debug(" data: %s" % data
)
140 req
= urllib2
.Request(url
, data
=data
)
142 if username
and password
:
143 basic_auth_header
= self
._make
_basic
_auth
_header
(username
, password
)
144 req
.add_header("Authorization", "Basic %s" % basic_auth_header
)
146 # Set the user agent.
147 req
.add_header("User-Agent", self
.USER_AGENT
)
149 # All requests should not be cached anywhere.
150 req
.add_header("Pragma", "no-cache")
152 # Set the upstream proxy if needed.
154 logger
.debug("Using proxy: %s" % self
.proxy
)
156 # Configure the proxy for this request.
157 req
.set_proxy(self
.proxy
, "http")
159 assert req
.get_method() == method
161 logger
.debug(_("Request header:"))
162 for k
, v
in req
.headers
.items():
163 logger
.debug(" %s: %s" % (k
, v
))
166 resp
= urllib2
.urlopen(req
, timeout
=timeout
)
168 # Log response header.
169 logger
.debug(_("Response header (Status Code %s):") % resp
.code
)
170 for k
, v
in resp
.info().items():
171 logger
.debug(" %s: %s" % (k
, v
))
173 # Return the entire response object.
176 except urllib2
.HTTPError
, e
:
177 # Log response header.
178 logger
.debug(_("Response header (Status Code %s):") % e
.code
)
179 for k
, v
in e
.hdrs
.items():
180 logger
.debug(" %s: %s" % (k
, v
))
184 raise DDNSRequestError(e
.reason
)
186 # 401 - Authorization Required
188 elif e
.code
in (401, 403):
189 raise DDNSAuthenticationError(e
.reason
)
192 # Either the provider has changed the API, or
193 # there is an error on the server
195 raise DDNSNotFound(e
.reason
)
197 # 429 - Too Many Requests
199 raise DDNSTooManyRequests(e
.reason
)
201 # 500 - Internal Server Error
203 raise DDNSInternalServerError(e
.reason
)
205 # 503 - Service Unavailable
207 raise DDNSServiceUnavailableError(e
.reason
)
209 # Raise all other unhandled exceptions.
212 except urllib2
.URLError
, e
:
215 if isinstance(e
.reason
, ssl
.SSLError
):
218 if e
.reason
== "CERTIFICATE_VERIFY_FAILED":
219 raise DDNSCertificateError
221 # Raise all other SSL errors
222 raise DDNSSSLError(e
.reason
)
224 # Name or service not known
225 if e
.reason
.errno
== -2:
226 raise DDNSResolveError
228 # Network Unreachable (e.g. no IPv6 access)
229 if e
.reason
.errno
== 101:
230 raise DDNSNetworkUnreachableError
233 elif e
.reason
.errno
== 111:
234 raise DDNSConnectionRefusedError
237 elif e
.reason
.errno
== 113:
238 raise DDNSNoRouteToHostError(req
.host
)
240 # Raise all other unhandled exceptions.
243 except socket
.timeout
, e
:
244 logger
.debug(_("Connection timeout"))
246 raise DDNSConnectionTimeoutError
248 def _format_query_args(self
, data
):
251 for k
, v
in data
.items():
252 arg
= "%s=%s" % (k
, urllib
.quote(v
))
255 return "&".join(args
)
257 def _make_basic_auth_header(self
, username
, password
):
258 authstring
= "%s:%s" % (username
, password
)
260 # Encode authorization data in base64.
261 authstring
= base64
.encodestring(authstring
)
263 # Remove any newline characters.
264 authstring
= authstring
.replace("\n", "")
268 def get_address(self
, proto
):
270 Returns the current IP address for
271 the given IP protocol.
274 return self
.__addresses
[proto
]
276 # IP is currently unknown and needs to be retrieved.
278 self
.__addresses
[proto
] = address
= \
279 self
._get
_address
(proto
)
283 def _get_address(self
, proto
):
284 assert proto
in ("ipv6", "ipv4")
286 # IPFire 2 does not support IPv6.
287 if self
.distro
== "ipfire-2" and proto
== "ipv6":
290 # Check if the external IP address should be guessed from
292 guess_ip
= self
.core
.settings
.get("guess_external_ip", "true")
293 guess_ip
= guess_ip
in ("true", "yes", "1")
295 # Get the local IP address.
296 local_ip_address
= None
300 local_ip_address
= self
.get_local_ip_address(proto
)
301 except NotImplementedError:
302 logger
.warning(_("Falling back to check the IP address with help of a public server"))
304 # If no local IP address could be determined, we will fall back to the guess
305 # it with help of an external server...
306 if not local_ip_address
:
307 local_ip_address
= self
.guess_external_ip_address(proto
)
309 return local_ip_address
311 def _is_usable_ip_address(self
, proto
, address
):
313 Returns True is the local IP address is usable
314 for dynamic DNS (i.e. is not a RFC1918 address or similar).
317 # This is not the most perfect solution to match
318 # these addresses, but instead of pulling in an entire
319 # library to handle the IP addresses better, we match
320 # with regular expressions instead.
322 # RFC1918 address space
323 r
"^10\.\d+\.\d+\.\d+$",
324 r
"^192\.168\.\d+\.\d+$",
325 r
"^172\.(1[6-9]|2[0-9]|31)\.\d+\.\d+$",
327 # Dual Stack Lite address space
328 r
"^100\.(6[4-9]|[7-9][0-9]|1[01][0-9]|12[0-7])\.\d+\.\d+$",
331 for match
in matches
:
332 m
= re
.match(match
, address
)
336 # Found a match. IP address is not usable.
339 # In all other cases, return OK.
342 def resolve(self
, hostname
, proto
=None):
347 elif proto
== "ipv6":
348 family
= socket
.AF_INET6
349 elif proto
== "ipv4":
350 family
= socket
.AF_INET
352 raise ValueError("Protocol not supported: %s" % proto
)
354 # Resolve the host address.
356 response
= socket
.getaddrinfo(hostname
, None, family
)
357 except socket
.gaierror
, e
:
358 # Name or service not known
362 # Temporary failure in name resolution
364 raise DDNSResolveError(hostname
)
366 # No record for requested family available (e.g. no AAAA)
373 for family
, socktype
, proto
, canonname
, sockaddr
in response
:
375 if family
== socket
.AF_INET6
:
376 address
, port
, flow_info
, scope_id
= sockaddr
378 # Only use the global scope.
379 if not scope_id
== 0:
383 elif family
== socket
.AF_INET
:
384 address
, port
= sockaddr
386 # Ignore everything else...
390 # Add to repsonse list if not already in there.
391 if not address
in addresses
:
392 addresses
.append(address
)
396 def _get_distro_identifier(self
):
398 Returns a unique identifier for the distribution
401 os_release
= self
.__parse
_os
_release
()
405 system_release
= self
.__parse
_system
_release
()
407 return system_release
409 # If nothing else could be found, we return
413 def __parse_os_release(self
):
415 Tries to parse /etc/os-release and
416 returns a unique distribution identifier
420 f
= open("/etc/os-release", "r")
430 for line
in f
.readlines():
431 m
= re
.match(r
"^([A-Z\_]+)=(.*)$", line
)
435 os_release
[m
.group(1)] = m
.group(2)
438 return "%(ID)s-%(VERSION_ID)s" % os_release
442 def __parse_system_release(self
):
444 Tries to parse /etc/system-release and
445 returns a unique distribution identifier
449 f
= open("/etc/system-release", "r")
461 # Check for IPFire systems
462 m
= re
.match(r
"^IPFire (\d).(\d+)", line
)
464 return "ipfire-%s" % m
.group(1)