Update providers so they don't need to format the request URL.
[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 re
23 import urllib
24 import urllib2
25
26 from __version__ import CLIENT_VERSION
27 from i18n import _
28
29 # Initialize the logger.
30 import logging
31 logger = logging.getLogger("ddns.system")
32 logger.propagate = 1
33
34 class DDNSSystem(object):
35         """
36                 The DDNSSystem class adds a layer of abstraction
37                 between the ddns software and the system.
38         """
39
40         # The default useragent.
41         USER_AGENT = "IPFireDDNSUpdater/%s" % CLIENT_VERSION
42
43         def __init__(self, core):
44                 # Connection to the core of the program.
45                 self.core = core
46
47         @property
48         def proxy(self):
49                 proxy = self.core.settings.get("proxy")
50
51                 # Strip http:// at the beginning.
52                 if proxy and proxy.startswith("http://"):
53                         proxy = proxy[7:]
54
55                 return proxy
56
57         def guess_external_ipv6_address(self):
58                 """
59                         Sends a request to an external web server
60                         to determine the current default IP address.
61                 """
62                 response = self.send_request("http://checkip6.dns.lightningwirelabs.com")
63
64                 if not response.code == 200:
65                         return
66
67                 match = re.search(r"^Your IP address is: (.*)$", response.read())
68                 if match is None:
69                         return
70
71                 return match.group(1)
72
73         def guess_external_ipv4_address(self):
74                 """
75                         Sends a request to the internet to determine
76                         the public IP address.
77
78                         XXX does not work for IPv6.
79                 """
80                 response = self.send_request("http://checkip4.dns.lightningwirelabs.com")
81
82                 if response.code == 200:
83                         match = re.search(r"Your IP address is: (\d+.\d+.\d+.\d+)", response.read())
84                         if match is None:
85                                 return
86
87                         return match.group(1)
88
89         def send_request(self, url, method="GET", data=None, timeout=30):
90                 assert method in ("GET", "POST")
91
92                 # Add all arguments in the data dict to the URL and escape them properly.
93                 if method == "GET" and data:
94                         query_args = self._format_query_args(data)
95                         data = None
96
97                         url = "%s?%s" % (url, query_args)
98
99                 logger.debug("Sending request (%s): %s" % (method, url))
100                 if data:
101                         logger.debug("  data: %s" % data)
102
103                 req = urllib2.Request(url, data=data)
104
105                 # Set the user agent.
106                 req.add_header("User-Agent", self.USER_AGENT)
107
108                 # All requests should not be cached anywhere.
109                 req.add_header("Pragma", "no-cache")
110
111                 # Set the upstream proxy if needed.
112                 if self.proxy:
113                         logger.debug("Using proxy: %s" % self.proxy)
114
115                         # Configure the proxy for this request.
116                         req.set_proxy(self.proxy, "http")
117
118                 assert req.get_method() == method
119
120                 logger.debug(_("Request header:"))
121                 for k, v in req.headers.items():
122                         logger.debug("  %s: %s" % (k, v))
123
124                 try:
125                         resp = urllib2.urlopen(req)
126
127                         # Log response header.
128                         logger.debug(_("Response header:"))
129                         for k, v in resp.info().items():
130                                 logger.debug("  %s: %s" % (k, v))
131
132                         # Return the entire response object.
133                         return resp
134
135                 except urllib2.URLError, e:
136                         raise
137
138         def _format_query_args(self, data):
139                 args = []
140
141                 for k, v in data.items():
142                         arg = "%s=%s" % (k, urllib.quote(v))
143                         args.append(arg)
144
145                 return "&".join(args)
146
147         def get_address(self, proto):
148                 assert proto in ("ipv6", "ipv4")
149
150                 # Check if the external IP address should be guessed from
151                 # a remote server.
152                 guess_ip = self.core.settings.get("guess_external_ip", "true")
153
154                 # If the external IP address should be used, we just do
155                 # that.
156                 if guess_ip in ("true", "yes", "1"):
157                         if proto == "ipv6":
158                                 return self.guess_external_ipv6_address()
159
160                         elif proto == "ipv4":
161                                 return self.guess_external_ipv4_address()
162
163                 # XXX TODO
164                 assert False