/
__init__.py
2072 lines (1789 loc) · 73.9 KB
/
__init__.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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""Small, fast HTTP client library for Python."""
__author__ = "Joe Gregorio (joe@bitworking.org)"
__copyright__ = "Copyright 2006, Joe Gregorio"
__contributors__ = [
"Thomas Broyer (t.broyer@ltgt.net)",
"James Antill",
"Xavier Verges Farrero",
"Jonathan Feinberg",
"Blair Zajac",
"Sam Ruby",
"Louis Nyffenegger",
"Mark Pilgrim",
"Alex Yu",
]
__license__ = "MIT"
__version__ = '0.15.0'
import base64
import calendar
import copy
import email
import email.feedparser
from email import header
import email.message
import email.utils
import errno
from gettext import gettext as _
import gzip
from hashlib import md5 as _md5
from hashlib import sha1 as _sha
import hmac
import http.client
import io
import os
import random
import re
import socket
import ssl
import sys
import time
import urllib.parse
import zlib
try:
import socks
except ImportError:
# TODO: remove this fallback and copypasted socksipy module upon py2/3 merge,
# idea is to have soft-dependency on any compatible module called socks
from . import socks
from .iri2uri import iri2uri
def has_timeout(timeout):
if hasattr(socket, "_GLOBAL_DEFAULT_TIMEOUT"):
return timeout is not None and timeout is not socket._GLOBAL_DEFAULT_TIMEOUT
return timeout is not None
__all__ = [
"debuglevel",
"FailedToDecompressContent",
"Http",
"HttpLib2Error",
"ProxyInfo",
"RedirectLimit",
"RedirectMissingLocation",
"Response",
"RETRIES",
"UnimplementedDigestAuthOptionError",
"UnimplementedHmacDigestAuthOptionError",
]
# The httplib debug level, set to a non-zero value to get debug output
debuglevel = 0
# A request will be tried 'RETRIES' times if it fails at the socket/connection level.
RETRIES = 2
# All exceptions raised here derive from HttpLib2Error
class HttpLib2Error(Exception):
pass
# Some exceptions can be caught and optionally
# be turned back into responses.
class HttpLib2ErrorWithResponse(HttpLib2Error):
def __init__(self, desc, response, content):
self.response = response
self.content = content
HttpLib2Error.__init__(self, desc)
class RedirectMissingLocation(HttpLib2ErrorWithResponse):
pass
class RedirectLimit(HttpLib2ErrorWithResponse):
pass
class FailedToDecompressContent(HttpLib2ErrorWithResponse):
pass
class UnimplementedDigestAuthOptionError(HttpLib2ErrorWithResponse):
pass
class UnimplementedHmacDigestAuthOptionError(HttpLib2ErrorWithResponse):
pass
class MalformedHeader(HttpLib2Error):
pass
class RelativeURIError(HttpLib2Error):
pass
class ServerNotFoundError(HttpLib2Error):
pass
class ProxiesUnavailableError(HttpLib2Error):
pass
# Open Items:
# -----------
# Are we removing the cached content too soon on PUT (only delete on 200 Maybe?)
# Pluggable cache storage (supports storing the cache in
# flat files by default. We need a plug-in architecture
# that can support Berkeley DB and Squid)
# == Known Issues ==
# Does not handle a resource that uses conneg and Last-Modified but no ETag as a cache validator.
# Does not handle Cache-Control: max-stale
# Does not use Age: headers when calculating cache freshness.
# The number of redirections to follow before giving up.
# Note that only GET redirects are automatically followed.
# Will also honor 301 requests by saving that info and never
# requesting that URI again.
DEFAULT_MAX_REDIRECTS = 5
# Which headers are hop-by-hop headers by default
HOP_BY_HOP = [
"connection",
"keep-alive",
"proxy-authenticate",
"proxy-authorization",
"te",
"trailers",
"transfer-encoding",
"upgrade",
]
# https://tools.ietf.org/html/rfc7231#section-8.1.3
SAFE_METHODS = ("GET", "HEAD", "OPTIONS", "TRACE")
from httplib2 import certs
CA_CERTS = certs.where()
# PROTOCOL_TLS is python 3.5.3+. PROTOCOL_SSLv23 is deprecated.
# Both PROTOCOL_TLS and PROTOCOL_SSLv23 are equivalent and means:
# > Selects the highest protocol version that both the client and server support.
# > Despite the name, this option can select “TLS” protocols as well as “SSL”.
# source: https://docs.python.org/3.5/library/ssl.html#ssl.PROTOCOL_TLS
DEFAULT_TLS_VERSION = getattr(ssl, "PROTOCOL_TLS", None) or getattr(
ssl, "PROTOCOL_SSLv23"
)
def _build_ssl_context(
disable_ssl_certificate_validation, ca_certs, cert_file=None, key_file=None,
maximum_version=None, minimum_version=None, key_password=None,
):
if not hasattr(ssl, "SSLContext"):
raise RuntimeError("httplib2 requires Python 3.2+ for ssl.SSLContext")
context = ssl.SSLContext(DEFAULT_TLS_VERSION)
context.verify_mode = (
ssl.CERT_NONE if disable_ssl_certificate_validation else ssl.CERT_REQUIRED
)
# SSLContext.maximum_version and SSLContext.minimum_version are python 3.7+.
# source: https://docs.python.org/3/library/ssl.html#ssl.SSLContext.maximum_version
if maximum_version is not None:
if hasattr(context, "maximum_version"):
context.maximum_version = getattr(ssl.TLSVersion, maximum_version)
else:
raise RuntimeError("setting tls_maximum_version requires Python 3.7 and OpenSSL 1.1 or newer")
if minimum_version is not None:
if hasattr(context, "minimum_version"):
context.minimum_version = getattr(ssl.TLSVersion, minimum_version)
else:
raise RuntimeError("setting tls_minimum_version requires Python 3.7 and OpenSSL 1.1 or newer")
# check_hostname requires python 3.4+
# we will perform the equivalent in HTTPSConnectionWithTimeout.connect() by calling ssl.match_hostname
# if check_hostname is not supported.
if hasattr(context, "check_hostname"):
context.check_hostname = not disable_ssl_certificate_validation
context.load_verify_locations(ca_certs)
if cert_file:
context.load_cert_chain(cert_file, key_file, key_password)
return context
def _get_end2end_headers(response):
hopbyhop = list(HOP_BY_HOP)
hopbyhop.extend([x.strip() for x in response.get("connection", "").split(",")])
return [header for header in list(response.keys()) if header not in hopbyhop]
URI = re.compile(r"^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?")
def parse_uri(uri):
"""Parses a URI using the regex given in Appendix B of RFC 3986.
(scheme, authority, path, query, fragment) = parse_uri(uri)
"""
groups = URI.match(uri).groups()
return (groups[1], groups[3], groups[4], groups[6], groups[8])
def urlnorm(uri):
(scheme, authority, path, query, fragment) = parse_uri(uri)
if not scheme or not authority:
raise RelativeURIError("Only absolute URIs are allowed. uri = %s" % uri)
authority = authority.lower()
scheme = scheme.lower()
if not path:
path = "/"
# Could do syntax based normalization of the URI before
# computing the digest. See Section 6.2.2 of Std 66.
request_uri = query and "?".join([path, query]) or path
scheme = scheme.lower()
defrag_uri = scheme + "://" + authority + request_uri
return scheme, authority, request_uri, defrag_uri
# Cache filename construction (original borrowed from Venus http://intertwingly.net/code/venus/)
re_url_scheme = re.compile(r"^\w+://")
re_unsafe = re.compile(r"[^\w\-_.()=!]+", re.ASCII)
def safename(filename):
"""Return a filename suitable for the cache.
Strips dangerous and common characters to create a filename we
can use to store the cache in.
"""
if isinstance(filename, bytes):
filename_bytes = filename
filename = filename.decode("utf-8")
else:
filename_bytes = filename.encode("utf-8")
filemd5 = _md5(filename_bytes).hexdigest()
filename = re_url_scheme.sub("", filename)
filename = re_unsafe.sub("", filename)
# limit length of filename (vital for Windows)
# https://github.com/httplib2/httplib2/pull/74
# C:\Users\ <username> \AppData\Local\Temp\ <safe_filename> , <md5>
# 9 chars + max 104 chars + 20 chars + x + 1 + 32 = max 259 chars
# Thus max safe filename x = 93 chars. Let it be 90 to make a round sum:
filename = filename[:90]
return ",".join((filename, filemd5))
NORMALIZE_SPACE = re.compile(r"(?:\r\n)?[ \t]+")
def _normalize_headers(headers):
return dict(
[
(
_convert_byte_str(key).lower(),
NORMALIZE_SPACE.sub(_convert_byte_str(value), " ").strip(),
)
for (key, value) in headers.items()
]
)
def _convert_byte_str(s):
if not isinstance(s, str):
return str(s, "utf-8")
return s
def _parse_cache_control(headers):
retval = {}
if "cache-control" in headers:
parts = headers["cache-control"].split(",")
parts_with_args = [
tuple([x.strip().lower() for x in part.split("=", 1)])
for part in parts
if -1 != part.find("=")
]
parts_wo_args = [
(name.strip().lower(), 1) for name in parts if -1 == name.find("=")
]
retval = dict(parts_with_args + parts_wo_args)
return retval
# Whether to use a strict mode to parse WWW-Authenticate headers
# Might lead to bad results in case of ill-formed header value,
# so disabled by default, falling back to relaxed parsing.
# Set to true to turn on, useful for testing servers.
USE_WWW_AUTH_STRICT_PARSING = 0
# In regex below:
# [^\0-\x1f\x7f-\xff()<>@,;:\\\"/[\]?={} \t]+ matches a "token" as defined by HTTP
# "(?:[^\0-\x08\x0A-\x1f\x7f-\xff\\\"]|\\[\0-\x7f])*?" matches a "quoted-string" as defined by HTTP, when LWS have already been replaced by a single space
# Actually, as an auth-param value can be either a token or a quoted-string, they are combined in a single pattern which matches both:
# \"?((?<=\")(?:[^\0-\x1f\x7f-\xff\\\"]|\\[\0-\x7f])*?(?=\")|(?<!\")[^\0-\x08\x0A-\x1f\x7f-\xff()<>@,;:\\\"/[\]?={} \t]+(?!\"))\"?
WWW_AUTH_STRICT = re.compile(
r"^(?:\s*(?:,\s*)?([^\0-\x1f\x7f-\xff()<>@,;:\\\"/[\]?={} \t]+)\s*=\s*\"?((?<=\")(?:[^\0-\x08\x0A-\x1f\x7f-\xff\\\"]|\\[\0-\x7f])*?(?=\")|(?<!\")[^\0-\x1f\x7f-\xff()<>@,;:\\\"/[\]?={} \t]+(?!\"))\"?)(.*)$"
)
WWW_AUTH_RELAXED = re.compile(
r"^(?:\s*(?:,\s*)?([^ \t\r\n=]+)\s*=\s*\"?((?<=\")(?:[^\\\"]|\\.)*?(?=\")|(?<!\")[^ \t\r\n,]+(?!\"))\"?)(.*)$"
)
UNQUOTE_PAIRS = re.compile(r"\\(.)")
def _parse_www_authenticate(headers, headername="www-authenticate"):
"""Returns a dictionary of dictionaries, one dict
per auth_scheme."""
retval = {}
if headername in headers:
try:
authenticate = headers[headername].strip()
www_auth = (
USE_WWW_AUTH_STRICT_PARSING and WWW_AUTH_STRICT or WWW_AUTH_RELAXED
)
while authenticate:
# Break off the scheme at the beginning of the line
if headername == "authentication-info":
(auth_scheme, the_rest) = ("digest", authenticate)
else:
(auth_scheme, the_rest) = authenticate.split(" ", 1)
# Now loop over all the key value pairs that come after the scheme,
# being careful not to roll into the next scheme
match = www_auth.search(the_rest)
auth_params = {}
while match:
if match and len(match.groups()) == 3:
(key, value, the_rest) = match.groups()
auth_params[key.lower()] = UNQUOTE_PAIRS.sub(
r"\1", value
) # '\\'.join([x.replace('\\', '') for x in value.split('\\\\')])
match = www_auth.search(the_rest)
retval[auth_scheme.lower()] = auth_params
authenticate = the_rest.strip()
except ValueError:
raise MalformedHeader("WWW-Authenticate")
return retval
def _entry_disposition(response_headers, request_headers):
"""Determine freshness from the Date, Expires and Cache-Control headers.
We don't handle the following:
1. Cache-Control: max-stale
2. Age: headers are not used in the calculations.
Not that this algorithm is simpler than you might think
because we are operating as a private (non-shared) cache.
This lets us ignore 's-maxage'. We can also ignore
'proxy-invalidate' since we aren't a proxy.
We will never return a stale document as
fresh as a design decision, and thus the non-implementation
of 'max-stale'. This also lets us safely ignore 'must-revalidate'
since we operate as if every server has sent 'must-revalidate'.
Since we are private we get to ignore both 'public' and
'private' parameters. We also ignore 'no-transform' since
we don't do any transformations.
The 'no-store' parameter is handled at a higher level.
So the only Cache-Control parameters we look at are:
no-cache
only-if-cached
max-age
min-fresh
"""
retval = "STALE"
cc = _parse_cache_control(request_headers)
cc_response = _parse_cache_control(response_headers)
if (
"pragma" in request_headers
and request_headers["pragma"].lower().find("no-cache") != -1
):
retval = "TRANSPARENT"
if "cache-control" not in request_headers:
request_headers["cache-control"] = "no-cache"
elif "no-cache" in cc:
retval = "TRANSPARENT"
elif "no-cache" in cc_response:
retval = "STALE"
elif "only-if-cached" in cc:
retval = "FRESH"
elif "date" in response_headers:
date = calendar.timegm(email.utils.parsedate_tz(response_headers["date"]))
now = time.time()
current_age = max(0, now - date)
if "max-age" in cc_response:
try:
freshness_lifetime = int(cc_response["max-age"])
except ValueError:
freshness_lifetime = 0
elif "expires" in response_headers:
expires = email.utils.parsedate_tz(response_headers["expires"])
if None == expires:
freshness_lifetime = 0
else:
freshness_lifetime = max(0, calendar.timegm(expires) - date)
else:
freshness_lifetime = 0
if "max-age" in cc:
try:
freshness_lifetime = int(cc["max-age"])
except ValueError:
freshness_lifetime = 0
if "min-fresh" in cc:
try:
min_fresh = int(cc["min-fresh"])
except ValueError:
min_fresh = 0
current_age += min_fresh
if freshness_lifetime > current_age:
retval = "FRESH"
return retval
def _decompressContent(response, new_content):
content = new_content
try:
encoding = response.get("content-encoding", None)
if encoding in ["gzip", "deflate"]:
if encoding == "gzip":
content = gzip.GzipFile(fileobj=io.BytesIO(new_content)).read()
if encoding == "deflate":
content = zlib.decompress(content, -zlib.MAX_WBITS)
response["content-length"] = str(len(content))
# Record the historical presence of the encoding in a way the won't interfere.
response["-content-encoding"] = response["content-encoding"]
del response["content-encoding"]
except (IOError, zlib.error):
content = ""
raise FailedToDecompressContent(
_("Content purported to be compressed with %s but failed to decompress.")
% response.get("content-encoding"),
response,
content,
)
return content
def _bind_write_headers(msg):
def _write_headers(self):
# Self refers to the Generator object.
for h, v in msg.items():
print("%s:" % h, end=" ", file=self._fp)
if isinstance(v, header.Header):
print(v.encode(maxlinelen=self._maxheaderlen), file=self._fp)
else:
# email.Header got lots of smarts, so use it.
headers = header.Header(
v, maxlinelen=self._maxheaderlen, charset="utf-8", header_name=h
)
print(headers.encode(), file=self._fp)
# A blank line always separates headers from body.
print(file=self._fp)
return _write_headers
def _updateCache(request_headers, response_headers, content, cache, cachekey):
if cachekey:
cc = _parse_cache_control(request_headers)
cc_response = _parse_cache_control(response_headers)
if "no-store" in cc or "no-store" in cc_response:
cache.delete(cachekey)
else:
info = email.message.Message()
for key, value in response_headers.items():
if key not in ["status", "content-encoding", "transfer-encoding"]:
info[key] = value
# Add annotations to the cache to indicate what headers
# are variant for this request.
vary = response_headers.get("vary", None)
if vary:
vary_headers = vary.lower().replace(" ", "").split(",")
for header in vary_headers:
key = "-varied-%s" % header
try:
info[key] = request_headers[header]
except KeyError:
pass
status = response_headers.status
if status == 304:
status = 200
status_header = "status: %d\r\n" % status
try:
header_str = info.as_string()
except UnicodeEncodeError:
setattr(info, "_write_headers", _bind_write_headers(info))
header_str = info.as_string()
header_str = re.sub("\r(?!\n)|(?<!\r)\n", "\r\n", header_str)
text = b"".join(
[status_header.encode("utf-8"), header_str.encode("utf-8"), content]
)
cache.set(cachekey, text)
def _cnonce():
dig = _md5(
(
"%s:%s"
% (time.ctime(), ["0123456789"[random.randrange(0, 9)] for i in range(20)])
).encode("utf-8")
).hexdigest()
return dig[:16]
def _wsse_username_token(cnonce, iso_now, password):
return base64.b64encode(
_sha(("%s%s%s" % (cnonce, iso_now, password)).encode("utf-8")).digest()
).strip()
# For credentials we need two things, first
# a pool of credential to try (not necesarily tied to BAsic, Digest, etc.)
# Then we also need a list of URIs that have already demanded authentication
# That list is tricky since sub-URIs can take the same auth, or the
# auth scheme may change as you descend the tree.
# So we also need each Auth instance to be able to tell us
# how close to the 'top' it is.
class Authentication(object):
def __init__(
self, credentials, host, request_uri, headers, response, content, http
):
(scheme, authority, path, query, fragment) = parse_uri(request_uri)
self.path = path
self.host = host
self.credentials = credentials
self.http = http
def depth(self, request_uri):
(scheme, authority, path, query, fragment) = parse_uri(request_uri)
return request_uri[len(self.path) :].count("/")
def inscope(self, host, request_uri):
# XXX Should we normalize the request_uri?
(scheme, authority, path, query, fragment) = parse_uri(request_uri)
return (host == self.host) and path.startswith(self.path)
def request(self, method, request_uri, headers, content):
"""Modify the request headers to add the appropriate
Authorization header. Over-rise this in sub-classes."""
pass
def response(self, response, content):
"""Gives us a chance to update with new nonces
or such returned from the last authorized response.
Over-rise this in sub-classes if necessary.
Return TRUE is the request is to be retried, for
example Digest may return stale=true.
"""
return False
def __eq__(self, auth):
return False
def __ne__(self, auth):
return True
def __lt__(self, auth):
return True
def __gt__(self, auth):
return False
def __le__(self, auth):
return True
def __ge__(self, auth):
return False
def __bool__(self):
return True
class BasicAuthentication(Authentication):
def __init__(
self, credentials, host, request_uri, headers, response, content, http
):
Authentication.__init__(
self, credentials, host, request_uri, headers, response, content, http
)
def request(self, method, request_uri, headers, content):
"""Modify the request headers to add the appropriate
Authorization header."""
headers["authorization"] = "Basic " + base64.b64encode(
("%s:%s" % self.credentials).encode("utf-8")
).strip().decode("utf-8")
class DigestAuthentication(Authentication):
"""Only do qop='auth' and MD5, since that
is all Apache currently implements"""
def __init__(
self, credentials, host, request_uri, headers, response, content, http
):
Authentication.__init__(
self, credentials, host, request_uri, headers, response, content, http
)
challenge = _parse_www_authenticate(response, "www-authenticate")
self.challenge = challenge["digest"]
qop = self.challenge.get("qop", "auth")
self.challenge["qop"] = (
("auth" in [x.strip() for x in qop.split()]) and "auth" or None
)
if self.challenge["qop"] is None:
raise UnimplementedDigestAuthOptionError(
_("Unsupported value for qop: %s." % qop)
)
self.challenge["algorithm"] = self.challenge.get("algorithm", "MD5").upper()
if self.challenge["algorithm"] != "MD5":
raise UnimplementedDigestAuthOptionError(
_("Unsupported value for algorithm: %s." % self.challenge["algorithm"])
)
self.A1 = "".join(
[
self.credentials[0],
":",
self.challenge["realm"],
":",
self.credentials[1],
]
)
self.challenge["nc"] = 1
def request(self, method, request_uri, headers, content, cnonce=None):
"""Modify the request headers"""
H = lambda x: _md5(x.encode("utf-8")).hexdigest()
KD = lambda s, d: H("%s:%s" % (s, d))
A2 = "".join([method, ":", request_uri])
self.challenge["cnonce"] = cnonce or _cnonce()
request_digest = '"%s"' % KD(
H(self.A1),
"%s:%s:%s:%s:%s"
% (
self.challenge["nonce"],
"%08x" % self.challenge["nc"],
self.challenge["cnonce"],
self.challenge["qop"],
H(A2),
),
)
headers["authorization"] = (
'Digest username="%s", realm="%s", nonce="%s", '
'uri="%s", algorithm=%s, response=%s, qop=%s, '
'nc=%08x, cnonce="%s"'
) % (
self.credentials[0],
self.challenge["realm"],
self.challenge["nonce"],
request_uri,
self.challenge["algorithm"],
request_digest,
self.challenge["qop"],
self.challenge["nc"],
self.challenge["cnonce"],
)
if self.challenge.get("opaque"):
headers["authorization"] += ', opaque="%s"' % self.challenge["opaque"]
self.challenge["nc"] += 1
def response(self, response, content):
if "authentication-info" not in response:
challenge = _parse_www_authenticate(response, "www-authenticate").get(
"digest", {}
)
if "true" == challenge.get("stale"):
self.challenge["nonce"] = challenge["nonce"]
self.challenge["nc"] = 1
return True
else:
updated_challenge = _parse_www_authenticate(
response, "authentication-info"
).get("digest", {})
if "nextnonce" in updated_challenge:
self.challenge["nonce"] = updated_challenge["nextnonce"]
self.challenge["nc"] = 1
return False
class HmacDigestAuthentication(Authentication):
"""Adapted from Robert Sayre's code and DigestAuthentication above."""
__author__ = "Thomas Broyer (t.broyer@ltgt.net)"
def __init__(
self, credentials, host, request_uri, headers, response, content, http
):
Authentication.__init__(
self, credentials, host, request_uri, headers, response, content, http
)
challenge = _parse_www_authenticate(response, "www-authenticate")
self.challenge = challenge["hmacdigest"]
# TODO: self.challenge['domain']
self.challenge["reason"] = self.challenge.get("reason", "unauthorized")
if self.challenge["reason"] not in ["unauthorized", "integrity"]:
self.challenge["reason"] = "unauthorized"
self.challenge["salt"] = self.challenge.get("salt", "")
if not self.challenge.get("snonce"):
raise UnimplementedHmacDigestAuthOptionError(
_("The challenge doesn't contain a server nonce, or this one is empty.")
)
self.challenge["algorithm"] = self.challenge.get("algorithm", "HMAC-SHA-1")
if self.challenge["algorithm"] not in ["HMAC-SHA-1", "HMAC-MD5"]:
raise UnimplementedHmacDigestAuthOptionError(
_("Unsupported value for algorithm: %s." % self.challenge["algorithm"])
)
self.challenge["pw-algorithm"] = self.challenge.get("pw-algorithm", "SHA-1")
if self.challenge["pw-algorithm"] not in ["SHA-1", "MD5"]:
raise UnimplementedHmacDigestAuthOptionError(
_(
"Unsupported value for pw-algorithm: %s."
% self.challenge["pw-algorithm"]
)
)
if self.challenge["algorithm"] == "HMAC-MD5":
self.hashmod = _md5
else:
self.hashmod = _sha
if self.challenge["pw-algorithm"] == "MD5":
self.pwhashmod = _md5
else:
self.pwhashmod = _sha
self.key = "".join(
[
self.credentials[0],
":",
self.pwhashmod.new(
"".join([self.credentials[1], self.challenge["salt"]])
)
.hexdigest()
.lower(),
":",
self.challenge["realm"],
]
)
self.key = self.pwhashmod.new(self.key).hexdigest().lower()
def request(self, method, request_uri, headers, content):
"""Modify the request headers"""
keys = _get_end2end_headers(headers)
keylist = "".join(["%s " % k for k in keys])
headers_val = "".join([headers[k] for k in keys])
created = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
cnonce = _cnonce()
request_digest = "%s:%s:%s:%s:%s" % (
method,
request_uri,
cnonce,
self.challenge["snonce"],
headers_val,
)
request_digest = (
hmac.new(self.key, request_digest, self.hashmod).hexdigest().lower()
)
headers["authorization"] = (
'HMACDigest username="%s", realm="%s", snonce="%s",'
' cnonce="%s", uri="%s", created="%s", '
'response="%s", headers="%s"'
) % (
self.credentials[0],
self.challenge["realm"],
self.challenge["snonce"],
cnonce,
request_uri,
created,
request_digest,
keylist,
)
def response(self, response, content):
challenge = _parse_www_authenticate(response, "www-authenticate").get(
"hmacdigest", {}
)
if challenge.get("reason") in ["integrity", "stale"]:
return True
return False
class WsseAuthentication(Authentication):
"""This is thinly tested and should not be relied upon.
At this time there isn't any third party server to test against.
Blogger and TypePad implemented this algorithm at one point
but Blogger has since switched to Basic over HTTPS and
TypePad has implemented it wrong, by never issuing a 401
challenge but instead requiring your client to telepathically know that
their endpoint is expecting WSSE profile="UsernameToken"."""
def __init__(
self, credentials, host, request_uri, headers, response, content, http
):
Authentication.__init__(
self, credentials, host, request_uri, headers, response, content, http
)
def request(self, method, request_uri, headers, content):
"""Modify the request headers to add the appropriate
Authorization header."""
headers["authorization"] = 'WSSE profile="UsernameToken"'
iso_now = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
cnonce = _cnonce()
password_digest = _wsse_username_token(cnonce, iso_now, self.credentials[1])
headers["X-WSSE"] = (
'UsernameToken Username="%s", PasswordDigest="%s", '
'Nonce="%s", Created="%s"'
) % (self.credentials[0], password_digest, cnonce, iso_now)
class GoogleLoginAuthentication(Authentication):
def __init__(
self, credentials, host, request_uri, headers, response, content, http
):
from urllib.parse import urlencode
Authentication.__init__(
self, credentials, host, request_uri, headers, response, content, http
)
challenge = _parse_www_authenticate(response, "www-authenticate")
service = challenge["googlelogin"].get("service", "xapi")
# Bloggger actually returns the service in the challenge
# For the rest we guess based on the URI
if service == "xapi" and request_uri.find("calendar") > 0:
service = "cl"
# No point in guessing Base or Spreadsheet
# elif request_uri.find("spreadsheets") > 0:
# service = "wise"
auth = dict(
Email=credentials[0],
Passwd=credentials[1],
service=service,
source=headers["user-agent"],
)
resp, content = self.http.request(
"https://www.google.com/accounts/ClientLogin",
method="POST",
body=urlencode(auth),
headers={"Content-Type": "application/x-www-form-urlencoded"},
)
lines = content.split("\n")
d = dict([tuple(line.split("=", 1)) for line in lines if line])
if resp.status == 403:
self.Auth = ""
else:
self.Auth = d["Auth"]
def request(self, method, request_uri, headers, content):
"""Modify the request headers to add the appropriate
Authorization header."""
headers["authorization"] = "GoogleLogin Auth=" + self.Auth
AUTH_SCHEME_CLASSES = {
"basic": BasicAuthentication,
"wsse": WsseAuthentication,
"digest": DigestAuthentication,
"hmacdigest": HmacDigestAuthentication,
"googlelogin": GoogleLoginAuthentication,
}
AUTH_SCHEME_ORDER = ["hmacdigest", "googlelogin", "digest", "wsse", "basic"]
class FileCache(object):
"""Uses a local directory as a store for cached files.
Not really safe to use if multiple threads or processes are going to
be running on the same cache.
"""
def __init__(
self, cache, safe=safename
): # use safe=lambda x: md5.new(x).hexdigest() for the old behavior
self.cache = cache
self.safe = safe
if not os.path.exists(cache):
os.makedirs(self.cache)
def get(self, key):
retval = None
cacheFullPath = os.path.join(self.cache, self.safe(key))
try:
f = open(cacheFullPath, "rb")
retval = f.read()
f.close()
except IOError:
pass
return retval
def set(self, key, value):
cacheFullPath = os.path.join(self.cache, self.safe(key))
f = open(cacheFullPath, "wb")
f.write(value)
f.close()
def delete(self, key):
cacheFullPath = os.path.join(self.cache, self.safe(key))
if os.path.exists(cacheFullPath):
os.remove(cacheFullPath)
class Credentials(object):
def __init__(self):
self.credentials = []
def add(self, name, password, domain=""):
self.credentials.append((domain.lower(), name, password))
def clear(self):
self.credentials = []
def iter(self, domain):
for (cdomain, name, password) in self.credentials:
if cdomain == "" or domain == cdomain:
yield (name, password)
class KeyCerts(Credentials):
"""Identical to Credentials except that
name/password are mapped to key/cert."""
def add(self, key, cert, domain, password):
self.credentials.append((domain.lower(), key, cert, password))
def iter(self, domain):
for (cdomain, key, cert, password) in self.credentials:
if cdomain == "" or domain == cdomain:
yield (key, cert, password)
class AllHosts(object):
pass
class ProxyInfo(object):
"""Collect information required to use a proxy."""
bypass_hosts = ()
def __init__(
self,
proxy_type,
proxy_host,
proxy_port,
proxy_rdns=True,
proxy_user=None,
proxy_pass=None,
proxy_headers=None,
):
"""Args:
proxy_type: The type of proxy server. This must be set to one of
socks.PROXY_TYPE_XXX constants. For example: p =
ProxyInfo(proxy_type=socks.PROXY_TYPE_HTTP, proxy_host='localhost',
proxy_port=8000)
proxy_host: The hostname or IP address of the proxy server.