client.py 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495
  1. r"""HTTP/1.1 client library
  2. <intro stuff goes here>
  3. <other stuff, too>
  4. HTTPConnection goes through a number of "states", which define when a client
  5. may legally make another request or fetch the response for a particular
  6. request. This diagram details these state transitions:
  7. (null)
  8. |
  9. | HTTPConnection()
  10. v
  11. Idle
  12. |
  13. | putrequest()
  14. v
  15. Request-started
  16. |
  17. | ( putheader() )* endheaders()
  18. v
  19. Request-sent
  20. |\_____________________________
  21. | | getresponse() raises
  22. | response = getresponse() | ConnectionError
  23. v v
  24. Unread-response Idle
  25. [Response-headers-read]
  26. |\____________________
  27. | |
  28. | response.read() | putrequest()
  29. v v
  30. Idle Req-started-unread-response
  31. ______/|
  32. / |
  33. response.read() | | ( putheader() )* endheaders()
  34. v v
  35. Request-started Req-sent-unread-response
  36. |
  37. | response.read()
  38. v
  39. Request-sent
  40. This diagram presents the following rules:
  41. -- a second request may not be started until {response-headers-read}
  42. -- a response [object] cannot be retrieved until {request-sent}
  43. -- there is no differentiation between an unread response body and a
  44. partially read response body
  45. Note: this enforcement is applied by the HTTPConnection class. The
  46. HTTPResponse class does not enforce this state machine, which
  47. implies sophisticated clients may accelerate the request/response
  48. pipeline. Caution should be taken, though: accelerating the states
  49. beyond the above pattern may imply knowledge of the server's
  50. connection-close behavior for certain requests. For example, it
  51. is impossible to tell whether the server will close the connection
  52. UNTIL the response headers have been read; this means that further
  53. requests cannot be placed into the pipeline until it is known that
  54. the server will NOT be closing the connection.
  55. Logical State __state __response
  56. ------------- ------- ----------
  57. Idle _CS_IDLE None
  58. Request-started _CS_REQ_STARTED None
  59. Request-sent _CS_REQ_SENT None
  60. Unread-response _CS_IDLE <response_class>
  61. Req-started-unread-response _CS_REQ_STARTED <response_class>
  62. Req-sent-unread-response _CS_REQ_SENT <response_class>
  63. """
  64. import email.parser
  65. import email.message
  66. import http
  67. import io
  68. import re
  69. import socket
  70. import collections.abc
  71. from urllib.parse import urlsplit
  72. # HTTPMessage, parse_headers(), and the HTTP status code constants are
  73. # intentionally omitted for simplicity
  74. __all__ = ["HTTPResponse", "HTTPConnection",
  75. "HTTPException", "NotConnected", "UnknownProtocol",
  76. "UnknownTransferEncoding", "UnimplementedFileMode",
  77. "IncompleteRead", "InvalidURL", "ImproperConnectionState",
  78. "CannotSendRequest", "CannotSendHeader", "ResponseNotReady",
  79. "BadStatusLine", "LineTooLong", "RemoteDisconnected", "error",
  80. "responses"]
  81. HTTP_PORT = 80
  82. HTTPS_PORT = 443
  83. _UNKNOWN = 'UNKNOWN'
  84. # connection states
  85. _CS_IDLE = 'Idle'
  86. _CS_REQ_STARTED = 'Request-started'
  87. _CS_REQ_SENT = 'Request-sent'
  88. # hack to maintain backwards compatibility
  89. globals().update(http.HTTPStatus.__members__)
  90. # another hack to maintain backwards compatibility
  91. # Mapping status codes to official W3C names
  92. responses = {v: v.phrase for v in http.HTTPStatus.__members__.values()}
  93. # maximal line length when calling readline().
  94. _MAXLINE = 65536
  95. _MAXHEADERS = 100
  96. # Header name/value ABNF (http://tools.ietf.org/html/rfc7230#section-3.2)
  97. #
  98. # VCHAR = %x21-7E
  99. # obs-text = %x80-FF
  100. # header-field = field-name ":" OWS field-value OWS
  101. # field-name = token
  102. # field-value = *( field-content / obs-fold )
  103. # field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
  104. # field-vchar = VCHAR / obs-text
  105. #
  106. # obs-fold = CRLF 1*( SP / HTAB )
  107. # ; obsolete line folding
  108. # ; see Section 3.2.4
  109. # token = 1*tchar
  110. #
  111. # tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*"
  112. # / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~"
  113. # / DIGIT / ALPHA
  114. # ; any VCHAR, except delimiters
  115. #
  116. # VCHAR defined in http://tools.ietf.org/html/rfc5234#appendix-B.1
  117. # the patterns for both name and value are more lenient than RFC
  118. # definitions to allow for backwards compatibility
  119. _is_legal_header_name = re.compile(rb'[^:\s][^:\r\n]*').fullmatch
  120. _is_illegal_header_value = re.compile(rb'\n(?![ \t])|\r(?![ \t\n])').search
  121. # These characters are not allowed within HTTP URL paths.
  122. # See https://tools.ietf.org/html/rfc3986#section-3.3 and the
  123. # https://tools.ietf.org/html/rfc3986#appendix-A pchar definition.
  124. # Prevents CVE-2019-9740. Includes control characters such as \r\n.
  125. # We don't restrict chars above \x7f as putrequest() limits us to ASCII.
  126. _contains_disallowed_url_pchar_re = re.compile('[\x00-\x20\x7f]')
  127. # Arguably only these _should_ allowed:
  128. # _is_allowed_url_pchars_re = re.compile(r"^[/!$&'()*+,;=:@%a-zA-Z0-9._~-]+$")
  129. # We are more lenient for assumed real world compatibility purposes.
  130. # These characters are not allowed within HTTP method names
  131. # to prevent http header injection.
  132. _contains_disallowed_method_pchar_re = re.compile('[\x00-\x1f]')
  133. # We always set the Content-Length header for these methods because some
  134. # servers will otherwise respond with a 411
  135. _METHODS_EXPECTING_BODY = {'PATCH', 'POST', 'PUT'}
  136. def _encode(data, name='data'):
  137. """Call data.encode("latin-1") but show a better error message."""
  138. try:
  139. return data.encode("latin-1")
  140. except UnicodeEncodeError as err:
  141. raise UnicodeEncodeError(
  142. err.encoding,
  143. err.object,
  144. err.start,
  145. err.end,
  146. "%s (%.20r) is not valid Latin-1. Use %s.encode('utf-8') "
  147. "if you want to send it encoded in UTF-8." %
  148. (name.title(), data[err.start:err.end], name)) from None
  149. class HTTPMessage(email.message.Message):
  150. # XXX The only usage of this method is in
  151. # http.server.CGIHTTPRequestHandler. Maybe move the code there so
  152. # that it doesn't need to be part of the public API. The API has
  153. # never been defined so this could cause backwards compatibility
  154. # issues.
  155. def getallmatchingheaders(self, name):
  156. """Find all header lines matching a given header name.
  157. Look through the list of headers and find all lines matching a given
  158. header name (and their continuation lines). A list of the lines is
  159. returned, without interpretation. If the header does not occur, an
  160. empty list is returned. If the header occurs multiple times, all
  161. occurrences are returned. Case is not important in the header name.
  162. """
  163. name = name.lower() + ':'
  164. n = len(name)
  165. lst = []
  166. hit = 0
  167. for line in self.keys():
  168. if line[:n].lower() == name:
  169. hit = 1
  170. elif not line[:1].isspace():
  171. hit = 0
  172. if hit:
  173. lst.append(line)
  174. return lst
  175. def parse_headers(fp, _class=HTTPMessage):
  176. """Parses only RFC2822 headers from a file pointer.
  177. email Parser wants to see strings rather than bytes.
  178. But a TextIOWrapper around self.rfile would buffer too many bytes
  179. from the stream, bytes which we later need to read as bytes.
  180. So we read the correct bytes here, as bytes, for email Parser
  181. to parse.
  182. """
  183. headers = []
  184. while True:
  185. line = fp.readline(_MAXLINE + 1)
  186. if len(line) > _MAXLINE:
  187. raise LineTooLong("header line")
  188. headers.append(line)
  189. if len(headers) > _MAXHEADERS:
  190. raise HTTPException("got more than %d headers" % _MAXHEADERS)
  191. if line in (b'\r\n', b'\n', b''):
  192. break
  193. hstring = b''.join(headers).decode('iso-8859-1')
  194. return email.parser.Parser(_class=_class).parsestr(hstring)
  195. class HTTPResponse(io.BufferedIOBase):
  196. # See RFC 2616 sec 19.6 and RFC 1945 sec 6 for details.
  197. # The bytes from the socket object are iso-8859-1 strings.
  198. # See RFC 2616 sec 2.2 which notes an exception for MIME-encoded
  199. # text following RFC 2047. The basic status line parsing only
  200. # accepts iso-8859-1.
  201. def __init__(self, sock, debuglevel=0, method=None, url=None):
  202. # If the response includes a content-length header, we need to
  203. # make sure that the client doesn't read more than the
  204. # specified number of bytes. If it does, it will block until
  205. # the server times out and closes the connection. This will
  206. # happen if a self.fp.read() is done (without a size) whether
  207. # self.fp is buffered or not. So, no self.fp.read() by
  208. # clients unless they know what they are doing.
  209. self.fp = sock.makefile("rb")
  210. self.debuglevel = debuglevel
  211. self._method = method
  212. # The HTTPResponse object is returned via urllib. The clients
  213. # of http and urllib expect different attributes for the
  214. # headers. headers is used here and supports urllib. msg is
  215. # provided as a backwards compatibility layer for http
  216. # clients.
  217. self.headers = self.msg = None
  218. # from the Status-Line of the response
  219. self.version = _UNKNOWN # HTTP-Version
  220. self.status = _UNKNOWN # Status-Code
  221. self.reason = _UNKNOWN # Reason-Phrase
  222. self.chunked = _UNKNOWN # is "chunked" being used?
  223. self.chunk_left = _UNKNOWN # bytes left to read in current chunk
  224. self.length = _UNKNOWN # number of bytes left in response
  225. self.will_close = _UNKNOWN # conn will close at end of response
  226. def _read_status(self):
  227. line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
  228. if len(line) > _MAXLINE:
  229. raise LineTooLong("status line")
  230. if self.debuglevel > 0:
  231. print("reply:", repr(line))
  232. if not line:
  233. # Presumably, the server closed the connection before
  234. # sending a valid response.
  235. raise RemoteDisconnected("Remote end closed connection without"
  236. " response")
  237. try:
  238. version, status, reason = line.split(None, 2)
  239. except ValueError:
  240. try:
  241. version, status = line.split(None, 1)
  242. reason = ""
  243. except ValueError:
  244. # empty version will cause next test to fail.
  245. version = ""
  246. if not version.startswith("HTTP/"):
  247. self._close_conn()
  248. raise BadStatusLine(line)
  249. # The status code is a three-digit number
  250. try:
  251. status = int(status)
  252. if status < 100 or status > 999:
  253. raise BadStatusLine(line)
  254. except ValueError:
  255. raise BadStatusLine(line)
  256. return version, status, reason
  257. def begin(self):
  258. if self.headers is not None:
  259. # we've already started reading the response
  260. return
  261. # read until we get a non-100 response
  262. while True:
  263. version, status, reason = self._read_status()
  264. if status != CONTINUE:
  265. break
  266. # skip the header from the 100 response
  267. while True:
  268. skip = self.fp.readline(_MAXLINE + 1)
  269. if len(skip) > _MAXLINE:
  270. raise LineTooLong("header line")
  271. skip = skip.strip()
  272. if not skip:
  273. break
  274. if self.debuglevel > 0:
  275. print("header:", skip)
  276. self.code = self.status = status
  277. self.reason = reason.strip()
  278. if version in ("HTTP/1.0", "HTTP/0.9"):
  279. # Some servers might still return "0.9", treat it as 1.0 anyway
  280. self.version = 10
  281. elif version.startswith("HTTP/1."):
  282. self.version = 11 # use HTTP/1.1 code for HTTP/1.x where x>=1
  283. else:
  284. raise UnknownProtocol(version)
  285. self.headers = self.msg = parse_headers(self.fp)
  286. if self.debuglevel > 0:
  287. for hdr, val in self.headers.items():
  288. print("header:", hdr + ":", val)
  289. # are we using the chunked-style of transfer encoding?
  290. tr_enc = self.headers.get("transfer-encoding")
  291. if tr_enc and tr_enc.lower() == "chunked":
  292. self.chunked = True
  293. self.chunk_left = None
  294. else:
  295. self.chunked = False
  296. # will the connection close at the end of the response?
  297. self.will_close = self._check_close()
  298. # do we have a Content-Length?
  299. # NOTE: RFC 2616, S4.4, #3 says we ignore this if tr_enc is "chunked"
  300. self.length = None
  301. length = self.headers.get("content-length")
  302. # are we using the chunked-style of transfer encoding?
  303. tr_enc = self.headers.get("transfer-encoding")
  304. if length and not self.chunked:
  305. try:
  306. self.length = int(length)
  307. except ValueError:
  308. self.length = None
  309. else:
  310. if self.length < 0: # ignore nonsensical negative lengths
  311. self.length = None
  312. else:
  313. self.length = None
  314. # does the body have a fixed length? (of zero)
  315. if (status == NO_CONTENT or status == NOT_MODIFIED or
  316. 100 <= status < 200 or # 1xx codes
  317. self._method == "HEAD"):
  318. self.length = 0
  319. # if the connection remains open, and we aren't using chunked, and
  320. # a content-length was not provided, then assume that the connection
  321. # WILL close.
  322. if (not self.will_close and
  323. not self.chunked and
  324. self.length is None):
  325. self.will_close = True
  326. def _check_close(self):
  327. conn = self.headers.get("connection")
  328. if self.version == 11:
  329. # An HTTP/1.1 proxy is assumed to stay open unless
  330. # explicitly closed.
  331. if conn and "close" in conn.lower():
  332. return True
  333. return False
  334. # Some HTTP/1.0 implementations have support for persistent
  335. # connections, using rules different than HTTP/1.1.
  336. # For older HTTP, Keep-Alive indicates persistent connection.
  337. if self.headers.get("keep-alive"):
  338. return False
  339. # At least Akamai returns a "Connection: Keep-Alive" header,
  340. # which was supposed to be sent by the client.
  341. if conn and "keep-alive" in conn.lower():
  342. return False
  343. # Proxy-Connection is a netscape hack.
  344. pconn = self.headers.get("proxy-connection")
  345. if pconn and "keep-alive" in pconn.lower():
  346. return False
  347. # otherwise, assume it will close
  348. return True
  349. def _close_conn(self):
  350. fp = self.fp
  351. self.fp = None
  352. fp.close()
  353. def close(self):
  354. try:
  355. super().close() # set "closed" flag
  356. finally:
  357. if self.fp:
  358. self._close_conn()
  359. # These implementations are for the benefit of io.BufferedReader.
  360. # XXX This class should probably be revised to act more like
  361. # the "raw stream" that BufferedReader expects.
  362. def flush(self):
  363. super().flush()
  364. if self.fp:
  365. self.fp.flush()
  366. def readable(self):
  367. """Always returns True"""
  368. return True
  369. # End of "raw stream" methods
  370. def isclosed(self):
  371. """True if the connection is closed."""
  372. # NOTE: it is possible that we will not ever call self.close(). This
  373. # case occurs when will_close is TRUE, length is None, and we
  374. # read up to the last byte, but NOT past it.
  375. #
  376. # IMPLIES: if will_close is FALSE, then self.close() will ALWAYS be
  377. # called, meaning self.isclosed() is meaningful.
  378. return self.fp is None
  379. def read(self, amt=None):
  380. if self.fp is None:
  381. return b""
  382. if self._method == "HEAD":
  383. self._close_conn()
  384. return b""
  385. if amt is not None:
  386. # Amount is given, implement using readinto
  387. b = bytearray(amt)
  388. n = self.readinto(b)
  389. return memoryview(b)[:n].tobytes()
  390. else:
  391. # Amount is not given (unbounded read) so we must check self.length
  392. # and self.chunked
  393. if self.chunked:
  394. return self._readall_chunked()
  395. if self.length is None:
  396. s = self.fp.read()
  397. else:
  398. try:
  399. s = self._safe_read(self.length)
  400. except IncompleteRead:
  401. self._close_conn()
  402. raise
  403. self.length = 0
  404. self._close_conn() # we read everything
  405. return s
  406. def readinto(self, b):
  407. """Read up to len(b) bytes into bytearray b and return the number
  408. of bytes read.
  409. """
  410. if self.fp is None:
  411. return 0
  412. if self._method == "HEAD":
  413. self._close_conn()
  414. return 0
  415. if self.chunked:
  416. return self._readinto_chunked(b)
  417. if self.length is not None:
  418. if len(b) > self.length:
  419. # clip the read to the "end of response"
  420. b = memoryview(b)[0:self.length]
  421. # we do not use _safe_read() here because this may be a .will_close
  422. # connection, and the user is reading more bytes than will be provided
  423. # (for example, reading in 1k chunks)
  424. n = self.fp.readinto(b)
  425. if not n and b:
  426. # Ideally, we would raise IncompleteRead if the content-length
  427. # wasn't satisfied, but it might break compatibility.
  428. self._close_conn()
  429. elif self.length is not None:
  430. self.length -= n
  431. if not self.length:
  432. self._close_conn()
  433. return n
  434. def _read_next_chunk_size(self):
  435. # Read the next chunk size from the file
  436. line = self.fp.readline(_MAXLINE + 1)
  437. if len(line) > _MAXLINE:
  438. raise LineTooLong("chunk size")
  439. i = line.find(b";")
  440. if i >= 0:
  441. line = line[:i] # strip chunk-extensions
  442. try:
  443. return int(line, 16)
  444. except ValueError:
  445. # close the connection as protocol synchronisation is
  446. # probably lost
  447. self._close_conn()
  448. raise
  449. def _read_and_discard_trailer(self):
  450. # read and discard trailer up to the CRLF terminator
  451. ### note: we shouldn't have any trailers!
  452. while True:
  453. line = self.fp.readline(_MAXLINE + 1)
  454. if len(line) > _MAXLINE:
  455. raise LineTooLong("trailer line")
  456. if not line:
  457. # a vanishingly small number of sites EOF without
  458. # sending the trailer
  459. break
  460. if line in (b'\r\n', b'\n', b''):
  461. break
  462. def _get_chunk_left(self):
  463. # return self.chunk_left, reading a new chunk if necessary.
  464. # chunk_left == 0: at the end of the current chunk, need to close it
  465. # chunk_left == None: No current chunk, should read next.
  466. # This function returns non-zero or None if the last chunk has
  467. # been read.
  468. chunk_left = self.chunk_left
  469. if not chunk_left: # Can be 0 or None
  470. if chunk_left is not None:
  471. # We are at the end of chunk, discard chunk end
  472. self._safe_read(2) # toss the CRLF at the end of the chunk
  473. try:
  474. chunk_left = self._read_next_chunk_size()
  475. except ValueError:
  476. raise IncompleteRead(b'')
  477. if chunk_left == 0:
  478. # last chunk: 1*("0") [ chunk-extension ] CRLF
  479. self._read_and_discard_trailer()
  480. # we read everything; close the "file"
  481. self._close_conn()
  482. chunk_left = None
  483. self.chunk_left = chunk_left
  484. return chunk_left
  485. def _readall_chunked(self):
  486. assert self.chunked != _UNKNOWN
  487. value = []
  488. try:
  489. while True:
  490. chunk_left = self._get_chunk_left()
  491. if chunk_left is None:
  492. break
  493. value.append(self._safe_read(chunk_left))
  494. self.chunk_left = 0
  495. return b''.join(value)
  496. except IncompleteRead:
  497. raise IncompleteRead(b''.join(value))
  498. def _readinto_chunked(self, b):
  499. assert self.chunked != _UNKNOWN
  500. total_bytes = 0
  501. mvb = memoryview(b)
  502. try:
  503. while True:
  504. chunk_left = self._get_chunk_left()
  505. if chunk_left is None:
  506. return total_bytes
  507. if len(mvb) <= chunk_left:
  508. n = self._safe_readinto(mvb)
  509. self.chunk_left = chunk_left - n
  510. return total_bytes + n
  511. temp_mvb = mvb[:chunk_left]
  512. n = self._safe_readinto(temp_mvb)
  513. mvb = mvb[n:]
  514. total_bytes += n
  515. self.chunk_left = 0
  516. except IncompleteRead:
  517. raise IncompleteRead(bytes(b[0:total_bytes]))
  518. def _safe_read(self, amt):
  519. """Read the number of bytes requested.
  520. This function should be used when <amt> bytes "should" be present for
  521. reading. If the bytes are truly not available (due to EOF), then the
  522. IncompleteRead exception can be used to detect the problem.
  523. """
  524. data = self.fp.read(amt)
  525. if len(data) < amt:
  526. raise IncompleteRead(data, amt-len(data))
  527. return data
  528. def _safe_readinto(self, b):
  529. """Same as _safe_read, but for reading into a buffer."""
  530. amt = len(b)
  531. n = self.fp.readinto(b)
  532. if n < amt:
  533. raise IncompleteRead(bytes(b[:n]), amt-n)
  534. return n
  535. def read1(self, n=-1):
  536. """Read with at most one underlying system call. If at least one
  537. byte is buffered, return that instead.
  538. """
  539. if self.fp is None or self._method == "HEAD":
  540. return b""
  541. if self.chunked:
  542. return self._read1_chunked(n)
  543. if self.length is not None and (n < 0 or n > self.length):
  544. n = self.length
  545. result = self.fp.read1(n)
  546. if not result and n:
  547. self._close_conn()
  548. elif self.length is not None:
  549. self.length -= len(result)
  550. return result
  551. def peek(self, n=-1):
  552. # Having this enables IOBase.readline() to read more than one
  553. # byte at a time
  554. if self.fp is None or self._method == "HEAD":
  555. return b""
  556. if self.chunked:
  557. return self._peek_chunked(n)
  558. return self.fp.peek(n)
  559. def readline(self, limit=-1):
  560. if self.fp is None or self._method == "HEAD":
  561. return b""
  562. if self.chunked:
  563. # Fallback to IOBase readline which uses peek() and read()
  564. return super().readline(limit)
  565. if self.length is not None and (limit < 0 or limit > self.length):
  566. limit = self.length
  567. result = self.fp.readline(limit)
  568. if not result and limit:
  569. self._close_conn()
  570. elif self.length is not None:
  571. self.length -= len(result)
  572. return result
  573. def _read1_chunked(self, n):
  574. # Strictly speaking, _get_chunk_left() may cause more than one read,
  575. # but that is ok, since that is to satisfy the chunked protocol.
  576. chunk_left = self._get_chunk_left()
  577. if chunk_left is None or n == 0:
  578. return b''
  579. if not (0 <= n <= chunk_left):
  580. n = chunk_left # if n is negative or larger than chunk_left
  581. read = self.fp.read1(n)
  582. self.chunk_left -= len(read)
  583. if not read:
  584. raise IncompleteRead(b"")
  585. return read
  586. def _peek_chunked(self, n):
  587. # Strictly speaking, _get_chunk_left() may cause more than one read,
  588. # but that is ok, since that is to satisfy the chunked protocol.
  589. try:
  590. chunk_left = self._get_chunk_left()
  591. except IncompleteRead:
  592. return b'' # peek doesn't worry about protocol
  593. if chunk_left is None:
  594. return b'' # eof
  595. # peek is allowed to return more than requested. Just request the
  596. # entire chunk, and truncate what we get.
  597. return self.fp.peek(chunk_left)[:chunk_left]
  598. def fileno(self):
  599. return self.fp.fileno()
  600. def getheader(self, name, default=None):
  601. '''Returns the value of the header matching *name*.
  602. If there are multiple matching headers, the values are
  603. combined into a single string separated by commas and spaces.
  604. If no matching header is found, returns *default* or None if
  605. the *default* is not specified.
  606. If the headers are unknown, raises http.client.ResponseNotReady.
  607. '''
  608. if self.headers is None:
  609. raise ResponseNotReady()
  610. headers = self.headers.get_all(name) or default
  611. if isinstance(headers, str) or not hasattr(headers, '__iter__'):
  612. return headers
  613. else:
  614. return ', '.join(headers)
  615. def getheaders(self):
  616. """Return list of (header, value) tuples."""
  617. if self.headers is None:
  618. raise ResponseNotReady()
  619. return list(self.headers.items())
  620. # We override IOBase.__iter__ so that it doesn't check for closed-ness
  621. def __iter__(self):
  622. return self
  623. # For compatibility with old-style urllib responses.
  624. def info(self):
  625. '''Returns an instance of the class mimetools.Message containing
  626. meta-information associated with the URL.
  627. When the method is HTTP, these headers are those returned by
  628. the server at the head of the retrieved HTML page (including
  629. Content-Length and Content-Type).
  630. When the method is FTP, a Content-Length header will be
  631. present if (as is now usual) the server passed back a file
  632. length in response to the FTP retrieval request. A
  633. Content-Type header will be present if the MIME type can be
  634. guessed.
  635. When the method is local-file, returned headers will include
  636. a Date representing the file's last-modified time, a
  637. Content-Length giving file size, and a Content-Type
  638. containing a guess at the file's type. See also the
  639. description of the mimetools module.
  640. '''
  641. return self.headers
  642. def geturl(self):
  643. '''Return the real URL of the page.
  644. In some cases, the HTTP server redirects a client to another
  645. URL. The urlopen() function handles this transparently, but in
  646. some cases the caller needs to know which URL the client was
  647. redirected to. The geturl() method can be used to get at this
  648. redirected URL.
  649. '''
  650. return self.url
  651. def getcode(self):
  652. '''Return the HTTP status code that was sent with the response,
  653. or None if the URL is not an HTTP URL.
  654. '''
  655. return self.status
  656. class HTTPConnection:
  657. _http_vsn = 11
  658. _http_vsn_str = 'HTTP/1.1'
  659. response_class = HTTPResponse
  660. default_port = HTTP_PORT
  661. auto_open = 1
  662. debuglevel = 0
  663. @staticmethod
  664. def _is_textIO(stream):
  665. """Test whether a file-like object is a text or a binary stream.
  666. """
  667. return isinstance(stream, io.TextIOBase)
  668. @staticmethod
  669. def _get_content_length(body, method):
  670. """Get the content-length based on the body.
  671. If the body is None, we set Content-Length: 0 for methods that expect
  672. a body (RFC 7230, Section 3.3.2). We also set the Content-Length for
  673. any method if the body is a str or bytes-like object and not a file.
  674. """
  675. if body is None:
  676. # do an explicit check for not None here to distinguish
  677. # between unset and set but empty
  678. if method.upper() in _METHODS_EXPECTING_BODY:
  679. return 0
  680. else:
  681. return None
  682. if hasattr(body, 'read'):
  683. # file-like object.
  684. return None
  685. try:
  686. # does it implement the buffer protocol (bytes, bytearray, array)?
  687. mv = memoryview(body)
  688. return mv.nbytes
  689. except TypeError:
  690. pass
  691. if isinstance(body, str):
  692. return len(body)
  693. return None
  694. def __init__(self, host, port=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
  695. source_address=None, blocksize=8192):
  696. self.timeout = timeout
  697. self.source_address = source_address
  698. self.blocksize = blocksize
  699. self.sock = None
  700. self._buffer = []
  701. self.__response = None
  702. self.__state = _CS_IDLE
  703. self._method = None
  704. self._tunnel_host = None
  705. self._tunnel_port = None
  706. self._tunnel_headers = {}
  707. (self.host, self.port) = self._get_hostport(host, port)
  708. self._validate_host(self.host)
  709. # This is stored as an instance variable to allow unit
  710. # tests to replace it with a suitable mockup
  711. self._create_connection = socket.create_connection
  712. def set_tunnel(self, host, port=None, headers=None):
  713. """Set up host and port for HTTP CONNECT tunnelling.
  714. In a connection that uses HTTP CONNECT tunneling, the host passed to the
  715. constructor is used as a proxy server that relays all communication to
  716. the endpoint passed to `set_tunnel`. This done by sending an HTTP
  717. CONNECT request to the proxy server when the connection is established.
  718. This method must be called before the HTML connection has been
  719. established.
  720. The headers argument should be a mapping of extra HTTP headers to send
  721. with the CONNECT request.
  722. """
  723. if self.sock:
  724. raise RuntimeError("Can't set up tunnel for established connection")
  725. self._tunnel_host, self._tunnel_port = self._get_hostport(host, port)
  726. if headers:
  727. self._tunnel_headers = headers
  728. else:
  729. self._tunnel_headers.clear()
  730. def _get_hostport(self, host, port):
  731. if port is None:
  732. i = host.rfind(':')
  733. j = host.rfind(']') # ipv6 addresses have [...]
  734. if i > j:
  735. try:
  736. port = int(host[i+1:])
  737. except ValueError:
  738. if host[i+1:] == "": # http://foo.com:/ == http://foo.com/
  739. port = self.default_port
  740. else:
  741. raise InvalidURL("nonnumeric port: '%s'" % host[i+1:])
  742. host = host[:i]
  743. else:
  744. port = self.default_port
  745. if host and host[0] == '[' and host[-1] == ']':
  746. host = host[1:-1]
  747. return (host, port)
  748. def set_debuglevel(self, level):
  749. self.debuglevel = level
  750. def _tunnel(self):
  751. connect_str = "CONNECT %s:%d HTTP/1.0\r\n" % (self._tunnel_host,
  752. self._tunnel_port)
  753. connect_bytes = connect_str.encode("ascii")
  754. self.send(connect_bytes)
  755. for header, value in self._tunnel_headers.items():
  756. header_str = "%s: %s\r\n" % (header, value)
  757. header_bytes = header_str.encode("latin-1")
  758. self.send(header_bytes)
  759. self.send(b'\r\n')
  760. response = self.response_class(self.sock, method=self._method)
  761. (version, code, message) = response._read_status()
  762. if code != http.HTTPStatus.OK:
  763. self.close()
  764. raise OSError("Tunnel connection failed: %d %s" % (code,
  765. message.strip()))
  766. while True:
  767. line = response.fp.readline(_MAXLINE + 1)
  768. if len(line) > _MAXLINE:
  769. raise LineTooLong("header line")
  770. if not line:
  771. # for sites which EOF without sending a trailer
  772. break
  773. if line in (b'\r\n', b'\n', b''):
  774. break
  775. if self.debuglevel > 0:
  776. print('header:', line.decode())
  777. def connect(self):
  778. """Connect to the host and port specified in __init__."""
  779. self.sock = self._create_connection(
  780. (self.host,self.port), self.timeout, self.source_address)
  781. self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
  782. if self._tunnel_host:
  783. self._tunnel()
  784. def close(self):
  785. """Close the connection to the HTTP server."""
  786. self.__state = _CS_IDLE
  787. try:
  788. sock = self.sock
  789. if sock:
  790. self.sock = None
  791. sock.close() # close it manually... there may be other refs
  792. finally:
  793. response = self.__response
  794. if response:
  795. self.__response = None
  796. response.close()
  797. def send(self, data):
  798. """Send `data' to the server.
  799. ``data`` can be a string object, a bytes object, an array object, a
  800. file-like object that supports a .read() method, or an iterable object.
  801. """
  802. if self.sock is None:
  803. if self.auto_open:
  804. self.connect()
  805. else:
  806. raise NotConnected()
  807. if self.debuglevel > 0:
  808. print("send:", repr(data))
  809. if hasattr(data, "read") :
  810. if self.debuglevel > 0:
  811. print("sendIng a read()able")
  812. encode = self._is_textIO(data)
  813. if encode and self.debuglevel > 0:
  814. print("encoding file using iso-8859-1")
  815. while 1:
  816. datablock = data.read(self.blocksize)
  817. if not datablock:
  818. break
  819. if encode:
  820. datablock = datablock.encode("iso-8859-1")
  821. self.sock.sendall(datablock)
  822. return
  823. try:
  824. self.sock.sendall(data)
  825. except TypeError:
  826. if isinstance(data, collections.abc.Iterable):
  827. for d in data:
  828. self.sock.sendall(d)
  829. else:
  830. raise TypeError("data should be a bytes-like object "
  831. "or an iterable, got %r" % type(data))
  832. def _output(self, s):
  833. """Add a line of output to the current request buffer.
  834. Assumes that the line does *not* end with \\r\\n.
  835. """
  836. self._buffer.append(s)
  837. def _read_readable(self, readable):
  838. if self.debuglevel > 0:
  839. print("sendIng a read()able")
  840. encode = self._is_textIO(readable)
  841. if encode and self.debuglevel > 0:
  842. print("encoding file using iso-8859-1")
  843. while True:
  844. datablock = readable.read(self.blocksize)
  845. if not datablock:
  846. break
  847. if encode:
  848. datablock = datablock.encode("iso-8859-1")
  849. yield datablock
  850. def _send_output(self, message_body=None, encode_chunked=False):
  851. """Send the currently buffered request and clear the buffer.
  852. Appends an extra \\r\\n to the buffer.
  853. A message_body may be specified, to be appended to the request.
  854. """
  855. self._buffer.extend((b"", b""))
  856. msg = b"\r\n".join(self._buffer)
  857. del self._buffer[:]
  858. self.send(msg)
  859. if message_body is not None:
  860. # create a consistent interface to message_body
  861. if hasattr(message_body, 'read'):
  862. # Let file-like take precedence over byte-like. This
  863. # is needed to allow the current position of mmap'ed
  864. # files to be taken into account.
  865. chunks = self._read_readable(message_body)
  866. else:
  867. try:
  868. # this is solely to check to see if message_body
  869. # implements the buffer API. it /would/ be easier
  870. # to capture if PyObject_CheckBuffer was exposed
  871. # to Python.
  872. memoryview(message_body)
  873. except TypeError:
  874. try:
  875. chunks = iter(message_body)
  876. except TypeError:
  877. raise TypeError("message_body should be a bytes-like "
  878. "object or an iterable, got %r"
  879. % type(message_body))
  880. else:
  881. # the object implements the buffer interface and
  882. # can be passed directly into socket methods
  883. chunks = (message_body,)
  884. for chunk in chunks:
  885. if not chunk:
  886. if self.debuglevel > 0:
  887. print('Zero length chunk ignored')
  888. continue
  889. if encode_chunked and self._http_vsn == 11:
  890. # chunked encoding
  891. chunk = f'{len(chunk):X}\r\n'.encode('ascii') + chunk \
  892. + b'\r\n'
  893. self.send(chunk)
  894. if encode_chunked and self._http_vsn == 11:
  895. # end chunked transfer
  896. self.send(b'0\r\n\r\n')
  897. def putrequest(self, method, url, skip_host=False,
  898. skip_accept_encoding=False):
  899. """Send a request to the server.
  900. `method' specifies an HTTP request method, e.g. 'GET'.
  901. `url' specifies the object being requested, e.g. '/index.html'.
  902. `skip_host' if True does not add automatically a 'Host:' header
  903. `skip_accept_encoding' if True does not add automatically an
  904. 'Accept-Encoding:' header
  905. """
  906. # if a prior response has been completed, then forget about it.
  907. if self.__response and self.__response.isclosed():
  908. self.__response = None
  909. # in certain cases, we cannot issue another request on this connection.
  910. # this occurs when:
  911. # 1) we are in the process of sending a request. (_CS_REQ_STARTED)
  912. # 2) a response to a previous request has signalled that it is going
  913. # to close the connection upon completion.
  914. # 3) the headers for the previous response have not been read, thus
  915. # we cannot determine whether point (2) is true. (_CS_REQ_SENT)
  916. #
  917. # if there is no prior response, then we can request at will.
  918. #
  919. # if point (2) is true, then we will have passed the socket to the
  920. # response (effectively meaning, "there is no prior response"), and
  921. # will open a new one when a new request is made.
  922. #
  923. # Note: if a prior response exists, then we *can* start a new request.
  924. # We are not allowed to begin fetching the response to this new
  925. # request, however, until that prior response is complete.
  926. #
  927. if self.__state == _CS_IDLE:
  928. self.__state = _CS_REQ_STARTED
  929. else:
  930. raise CannotSendRequest(self.__state)
  931. self._validate_method(method)
  932. # Save the method for use later in the response phase
  933. self._method = method
  934. url = url or '/'
  935. self._validate_path(url)
  936. request = '%s %s %s' % (method, url, self._http_vsn_str)
  937. self._output(self._encode_request(request))
  938. if self._http_vsn == 11:
  939. # Issue some standard headers for better HTTP/1.1 compliance
  940. if not skip_host:
  941. # this header is issued *only* for HTTP/1.1
  942. # connections. more specifically, this means it is
  943. # only issued when the client uses the new
  944. # HTTPConnection() class. backwards-compat clients
  945. # will be using HTTP/1.0 and those clients may be
  946. # issuing this header themselves. we should NOT issue
  947. # it twice; some web servers (such as Apache) barf
  948. # when they see two Host: headers
  949. # If we need a non-standard port,include it in the
  950. # header. If the request is going through a proxy,
  951. # but the host of the actual URL, not the host of the
  952. # proxy.
  953. netloc = ''
  954. if url.startswith('http'):
  955. nil, netloc, nil, nil, nil = urlsplit(url)
  956. if netloc:
  957. try:
  958. netloc_enc = netloc.encode("ascii")
  959. except UnicodeEncodeError:
  960. netloc_enc = netloc.encode("idna")
  961. self.putheader('Host', netloc_enc)
  962. else:
  963. if self._tunnel_host:
  964. host = self._tunnel_host
  965. port = self._tunnel_port
  966. else:
  967. host = self.host
  968. port = self.port
  969. try:
  970. host_enc = host.encode("ascii")
  971. except UnicodeEncodeError:
  972. host_enc = host.encode("idna")
  973. # As per RFC 273, IPv6 address should be wrapped with []
  974. # when used as Host header
  975. if host.find(':') >= 0:
  976. host_enc = b'[' + host_enc + b']'
  977. if port == self.default_port:
  978. self.putheader('Host', host_enc)
  979. else:
  980. host_enc = host_enc.decode("ascii")
  981. self.putheader('Host', "%s:%s" % (host_enc, port))
  982. # note: we are assuming that clients will not attempt to set these
  983. # headers since *this* library must deal with the
  984. # consequences. this also means that when the supporting
  985. # libraries are updated to recognize other forms, then this
  986. # code should be changed (removed or updated).
  987. # we only want a Content-Encoding of "identity" since we don't
  988. # support encodings such as x-gzip or x-deflate.
  989. if not skip_accept_encoding:
  990. self.putheader('Accept-Encoding', 'identity')
  991. # we can accept "chunked" Transfer-Encodings, but no others
  992. # NOTE: no TE header implies *only* "chunked"
  993. #self.putheader('TE', 'chunked')
  994. # if TE is supplied in the header, then it must appear in a
  995. # Connection header.
  996. #self.putheader('Connection', 'TE')
  997. else:
  998. # For HTTP/1.0, the server will assume "not chunked"
  999. pass
  1000. def _encode_request(self, request):
  1001. # ASCII also helps prevent CVE-2019-9740.
  1002. return request.encode('ascii')
  1003. def _validate_method(self, method):
  1004. """Validate a method name for putrequest."""
  1005. # prevent http header injection
  1006. match = _contains_disallowed_method_pchar_re.search(method)
  1007. if match:
  1008. raise ValueError(
  1009. f"method can't contain control characters. {method!r} "
  1010. f"(found at least {match.group()!r})")
  1011. def _validate_path(self, url):
  1012. """Validate a url for putrequest."""
  1013. # Prevent CVE-2019-9740.
  1014. match = _contains_disallowed_url_pchar_re.search(url)
  1015. if match:
  1016. raise InvalidURL(f"URL can't contain control characters. {url!r} "
  1017. f"(found at least {match.group()!r})")
  1018. def _validate_host(self, host):
  1019. """Validate a host so it doesn't contain control characters."""
  1020. # Prevent CVE-2019-18348.
  1021. match = _contains_disallowed_url_pchar_re.search(host)
  1022. if match:
  1023. raise InvalidURL(f"URL can't contain control characters. {host!r} "
  1024. f"(found at least {match.group()!r})")
  1025. def putheader(self, header, *values):
  1026. """Send a request header line to the server.
  1027. For example: h.putheader('Accept', 'text/html')
  1028. """
  1029. if self.__state != _CS_REQ_STARTED:
  1030. raise CannotSendHeader()
  1031. if hasattr(header, 'encode'):
  1032. header = header.encode('ascii')
  1033. if not _is_legal_header_name(header):
  1034. raise ValueError('Invalid header name %r' % (header,))
  1035. values = list(values)
  1036. for i, one_value in enumerate(values):
  1037. if hasattr(one_value, 'encode'):
  1038. values[i] = one_value.encode('latin-1')
  1039. elif isinstance(one_value, int):
  1040. values[i] = str(one_value).encode('ascii')
  1041. if _is_illegal_header_value(values[i]):
  1042. raise ValueError('Invalid header value %r' % (values[i],))
  1043. value = b'\r\n\t'.join(values)
  1044. header = header + b': ' + value
  1045. self._output(header)
  1046. def endheaders(self, message_body=None, *, encode_chunked=False):
  1047. """Indicate that the last header line has been sent to the server.
  1048. This method sends the request to the server. The optional message_body
  1049. argument can be used to pass a message body associated with the
  1050. request.
  1051. """
  1052. if self.__state == _CS_REQ_STARTED:
  1053. self.__state = _CS_REQ_SENT
  1054. else:
  1055. raise CannotSendHeader()
  1056. self._send_output(message_body, encode_chunked=encode_chunked)
  1057. def request(self, method, url, body=None, headers={}, *,
  1058. encode_chunked=False):
  1059. """Send a complete request to the server."""
  1060. self._send_request(method, url, body, headers, encode_chunked)
  1061. def _send_request(self, method, url, body, headers, encode_chunked):
  1062. # Honor explicitly requested Host: and Accept-Encoding: headers.
  1063. header_names = frozenset(k.lower() for k in headers)
  1064. skips = {}
  1065. if 'host' in header_names:
  1066. skips['skip_host'] = 1
  1067. if 'accept-encoding' in header_names:
  1068. skips['skip_accept_encoding'] = 1
  1069. self.putrequest(method, url, **skips)
  1070. # chunked encoding will happen if HTTP/1.1 is used and either
  1071. # the caller passes encode_chunked=True or the following
  1072. # conditions hold:
  1073. # 1. content-length has not been explicitly set
  1074. # 2. the body is a file or iterable, but not a str or bytes-like
  1075. # 3. Transfer-Encoding has NOT been explicitly set by the caller
  1076. if 'content-length' not in header_names:
  1077. # only chunk body if not explicitly set for backwards
  1078. # compatibility, assuming the client code is already handling the
  1079. # chunking
  1080. if 'transfer-encoding' not in header_names:
  1081. # if content-length cannot be automatically determined, fall
  1082. # back to chunked encoding
  1083. encode_chunked = False
  1084. content_length = self._get_content_length(body, method)
  1085. if content_length is None:
  1086. if body is not None:
  1087. if self.debuglevel > 0:
  1088. print('Unable to determine size of %r' % body)
  1089. encode_chunked = True
  1090. self.putheader('Transfer-Encoding', 'chunked')
  1091. else:
  1092. self.putheader('Content-Length', str(content_length))
  1093. else:
  1094. encode_chunked = False
  1095. for hdr, value in headers.items():
  1096. self.putheader(hdr, value)
  1097. if isinstance(body, str):
  1098. # RFC 2616 Section 3.7.1 says that text default has a
  1099. # default charset of iso-8859-1.
  1100. body = _encode(body, 'body')
  1101. self.endheaders(body, encode_chunked=encode_chunked)
  1102. def getresponse(self):
  1103. """Get the response from the server.
  1104. If the HTTPConnection is in the correct state, returns an
  1105. instance of HTTPResponse or of whatever object is returned by
  1106. the response_class variable.
  1107. If a request has not been sent or if a previous response has
  1108. not be handled, ResponseNotReady is raised. If the HTTP
  1109. response indicates that the connection should be closed, then
  1110. it will be closed before the response is returned. When the
  1111. connection is closed, the underlying socket is closed.
  1112. """
  1113. # if a prior response has been completed, then forget about it.
  1114. if self.__response and self.__response.isclosed():
  1115. self.__response = None
  1116. # if a prior response exists, then it must be completed (otherwise, we
  1117. # cannot read this response's header to determine the connection-close
  1118. # behavior)
  1119. #
  1120. # note: if a prior response existed, but was connection-close, then the
  1121. # socket and response were made independent of this HTTPConnection
  1122. # object since a new request requires that we open a whole new
  1123. # connection
  1124. #
  1125. # this means the prior response had one of two states:
  1126. # 1) will_close: this connection was reset and the prior socket and
  1127. # response operate independently
  1128. # 2) persistent: the response was retained and we await its
  1129. # isclosed() status to become true.
  1130. #
  1131. if self.__state != _CS_REQ_SENT or self.__response:
  1132. raise ResponseNotReady(self.__state)
  1133. if self.debuglevel > 0:
  1134. response = self.response_class(self.sock, self.debuglevel,
  1135. method=self._method)
  1136. else:
  1137. response = self.response_class(self.sock, method=self._method)
  1138. try:
  1139. try:
  1140. response.begin()
  1141. except ConnectionError:
  1142. self.close()
  1143. raise
  1144. assert response.will_close != _UNKNOWN
  1145. self.__state = _CS_IDLE
  1146. if response.will_close:
  1147. # this effectively passes the connection to the response
  1148. self.close()
  1149. else:
  1150. # remember this, so we can tell when it is complete
  1151. self.__response = response
  1152. return response
  1153. except:
  1154. response.close()
  1155. raise
  1156. try:
  1157. import ssl
  1158. except ImportError:
  1159. pass
  1160. else:
  1161. class HTTPSConnection(HTTPConnection):
  1162. "This class allows communication via SSL."
  1163. default_port = HTTPS_PORT
  1164. # XXX Should key_file and cert_file be deprecated in favour of context?
  1165. def __init__(self, host, port=None, key_file=None, cert_file=None,
  1166. timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
  1167. source_address=None, *, context=None,
  1168. check_hostname=None, blocksize=8192):
  1169. super(HTTPSConnection, self).__init__(host, port, timeout,
  1170. source_address,
  1171. blocksize=blocksize)
  1172. if (key_file is not None or cert_file is not None or
  1173. check_hostname is not None):
  1174. import warnings
  1175. warnings.warn("key_file, cert_file and check_hostname are "
  1176. "deprecated, use a custom context instead.",
  1177. DeprecationWarning, 2)
  1178. self.key_file = key_file
  1179. self.cert_file = cert_file
  1180. if context is None:
  1181. context = ssl._create_default_https_context()
  1182. # enable PHA for TLS 1.3 connections if available
  1183. if context.post_handshake_auth is not None:
  1184. context.post_handshake_auth = True
  1185. will_verify = context.verify_mode != ssl.CERT_NONE
  1186. if check_hostname is None:
  1187. check_hostname = context.check_hostname
  1188. if check_hostname and not will_verify:
  1189. raise ValueError("check_hostname needs a SSL context with "
  1190. "either CERT_OPTIONAL or CERT_REQUIRED")
  1191. if key_file or cert_file:
  1192. context.load_cert_chain(cert_file, key_file)
  1193. # cert and key file means the user wants to authenticate.
  1194. # enable TLS 1.3 PHA implicitly even for custom contexts.
  1195. if context.post_handshake_auth is not None:
  1196. context.post_handshake_auth = True
  1197. self._context = context
  1198. if check_hostname is not None:
  1199. self._context.check_hostname = check_hostname
  1200. def connect(self):
  1201. "Connect to a host on a given (SSL) port."
  1202. super().connect()
  1203. if self._tunnel_host:
  1204. server_hostname = self._tunnel_host
  1205. else:
  1206. server_hostname = self.host
  1207. self.sock = self._context.wrap_socket(self.sock,
  1208. server_hostname=server_hostname)
  1209. __all__.append("HTTPSConnection")
  1210. class HTTPException(Exception):
  1211. # Subclasses that define an __init__ must call Exception.__init__
  1212. # or define self.args. Otherwise, str() will fail.
  1213. pass
  1214. class NotConnected(HTTPException):
  1215. pass
  1216. class InvalidURL(HTTPException):
  1217. pass
  1218. class UnknownProtocol(HTTPException):
  1219. def __init__(self, version):
  1220. self.args = version,
  1221. self.version = version
  1222. class UnknownTransferEncoding(HTTPException):
  1223. pass
  1224. class UnimplementedFileMode(HTTPException):
  1225. pass
  1226. class IncompleteRead(HTTPException):
  1227. def __init__(self, partial, expected=None):
  1228. self.args = partial,
  1229. self.partial = partial
  1230. self.expected = expected
  1231. def __repr__(self):
  1232. if self.expected is not None:
  1233. e = ', %i more expected' % self.expected
  1234. else:
  1235. e = ''
  1236. return '%s(%i bytes read%s)' % (self.__class__.__name__,
  1237. len(self.partial), e)
  1238. __str__ = object.__str__
  1239. class ImproperConnectionState(HTTPException):
  1240. pass
  1241. class CannotSendRequest(ImproperConnectionState):
  1242. pass
  1243. class CannotSendHeader(ImproperConnectionState):
  1244. pass
  1245. class ResponseNotReady(ImproperConnectionState):
  1246. pass
  1247. class BadStatusLine(HTTPException):
  1248. def __init__(self, line):
  1249. if not line:
  1250. line = repr(line)
  1251. self.args = line,
  1252. self.line = line
  1253. class LineTooLong(HTTPException):
  1254. def __init__(self, line_type):
  1255. HTTPException.__init__(self, "got more than %d bytes when reading %s"
  1256. % (_MAXLINE, line_type))
  1257. class RemoteDisconnected(ConnectionResetError, BadStatusLine):
  1258. def __init__(self, *pos, **kw):
  1259. BadStatusLine.__init__(self, "")
  1260. ConnectionResetError.__init__(self, *pos, **kw)
  1261. # for backwards compatibility
  1262. error = HTTPException