]>
git.ipfire.org Git - oddments/ddns.git/blob - src/ddns/system.py
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
31 # Initialize the logger.
33 logger
= logging
.getLogger("ddns.system")
36 class DDNSSystem(object):
38 The DDNSSystem class adds a layer of abstraction
39 between the ddns software and the system.
42 # The default useragent.
43 USER_AGENT
= "IPFireDDNSUpdater/%s" % CLIENT_VERSION
45 def __init__(self
, core
):
46 # Connection to the core of the program.
51 proxy
= self
.core
.settings
.get("proxy")
53 # Strip http:// at the beginning.
54 if proxy
and proxy
.startswith("http://"):
59 def guess_external_ipv6_address(self
):
61 Sends a request to an external web server
62 to determine the current default IP address.
64 response
= self
.send_request("http://checkip6.dns.lightningwirelabs.com")
66 if not response
.code
== 200:
69 match
= re
.search(r
"^Your IP address is: (.*)$", response
.read())
75 def guess_external_ipv4_address(self
):
77 Sends a request to the internet to determine
78 the public IP address.
80 XXX does not work for IPv6.
82 response
= self
.send_request("http://checkip4.dns.lightningwirelabs.com")
84 if response
.code
== 200:
85 match
= re
.search(r
"Your IP address is: (\d+.\d+.\d+.\d+)", response
.read())
91 def send_request(self
, url
, method
="GET", data
=None, username
=None, password
=None, timeout
=30):
92 assert method
in ("GET", "POST")
94 # Add all arguments in the data dict to the URL and escape them properly.
95 if method
== "GET" and data
:
96 query_args
= self
._format
_query
_args
(data
)
99 url
= "%s?%s" % (url
, query_args
)
101 logger
.debug("Sending request (%s): %s" % (method
, url
))
103 logger
.debug(" data: %s" % data
)
105 req
= urllib2
.Request(url
, data
=data
)
107 if username
and password
:
108 basic_auth_header
= self
._make
_basic
_auth
_header
(username
, password
)
109 print repr(basic_auth_header
)
110 req
.add_header("Authorization", "Basic %s" % basic_auth_header
)
112 # Set the user agent.
113 req
.add_header("User-Agent", self
.USER_AGENT
)
115 # All requests should not be cached anywhere.
116 req
.add_header("Pragma", "no-cache")
118 # Set the upstream proxy if needed.
120 logger
.debug("Using proxy: %s" % self
.proxy
)
122 # Configure the proxy for this request.
123 req
.set_proxy(self
.proxy
, "http")
125 assert req
.get_method() == method
127 logger
.debug(_("Request header:"))
128 for k
, v
in req
.headers
.items():
129 logger
.debug(" %s: %s" % (k
, v
))
132 resp
= urllib2
.urlopen(req
)
134 # Log response header.
135 logger
.debug(_("Response header:"))
136 for k
, v
in resp
.info().items():
137 logger
.debug(" %s: %s" % (k
, v
))
139 # Return the entire response object.
142 except urllib2
.URLError
, e
:
145 def _format_query_args(self
, data
):
148 for k
, v
in data
.items():
149 arg
= "%s=%s" % (k
, urllib
.quote(v
))
152 return "&".join(args
)
154 def _make_basic_auth_header(self
, username
, password
):
155 authstring
= "%s:%s" % (username
, password
)
157 # Encode authorization data in base64.
158 authstring
= base64
.encodestring(authstring
)
160 # Remove any newline characters.
161 authstring
= authstring
.replace("\n", "")
165 def get_address(self
, proto
):
166 assert proto
in ("ipv6", "ipv4")
168 # Check if the external IP address should be guessed from
170 guess_ip
= self
.core
.settings
.get("guess_external_ip", "true")
172 # If the external IP address should be used, we just do
174 if guess_ip
in ("true", "yes", "1"):
176 return self
.guess_external_ipv6_address()
178 elif proto
== "ipv4":
179 return self
.guess_external_ipv4_address()
184 def resolve(self
, hostname
, proto
=None):
189 elif proto
== "ipv6":
190 family
= socket
.AF_INET6
191 elif proto
== "ipv4":
192 family
= socket
.AF_INET
194 raise ValueError("Protocol not supported: %s" % proto
)
196 # Resolve the host address.
198 response
= socket
.getaddrinfo(hostname
, None, family
)
199 except socket
.gaierror
, e
:
200 # Name or service not known
207 for family
, socktype
, proto
, canonname
, sockaddr
in response
:
209 if family
== socket
.AF_INET6
:
210 address
, port
, flow_info
, scope_id
= sockaddr
212 # Only use the global scope.
213 if not scope_id
== 0:
217 elif family
== socket
.AF_INET
:
218 address
, port
= sockaddr
220 # Ignore everything else...
224 # Add to repsonse list if not already in there.
225 if not address
in addresses
:
226 addresses
.append(address
)