client.py 55 KB

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