-
Notifications
You must be signed in to change notification settings - Fork 1
/
net.py
441 lines (390 loc) · 15.1 KB
/
net.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
from urllib.parse import urlsplit, urlunsplit
import urllib.parse
from socketserver import BaseServer
import sys
from ssl import SSLError
from misc import Context
import urllib.request
import http.client
from errno import EPIPE, ENOTCONN, ECONNRESET
from select import select
from contextlib import contextmanager
from streams import DelegateWriter, TeeReader
import os, os.path
import hashlib
from base64 import urlsafe_b64encode
from email.message import Message
import email.generator
from io import TextIOWrapper
from gzip import GzipFile
import mimetypes
try: # Python 3.3
ConnectionError
except NameError: # Python < 3.3
ConnectionError = ()
DISCONNECTION_ERRNOS = {EPIPE, ENOTCONN, ECONNRESET}
def url_port(url, scheme, ports):
"""Raises "ValueError" if the URL is not valid"""
parsed = urlsplit(url, scheme=scheme)
if not parsed.hostname:
parsed = urlsplit("//" + url, scheme=scheme)
if not parsed.hostname:
raise ValueError("No host name specified: {0!r}".format(url))
try:
def_port = ports[parsed.scheme]
except LookupError:
raise ValueError("Unhandled scheme: {0}".format(parsed.scheme))
port = parsed.port
if port is None:
port = def_port
path = urlunsplit(("", "", parsed.path, parsed.query, parsed.fragment))
return dict(scheme=parsed.scheme, hostname=parsed.hostname, port=port,
path=path, username=parsed.username, password=parsed.password)
def Url(scheme="", netloc="", path="", params="", query="", fragment=""):
return urllib.parse.ParseResult(
scheme, netloc, path, params, query, fragment)
def url_replace(url,
scheme=None, netloc=None, path=None, params=None, query=None, fragment=None):
res = list()
mods = (scheme, netloc, path, params, query, fragment)
for [orig, part] in zip(url, mods):
if part is None:
part = orig
res.append(part)
return urllib.parse.urlunparse(res)
def format_addr(address):
[address, port] = address
if not frozenset("[]:").isdisjoint(address):
address = "[{}]".format(address)
if port is not None:
address = "{}:{}".format(address, port)
return address
def parse_addr(address, defport=None):
address = Url(netloc=address)
host = address.hostname
if host is None:
host = ""
port = address.port
if port is None:
port = defport
return (host, port)
def header_list(message, header):
for header in message.get_all(header, ()):
yield from header_split(header, ",")
class HeaderParams(dict):
def __init__(self, params):
dict.__init__(self)
for param in header_split(params, ";"):
[param, value] = header_partition(param, "=")
param = param.strip().lower()
self.setdefault(param, list()).append(value.strip())
def __missing__(*pos, **kw):
return ()
def get_single(self, name):
value = self[name]
if not value:
raise KeyError("Missing {!r} parameter".format(name))
if len(value) > 1:
raise ValueError("Multiple {!r} parameters".format(name))
[value] = value
return value
def header_split(header, delim):
while header:
[elem, header] = header_partition(header, delim)
if elem:
yield elem
def header_partition(header, sep):
sentinelled = header + sep + '"\\'
pos = 0
while True: # For each quoted segment
end = sentinelled.index(sep, pos)
quote = sentinelled.index('"', pos)
if end < quote:
break
pos = quote + 1
while True: # For each backslash escape in quote
quote = sentinelled.index('"', pos)
backslash = sentinelled.index("\\", pos)
if quote < backslash:
break
pos = min(backslash + 2, len(header))
pos = min(quote + 1, len(header))
return (header[:end].strip(), header[end + 1:].strip())
def header_unquote(header):
segments = list()
while header: # For each quoted segment
[unquoted, _, header] = header.partition('"')
segments.append(unquoted)
sentinelled = header + '"\\'
start = 0
pos = 0
while True: # For each backslash escape in quote
quote = sentinelled.index('"', pos)
backslash = sentinelled.index("\\", pos)
if quote < backslash:
break
segments.append(header[start:backslash])
start = min(backslash + 1, len(header))
pos = min(start + 2, len(header))
segments.append(header[start:quote])
header = header[quote + 1:]
return "".join(segments)
class Server(BaseServer, Context):
default_port = 0
def __init__(self, address=("", None), RequestHandlerClass=None):
[host, port] = address
if port is None:
port = self.default_port
super().__init__((host, port), RequestHandlerClass)
def close(self):
return self.server_close()
def handle_error(self, request, client_address):
[_, exc, *_] = sys.exc_info()
if isinstance(exc, ConnectionError):
return
if (isinstance(exc, SSLError) and
exc.reason == "TLSV1_ALERT_UNKNOWN_CA"):
return
if not isinstance(exc, Exception):
self.close_request(request)
raise # Force server loop to exit
super().handle_error(request, client_address)
class PersistentConnectionHandler(urllib.request.BaseHandler):
"""URL handler for HTTP persistent connections
with PersistentConnectionHandler(timeout=10) as handler:
opener = urllib.request.build_opener(handler)
# First request opens connection
with opener.open("http://localhost/one") as response:
response.read()
# Subsequent requests reuse existing connection, unless it got closed
with opener.open("http://localhost/two") as response:
response.read()
# Closes old connection when new host specified
with opener.open("http://example/three") as response:
response.read()
# Socket freed at context manager exit
Currently does not reuse an existing connection if
two host names happen to resolve to the same Internet address.
"""
conn_classes = {
"http": http.client.HTTPConnection,
"https": http.client.HTTPSConnection,
}
def __init__(self, *pos, **kw):
self._type = None
self._host = None
self._pos = pos
self._kw = kw
self._connection = None
def default_open(self, req):
if req.type not in self.conn_classes:
return None
with self._setup_request(req):
headers = dict(req.header_items())
# On a fresh connection, only attempt request once
response = self._reuse_connection(req, headers)
if not response:
# (Re)try request on a fresh connection
self._attempt_request(req, headers)
response = self._connection.getresponse()
# Odd impedance mismatch between "http.client" and "urllib.request"
response.msg = response.reason
return response
def start_request(self, request):
with self._setup_request(request):
self._check_reusable()
self._connection.putrequest(
request.get_method(), request.selector)
for item in request.header_items():
self._connection.putheader(*item)
self._connection.endheaders()
def get_writer(self):
return DelegateWriter(self._connection.send)
def get_response(self):
response = self._connection.getresponse()
response.msg.set_default_type(None)
return response
@contextmanager
def _setup_request(self, req):
if req.type != self._type or req.host != self._host:
if self._connection:
self._connection.close()
conn_class = self.conn_classes[req.type]
self._connection = conn_class(req.host, *self._pos, **self._kw)
self._type = req.type
self._host = req.host
try:
yield
except:
self._connection.close() # Allow caller to make more requests
raise
def _check_reusable(self):
if self._connection.sock is None:
return False
if any(select((self._connection.sock,), (), (), 0)):
# Assume EOF or 408 Request Timeout has been signalled
self._connection.close()
return False
return True
def _reuse_connection(self, req, headers):
if not self._check_reusable():
return None
# Attempt request on existing connection
self._attempt_request(req, headers)
try:
try:
response = self._connection.getresponse()
except EnvironmentError as err: # Python < 3.3 compat.
if err.errno not in DISCONNECTION_ERRNOS:
raise
raise http.client.BadStatusLine(err) from err
except (ConnectionError, http.client.BadStatusLine):
idempotents = {
"GET", "HEAD", "PUT", "DELETE", "TRACE", "OPTIONS"}
if req.get_method() not in idempotents:
raise
self._connection.close()
return None # Retry requests whose method indicates idempotence
if response.status == http.client.REQUEST_TIMEOUT:
# Server indicated it did not handle request
return None
return response
def _attempt_request(self, req, headers):
"""Send HTTP request, ignoring broken pipe and similar errors"""
try:
self._connection.request(req.get_method(), req.selector,
req.data, headers)
except (ConnectionRefusedError, ConnectionAbortedError):
raise # Assume connection was not established
except ConnectionError:
pass # Continue and read server response if available
except EnvironmentError as err: # Python < 3.3 compatibility
if err.errno not in DISCONNECTION_ERRNOS:
raise
def close(self):
if self._connection:
self._connection.close()
def __enter__(self):
return self
def __exit__(self, *exc):
self.close()
def http_request(url, types=None, *,
urlopen=urllib.request.urlopen, headers=(), **kw):
headers = dict(headers)
if types is not None:
headers["Accept"] = ", ".join(types)
req = urllib.request.Request(url, headers=headers, **kw)
response = urlopen(req)
try:
headers = response.info()
[type, _] = headers.get_params([(None, None)])[0]
if types is not None and type not in types:
msg = "Unexpected content type {}"
raise TypeError(msg.format(type))
return response
except:
response.close()
raise
def request_cached(url, msg=None, *, cache=True, cleanup, **kw):
if msg is None:
msg = url
data = kw.get('data')
method = kw.get('method')
if not method:
method = 'GET' if data is None else 'POST'
print(method, msg, end=" ", flush=True, file=sys.stderr)
try:
if not cache:
raise FileNotFoundError()
path = url[:100].split("/")
dir = os.path.join(*path[:-1])
suffix = hashlib.md5()
if method not in {'GET', 'HEAD'}:
suffix.update(method.encode('ascii'))
suffix.update(url.encode())
if data is not None:
suffix.update(data)
suffix = suffix.digest()[:6]
suffix = urlsafe_b64encode(suffix).decode("ascii")
if path[-1]:
suffix = path[-1] + os.extsep + suffix
metadata = os.path.join(dir, suffix + os.extsep + "mime")
metadata = open(metadata, "rb")
except FileNotFoundError:
response = http_request(url, **kw)
cleanup.enter_context(response)
print(response.status, response.reason, flush=True,
file=sys.stderr)
header = response.info()
if cache:
for field in header_list(header, "Connection"):
del header[field]
for field in (
"Close", "Connection", "Keep-Alive",
"Proxy-Authenticate", "Proxy-Authorization",
"Public",
"Transfer-Encoding", "TE", "Trailer",
"Upgrade",
):
del header[field]
[type, value] = header.get_params()[0]
if type != 'application/octet-stream':
ext = {
'text/html': 'html', 'text/javascript': 'js',
'application/json': 'json',
'audio/mpeg': 'mpga',
'image/jpeg': 'jpeg',
}.get(type)
if ext is None:
suffix += mimetypes.guess_extension(type, strict=False)
else:
suffix += os.extsep + ext
for encoding in header_list(header, "Content-Encoding"):
if encoding.lower() in {"gzip", "x-gzip"}:
suffix += os.extsep + "gz"
break
os.makedirs(dir, exist_ok=True)
cache = open(os.path.join(dir, suffix), "xb")
cleanup.enter_context(cache)
msg = Message()
msg.add_header("Content-Type",
"message/external-body; access-type=local-file",
name=suffix)
header.add_header('Status',
'{} {}'.format(response.status, response.reason))
msg.attach(header)
with open(metadata, "xb") as metadata:
metadata = email.generator.BytesGenerator(metadata,
mangle_from_=False, maxheaderlen=0)
metadata.flatten(msg)
response = TeeReader(response, cache.write)
return (header, response)
with metadata:
msg = email.message_from_binary_file(metadata)
cache = os.path.join(dir, msg.get_param("name"))
[msg] = msg.get_payload()
response = cleanup.enter_context(open(cache, "rb"))
print("(cached)", flush=True, file=sys.stderr)
return (msg, response)
def request_decoded(*pos, headers=(), **kw):
headers += (
("Accept-Encoding", "gzip, x-gzip"),
)
[header, response] = request_cached(*pos, headers=headers, **kw)
for encoding in header_list(header, "Content-Encoding"):
if encoding.lower() in {"gzip", "x-gzip"}:
if isinstance(response, GzipFile):
raise TypeError("Recursive gzip encoding")
response = GzipFile(fileobj=response, mode="rb")
else:
msg = "Unhandled encoding: " + repr(encoding)
raise TypeError(msg)
return (header, response)
def request_text(*pos, **kw):
[header, response] = request_decoded(*pos, **kw)
try:
charset = header.get_content_charset()
return (header, TextIOWrapper(response, charset))
except:
response.close()
raise