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