Only show success message when no exception occured.
[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
6cecd141 24import socket
adb124d0 25import urllib
f22ab085
MT
26import urllib2
27
28from __version__ import CLIENT_VERSION
29from i18n import _
30
31# Initialize the logger.
32import logging
33logger = logging.getLogger("ddns.system")
34logger.propagate = 1
35
36class 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.
fd898828 54 if proxy and proxy.startswith("http://"):
f22ab085
MT
55 proxy = proxy[7:]
56
57 return proxy
58
30270391
MT
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
f22ab085
MT
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 """
30270391 82 response = self.send_request("http://checkip4.dns.lightningwirelabs.com")
f22ab085
MT
83
84 if response.code == 200:
30270391 85 match = re.search(r"Your IP address is: (\d+.\d+.\d+.\d+)", response.read())
f22ab085
MT
86 if match is None:
87 return
88
89 return match.group(1)
90
d4c5c0d5 91 def send_request(self, url, method="GET", data=None, username=None, password=None, timeout=30):
adb124d0
MT
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))
f22ab085
MT
102 if data:
103 logger.debug(" data: %s" % data)
104
105 req = urllib2.Request(url, data=data)
106
d4c5c0d5
SS
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
f22ab085
MT
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
adb124d0
MT
125 assert req.get_method() == method
126
f22ab085
MT
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
adb124d0
MT
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
d4c5c0d5
SS
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
f22ab085
MT
165 def get_address(self, proto):
166 assert proto in ("ipv6", "ipv4")
167
30270391
MT
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()
f22ab085 177
30270391 178 elif proto == "ipv4":
f22ab085
MT
179 return self.guess_external_ipv4_address()
180
181 # XXX TODO
182 assert False
6cecd141
MT
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.
73f2bc0b
MT
197 try:
198 response = socket.getaddrinfo(hostname, None, family)
199 except socket.gaierror, e:
200 # Name or service not known
201 if e.errno == -2:
202 return []
203
204 raise
6cecd141
MT
205
206 # Handle responses.
207 for family, socktype, proto, canonname, sockaddr in response:
208 # IPv6
209 if family == socket.AF_INET6:
210 address, port, flow_info, scope_id = sockaddr
211
212 # Only use the global scope.
213 if not scope_id == 0:
214 continue
215
216 # IPv4
217 elif family == socket.AF_INET:
218 address, port = sockaddr
219
220 # Ignore everything else...
221 else:
222 continue
223
224 # Add to repsonse list if not already in there.
225 if not address in addresses:
226 addresses.append(address)
227
228 return addresses