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 ###############################################################################
28 from __version__
import CLIENT_VERSION
32 # Initialize the logger.
34 logger
= logging
.getLogger("ddns.system")
37 class DDNSSystem(object):
39 The DDNSSystem class adds a layer of abstraction
40 between the ddns software and the system.
43 # The default useragent.
44 USER_AGENT
= "IPFireDDNSUpdater/%s" % CLIENT_VERSION
46 def __init__(self
, core
):
47 # Connection to the core of the program.
53 # Find out on which distribution we are running.
54 self
.distro
= self
._get
_distro
_identifier
()
55 logger
.debug(_("Running on distribution: %s") % self
.distro
)
59 proxy
= self
.core
.settings
.get("proxy")
61 # Strip http:// at the beginning.
62 if proxy
and proxy
.startswith("http://"):
67 def get_local_ip_address(self
, proto
):
68 # Legacy code for IPFire 2.
69 if self
.distro
== "ipfire-2" and proto
== "ipv4":
71 with
open("/var/ipfire/red/local-ipaddress") as f
:
82 raise NotImplementedError
84 def _guess_external_ip_address(self
, url
, timeout
=10):
86 Sends a request to an external web server
87 to determine the current default IP address.
90 response
= self
.send_request(url
, timeout
=timeout
)
92 # If the server could not be reached, we will return nothing.
93 except DDNSNetworkError
:
96 if not response
.code
== 200:
99 match
= re
.search(r
"^Your IP address is: (.*)$", response
.read())
103 return match
.group(1)
105 def guess_external_ip_address(self
, family
, **kwargs
):
107 url
= "http://checkip6.dns.lightningwirelabs.com"
108 elif family
== "ipv4":
109 url
= "http://checkip4.dns.lightningwirelabs.com"
111 raise ValueError("unknown address family")
113 return self
._guess
_external
_ip
_address
(url
, **kwargs
)
115 def send_request(self
, url
, method
="GET", data
=None, username
=None, password
=None, timeout
=30):
116 assert method
in ("GET", "POST")
118 # Add all arguments in the data dict to the URL and escape them properly.
119 if method
== "GET" and data
:
120 query_args
= self
._format
_query
_args
(data
)
124 url
= "%s&%s" % (url
, query_args
)
126 url
= "%s?%s" % (url
, query_args
)
128 logger
.debug("Sending request (%s): %s" % (method
, url
))
130 logger
.debug(" data: %s" % data
)
132 req
= urllib2
.Request(url
, data
=data
)
134 if username
and password
:
135 basic_auth_header
= self
._make
_basic
_auth
_header
(username
, password
)
136 req
.add_header("Authorization", "Basic %s" % basic_auth_header
)
138 # Set the user agent.
139 req
.add_header("User-Agent", self
.USER_AGENT
)
141 # All requests should not be cached anywhere.
142 req
.add_header("Pragma", "no-cache")
144 # Set the upstream proxy if needed.
146 logger
.debug("Using proxy: %s" % self
.proxy
)
148 # Configure the proxy for this request.
149 req
.set_proxy(self
.proxy
, "http")
151 assert req
.get_method() == method
153 logger
.debug(_("Request header:"))
154 for k
, v
in req
.headers
.items():
155 logger
.debug(" %s: %s" % (k
, v
))
158 resp
= urllib2
.urlopen(req
, timeout
=timeout
)
160 # Log response header.
161 logger
.debug(_("Response header (Status Code %s):") % resp
.code
)
162 for k
, v
in resp
.info().items():
163 logger
.debug(" %s: %s" % (k
, v
))
165 # Return the entire response object.
168 except urllib2
.HTTPError
, e
:
171 raise DDNSRequestError(e
.reason
)
173 # 401 - Authorization Required
175 elif e
.code
in (401, 403):
176 raise DDNSAuthenticationError(e
.reason
)
178 # 500 - Internal Server Error
180 raise DDNSInternalServerError(e
.reason
)
182 # 503 - Service Unavailable
184 raise DDNSServiceUnavailableError(e
.reason
)
186 # Raise all other unhandled exceptions.
189 except urllib2
.URLError
, e
:
191 # Network Unreachable (e.g. no IPv6 access)
192 if e
.reason
.errno
== 101:
193 raise DDNSNetworkUnreachableError
194 elif e
.reason
.errno
== 111:
195 raise DDNSConnectionRefusedError
197 # Raise all other unhandled exceptions.
200 except socket
.timeout
, e
:
201 logger
.debug(_("Connection timeout"))
203 raise DDNSConnectionTimeoutError
205 def _format_query_args(self
, data
):
208 for k
, v
in data
.items():
209 arg
= "%s=%s" % (k
, urllib
.quote(v
))
212 return "&".join(args
)
214 def _make_basic_auth_header(self
, username
, password
):
215 authstring
= "%s:%s" % (username
, password
)
217 # Encode authorization data in base64.
218 authstring
= base64
.encodestring(authstring
)
220 # Remove any newline characters.
221 authstring
= authstring
.replace("\n", "")
225 def get_address(self
, proto
):
227 Returns the current IP address for
228 the given IP protocol.
231 return self
.__addresses
[proto
]
233 # IP is currently unknown and needs to be retrieved.
235 self
.__addresses
[proto
] = address
= \
236 self
._get
_address
(proto
)
240 def _get_address(self
, proto
):
241 assert proto
in ("ipv6", "ipv4")
243 # IPFire 2 does not support IPv6.
244 if self
.distro
== "ipfire-2" and proto
== "ipv6":
247 # Check if the external IP address should be guessed from
249 guess_ip
= self
.core
.settings
.get("guess_external_ip", "true")
250 guess_ip
= guess_ip
in ("true", "yes", "1")
252 # If the external IP address should be used, we just do that.
254 return self
.guess_external_ip_address(proto
)
256 # Get the local IP address.
257 local_ip_address
= self
.get_local_ip_address(proto
)
259 # If the local IP address is not usable, we must guess
260 # the correct IP address...
261 if not self
._is
_usable
_ip
_address
(proto
, local_ip_address
):
262 local_ip_address
= self
.guess_external_ip_address(proto
)
264 return local_ip_address
266 def _is_usable_ip_address(self
, proto
, address
):
268 Returns True is the local IP address is usable
269 for dynamic DNS (i.e. is not a RFC1918 address or similar).
272 # This is not the most perfect solution to match
273 # these addresses, but instead of pulling in an entire
274 # library to handle the IP addresses better, we match
275 # with regular expressions instead.
277 # RFC1918 address space
278 r
"^10\.\d+\.\d+\.\d+$",
279 r
"^192\.168\.\d+\.\d+$",
280 r
"^172\.(1[6-9]|2[0-9]|31)\.\d+\.\d+$",
282 # Dual Stack Lite address space
283 r
"^100\.(6[4-9]|[7-9][0-9]|1[01][0-9]|12[0-7])\.\d+\.\d+",
286 for match
in matches
:
287 m
= re
.match(match
, address
)
291 # Found a match. IP address is not usable.
294 # In all other cases, return OK.
297 def resolve(self
, hostname
, proto
=None):
302 elif proto
== "ipv6":
303 family
= socket
.AF_INET6
304 elif proto
== "ipv4":
305 family
= socket
.AF_INET
307 raise ValueError("Protocol not supported: %s" % proto
)
309 # Resolve the host address.
311 response
= socket
.getaddrinfo(hostname
, None, family
)
312 except socket
.gaierror
, e
:
313 # Name or service not known
317 # No record for requested family available (e.g. no AAAA)
324 for family
, socktype
, proto
, canonname
, sockaddr
in response
:
326 if family
== socket
.AF_INET6
:
327 address
, port
, flow_info
, scope_id
= sockaddr
329 # Only use the global scope.
330 if not scope_id
== 0:
334 elif family
== socket
.AF_INET
:
335 address
, port
= sockaddr
337 # Ignore everything else...
341 # Add to repsonse list if not already in there.
342 if not address
in addresses
:
343 addresses
.append(address
)
347 def _get_distro_identifier(self
):
349 Returns a unique identifier for the distribution
352 os_release
= self
.__parse
_os
_release
()
356 system_release
= self
.__parse
_system
_release
()
358 return system_release
360 # If nothing else could be found, we return
364 def __parse_os_release(self
):
366 Tries to parse /etc/os-release and
367 returns a unique distribution identifier
371 f
= open("/etc/os-release", "r")
381 for line
in f
.readlines():
382 m
= re
.match(r
"^([A-Z\_]+)=(.*)$", line
)
386 os_release
[m
.group(1)] = m
.group(2)
389 return "%(ID)s-%(VERSION_ID)s" % os_release
393 def __parse_system_release(self
):
395 Tries to parse /etc/system-release and
396 returns a unique distribution identifier
400 f
= open("/etc/system-release", "r")
412 # Check for IPFire systems
413 m
= re
.match(r
"^IPFire (\d).(\d+)", line
)
415 return "ipfire-%s" % m
.group(1)