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_ipv6_address(self
):
70 def get_local_ipv4_address(self
):
71 if self
.distro
== "ipfire-2":
73 with
open("/var/ipfire/red/local-ipaddress") as f
:
85 def _guess_external_ip_address(self
, url
, timeout
=10):
87 Sends a request to an external web server
88 to determine the current default IP address.
91 response
= self
.send_request(url
, timeout
=timeout
)
93 # If the server could not be reached, we will return nothing.
94 except DDNSNetworkError
:
97 if not response
.code
== 200:
100 match
= re
.search(r
"^Your IP address is: (.*)$", response
.read())
104 return match
.group(1)
106 def guess_external_ip_address(self
, family
, **kwargs
):
108 url
= "http://checkip6.dns.lightningwirelabs.com"
109 elif family
== "ipv4":
110 url
= "http://checkip4.dns.lightningwirelabs.com"
112 raise ValueError("unknown address family")
114 return self
._guess
_external
_ip
_address
(url
, **kwargs
)
116 def send_request(self
, url
, method
="GET", data
=None, username
=None, password
=None, timeout
=30):
117 assert method
in ("GET", "POST")
119 # Add all arguments in the data dict to the URL and escape them properly.
120 if method
== "GET" and data
:
121 query_args
= self
._format
_query
_args
(data
)
125 url
= "%s&%s" % (url
, query_args
)
127 url
= "%s?%s" % (url
, query_args
)
129 logger
.debug("Sending request (%s): %s" % (method
, url
))
131 logger
.debug(" data: %s" % data
)
133 req
= urllib2
.Request(url
, data
=data
)
135 if username
and password
:
136 basic_auth_header
= self
._make
_basic
_auth
_header
(username
, password
)
137 req
.add_header("Authorization", "Basic %s" % basic_auth_header
)
139 # Set the user agent.
140 req
.add_header("User-Agent", self
.USER_AGENT
)
142 # All requests should not be cached anywhere.
143 req
.add_header("Pragma", "no-cache")
145 # Set the upstream proxy if needed.
147 logger
.debug("Using proxy: %s" % self
.proxy
)
149 # Configure the proxy for this request.
150 req
.set_proxy(self
.proxy
, "http")
152 assert req
.get_method() == method
154 logger
.debug(_("Request header:"))
155 for k
, v
in req
.headers
.items():
156 logger
.debug(" %s: %s" % (k
, v
))
159 resp
= urllib2
.urlopen(req
, timeout
=timeout
)
161 # Log response header.
162 logger
.debug(_("Response header (Status Code %s):") % resp
.code
)
163 for k
, v
in resp
.info().items():
164 logger
.debug(" %s: %s" % (k
, v
))
166 # Return the entire response object.
169 except urllib2
.HTTPError
, e
:
172 raise DDNSRequestError(e
.reason
)
174 # 401 - Authorization Required
176 elif e
.code
in (401, 403):
177 raise DDNSAuthenticationError(e
.reason
)
179 # 500 - Internal Server Error
181 raise DDNSInternalServerError(e
.reason
)
183 # 503 - Service Unavailable
185 raise DDNSServiceUnavailableError(e
.reason
)
187 # Raise all other unhandled exceptions.
190 except urllib2
.URLError
, e
:
192 # Network Unreachable (e.g. no IPv6 access)
193 if e
.reason
.errno
== 101:
194 raise DDNSNetworkUnreachableError
195 elif e
.reason
.errno
== 111:
196 raise DDNSConnectionRefusedError
198 # Raise all other unhandled exceptions.
201 except socket
.timeout
, e
:
202 logger
.debug(_("Connection timeout"))
204 raise DDNSConnectionTimeoutError
206 def _format_query_args(self
, data
):
209 for k
, v
in data
.items():
210 arg
= "%s=%s" % (k
, urllib
.quote(v
))
213 return "&".join(args
)
215 def _make_basic_auth_header(self
, username
, password
):
216 authstring
= "%s:%s" % (username
, password
)
218 # Encode authorization data in base64.
219 authstring
= base64
.encodestring(authstring
)
221 # Remove any newline characters.
222 authstring
= authstring
.replace("\n", "")
226 def get_address(self
, proto
):
228 Returns the current IP address for
229 the given IP protocol.
232 return self
.__addresses
[proto
]
234 # IP is currently unknown and needs to be retrieved.
236 self
.__addresses
[proto
] = address
= \
237 self
._get
_address
(proto
)
241 def _get_address(self
, proto
):
242 assert proto
in ("ipv6", "ipv4")
244 # IPFire 2 does not support IPv6.
245 if self
.distro
== "ipfire-2" and proto
== "ipv6":
248 # Check if the external IP address should be guessed from
250 guess_ip
= self
.core
.settings
.get("guess_external_ip", "true")
252 # If the external IP address should be used, we just do
254 if guess_ip
in ("true", "yes", "1"):
255 return self
.guess_external_ip_address(proto
)
257 # Get the local IP addresses.
260 return self
.get_local_ipv6_address()
261 elif proto
== "ipv4":
262 return self
.get_local_ipv4_address()
264 def resolve(self
, hostname
, proto
=None):
269 elif proto
== "ipv6":
270 family
= socket
.AF_INET6
271 elif proto
== "ipv4":
272 family
= socket
.AF_INET
274 raise ValueError("Protocol not supported: %s" % proto
)
276 # Resolve the host address.
278 response
= socket
.getaddrinfo(hostname
, None, family
)
279 except socket
.gaierror
, e
:
280 # Name or service not known
284 # No record for requested family available (e.g. no AAAA)
291 for family
, socktype
, proto
, canonname
, sockaddr
in response
:
293 if family
== socket
.AF_INET6
:
294 address
, port
, flow_info
, scope_id
= sockaddr
296 # Only use the global scope.
297 if not scope_id
== 0:
301 elif family
== socket
.AF_INET
:
302 address
, port
= sockaddr
304 # Ignore everything else...
308 # Add to repsonse list if not already in there.
309 if not address
in addresses
:
310 addresses
.append(address
)
314 def _get_distro_identifier(self
):
316 Returns a unique identifier for the distribution
319 os_release
= self
.__parse
_os
_release
()
323 system_release
= self
.__parse
_system
_release
()
325 return system_release
327 # If nothing else could be found, we return
331 def __parse_os_release(self
):
333 Tries to parse /etc/os-release and
334 returns a unique distribution identifier
338 f
= open("/etc/os-release", "r")
348 for line
in f
.readlines():
349 m
= re
.match(r
"^([A-Z\_]+)=(.*)$", line
)
353 os_release
[m
.group(1)] = m
.group(2)
356 return "%(ID)s-%(VERSION_ID)s" % os_release
360 def __parse_system_release(self
):
362 Tries to parse /etc/system-release and
363 returns a unique distribution identifier
367 f
= open("/etc/system-release", "r")
379 # Check for IPFire systems
380 m
= re
.match(r
"^IPFire (\d).(\d+)", line
)
382 return "ipfire-%s" % m
.group(1)