client.py 56 KB

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