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.
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
)
56 proxy
= self
.core
.settings
.get("proxy")
58 # Strip http:// at the beginning.
59 if proxy
and proxy
.startswith("http://"):
64 def _guess_external_ip_address(self
, url
, timeout
=10):
66 Sends a request to an external web server
67 to determine the current default IP address.
70 response
= self
.send_request(url
, timeout
=timeout
)
72 # If the server could not be reached, we will return nothing.
73 except DDNSNetworkError
:
76 if not response
.code
== 200:
79 match
= re
.search(r
"^Your IP address is: (.*)$", response
.read())
85 def guess_external_ipv6_address(self
):
87 Sends a request to the internet to determine
88 the public IPv6 address.
90 return self
._guess
_external
_ip
_address
("http://checkip6.dns.lightningwirelabs.com")
92 def guess_external_ipv4_address(self
):
94 Sends a request to the internet to determine
95 the public IPv4 address.
97 return self
._guess
_external
_ip
_address
("http://checkip4.dns.lightningwirelabs.com")
99 def send_request(self
, url
, method
="GET", data
=None, username
=None, password
=None, timeout
=30):
100 assert method
in ("GET", "POST")
102 # Add all arguments in the data dict to the URL and escape them properly.
103 if method
== "GET" and data
:
104 query_args
= self
._format
_query
_args
(data
)
108 url
= "%s&%s" % (url
, query_args
)
110 url
= "%s?%s" % (url
, query_args
)
112 logger
.debug("Sending request (%s): %s" % (method
, url
))
114 logger
.debug(" data: %s" % data
)
116 req
= urllib2
.Request(url
, data
=data
)
118 if username
and password
:
119 basic_auth_header
= self
._make
_basic
_auth
_header
(username
, password
)
120 req
.add_header("Authorization", "Basic %s" % basic_auth_header
)
122 # Set the user agent.
123 req
.add_header("User-Agent", self
.USER_AGENT
)
125 # All requests should not be cached anywhere.
126 req
.add_header("Pragma", "no-cache")
128 # Set the upstream proxy if needed.
130 logger
.debug("Using proxy: %s" % self
.proxy
)
132 # Configure the proxy for this request.
133 req
.set_proxy(self
.proxy
, "http")
135 assert req
.get_method() == method
137 logger
.debug(_("Request header:"))
138 for k
, v
in req
.headers
.items():
139 logger
.debug(" %s: %s" % (k
, v
))
142 resp
= urllib2
.urlopen(req
, timeout
=timeout
)
144 # Log response header.
145 logger
.debug(_("Response header:"))
146 for k
, v
in resp
.info().items():
147 logger
.debug(" %s: %s" % (k
, v
))
149 # Return the entire response object.
152 except urllib2
.HTTPError
, e
:
153 # 503 - Service Unavailable
155 raise DDNSServiceUnavailableError
157 # Raise all other unhandled exceptions.
160 except urllib2
.URLError
, e
:
162 # Network Unreachable (e.g. no IPv6 access)
163 if e
.reason
.errno
== 101:
164 raise DDNSNetworkUnreachableError
165 elif e
.reason
.errno
== 111:
166 raise DDNSConnectionRefusedError
168 # Raise all other unhandled exceptions.
171 except socket
.timeout
, e
:
172 logger
.debug(_("Connection timeout"))
174 raise DDNSConnectionTimeoutError
176 def _format_query_args(self
, data
):
179 for k
, v
in data
.items():
180 arg
= "%s=%s" % (k
, urllib
.quote(v
))
183 return "&".join(args
)
185 def _make_basic_auth_header(self
, username
, password
):
186 authstring
= "%s:%s" % (username
, password
)
188 # Encode authorization data in base64.
189 authstring
= base64
.encodestring(authstring
)
191 # Remove any newline characters.
192 authstring
= authstring
.replace("\n", "")
196 def get_address(self
, proto
):
197 assert proto
in ("ipv6", "ipv4")
199 # Check if the external IP address should be guessed from
201 guess_ip
= self
.core
.settings
.get("guess_external_ip", "true")
203 # If the external IP address should be used, we just do
205 if guess_ip
in ("true", "yes", "1"):
207 return self
.guess_external_ipv6_address()
209 elif proto
== "ipv4":
210 return self
.guess_external_ipv4_address()
215 def resolve(self
, hostname
, proto
=None):
220 elif proto
== "ipv6":
221 family
= socket
.AF_INET6
222 elif proto
== "ipv4":
223 family
= socket
.AF_INET
225 raise ValueError("Protocol not supported: %s" % proto
)
227 # Resolve the host address.
229 response
= socket
.getaddrinfo(hostname
, None, family
)
230 except socket
.gaierror
, e
:
231 # Name or service not known
235 # No record for requested family available (e.g. no AAAA)
242 for family
, socktype
, proto
, canonname
, sockaddr
in response
:
244 if family
== socket
.AF_INET6
:
245 address
, port
, flow_info
, scope_id
= sockaddr
247 # Only use the global scope.
248 if not scope_id
== 0:
252 elif family
== socket
.AF_INET
:
253 address
, port
= sockaddr
255 # Ignore everything else...
259 # Add to repsonse list if not already in there.
260 if not address
in addresses
:
261 addresses
.append(address
)
265 def _get_distro_identifier(self
):
267 Returns a unique identifier for the distribution
270 os_release
= self
.__parse
_os
_release
()
274 system_release
= self
.__parse
_system
_release
()
276 return system_release
278 # If nothing else could be found, we return
282 def __parse_os_release(self
):
284 Tries to parse /etc/os-release and
285 returns a unique distribution identifier
289 f
= open("/etc/os-release", "r")
299 for line
in f
.readlines():
300 m
= re
.match(r
"^([A-Z\_]+)=(.*)$", line
)
304 os_release
[m
.group(1)] = m
.group(2)
307 return "%(ID)s-%(VERSION_ID)s" % os_release
311 def __parse_system_release(self
):
313 Tries to parse /etc/system-release and
314 returns a unique distribution identifier
318 f
= open("/etc/system-release", "r")
330 # Check for IPFire systems
331 m
= re
.match(r
"^IPFire (\d).(\d+)", line
)
333 return "ipfire-%s" % m
.group(1)