3342f9d9b9bcbf7b430fe5120ecf06b11845161f
[oddments/ddns.git] / src / ddns / system.py
1 #!/usr/bin/python
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 ###############################################################################
21
22 import base64
23 import re
24 import socket
25 import urllib
26 import urllib2
27
28 from __version__ import CLIENT_VERSION
29 from .errors import *
30 from i18n import _
31
32 # Initialize the logger.
33 import logging
34 logger = logging.getLogger("ddns.system")
35 logger.propagate = 1
36
37 class 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.
55                 if proxy and proxy.startswith("http://"):
56                         proxy = proxy[7:]
57
58                 return proxy
59
60         def _guess_external_ip_address(self, url, timeout=10):
61                 """
62                         Sends a request to an external web server
63                         to determine the current default IP address.
64                 """
65                 try:
66                         response = self.send_request(url, timeout=timeout)
67
68                 # If the server could not be reached, we will return nothing.
69                 except DDNSNetworkError:
70                         return
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
81         def guess_external_ipv6_address(self):
82                 """
83                         Sends a request to the internet to determine
84                         the public IPv6 address.
85                 """
86                 return self._guess_external_ip_address("http://checkip6.dns.lightningwirelabs.com")
87
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")
94
95         def send_request(self, url, method="GET", data=None, username=None, password=None, timeout=30):
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                         if "?" in url:
104                                 url = "%s&%s" % (url, query_args)
105                         else:
106                                 url = "%s?%s" % (url, query_args)
107
108                 logger.debug("Sending request (%s): %s" % (method, url))
109                 if data:
110                         logger.debug("  data: %s" % data)
111
112                 req = urllib2.Request(url, data=data)
113
114                 if username and password:
115                         basic_auth_header = self._make_basic_auth_header(username, password)
116                         req.add_header("Authorization", "Basic %s" % basic_auth_header)
117
118                 # Set the user agent.
119                 req.add_header("User-Agent", self.USER_AGENT)
120
121                 # All requests should not be cached anywhere.
122                 req.add_header("Pragma", "no-cache")
123
124                 # Set the upstream proxy if needed.
125                 if self.proxy:
126                         logger.debug("Using proxy: %s" % self.proxy)
127
128                         # Configure the proxy for this request.
129                         req.set_proxy(self.proxy, "http")
130
131                 assert req.get_method() == method
132
133                 logger.debug(_("Request header:"))
134                 for k, v in req.headers.items():
135                         logger.debug("  %s: %s" % (k, v))
136
137                 try:
138                         resp = urllib2.urlopen(req, timeout=timeout)
139
140                         # Log response header.
141                         logger.debug(_("Response header:"))
142                         for k, v in resp.info().items():
143                                 logger.debug("  %s: %s" % (k, v))
144
145                         # Return the entire response object.
146                         return resp
147
148                 except urllib2.HTTPError, e:
149                         # 503 - Service Unavailable
150                         if e.code == 503:
151                                 raise DDNSServiceUnavailableError
152
153                         # Raise all other unhandled exceptions.
154                         raise
155
156                 except urllib2.URLError, e:
157                         if e.reason:
158                                 # Network Unreachable (e.g. no IPv6 access)
159                                 if e.reason.errno == 101:
160                                         raise DDNSNetworkUnreachableError
161                                 elif e.reason.errno == 111:
162                                         raise DDNSConnectionRefusedError
163
164                         # Raise all other unhandled exceptions.
165                         raise
166
167                 except socket.timeout, e:
168                         logger.debug(_("Connection timeout"))
169
170                         raise DDNSConnectionTimeoutError
171
172         def _format_query_args(self, data):
173                 args = []
174
175                 for k, v in data.items():
176                         arg = "%s=%s" % (k, urllib.quote(v))
177                         args.append(arg)
178
179                 return "&".join(args)
180
181         def _make_basic_auth_header(self, username, password):
182                 authstring = "%s:%s" % (username, password)
183
184                 # Encode authorization data in base64.
185                 authstring = base64.encodestring(authstring)
186
187                 # Remove any newline characters.
188                 authstring = authstring.replace("\n", "")
189
190                 return authstring
191
192         def get_address(self, proto):
193                 assert proto in ("ipv6", "ipv4")
194
195                 # Check if the external IP address should be guessed from
196                 # a remote server.
197                 guess_ip = self.core.settings.get("guess_external_ip", "true")
198
199                 # If the external IP address should be used, we just do
200                 # that.
201                 if guess_ip in ("true", "yes", "1"):
202                         if proto == "ipv6":
203                                 return self.guess_external_ipv6_address()
204
205                         elif proto == "ipv4":
206                                 return self.guess_external_ipv4_address()
207
208                 # XXX TODO
209                 assert False
210
211         def resolve(self, hostname, proto=None):
212                 addresses = []
213
214                 if proto is None:
215                         family = 0
216                 elif proto == "ipv6":
217                         family = socket.AF_INET6
218                 elif proto == "ipv4":
219                         family = socket.AF_INET
220                 else:
221                         raise ValueError("Protocol not supported: %s" % proto)
222
223                 # Resolve the host address.
224                 try:
225                         response = socket.getaddrinfo(hostname, None, family)
226                 except socket.gaierror, e:
227                         # Name or service not known
228                         if e.errno == -2:
229                                 return []
230
231                         # No record for requested family available (e.g. no AAAA)
232                         elif e.errno == -5:
233                                 return []
234
235                         raise
236
237                 # Handle responses.
238                 for family, socktype, proto, canonname, sockaddr in response:
239                         # IPv6
240                         if family == socket.AF_INET6:
241                                 address, port, flow_info, scope_id = sockaddr
242
243                                 # Only use the global scope.
244                                 if not scope_id == 0:
245                                         continue
246
247                         # IPv4
248                         elif family == socket.AF_INET:
249                                 address, port = sockaddr
250
251                         # Ignore everything else...
252                         else:
253                                 continue
254
255                         # Add to repsonse list if not already in there.
256                         if not address in addresses:
257                                 addresses.append(address)
258
259                 return addresses