Add a simple call to resolve a hostname.
[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 i18n import _
30
31 # Initialize the logger.
32 import logging
33 logger = logging.getLogger("ddns.system")
34 logger.propagate = 1
35
36 class DDNSSystem(object):
37         """
38                 The DDNSSystem class adds a layer of abstraction
39                 between the ddns software and the system.
40         """
41
42         # The default useragent.
43         USER_AGENT = "IPFireDDNSUpdater/%s" % CLIENT_VERSION
44
45         def __init__(self, core):
46                 # Connection to the core of the program.
47                 self.core = core
48
49         @property
50         def proxy(self):
51                 proxy = self.core.settings.get("proxy")
52
53                 # Strip http:// at the beginning.
54                 if proxy and proxy.startswith("http://"):
55                         proxy = proxy[7:]
56
57                 return proxy
58
59         def guess_external_ipv6_address(self):
60                 """
61                         Sends a request to an external web server
62                         to determine the current default IP address.
63                 """
64                 response = self.send_request("http://checkip6.dns.lightningwirelabs.com")
65
66                 if not response.code == 200:
67                         return
68
69                 match = re.search(r"^Your IP address is: (.*)$", response.read())
70                 if match is None:
71                         return
72
73                 return match.group(1)
74
75         def guess_external_ipv4_address(self):
76                 """
77                         Sends a request to the internet to determine
78                         the public IP address.
79
80                         XXX does not work for IPv6.
81                 """
82                 response = self.send_request("http://checkip4.dns.lightningwirelabs.com")
83
84                 if response.code == 200:
85                         match = re.search(r"Your IP address is: (\d+.\d+.\d+.\d+)", response.read())
86                         if match is None:
87                                 return
88
89                         return match.group(1)
90
91         def send_request(self, url, method="GET", data=None, username=None, password=None, timeout=30):
92                 assert method in ("GET", "POST")
93
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)
97                         data = None
98
99                         url = "%s?%s" % (url, query_args)
100
101                 logger.debug("Sending request (%s): %s" % (method, url))
102                 if data:
103                         logger.debug("  data: %s" % data)
104
105                 req = urllib2.Request(url, data=data)
106
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)
111
112                 # Set the user agent.
113                 req.add_header("User-Agent", self.USER_AGENT)
114
115                 # All requests should not be cached anywhere.
116                 req.add_header("Pragma", "no-cache")
117
118                 # Set the upstream proxy if needed.
119                 if self.proxy:
120                         logger.debug("Using proxy: %s" % self.proxy)
121
122                         # Configure the proxy for this request.
123                         req.set_proxy(self.proxy, "http")
124
125                 assert req.get_method() == method
126
127                 logger.debug(_("Request header:"))
128                 for k, v in req.headers.items():
129                         logger.debug("  %s: %s" % (k, v))
130
131                 try:
132                         resp = urllib2.urlopen(req)
133
134                         # Log response header.
135                         logger.debug(_("Response header:"))
136                         for k, v in resp.info().items():
137                                 logger.debug("  %s: %s" % (k, v))
138
139                         # Return the entire response object.
140                         return resp
141
142                 except urllib2.URLError, e:
143                         raise
144
145         def _format_query_args(self, data):
146                 args = []
147
148                 for k, v in data.items():
149                         arg = "%s=%s" % (k, urllib.quote(v))
150                         args.append(arg)
151
152                 return "&".join(args)
153
154         def _make_basic_auth_header(self, username, password):
155                 authstring = "%s:%s" % (username, password)
156
157                 # Encode authorization data in base64.
158                 authstring = base64.encodestring(authstring)
159
160                 # Remove any newline characters.
161                 authstring = authstring.replace("\n", "")
162
163                 return authstring
164
165         def get_address(self, proto):
166                 assert proto in ("ipv6", "ipv4")
167
168                 # Check if the external IP address should be guessed from
169                 # a remote server.
170                 guess_ip = self.core.settings.get("guess_external_ip", "true")
171
172                 # If the external IP address should be used, we just do
173                 # that.
174                 if guess_ip in ("true", "yes", "1"):
175                         if proto == "ipv6":
176                                 return self.guess_external_ipv6_address()
177
178                         elif proto == "ipv4":
179                                 return self.guess_external_ipv4_address()
180
181                 # XXX TODO
182                 assert False
183
184         def resolve(self, hostname, proto=None):
185                 addresses = []
186
187                 if proto is None:
188                         family = 0
189                 elif proto == "ipv6":
190                         family = socket.AF_INET6
191                 elif proto == "ipv4":
192                         family = socket.AF_INET
193                 else:
194                         raise ValueError("Protocol not supported: %s" % proto)
195
196                 # Resolve the host address.
197                 response = socket.getaddrinfo(hostname, None, family)
198
199                 # Handle responses.
200                 for family, socktype, proto, canonname, sockaddr in response:
201                         # IPv6
202                         if family == socket.AF_INET6:
203                                 address, port, flow_info, scope_id = sockaddr
204
205                                 # Only use the global scope.
206                                 if not scope_id == 0:
207                                         continue
208
209                         # IPv4
210                         elif family == socket.AF_INET:
211                                 address, port = sockaddr
212
213                         # Ignore everything else...
214                         else:
215                                 continue
216
217                         # Add to repsonse list if not already in there.
218                         if not address in addresses:
219                                 addresses.append(address)
220
221                 return addresses