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