client.py 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525
  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 errno
  67. import http
  68. import io
  69. import re
  70. import socket
  71. import sys
  72. import collections.abc
  73. from urllib.parse import urlsplit
  74. # HTTPMessage, parse_headers(), and the HTTP status code constants are
  75. # intentionally omitted for simplicity
  76. __all__ = ["HTTPResponse", "HTTPConnection",
  77. "HTTPException", "NotConnected", "UnknownProtocol",
  78. "UnknownTransferEncoding", "UnimplementedFileMode",
  79. "IncompleteRead", "InvalidURL", "ImproperConnectionState",
  80. "CannotSendRequest", "CannotSendHeader", "ResponseNotReady",
  81. "BadStatusLine", "LineTooLong", "RemoteDisconnected", "error",
  82. "responses"]
  83. HTTP_PORT = 80
  84. HTTPS_PORT = 443
  85. _UNKNOWN = 'UNKNOWN'
  86. # connection states
  87. _CS_IDLE = 'Idle'
  88. _CS_REQ_STARTED = 'Request-started'
  89. _CS_REQ_SENT = 'Request-sent'
  90. # hack to maintain backwards compatibility
  91. globals().update(http.HTTPStatus.__members__)
  92. # another hack to maintain backwards compatibility
  93. # Mapping status codes to official W3C names
  94. responses = {v: v.phrase for v in http.HTTPStatus.__members__.values()}
  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. if length and not self.chunked:
  307. try:
  308. self.length = int(length)
  309. except ValueError:
  310. self.length = None
  311. else:
  312. if self.length < 0: # ignore nonsensical negative lengths
  313. self.length = None
  314. else:
  315. self.length = None
  316. # does the body have a fixed length? (of zero)
  317. if (status == NO_CONTENT or status == NOT_MODIFIED or
  318. 100 <= status < 200 or # 1xx codes
  319. self._method == "HEAD"):
  320. self.length = 0
  321. # if the connection remains open, and we aren't using chunked, and
  322. # a content-length was not provided, then assume that the connection
  323. # WILL close.
  324. if (not self.will_close and
  325. not self.chunked and
  326. self.length is None):
  327. self.will_close = True
  328. def _check_close(self):
  329. conn = self.headers.get("connection")
  330. if self.version == 11:
  331. # An HTTP/1.1 proxy is assumed to stay open unless
  332. # explicitly closed.
  333. if conn and "close" in conn.lower():
  334. return True
  335. return False
  336. # Some HTTP/1.0 implementations have support for persistent
  337. # connections, using rules different than HTTP/1.1.
  338. # For older HTTP, Keep-Alive indicates persistent connection.
  339. if self.headers.get("keep-alive"):
  340. return False
  341. # At least Akamai returns a "Connection: Keep-Alive" header,
  342. # which was supposed to be sent by the client.
  343. if conn and "keep-alive" in conn.lower():
  344. return False
  345. # Proxy-Connection is a netscape hack.
  346. pconn = self.headers.get("proxy-connection")
  347. if pconn and "keep-alive" in pconn.lower():
  348. return False
  349. # otherwise, assume it will close
  350. return True
  351. def _close_conn(self):
  352. fp = self.fp
  353. self.fp = None
  354. fp.close()
  355. def close(self):
  356. try:
  357. super().close() # set "closed" flag
  358. finally:
  359. if self.fp:
  360. self._close_conn()
  361. # These implementations are for the benefit of io.BufferedReader.
  362. # XXX This class should probably be revised to act more like
  363. # the "raw stream" that BufferedReader expects.
  364. def flush(self):
  365. super().flush()
  366. if self.fp:
  367. self.fp.flush()
  368. def readable(self):
  369. """Always returns True"""
  370. return True
  371. # End of "raw stream" methods
  372. def isclosed(self):
  373. """True if the connection is closed."""
  374. # NOTE: it is possible that we will not ever call self.close(). This
  375. # case occurs when will_close is TRUE, length is None, and we
  376. # read up to the last byte, but NOT past it.
  377. #
  378. # IMPLIES: if will_close is FALSE, then self.close() will ALWAYS be
  379. # called, meaning self.isclosed() is meaningful.
  380. return self.fp is None
  381. def read(self, amt=None):
  382. if self.fp is None:
  383. return b""
  384. if self._method == "HEAD":
  385. self._close_conn()
  386. return b""
  387. if self.chunked:
  388. return self._read_chunked(amt)
  389. if amt is not None:
  390. if self.length is not None and amt > self.length:
  391. # clip the read to the "end of response"
  392. amt = self.length
  393. s = self.fp.read(amt)
  394. if not s and amt:
  395. # Ideally, we would raise IncompleteRead if the content-length
  396. # wasn't satisfied, but it might break compatibility.
  397. self._close_conn()
  398. elif self.length is not None:
  399. self.length -= len(s)
  400. if not self.length:
  401. self._close_conn()
  402. return s
  403. else:
  404. # Amount is not given (unbounded read) so we must check self.length
  405. if self.length is None:
  406. s = self.fp.read()
  407. else:
  408. try:
  409. s = self._safe_read(self.length)
  410. except IncompleteRead:
  411. self._close_conn()
  412. raise
  413. self.length = 0
  414. self._close_conn() # we read everything
  415. return s
  416. def readinto(self, b):
  417. """Read up to len(b) bytes into bytearray b and return the number
  418. of bytes read.
  419. """
  420. if self.fp is None:
  421. return 0
  422. if self._method == "HEAD":
  423. self._close_conn()
  424. return 0
  425. if self.chunked:
  426. return self._readinto_chunked(b)
  427. if self.length is not None:
  428. if len(b) > self.length:
  429. # clip the read to the "end of response"
  430. b = memoryview(b)[0:self.length]
  431. # we do not use _safe_read() here because this may be a .will_close
  432. # connection, and the user is reading more bytes than will be provided
  433. # (for example, reading in 1k chunks)
  434. n = self.fp.readinto(b)
  435. if not n and b:
  436. # Ideally, we would raise IncompleteRead if the content-length
  437. # wasn't satisfied, but it might break compatibility.
  438. self._close_conn()
  439. elif self.length is not None:
  440. self.length -= n
  441. if not self.length:
  442. self._close_conn()
  443. return n
  444. def _read_next_chunk_size(self):
  445. # Read the next chunk size from the file
  446. line = self.fp.readline(_MAXLINE + 1)
  447. if len(line) > _MAXLINE:
  448. raise LineTooLong("chunk size")
  449. i = line.find(b";")
  450. if i >= 0:
  451. line = line[:i] # strip chunk-extensions
  452. try:
  453. return int(line, 16)
  454. except ValueError:
  455. # close the connection as protocol synchronisation is
  456. # probably lost
  457. self._close_conn()
  458. raise
  459. def _read_and_discard_trailer(self):
  460. # read and discard trailer up to the CRLF terminator
  461. ### note: we shouldn't have any trailers!
  462. while True:
  463. line = self.fp.readline(_MAXLINE + 1)
  464. if len(line) > _MAXLINE:
  465. raise LineTooLong("trailer line")
  466. if not line:
  467. # a vanishingly small number of sites EOF without
  468. # sending the trailer
  469. break
  470. if line in (b'\r\n', b'\n', b''):
  471. break
  472. def _get_chunk_left(self):
  473. # return self.chunk_left, reading a new chunk if necessary.
  474. # chunk_left == 0: at the end of the current chunk, need to close it
  475. # chunk_left == None: No current chunk, should read next.
  476. # This function returns non-zero or None if the last chunk has
  477. # been read.
  478. chunk_left = self.chunk_left
  479. if not chunk_left: # Can be 0 or None
  480. if chunk_left is not None:
  481. # We are at the end of chunk, discard chunk end
  482. self._safe_read(2) # toss the CRLF at the end of the chunk
  483. try:
  484. chunk_left = self._read_next_chunk_size()
  485. except ValueError:
  486. raise IncompleteRead(b'')
  487. if chunk_left == 0:
  488. # last chunk: 1*("0") [ chunk-extension ] CRLF
  489. self._read_and_discard_trailer()
  490. # we read everything; close the "file"
  491. self._close_conn()
  492. chunk_left = None
  493. self.chunk_left = chunk_left
  494. return chunk_left
  495. def _read_chunked(self, amt=None):
  496. assert self.chunked != _UNKNOWN
  497. value = []
  498. try:
  499. while True:
  500. chunk_left = self._get_chunk_left()
  501. if chunk_left is None:
  502. break
  503. if amt is not None and amt <= chunk_left:
  504. value.append(self._safe_read(amt))
  505. self.chunk_left = chunk_left - amt
  506. break
  507. value.append(self._safe_read(chunk_left))
  508. if amt is not None:
  509. amt -= chunk_left
  510. self.chunk_left = 0
  511. return b''.join(value)
  512. except IncompleteRead as exc:
  513. raise IncompleteRead(b''.join(value)) from exc
  514. def _readinto_chunked(self, b):
  515. assert self.chunked != _UNKNOWN
  516. total_bytes = 0
  517. mvb = memoryview(b)
  518. try:
  519. while True:
  520. chunk_left = self._get_chunk_left()
  521. if chunk_left is None:
  522. return total_bytes
  523. if len(mvb) <= chunk_left:
  524. n = self._safe_readinto(mvb)
  525. self.chunk_left = chunk_left - n
  526. return total_bytes + n
  527. temp_mvb = mvb[:chunk_left]
  528. n = self._safe_readinto(temp_mvb)
  529. mvb = mvb[n:]
  530. total_bytes += n
  531. self.chunk_left = 0
  532. except IncompleteRead:
  533. raise IncompleteRead(bytes(b[0:total_bytes]))
  534. def _safe_read(self, amt):
  535. """Read the number of bytes requested.
  536. This function should be used when <amt> bytes "should" be present for
  537. reading. If the bytes are truly not available (due to EOF), then the
  538. IncompleteRead exception can be used to detect the problem.
  539. """
  540. data = self.fp.read(amt)
  541. if len(data) < amt:
  542. raise IncompleteRead(data, amt-len(data))
  543. return data
  544. def _safe_readinto(self, b):
  545. """Same as _safe_read, but for reading into a buffer."""
  546. amt = len(b)
  547. n = self.fp.readinto(b)
  548. if n < amt:
  549. raise IncompleteRead(bytes(b[:n]), amt-n)
  550. return n
  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. self._validate_host(self.host)
  725. # This is stored as an instance variable to allow unit
  726. # tests to replace it with a suitable mockup
  727. self._create_connection = socket.create_connection
  728. def set_tunnel(self, host, port=None, headers=None):
  729. """Set up host and port for HTTP CONNECT tunnelling.
  730. In a connection that uses HTTP CONNECT tunneling, the host passed to the
  731. constructor is used as a proxy server that relays all communication to
  732. the endpoint passed to `set_tunnel`. This done by sending an HTTP
  733. CONNECT request to the proxy server when the connection is established.
  734. This method must be called before the HTTP connection has been
  735. established.
  736. The headers argument should be a mapping of extra HTTP headers to send
  737. with the CONNECT request.
  738. """
  739. if self.sock:
  740. raise RuntimeError("Can't set up tunnel for established connection")
  741. self._tunnel_host, self._tunnel_port = self._get_hostport(host, port)
  742. if headers:
  743. self._tunnel_headers = headers
  744. else:
  745. self._tunnel_headers.clear()
  746. def _get_hostport(self, host, port):
  747. if port is None:
  748. i = host.rfind(':')
  749. j = host.rfind(']') # ipv6 addresses have [...]
  750. if i > j:
  751. try:
  752. port = int(host[i+1:])
  753. except ValueError:
  754. if host[i+1:] == "": # http://foo.com:/ == http://foo.com/
  755. port = self.default_port
  756. else:
  757. raise InvalidURL("nonnumeric port: '%s'" % host[i+1:])
  758. host = host[:i]
  759. else:
  760. port = self.default_port
  761. if host and host[0] == '[' and host[-1] == ']':
  762. host = host[1:-1]
  763. return (host, port)
  764. def set_debuglevel(self, level):
  765. self.debuglevel = level
  766. def _tunnel(self):
  767. connect = b"CONNECT %s:%d HTTP/1.0\r\n" % (
  768. self._tunnel_host.encode("ascii"), self._tunnel_port)
  769. headers = [connect]
  770. for header, value in self._tunnel_headers.items():
  771. headers.append(f"{header}: {value}\r\n".encode("latin-1"))
  772. headers.append(b"\r\n")
  773. # Making a single send() call instead of one per line encourages
  774. # the host OS to use a more optimal packet size instead of
  775. # potentially emitting a series of small packets.
  776. self.send(b"".join(headers))
  777. del headers
  778. response = self.response_class(self.sock, method=self._method)
  779. (version, code, message) = response._read_status()
  780. if code != http.HTTPStatus.OK:
  781. self.close()
  782. raise OSError(f"Tunnel connection failed: {code} {message.strip()}")
  783. while True:
  784. line = response.fp.readline(_MAXLINE + 1)
  785. if len(line) > _MAXLINE:
  786. raise LineTooLong("header line")
  787. if not line:
  788. # for sites which EOF without sending a trailer
  789. break
  790. if line in (b'\r\n', b'\n', b''):
  791. break
  792. if self.debuglevel > 0:
  793. print('header:', line.decode())
  794. def connect(self):
  795. """Connect to the host and port specified in __init__."""
  796. sys.audit("http.client.connect", self, self.host, self.port)
  797. self.sock = self._create_connection(
  798. (self.host,self.port), self.timeout, self.source_address)
  799. # Might fail in OSs that don't implement TCP_NODELAY
  800. try:
  801. self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
  802. except OSError as e:
  803. if e.errno != errno.ENOPROTOOPT:
  804. raise
  805. if self._tunnel_host:
  806. self._tunnel()
  807. def close(self):
  808. """Close the connection to the HTTP server."""
  809. self.__state = _CS_IDLE
  810. try:
  811. sock = self.sock
  812. if sock:
  813. self.sock = None
  814. sock.close() # close it manually... there may be other refs
  815. finally:
  816. response = self.__response
  817. if response:
  818. self.__response = None
  819. response.close()
  820. def send(self, data):
  821. """Send `data' to the server.
  822. ``data`` can be a string object, a bytes object, an array object, a
  823. file-like object that supports a .read() method, or an iterable object.
  824. """
  825. if self.sock is None:
  826. if self.auto_open:
  827. self.connect()
  828. else:
  829. raise NotConnected()
  830. if self.debuglevel > 0:
  831. print("send:", repr(data))
  832. if hasattr(data, "read") :
  833. if self.debuglevel > 0:
  834. print("sendIng a read()able")
  835. encode = self._is_textIO(data)
  836. if encode and self.debuglevel > 0:
  837. print("encoding file using iso-8859-1")
  838. while 1:
  839. datablock = data.read(self.blocksize)
  840. if not datablock:
  841. break
  842. if encode:
  843. datablock = datablock.encode("iso-8859-1")
  844. sys.audit("http.client.send", self, datablock)
  845. self.sock.sendall(datablock)
  846. return
  847. sys.audit("http.client.send", self, data)
  848. try:
  849. self.sock.sendall(data)
  850. except TypeError:
  851. if isinstance(data, collections.abc.Iterable):
  852. for d in data:
  853. self.sock.sendall(d)
  854. else:
  855. raise TypeError("data should be a bytes-like object "
  856. "or an iterable, got %r" % type(data))
  857. def _output(self, s):
  858. """Add a line of output to the current request buffer.
  859. Assumes that the line does *not* end with \\r\\n.
  860. """
  861. self._buffer.append(s)
  862. def _read_readable(self, readable):
  863. if self.debuglevel > 0:
  864. print("sendIng a read()able")
  865. encode = self._is_textIO(readable)
  866. if encode and self.debuglevel > 0:
  867. print("encoding file using iso-8859-1")
  868. while True:
  869. datablock = readable.read(self.blocksize)
  870. if not datablock:
  871. break
  872. if encode:
  873. datablock = datablock.encode("iso-8859-1")
  874. yield datablock
  875. def _send_output(self, message_body=None, encode_chunked=False):
  876. """Send the currently buffered request and clear the buffer.
  877. Appends an extra \\r\\n to the buffer.
  878. A message_body may be specified, to be appended to the request.
  879. """
  880. self._buffer.extend((b"", b""))
  881. msg = b"\r\n".join(self._buffer)
  882. del self._buffer[:]
  883. self.send(msg)
  884. if message_body is not None:
  885. # create a consistent interface to message_body
  886. if hasattr(message_body, 'read'):
  887. # Let file-like take precedence over byte-like. This
  888. # is needed to allow the current position of mmap'ed
  889. # files to be taken into account.
  890. chunks = self._read_readable(message_body)
  891. else:
  892. try:
  893. # this is solely to check to see if message_body
  894. # implements the buffer API. it /would/ be easier
  895. # to capture if PyObject_CheckBuffer was exposed
  896. # to Python.
  897. memoryview(message_body)
  898. except TypeError:
  899. try:
  900. chunks = iter(message_body)
  901. except TypeError:
  902. raise TypeError("message_body should be a bytes-like "
  903. "object or an iterable, got %r"
  904. % type(message_body))
  905. else:
  906. # the object implements the buffer interface and
  907. # can be passed directly into socket methods
  908. chunks = (message_body,)
  909. for chunk in chunks:
  910. if not chunk:
  911. if self.debuglevel > 0:
  912. print('Zero length chunk ignored')
  913. continue
  914. if encode_chunked and self._http_vsn == 11:
  915. # chunked encoding
  916. chunk = f'{len(chunk):X}\r\n'.encode('ascii') + chunk \
  917. + b'\r\n'
  918. self.send(chunk)
  919. if encode_chunked and self._http_vsn == 11:
  920. # end chunked transfer
  921. self.send(b'0\r\n\r\n')
  922. def putrequest(self, method, url, skip_host=False,
  923. skip_accept_encoding=False):
  924. """Send a request to the server.
  925. `method' specifies an HTTP request method, e.g. 'GET'.
  926. `url' specifies the object being requested, e.g. '/index.html'.
  927. `skip_host' if True does not add automatically a 'Host:' header
  928. `skip_accept_encoding' if True does not add automatically an
  929. 'Accept-Encoding:' header
  930. """
  931. # if a prior response has been completed, then forget about it.
  932. if self.__response and self.__response.isclosed():
  933. self.__response = None
  934. # in certain cases, we cannot issue another request on this connection.
  935. # this occurs when:
  936. # 1) we are in the process of sending a request. (_CS_REQ_STARTED)
  937. # 2) a response to a previous request has signalled that it is going
  938. # to close the connection upon completion.
  939. # 3) the headers for the previous response have not been read, thus
  940. # we cannot determine whether point (2) is true. (_CS_REQ_SENT)
  941. #
  942. # if there is no prior response, then we can request at will.
  943. #
  944. # if point (2) is true, then we will have passed the socket to the
  945. # response (effectively meaning, "there is no prior response"), and
  946. # will open a new one when a new request is made.
  947. #
  948. # Note: if a prior response exists, then we *can* start a new request.
  949. # We are not allowed to begin fetching the response to this new
  950. # request, however, until that prior response is complete.
  951. #
  952. if self.__state == _CS_IDLE:
  953. self.__state = _CS_REQ_STARTED
  954. else:
  955. raise CannotSendRequest(self.__state)
  956. self._validate_method(method)
  957. # Save the method for use later in the response phase
  958. self._method = method
  959. url = url or '/'
  960. self._validate_path(url)
  961. request = '%s %s %s' % (method, url, self._http_vsn_str)
  962. self._output(self._encode_request(request))
  963. if self._http_vsn == 11:
  964. # Issue some standard headers for better HTTP/1.1 compliance
  965. if not skip_host:
  966. # this header is issued *only* for HTTP/1.1
  967. # connections. more specifically, this means it is
  968. # only issued when the client uses the new
  969. # HTTPConnection() class. backwards-compat clients
  970. # will be using HTTP/1.0 and those clients may be
  971. # issuing this header themselves. we should NOT issue
  972. # it twice; some web servers (such as Apache) barf
  973. # when they see two Host: headers
  974. # If we need a non-standard port,include it in the
  975. # header. If the request is going through a proxy,
  976. # but the host of the actual URL, not the host of the
  977. # proxy.
  978. netloc = ''
  979. if url.startswith('http'):
  980. nil, netloc, nil, nil, nil = urlsplit(url)
  981. if netloc:
  982. try:
  983. netloc_enc = netloc.encode("ascii")
  984. except UnicodeEncodeError:
  985. netloc_enc = netloc.encode("idna")
  986. self.putheader('Host', netloc_enc)
  987. else:
  988. if self._tunnel_host:
  989. host = self._tunnel_host
  990. port = self._tunnel_port
  991. else:
  992. host = self.host
  993. port = self.port
  994. try:
  995. host_enc = host.encode("ascii")
  996. except UnicodeEncodeError:
  997. host_enc = host.encode("idna")
  998. # As per RFC 273, IPv6 address should be wrapped with []
  999. # when used as Host header
  1000. if host.find(':') >= 0:
  1001. host_enc = b'[' + host_enc + b']'
  1002. if port == self.default_port:
  1003. self.putheader('Host', host_enc)
  1004. else:
  1005. host_enc = host_enc.decode("ascii")
  1006. self.putheader('Host', "%s:%s" % (host_enc, port))
  1007. # note: we are assuming that clients will not attempt to set these
  1008. # headers since *this* library must deal with the
  1009. # consequences. this also means that when the supporting
  1010. # libraries are updated to recognize other forms, then this
  1011. # code should be changed (removed or updated).
  1012. # we only want a Content-Encoding of "identity" since we don't
  1013. # support encodings such as x-gzip or x-deflate.
  1014. if not skip_accept_encoding:
  1015. self.putheader('Accept-Encoding', 'identity')
  1016. # we can accept "chunked" Transfer-Encodings, but no others
  1017. # NOTE: no TE header implies *only* "chunked"
  1018. #self.putheader('TE', 'chunked')
  1019. # if TE is supplied in the header, then it must appear in a
  1020. # Connection header.
  1021. #self.putheader('Connection', 'TE')
  1022. else:
  1023. # For HTTP/1.0, the server will assume "not chunked"
  1024. pass
  1025. def _encode_request(self, request):
  1026. # ASCII also helps prevent CVE-2019-9740.
  1027. return request.encode('ascii')
  1028. def _validate_method(self, method):
  1029. """Validate a method name for putrequest."""
  1030. # prevent http header injection
  1031. match = _contains_disallowed_method_pchar_re.search(method)
  1032. if match:
  1033. raise ValueError(
  1034. f"method can't contain control characters. {method!r} "
  1035. f"(found at least {match.group()!r})")
  1036. def _validate_path(self, url):
  1037. """Validate a url for putrequest."""
  1038. # Prevent CVE-2019-9740.
  1039. match = _contains_disallowed_url_pchar_re.search(url)
  1040. if match:
  1041. raise InvalidURL(f"URL can't contain control characters. {url!r} "
  1042. f"(found at least {match.group()!r})")
  1043. def _validate_host(self, host):
  1044. """Validate a host so it doesn't contain control characters."""
  1045. # Prevent CVE-2019-18348.
  1046. match = _contains_disallowed_url_pchar_re.search(host)
  1047. if match:
  1048. raise InvalidURL(f"URL can't contain control characters. {host!r} "
  1049. f"(found at least {match.group()!r})")
  1050. def putheader(self, header, *values):
  1051. """Send a request header line to the server.
  1052. For example: h.putheader('Accept', 'text/html')
  1053. """
  1054. if self.__state != _CS_REQ_STARTED:
  1055. raise CannotSendHeader()
  1056. if hasattr(header, 'encode'):
  1057. header = header.encode('ascii')
  1058. if not _is_legal_header_name(header):
  1059. raise ValueError('Invalid header name %r' % (header,))
  1060. values = list(values)
  1061. for i, one_value in enumerate(values):
  1062. if hasattr(one_value, 'encode'):
  1063. values[i] = one_value.encode('latin-1')
  1064. elif isinstance(one_value, int):
  1065. values[i] = str(one_value).encode('ascii')
  1066. if _is_illegal_header_value(values[i]):
  1067. raise ValueError('Invalid header value %r' % (values[i],))
  1068. value = b'\r\n\t'.join(values)
  1069. header = header + b': ' + value
  1070. self._output(header)
  1071. def endheaders(self, message_body=None, *, encode_chunked=False):
  1072. """Indicate that the last header line has been sent to the server.
  1073. This method sends the request to the server. The optional message_body
  1074. argument can be used to pass a message body associated with the
  1075. request.
  1076. """
  1077. if self.__state == _CS_REQ_STARTED:
  1078. self.__state = _CS_REQ_SENT
  1079. else:
  1080. raise CannotSendHeader()
  1081. self._send_output(message_body, encode_chunked=encode_chunked)
  1082. def request(self, method, url, body=None, headers={}, *,
  1083. encode_chunked=False):
  1084. """Send a complete request to the server."""
  1085. self._send_request(method, url, body, headers, encode_chunked)
  1086. def _send_request(self, method, url, body, headers, encode_chunked):
  1087. # Honor explicitly requested Host: and Accept-Encoding: headers.
  1088. header_names = frozenset(k.lower() for k in headers)
  1089. skips = {}
  1090. if 'host' in header_names:
  1091. skips['skip_host'] = 1
  1092. if 'accept-encoding' in header_names:
  1093. skips['skip_accept_encoding'] = 1
  1094. self.putrequest(method, url, **skips)
  1095. # chunked encoding will happen if HTTP/1.1 is used and either
  1096. # the caller passes encode_chunked=True or the following
  1097. # conditions hold:
  1098. # 1. content-length has not been explicitly set
  1099. # 2. the body is a file or iterable, but not a str or bytes-like
  1100. # 3. Transfer-Encoding has NOT been explicitly set by the caller
  1101. if 'content-length' not in header_names:
  1102. # only chunk body if not explicitly set for backwards
  1103. # compatibility, assuming the client code is already handling the
  1104. # chunking
  1105. if 'transfer-encoding' not in header_names:
  1106. # if content-length cannot be automatically determined, fall
  1107. # back to chunked encoding
  1108. encode_chunked = False
  1109. content_length = self._get_content_length(body, method)
  1110. if content_length is None:
  1111. if body is not None:
  1112. if self.debuglevel > 0:
  1113. print('Unable to determine size of %r' % body)
  1114. encode_chunked = True
  1115. self.putheader('Transfer-Encoding', 'chunked')
  1116. else:
  1117. self.putheader('Content-Length', str(content_length))
  1118. else:
  1119. encode_chunked = False
  1120. for hdr, value in headers.items():
  1121. self.putheader(hdr, value)
  1122. if isinstance(body, str):
  1123. # RFC 2616 Section 3.7.1 says that text default has a
  1124. # default charset of iso-8859-1.
  1125. body = _encode(body, 'body')
  1126. self.endheaders(body, encode_chunked=encode_chunked)
  1127. def getresponse(self):
  1128. """Get the response from the server.
  1129. If the HTTPConnection is in the correct state, returns an
  1130. instance of HTTPResponse or of whatever object is returned by
  1131. the response_class variable.
  1132. If a request has not been sent or if a previous response has
  1133. not be handled, ResponseNotReady is raised. If the HTTP
  1134. response indicates that the connection should be closed, then
  1135. it will be closed before the response is returned. When the
  1136. connection is closed, the underlying socket is closed.
  1137. """
  1138. # if a prior response has been completed, then forget about it.
  1139. if self.__response and self.__response.isclosed():
  1140. self.__response = None
  1141. # if a prior response exists, then it must be completed (otherwise, we
  1142. # cannot read this response's header to determine the connection-close
  1143. # behavior)
  1144. #
  1145. # note: if a prior response existed, but was connection-close, then the
  1146. # socket and response were made independent of this HTTPConnection
  1147. # object since a new request requires that we open a whole new
  1148. # connection
  1149. #
  1150. # this means the prior response had one of two states:
  1151. # 1) will_close: this connection was reset and the prior socket and
  1152. # response operate independently
  1153. # 2) persistent: the response was retained and we await its
  1154. # isclosed() status to become true.
  1155. #
  1156. if self.__state != _CS_REQ_SENT or self.__response:
  1157. raise ResponseNotReady(self.__state)
  1158. if self.debuglevel > 0:
  1159. response = self.response_class(self.sock, self.debuglevel,
  1160. method=self._method)
  1161. else:
  1162. response = self.response_class(self.sock, method=self._method)
  1163. try:
  1164. try:
  1165. response.begin()
  1166. except ConnectionError:
  1167. self.close()
  1168. raise
  1169. assert response.will_close != _UNKNOWN
  1170. self.__state = _CS_IDLE
  1171. if response.will_close:
  1172. # this effectively passes the connection to the response
  1173. self.close()
  1174. else:
  1175. # remember this, so we can tell when it is complete
  1176. self.__response = response
  1177. return response
  1178. except:
  1179. response.close()
  1180. raise
  1181. try:
  1182. import ssl
  1183. except ImportError:
  1184. pass
  1185. else:
  1186. class HTTPSConnection(HTTPConnection):
  1187. "This class allows communication via SSL."
  1188. default_port = HTTPS_PORT
  1189. # XXX Should key_file and cert_file be deprecated in favour of context?
  1190. def __init__(self, host, port=None, key_file=None, cert_file=None,
  1191. timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
  1192. source_address=None, *, context=None,
  1193. check_hostname=None, blocksize=8192):
  1194. super(HTTPSConnection, self).__init__(host, port, timeout,
  1195. source_address,
  1196. blocksize=blocksize)
  1197. if (key_file is not None or cert_file is not None or
  1198. check_hostname is not None):
  1199. import warnings
  1200. warnings.warn("key_file, cert_file and check_hostname are "
  1201. "deprecated, use a custom context instead.",
  1202. DeprecationWarning, 2)
  1203. self.key_file = key_file
  1204. self.cert_file = cert_file
  1205. if context is None:
  1206. context = ssl._create_default_https_context()
  1207. # send ALPN extension to indicate HTTP/1.1 protocol
  1208. if self._http_vsn == 11:
  1209. context.set_alpn_protocols(['http/1.1'])
  1210. # enable PHA for TLS 1.3 connections if available
  1211. if context.post_handshake_auth is not None:
  1212. context.post_handshake_auth = True
  1213. will_verify = context.verify_mode != ssl.CERT_NONE
  1214. if check_hostname is None:
  1215. check_hostname = context.check_hostname
  1216. if check_hostname and not will_verify:
  1217. raise ValueError("check_hostname needs a SSL context with "
  1218. "either CERT_OPTIONAL or CERT_REQUIRED")
  1219. if key_file or cert_file:
  1220. context.load_cert_chain(cert_file, key_file)
  1221. # cert and key file means the user wants to authenticate.
  1222. # enable TLS 1.3 PHA implicitly even for custom contexts.
  1223. if context.post_handshake_auth is not None:
  1224. context.post_handshake_auth = True
  1225. self._context = context
  1226. if check_hostname is not None:
  1227. self._context.check_hostname = check_hostname
  1228. def connect(self):
  1229. "Connect to a host on a given (SSL) port."
  1230. super().connect()
  1231. if self._tunnel_host:
  1232. server_hostname = self._tunnel_host
  1233. else:
  1234. server_hostname = self.host
  1235. self.sock = self._context.wrap_socket(self.sock,
  1236. server_hostname=server_hostname)
  1237. __all__.append("HTTPSConnection")
  1238. class HTTPException(Exception):
  1239. # Subclasses that define an __init__ must call Exception.__init__
  1240. # or define self.args. Otherwise, str() will fail.
  1241. pass
  1242. class NotConnected(HTTPException):
  1243. pass
  1244. class InvalidURL(HTTPException):
  1245. pass
  1246. class UnknownProtocol(HTTPException):
  1247. def __init__(self, version):
  1248. self.args = version,
  1249. self.version = version
  1250. class UnknownTransferEncoding(HTTPException):
  1251. pass
  1252. class UnimplementedFileMode(HTTPException):
  1253. pass
  1254. class IncompleteRead(HTTPException):
  1255. def __init__(self, partial, expected=None):
  1256. self.args = partial,
  1257. self.partial = partial
  1258. self.expected = expected
  1259. def __repr__(self):
  1260. if self.expected is not None:
  1261. e = ', %i more expected' % self.expected
  1262. else:
  1263. e = ''
  1264. return '%s(%i bytes read%s)' % (self.__class__.__name__,
  1265. len(self.partial), e)
  1266. __str__ = object.__str__
  1267. class ImproperConnectionState(HTTPException):
  1268. pass
  1269. class CannotSendRequest(ImproperConnectionState):
  1270. pass
  1271. class CannotSendHeader(ImproperConnectionState):
  1272. pass
  1273. class ResponseNotReady(ImproperConnectionState):
  1274. pass
  1275. class BadStatusLine(HTTPException):
  1276. def __init__(self, line):
  1277. if not line:
  1278. line = repr(line)
  1279. self.args = line,
  1280. self.line = line
  1281. class LineTooLong(HTTPException):
  1282. def __init__(self, line_type):
  1283. HTTPException.__init__(self, "got more than %d bytes when reading %s"
  1284. % (_MAXLINE, line_type))
  1285. class RemoteDisconnected(ConnectionResetError, BadStatusLine):
  1286. def __init__(self, *pos, **kw):
  1287. BadStatusLine.__init__(self, "")
  1288. ConnectionResetError.__init__(self, *pos, **kw)
  1289. # for backwards compatibility
  1290. error = HTTPException