domainnameapi 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- domainnameapi/__init__.py +38 -0
- domainnameapi/_php.py +482 -0
- domainnameapi/_version.py +4 -0
- domainnameapi/client.py +275 -0
- domainnameapi/py.typed +0 -0
- domainnameapi/rest.py +1689 -0
- domainnameapi/shared.py +182 -0
- domainnameapi/telemetry.py +471 -0
- domainnameapi/transport.py +217 -0
- domainnameapi-1.0.0.dist-info/METADATA +1637 -0
- domainnameapi-1.0.0.dist-info/RECORD +13 -0
- domainnameapi-1.0.0.dist-info/WHEEL +4 -0
- domainnameapi-1.0.0.dist-info/licenses/LICENSE +201 -0
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
"""HTTP transport.
|
|
2
|
+
|
|
3
|
+
The client talks to the gateway through a *transport*: any object with a
|
|
4
|
+
``send(request)`` method that takes an :class:`HttpRequest` and returns an
|
|
5
|
+
:class:`HttpResponse`, or raises :class:`TransportError` when the gateway
|
|
6
|
+
could not be reached at all. The default :class:`UrllibTransport` uses only
|
|
7
|
+
the standard library; tests replace it with a fake.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import functools
|
|
11
|
+
import http.client
|
|
12
|
+
import socket
|
|
13
|
+
import ssl
|
|
14
|
+
import time
|
|
15
|
+
import urllib.error
|
|
16
|
+
import urllib.request
|
|
17
|
+
|
|
18
|
+
# curl error numbers, so transport failures carry the same codes as php-dna.
|
|
19
|
+
CURLE_COULDNT_RESOLVE_HOST = 6
|
|
20
|
+
CURLE_COULDNT_CONNECT = 7
|
|
21
|
+
CURLE_PARTIAL_FILE = 18
|
|
22
|
+
CURLE_OPERATION_TIMEDOUT = 28
|
|
23
|
+
CURLE_SSL_CONNECT_ERROR = 35
|
|
24
|
+
CURLE_GOT_NOTHING = 52
|
|
25
|
+
CURLE_RECV_ERROR = 56
|
|
26
|
+
CURLE_PEER_FAILED_VERIFICATION = 60
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class HttpRequest(object):
|
|
30
|
+
"""One outgoing gateway call."""
|
|
31
|
+
|
|
32
|
+
__slots__ = ("method", "url", "headers", "body", "timeout", "connect_timeout", "verify_ssl")
|
|
33
|
+
|
|
34
|
+
def __init__(self, method, url, headers, body=None, timeout=30, connect_timeout=10, verify_ssl=True):
|
|
35
|
+
self.method = method
|
|
36
|
+
self.url = url
|
|
37
|
+
self.headers = headers
|
|
38
|
+
self.body = body
|
|
39
|
+
self.timeout = timeout
|
|
40
|
+
self.connect_timeout = connect_timeout
|
|
41
|
+
self.verify_ssl = verify_ssl
|
|
42
|
+
|
|
43
|
+
def __repr__(self):
|
|
44
|
+
return "HttpRequest(%r, %r)" % (self.method, self.url)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class HttpResponse(object):
|
|
48
|
+
"""Status, raw body text and response headers of one call."""
|
|
49
|
+
|
|
50
|
+
__slots__ = ("status", "body", "headers")
|
|
51
|
+
|
|
52
|
+
def __init__(self, status, body="", headers=None):
|
|
53
|
+
self.status = int(status)
|
|
54
|
+
self.body = body if body is not None else ""
|
|
55
|
+
self.headers = headers or {}
|
|
56
|
+
|
|
57
|
+
def __repr__(self):
|
|
58
|
+
return "HttpResponse(%d, %d bytes)" % (self.status, len(self.body))
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class TransportError(Exception):
|
|
62
|
+
"""The request never produced an HTTP response (timeout, DNS, TLS, reset).
|
|
63
|
+
|
|
64
|
+
``errno`` follows curl's numbering (28 = timeout, 6 = DNS, 7 = connect,
|
|
65
|
+
35/60 = TLS, 52/56 = connection dropped).
|
|
66
|
+
"""
|
|
67
|
+
|
|
68
|
+
def __init__(self, errno, message):
|
|
69
|
+
super().__init__(message)
|
|
70
|
+
self.errno = errno
|
|
71
|
+
self.message = message
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class _ConnectTimeoutMixin(object):
|
|
75
|
+
"""Use a shorter timeout for connect (+ TLS handshake) than for the rest."""
|
|
76
|
+
|
|
77
|
+
def __init__(self, *args, **kwargs):
|
|
78
|
+
self._connect_timeout = kwargs.pop("connect_timeout", None)
|
|
79
|
+
super(_ConnectTimeoutMixin, self).__init__(*args, **kwargs)
|
|
80
|
+
|
|
81
|
+
def connect(self):
|
|
82
|
+
total = self.timeout
|
|
83
|
+
if self._connect_timeout is not None:
|
|
84
|
+
self.timeout = self._connect_timeout
|
|
85
|
+
try:
|
|
86
|
+
super(_ConnectTimeoutMixin, self).connect()
|
|
87
|
+
finally:
|
|
88
|
+
self.timeout = total
|
|
89
|
+
if self.sock is not None:
|
|
90
|
+
self.sock.settimeout(total)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
class _HTTPConnection(_ConnectTimeoutMixin, http.client.HTTPConnection):
|
|
94
|
+
pass
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
class _HTTPSConnection(_ConnectTimeoutMixin, http.client.HTTPSConnection):
|
|
98
|
+
pass
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
class _HTTPHandler(urllib.request.HTTPHandler):
|
|
102
|
+
def __init__(self, connect_timeout):
|
|
103
|
+
super(_HTTPHandler, self).__init__()
|
|
104
|
+
self._connect_timeout = connect_timeout
|
|
105
|
+
|
|
106
|
+
def http_open(self, req):
|
|
107
|
+
return self.do_open(functools.partial(_HTTPConnection, connect_timeout=self._connect_timeout), req)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
class _HTTPSHandler(urllib.request.HTTPSHandler):
|
|
111
|
+
def __init__(self, connect_timeout, context):
|
|
112
|
+
super(_HTTPSHandler, self).__init__(context=context)
|
|
113
|
+
self._connect_timeout = connect_timeout
|
|
114
|
+
self._ctx = context
|
|
115
|
+
|
|
116
|
+
def https_open(self, req):
|
|
117
|
+
return self.do_open(
|
|
118
|
+
functools.partial(_HTTPSConnection, connect_timeout=self._connect_timeout),
|
|
119
|
+
req,
|
|
120
|
+
context=self._ctx,
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
class _NoRedirect(urllib.request.HTTPRedirectHandler):
|
|
125
|
+
"""curl does not follow redirects; a 301/302 must reach the client as is."""
|
|
126
|
+
|
|
127
|
+
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
|
128
|
+
return None
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _classify(exc):
|
|
132
|
+
"""Map a Python networking exception to (curl errno, curl-like message)."""
|
|
133
|
+
reason = exc
|
|
134
|
+
if isinstance(exc, urllib.error.URLError) and not isinstance(exc, urllib.error.HTTPError):
|
|
135
|
+
reason = exc.reason if exc.reason is not None else exc
|
|
136
|
+
text = str(reason) or reason.__class__.__name__
|
|
137
|
+
if isinstance(reason, (socket.timeout, TimeoutError)) or "timed out" in text.lower():
|
|
138
|
+
return CURLE_OPERATION_TIMEDOUT, text
|
|
139
|
+
if isinstance(reason, socket.gaierror):
|
|
140
|
+
return CURLE_COULDNT_RESOLVE_HOST, "Could not resolve host: " + text
|
|
141
|
+
if hasattr(ssl, "SSLCertVerificationError") and isinstance(reason, ssl.SSLCertVerificationError):
|
|
142
|
+
return CURLE_PEER_FAILED_VERIFICATION, "SSL certificate problem: " + text
|
|
143
|
+
if isinstance(reason, ssl.SSLError):
|
|
144
|
+
return CURLE_SSL_CONNECT_ERROR, "SSL connect error: " + text
|
|
145
|
+
if isinstance(reason, ConnectionRefusedError):
|
|
146
|
+
return CURLE_COULDNT_CONNECT, "Failed to connect: " + text
|
|
147
|
+
if isinstance(reason, http.client.RemoteDisconnected):
|
|
148
|
+
return CURLE_GOT_NOTHING, "Empty reply from server"
|
|
149
|
+
if isinstance(reason, http.client.IncompleteRead):
|
|
150
|
+
return CURLE_PARTIAL_FILE, "Transferred a partial file"
|
|
151
|
+
if isinstance(reason, ConnectionResetError):
|
|
152
|
+
return CURLE_RECV_ERROR, "Recv failure: Connection reset by peer"
|
|
153
|
+
if isinstance(reason, (http.client.HTTPException, ConnectionError)):
|
|
154
|
+
return CURLE_RECV_ERROR, "Recv failure: " + text
|
|
155
|
+
return CURLE_COULDNT_CONNECT, text
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _read_body(fp, deadline):
|
|
159
|
+
chunks = []
|
|
160
|
+
while True:
|
|
161
|
+
if time.monotonic() > deadline:
|
|
162
|
+
raise socket.timeout("Operation timed out while reading the response body")
|
|
163
|
+
chunk = fp.read(65536)
|
|
164
|
+
if not chunk:
|
|
165
|
+
break
|
|
166
|
+
chunks.append(chunk)
|
|
167
|
+
return b"".join(chunks).decode("utf-8", errors="replace")
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
class UrllibTransport(object):
|
|
171
|
+
"""Standard-library transport (``urllib.request``).
|
|
172
|
+
|
|
173
|
+
No redirects are followed (a 301/302 is reported to the client, as with
|
|
174
|
+
curl), the connect + TLS handshake must finish within ``connect_timeout``
|
|
175
|
+
seconds and the whole call within ``timeout`` seconds. Proxy environment
|
|
176
|
+
variables (``HTTPS_PROXY`` ...) are honoured.
|
|
177
|
+
"""
|
|
178
|
+
|
|
179
|
+
def send(self, request):
|
|
180
|
+
if request.verify_ssl:
|
|
181
|
+
context = ssl.create_default_context()
|
|
182
|
+
else:
|
|
183
|
+
context = ssl.create_default_context()
|
|
184
|
+
context.check_hostname = False
|
|
185
|
+
context.verify_mode = ssl.CERT_NONE
|
|
186
|
+
|
|
187
|
+
opener = urllib.request.build_opener(
|
|
188
|
+
_NoRedirect(),
|
|
189
|
+
_HTTPHandler(request.connect_timeout),
|
|
190
|
+
_HTTPSHandler(request.connect_timeout, context),
|
|
191
|
+
)
|
|
192
|
+
data = request.body.encode("utf-8") if isinstance(request.body, str) else request.body
|
|
193
|
+
req = urllib.request.Request(request.url, data=data, method=request.method)
|
|
194
|
+
for name, value in request.headers.items():
|
|
195
|
+
req.add_header(name, value)
|
|
196
|
+
|
|
197
|
+
deadline = time.monotonic() + request.timeout
|
|
198
|
+
try:
|
|
199
|
+
try:
|
|
200
|
+
resp = opener.open(req, timeout=request.timeout)
|
|
201
|
+
except urllib.error.HTTPError as err:
|
|
202
|
+
# Non-2xx statuses are responses, not transport failures.
|
|
203
|
+
body = _read_body(err, deadline) if err.fp is not None else ""
|
|
204
|
+
headers = dict(err.headers.items()) if err.headers is not None else {}
|
|
205
|
+
err.close()
|
|
206
|
+
return HttpResponse(err.code, body, headers)
|
|
207
|
+
with resp:
|
|
208
|
+
body = _read_body(resp, deadline)
|
|
209
|
+
return HttpResponse(resp.status, body, dict(resp.headers.items()))
|
|
210
|
+
except TransportError:
|
|
211
|
+
raise
|
|
212
|
+
except (urllib.error.URLError, OSError, http.client.HTTPException, ValueError) as exc:
|
|
213
|
+
if isinstance(exc, ValueError) and not isinstance(exc, (urllib.error.URLError,)):
|
|
214
|
+
# Malformed URL (e.g. a bad setServiceUrl value).
|
|
215
|
+
raise TransportError(3, "URL using bad/illegal format or missing URL: " + str(exc))
|
|
216
|
+
errno, message = _classify(exc)
|
|
217
|
+
raise TransportError(errno, message)
|