client.py 54 KB

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