client.py 55 KB

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