]> git.ipfire.org Git - ddns.git/blame - src/ddns/system.py
Merge remote-tracking branch 'stevee/dtdns.com'
[ddns.git] / src / ddns / system.py
CommitLineData
f22ab085 1#!/usr/bin/python
3fdcb9d1
MT
2###############################################################################
3# #
4# ddns - A dynamic DNS client for IPFire #
5# Copyright (C) 2012 IPFire development team #
6# #
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. #
11# #
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. #
16# #
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/>. #
19# #
20###############################################################################
f22ab085 21
d4c5c0d5 22import base64
f22ab085 23import re
6cecd141 24import socket
adb124d0 25import urllib
f22ab085
MT
26import urllib2
27
28from __version__ import CLIENT_VERSION
7a909224 29from .errors import *
f22ab085
MT
30from i18n import _
31
32# Initialize the logger.
33import logging
34logger = logging.getLogger("ddns.system")
35logger.propagate = 1
36
37class DDNSSystem(object):
38 """
39 The DDNSSystem class adds a layer of abstraction
40 between the ddns software and the system.
41 """
42
43 # The default useragent.
44 USER_AGENT = "IPFireDDNSUpdater/%s" % CLIENT_VERSION
45
46 def __init__(self, core):
47 # Connection to the core of the program.
48 self.core = core
49
50 @property
51 def proxy(self):
52 proxy = self.core.settings.get("proxy")
53
54 # Strip http:// at the beginning.
fd898828 55 if proxy and proxy.startswith("http://"):
f22ab085
MT
56 proxy = proxy[7:]
57
58 return proxy
59
46c23a71 60 def _guess_external_ip_address(self, url, timeout=10):
30270391
MT
61 """
62 Sends a request to an external web server
63 to determine the current default IP address.
64 """
7a909224 65 try:
46c23a71 66 response = self.send_request(url, timeout=timeout)
7a909224
MT
67
68 # If the server could not be reached, we will return nothing.
69 except DDNSNetworkError:
70 return
30270391
MT
71
72 if not response.code == 200:
73 return
74
75 match = re.search(r"^Your IP address is: (.*)$", response.read())
76 if match is None:
77 return
78
79 return match.group(1)
80
46c23a71 81 def guess_external_ipv6_address(self):
f22ab085
MT
82 """
83 Sends a request to the internet to determine
46c23a71 84 the public IPv6 address.
f22ab085 85 """
46c23a71 86 return self._guess_external_ip_address("http://checkip6.dns.lightningwirelabs.com")
f22ab085 87
46c23a71
MT
88 def guess_external_ipv4_address(self):
89 """
90 Sends a request to the internet to determine
91 the public IPv4 address.
92 """
93 return self._guess_external_ip_address("http://checkip4.dns.lightningwirelabs.com")
f22ab085 94
d4c5c0d5 95 def send_request(self, url, method="GET", data=None, username=None, password=None, timeout=30):
adb124d0
MT
96 assert method in ("GET", "POST")
97
98 # Add all arguments in the data dict to the URL and escape them properly.
99 if method == "GET" and data:
100 query_args = self._format_query_args(data)
101 data = None
102
103 url = "%s?%s" % (url, query_args)
104
105 logger.debug("Sending request (%s): %s" % (method, url))
f22ab085
MT
106 if data:
107 logger.debug(" data: %s" % data)
108
109 req = urllib2.Request(url, data=data)
110
d4c5c0d5
SS
111 if username and password:
112 basic_auth_header = self._make_basic_auth_header(username, password)
113 print repr(basic_auth_header)
114 req.add_header("Authorization", "Basic %s" % basic_auth_header)
115
f22ab085
MT
116 # Set the user agent.
117 req.add_header("User-Agent", self.USER_AGENT)
118
119 # All requests should not be cached anywhere.
120 req.add_header("Pragma", "no-cache")
121
122 # Set the upstream proxy if needed.
123 if self.proxy:
124 logger.debug("Using proxy: %s" % self.proxy)
125
126 # Configure the proxy for this request.
127 req.set_proxy(self.proxy, "http")
128
adb124d0
MT
129 assert req.get_method() == method
130
f22ab085
MT
131 logger.debug(_("Request header:"))
132 for k, v in req.headers.items():
133 logger.debug(" %s: %s" % (k, v))
134
135 try:
7a909224 136 resp = urllib2.urlopen(req, timeout=timeout)
f22ab085
MT
137
138 # Log response header.
139 logger.debug(_("Response header:"))
140 for k, v in resp.info().items():
141 logger.debug(" %s: %s" % (k, v))
142
143 # Return the entire response object.
144 return resp
145
7a909224
MT
146 except urllib2.HTTPError, e:
147 # 503 - Service Unavailable
148 if e.code == 503:
149 raise DDNSServiceUnavailableError
150
151 # Raise all other unhandled exceptions.
152 raise
153
f22ab085 154 except urllib2.URLError, e:
7a909224
MT
155 if e.reason:
156 # Network Unreachable (e.g. no IPv6 access)
157 if e.reason.errno == 101:
158 raise DDNSNetworkUnreachableError
159 elif e.reason.errno == 111:
160 raise DDNSConnectionRefusedError
161
162 # Raise all other unhandled exceptions.
f22ab085
MT
163 raise
164
7a909224
MT
165 except socket.timeout, e:
166 logger.debug(_("Connection timeout"))
167
168 raise DDNSConnectionTimeoutError
169
adb124d0
MT
170 def _format_query_args(self, data):
171 args = []
172
173 for k, v in data.items():
174 arg = "%s=%s" % (k, urllib.quote(v))
175 args.append(arg)
176
177 return "&".join(args)
178
d4c5c0d5
SS
179 def _make_basic_auth_header(self, username, password):
180 authstring = "%s:%s" % (username, password)
181
182 # Encode authorization data in base64.
183 authstring = base64.encodestring(authstring)
184
185 # Remove any newline characters.
186 authstring = authstring.replace("\n", "")
187
188 return authstring
189
f22ab085
MT
190 def get_address(self, proto):
191 assert proto in ("ipv6", "ipv4")
192
30270391
MT
193 # Check if the external IP address should be guessed from
194 # a remote server.
195 guess_ip = self.core.settings.get("guess_external_ip", "true")
196
197 # If the external IP address should be used, we just do
198 # that.
199 if guess_ip in ("true", "yes", "1"):
200 if proto == "ipv6":
201 return self.guess_external_ipv6_address()
f22ab085 202
30270391 203 elif proto == "ipv4":
f22ab085
MT
204 return self.guess_external_ipv4_address()
205
206 # XXX TODO
207 assert False
6cecd141
MT
208
209 def resolve(self, hostname, proto=None):
210 addresses = []
211
212 if proto is None:
213 family = 0
214 elif proto == "ipv6":
215 family = socket.AF_INET6
216 elif proto == "ipv4":
217 family = socket.AF_INET
218 else:
219 raise ValueError("Protocol not supported: %s" % proto)
220
221 # Resolve the host address.
73f2bc0b
MT
222 try:
223 response = socket.getaddrinfo(hostname, None, family)
224 except socket.gaierror, e:
225 # Name or service not known
226 if e.errno == -2:
227 return []
228
229 raise
6cecd141
MT
230
231 # Handle responses.
232 for family, socktype, proto, canonname, sockaddr in response:
233 # IPv6
234 if family == socket.AF_INET6:
235 address, port, flow_info, scope_id = sockaddr
236
237 # Only use the global scope.
238 if not scope_id == 0:
239 continue
240
241 # IPv4
242 elif family == socket.AF_INET:
243 address, port = sockaddr
244
245 # Ignore everything else...
246 else:
247 continue
248
249 # Add to repsonse list if not already in there.
250 if not address in addresses:
251 addresses.append(address)
252
253 return addresses