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
= "http://checkip6.dns.lightningwirelabs.com"
116 elif family
== "ipv4":
117 url
= "http://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 # 500 - Internal Server Error
199 raise DDNSInternalServerError(e
.reason
)
201 # 503 - Service Unavailable
203 raise DDNSServiceUnavailableError(e
.reason
)
205 # Raise all other unhandled exceptions.
208 except urllib2
.URLError
, e
:
211 if isinstance(e
.reason
, ssl
.SSLError
):
214 if e
.reason
== "CERTIFICATE_VERIFY_FAILED":
215 raise DDNSCertificateError
217 # Raise all other SSL errors
218 raise DDNSSSLError(e
.reason
)
220 # Name or service not known
221 if e
.reason
.errno
== -2:
222 raise DDNSResolveError
224 # Network Unreachable (e.g. no IPv6 access)
225 if e
.reason
.errno
== 101:
226 raise DDNSNetworkUnreachableError
229 elif e
.reason
.errno
== 111:
230 raise DDNSConnectionRefusedError
233 elif e
.reason
.errno
== 113:
234 raise DDNSNoRouteToHostError(req
.host
)
236 # Raise all other unhandled exceptions.
239 except socket
.timeout
, e
:
240 logger
.debug(_("Connection timeout"))
242 raise DDNSConnectionTimeoutError
244 def _format_query_args(self
, data
):
247 for k
, v
in data
.items():
248 arg
= "%s=%s" % (k
, urllib
.quote(v
))
251 return "&".join(args
)
253 def _make_basic_auth_header(self
, username
, password
):
254 authstring
= "%s:%s" % (username
, password
)
256 # Encode authorization data in base64.
257 authstring
= base64
.encodestring(authstring
)
259 # Remove any newline characters.
260 authstring
= authstring
.replace("\n", "")
264 def get_address(self
, proto
):
266 Returns the current IP address for
267 the given IP protocol.
270 return self
.__addresses
[proto
]
272 # IP is currently unknown and needs to be retrieved.
274 self
.__addresses
[proto
] = address
= \
275 self
._get
_address
(proto
)
279 def _get_address(self
, proto
):
280 assert proto
in ("ipv6", "ipv4")
282 # IPFire 2 does not support IPv6.
283 if self
.distro
== "ipfire-2" and proto
== "ipv6":
286 # Check if the external IP address should be guessed from
288 guess_ip
= self
.core
.settings
.get("guess_external_ip", "true")
289 guess_ip
= guess_ip
in ("true", "yes", "1")
291 # Get the local IP address.
292 local_ip_address
= None
296 local_ip_address
= self
.get_local_ip_address(proto
)
297 except NotImplementedError:
298 logger
.warning(_("Falling back to check the IP address with help of a public server"))
300 # If no local IP address could be determined, we will fall back to the guess
301 # it with help of an external server...
302 if not local_ip_address
:
303 local_ip_address
= self
.guess_external_ip_address(proto
)
305 return local_ip_address
307 def _is_usable_ip_address(self
, proto
, address
):
309 Returns True is the local IP address is usable
310 for dynamic DNS (i.e. is not a RFC1918 address or similar).
313 # This is not the most perfect solution to match
314 # these addresses, but instead of pulling in an entire
315 # library to handle the IP addresses better, we match
316 # with regular expressions instead.
318 # RFC1918 address space
319 r
"^10\.\d+\.\d+\.\d+$",
320 r
"^192\.168\.\d+\.\d+$",
321 r
"^172\.(1[6-9]|2[0-9]|31)\.\d+\.\d+$",
323 # Dual Stack Lite address space
324 r
"^100\.(6[4-9]|[7-9][0-9]|1[01][0-9]|12[0-7])\.\d+\.\d+$",
327 for match
in matches
:
328 m
= re
.match(match
, address
)
332 # Found a match. IP address is not usable.
335 # In all other cases, return OK.
338 def resolve(self
, hostname
, proto
=None):
343 elif proto
== "ipv6":
344 family
= socket
.AF_INET6
345 elif proto
== "ipv4":
346 family
= socket
.AF_INET
348 raise ValueError("Protocol not supported: %s" % proto
)
350 # Resolve the host address.
352 response
= socket
.getaddrinfo(hostname
, None, family
)
353 except socket
.gaierror
, e
:
354 # Name or service not known
358 # Temporary failure in name resolution
360 raise DDNSResolveError(hostname
)
362 # No record for requested family available (e.g. no AAAA)
369 for family
, socktype
, proto
, canonname
, sockaddr
in response
:
371 if family
== socket
.AF_INET6
:
372 address
, port
, flow_info
, scope_id
= sockaddr
374 # Only use the global scope.
375 if not scope_id
== 0:
379 elif family
== socket
.AF_INET
:
380 address
, port
= sockaddr
382 # Ignore everything else...
386 # Add to repsonse list if not already in there.
387 if not address
in addresses
:
388 addresses
.append(address
)
392 def _get_distro_identifier(self
):
394 Returns a unique identifier for the distribution
397 os_release
= self
.__parse
_os
_release
()
401 system_release
= self
.__parse
_system
_release
()
403 return system_release
405 # If nothing else could be found, we return
409 def __parse_os_release(self
):
411 Tries to parse /etc/os-release and
412 returns a unique distribution identifier
416 f
= open("/etc/os-release", "r")
426 for line
in f
.readlines():
427 m
= re
.match(r
"^([A-Z\_]+)=(.*)$", line
)
431 os_release
[m
.group(1)] = m
.group(2)
434 return "%(ID)s-%(VERSION_ID)s" % os_release
438 def __parse_system_release(self
):
440 Tries to parse /etc/system-release and
441 returns a unique distribution identifier
445 f
= open("/etc/system-release", "r")
457 # Check for IPFire systems
458 m
= re
.match(r
"^IPFire (\d).(\d+)", line
)
460 return "ipfire-%s" % m
.group(1)