httpserver_test.py 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296
  1. from tornado import gen, netutil
  2. from tornado.escape import (
  3. json_decode,
  4. json_encode,
  5. utf8,
  6. _unicode,
  7. recursive_unicode,
  8. native_str,
  9. )
  10. from tornado.http1connection import HTTP1Connection
  11. from tornado.httpclient import HTTPError
  12. from tornado.httpserver import HTTPServer
  13. from tornado.httputil import (
  14. HTTPHeaders,
  15. HTTPMessageDelegate,
  16. HTTPServerConnectionDelegate,
  17. ResponseStartLine,
  18. )
  19. from tornado.iostream import IOStream
  20. from tornado.locks import Event
  21. from tornado.log import gen_log
  22. from tornado.netutil import ssl_options_to_context
  23. from tornado.simple_httpclient import SimpleAsyncHTTPClient
  24. from tornado.testing import (
  25. AsyncHTTPTestCase,
  26. AsyncHTTPSTestCase,
  27. AsyncTestCase,
  28. ExpectLog,
  29. gen_test,
  30. )
  31. from tornado.test.util import skipOnTravis
  32. from tornado.web import Application, RequestHandler, stream_request_body
  33. from contextlib import closing
  34. import datetime
  35. import gzip
  36. import os
  37. import shutil
  38. import socket
  39. import ssl
  40. import sys
  41. import tempfile
  42. import unittest
  43. from io import BytesIO
  44. import typing
  45. if typing.TYPE_CHECKING:
  46. from typing import Dict, List # noqa: F401
  47. async def read_stream_body(stream):
  48. """Reads an HTTP response from `stream` and returns a tuple of its
  49. start_line, headers and body."""
  50. chunks = []
  51. class Delegate(HTTPMessageDelegate):
  52. def headers_received(self, start_line, headers):
  53. self.headers = headers
  54. self.start_line = start_line
  55. def data_received(self, chunk):
  56. chunks.append(chunk)
  57. def finish(self):
  58. conn.detach() # type: ignore
  59. conn = HTTP1Connection(stream, True)
  60. delegate = Delegate()
  61. await conn.read_response(delegate)
  62. return delegate.start_line, delegate.headers, b"".join(chunks)
  63. class HandlerBaseTestCase(AsyncHTTPTestCase):
  64. def get_app(self):
  65. return Application([("/", self.__class__.Handler)])
  66. def fetch_json(self, *args, **kwargs):
  67. response = self.fetch(*args, **kwargs)
  68. response.rethrow()
  69. return json_decode(response.body)
  70. class HelloWorldRequestHandler(RequestHandler):
  71. def initialize(self, protocol="http"):
  72. self.expected_protocol = protocol
  73. def get(self):
  74. if self.request.protocol != self.expected_protocol:
  75. raise Exception("unexpected protocol")
  76. self.finish("Hello world")
  77. def post(self):
  78. self.finish("Got %d bytes in POST" % len(self.request.body))
  79. # In pre-1.0 versions of openssl, SSLv23 clients always send SSLv2
  80. # ClientHello messages, which are rejected by SSLv3 and TLSv1
  81. # servers. Note that while the OPENSSL_VERSION_INFO was formally
  82. # introduced in python3.2, it was present but undocumented in
  83. # python 2.7
  84. skipIfOldSSL = unittest.skipIf(
  85. getattr(ssl, "OPENSSL_VERSION_INFO", (0, 0)) < (1, 0),
  86. "old version of ssl module and/or openssl",
  87. )
  88. class BaseSSLTest(AsyncHTTPSTestCase):
  89. def get_app(self):
  90. return Application([("/", HelloWorldRequestHandler, dict(protocol="https"))])
  91. class SSLTestMixin(object):
  92. def get_ssl_options(self):
  93. return dict(
  94. ssl_version=self.get_ssl_version(),
  95. **AsyncHTTPSTestCase.default_ssl_options()
  96. )
  97. def get_ssl_version(self):
  98. raise NotImplementedError()
  99. def test_ssl(self):
  100. response = self.fetch("/")
  101. self.assertEqual(response.body, b"Hello world")
  102. def test_large_post(self):
  103. response = self.fetch("/", method="POST", body="A" * 5000)
  104. self.assertEqual(response.body, b"Got 5000 bytes in POST")
  105. def test_non_ssl_request(self):
  106. # Make sure the server closes the connection when it gets a non-ssl
  107. # connection, rather than waiting for a timeout or otherwise
  108. # misbehaving.
  109. with ExpectLog(gen_log, "(SSL Error|uncaught exception)"):
  110. with ExpectLog(gen_log, "Uncaught exception", required=False):
  111. with self.assertRaises((IOError, HTTPError)):
  112. self.fetch(
  113. self.get_url("/").replace("https:", "http:"),
  114. request_timeout=3600,
  115. connect_timeout=3600,
  116. raise_error=True,
  117. )
  118. def test_error_logging(self):
  119. # No stack traces are logged for SSL errors.
  120. with ExpectLog(gen_log, "SSL Error") as expect_log:
  121. with self.assertRaises((IOError, HTTPError)):
  122. self.fetch(
  123. self.get_url("/").replace("https:", "http:"), raise_error=True
  124. )
  125. self.assertFalse(expect_log.logged_stack)
  126. # Python's SSL implementation differs significantly between versions.
  127. # For example, SSLv3 and TLSv1 throw an exception if you try to read
  128. # from the socket before the handshake is complete, but the default
  129. # of SSLv23 allows it.
  130. class SSLv23Test(BaseSSLTest, SSLTestMixin):
  131. def get_ssl_version(self):
  132. return ssl.PROTOCOL_SSLv23
  133. @skipIfOldSSL
  134. class SSLv3Test(BaseSSLTest, SSLTestMixin):
  135. def get_ssl_version(self):
  136. return ssl.PROTOCOL_SSLv3
  137. @skipIfOldSSL
  138. class TLSv1Test(BaseSSLTest, SSLTestMixin):
  139. def get_ssl_version(self):
  140. return ssl.PROTOCOL_TLSv1
  141. class SSLContextTest(BaseSSLTest, SSLTestMixin):
  142. def get_ssl_options(self):
  143. context = ssl_options_to_context(AsyncHTTPSTestCase.get_ssl_options(self))
  144. assert isinstance(context, ssl.SSLContext)
  145. return context
  146. class BadSSLOptionsTest(unittest.TestCase):
  147. def test_missing_arguments(self):
  148. application = Application()
  149. self.assertRaises(
  150. KeyError,
  151. HTTPServer,
  152. application,
  153. ssl_options={"keyfile": "/__missing__.crt"},
  154. )
  155. def test_missing_key(self):
  156. """A missing SSL key should cause an immediate exception."""
  157. application = Application()
  158. module_dir = os.path.dirname(__file__)
  159. existing_certificate = os.path.join(module_dir, "test.crt")
  160. existing_key = os.path.join(module_dir, "test.key")
  161. self.assertRaises(
  162. (ValueError, IOError),
  163. HTTPServer,
  164. application,
  165. ssl_options={"certfile": "/__mising__.crt"},
  166. )
  167. self.assertRaises(
  168. (ValueError, IOError),
  169. HTTPServer,
  170. application,
  171. ssl_options={
  172. "certfile": existing_certificate,
  173. "keyfile": "/__missing__.key",
  174. },
  175. )
  176. # This actually works because both files exist
  177. HTTPServer(
  178. application,
  179. ssl_options={"certfile": existing_certificate, "keyfile": existing_key},
  180. )
  181. class MultipartTestHandler(RequestHandler):
  182. def post(self):
  183. self.finish(
  184. {
  185. "header": self.request.headers["X-Header-Encoding-Test"],
  186. "argument": self.get_argument("argument"),
  187. "filename": self.request.files["files"][0].filename,
  188. "filebody": _unicode(self.request.files["files"][0]["body"]),
  189. }
  190. )
  191. # This test is also called from wsgi_test
  192. class HTTPConnectionTest(AsyncHTTPTestCase):
  193. def get_handlers(self):
  194. return [
  195. ("/multipart", MultipartTestHandler),
  196. ("/hello", HelloWorldRequestHandler),
  197. ]
  198. def get_app(self):
  199. return Application(self.get_handlers())
  200. def raw_fetch(self, headers, body, newline=b"\r\n"):
  201. with closing(IOStream(socket.socket())) as stream:
  202. self.io_loop.run_sync(
  203. lambda: stream.connect(("127.0.0.1", self.get_http_port()))
  204. )
  205. stream.write(
  206. newline.join(headers + [utf8("Content-Length: %d" % len(body))])
  207. + newline
  208. + newline
  209. + body
  210. )
  211. start_line, headers, body = self.io_loop.run_sync(
  212. lambda: read_stream_body(stream)
  213. )
  214. return body
  215. def test_multipart_form(self):
  216. # Encodings here are tricky: Headers are latin1, bodies can be
  217. # anything (we use utf8 by default).
  218. response = self.raw_fetch(
  219. [
  220. b"POST /multipart HTTP/1.0",
  221. b"Content-Type: multipart/form-data; boundary=1234567890",
  222. b"X-Header-encoding-test: \xe9",
  223. ],
  224. b"\r\n".join(
  225. [
  226. b"Content-Disposition: form-data; name=argument",
  227. b"",
  228. u"\u00e1".encode("utf-8"),
  229. b"--1234567890",
  230. u'Content-Disposition: form-data; name="files"; filename="\u00f3"'.encode(
  231. "utf8"
  232. ),
  233. b"",
  234. u"\u00fa".encode("utf-8"),
  235. b"--1234567890--",
  236. b"",
  237. ]
  238. ),
  239. )
  240. data = json_decode(response)
  241. self.assertEqual(u"\u00e9", data["header"])
  242. self.assertEqual(u"\u00e1", data["argument"])
  243. self.assertEqual(u"\u00f3", data["filename"])
  244. self.assertEqual(u"\u00fa", data["filebody"])
  245. def test_newlines(self):
  246. # We support both CRLF and bare LF as line separators.
  247. for newline in (b"\r\n", b"\n"):
  248. response = self.raw_fetch([b"GET /hello HTTP/1.0"], b"", newline=newline)
  249. self.assertEqual(response, b"Hello world")
  250. @gen_test
  251. def test_100_continue(self):
  252. # Run through a 100-continue interaction by hand:
  253. # When given Expect: 100-continue, we get a 100 response after the
  254. # headers, and then the real response after the body.
  255. stream = IOStream(socket.socket())
  256. yield stream.connect(("127.0.0.1", self.get_http_port()))
  257. yield stream.write(
  258. b"\r\n".join(
  259. [
  260. b"POST /hello HTTP/1.1",
  261. b"Content-Length: 1024",
  262. b"Expect: 100-continue",
  263. b"Connection: close",
  264. b"\r\n",
  265. ]
  266. )
  267. )
  268. data = yield stream.read_until(b"\r\n\r\n")
  269. self.assertTrue(data.startswith(b"HTTP/1.1 100 "), data)
  270. stream.write(b"a" * 1024)
  271. first_line = yield stream.read_until(b"\r\n")
  272. self.assertTrue(first_line.startswith(b"HTTP/1.1 200"), first_line)
  273. header_data = yield stream.read_until(b"\r\n\r\n")
  274. headers = HTTPHeaders.parse(native_str(header_data.decode("latin1")))
  275. body = yield stream.read_bytes(int(headers["Content-Length"]))
  276. self.assertEqual(body, b"Got 1024 bytes in POST")
  277. stream.close()
  278. class EchoHandler(RequestHandler):
  279. def get(self):
  280. self.write(recursive_unicode(self.request.arguments))
  281. def post(self):
  282. self.write(recursive_unicode(self.request.arguments))
  283. class TypeCheckHandler(RequestHandler):
  284. def prepare(self):
  285. self.errors = {} # type: Dict[str, str]
  286. fields = [
  287. ("method", str),
  288. ("uri", str),
  289. ("version", str),
  290. ("remote_ip", str),
  291. ("protocol", str),
  292. ("host", str),
  293. ("path", str),
  294. ("query", str),
  295. ]
  296. for field, expected_type in fields:
  297. self.check_type(field, getattr(self.request, field), expected_type)
  298. self.check_type("header_key", list(self.request.headers.keys())[0], str)
  299. self.check_type("header_value", list(self.request.headers.values())[0], str)
  300. self.check_type("cookie_key", list(self.request.cookies.keys())[0], str)
  301. self.check_type(
  302. "cookie_value", list(self.request.cookies.values())[0].value, str
  303. )
  304. # secure cookies
  305. self.check_type("arg_key", list(self.request.arguments.keys())[0], str)
  306. self.check_type("arg_value", list(self.request.arguments.values())[0][0], bytes)
  307. def post(self):
  308. self.check_type("body", self.request.body, bytes)
  309. self.write(self.errors)
  310. def get(self):
  311. self.write(self.errors)
  312. def check_type(self, name, obj, expected_type):
  313. actual_type = type(obj)
  314. if expected_type != actual_type:
  315. self.errors[name] = "expected %s, got %s" % (expected_type, actual_type)
  316. class HTTPServerTest(AsyncHTTPTestCase):
  317. def get_app(self):
  318. return Application(
  319. [
  320. ("/echo", EchoHandler),
  321. ("/typecheck", TypeCheckHandler),
  322. ("//doubleslash", EchoHandler),
  323. ]
  324. )
  325. def test_query_string_encoding(self):
  326. response = self.fetch("/echo?foo=%C3%A9")
  327. data = json_decode(response.body)
  328. self.assertEqual(data, {u"foo": [u"\u00e9"]})
  329. def test_empty_query_string(self):
  330. response = self.fetch("/echo?foo=&foo=")
  331. data = json_decode(response.body)
  332. self.assertEqual(data, {u"foo": [u"", u""]})
  333. def test_empty_post_parameters(self):
  334. response = self.fetch("/echo", method="POST", body="foo=&bar=")
  335. data = json_decode(response.body)
  336. self.assertEqual(data, {u"foo": [u""], u"bar": [u""]})
  337. def test_types(self):
  338. headers = {"Cookie": "foo=bar"}
  339. response = self.fetch("/typecheck?foo=bar", headers=headers)
  340. data = json_decode(response.body)
  341. self.assertEqual(data, {})
  342. response = self.fetch(
  343. "/typecheck", method="POST", body="foo=bar", headers=headers
  344. )
  345. data = json_decode(response.body)
  346. self.assertEqual(data, {})
  347. def test_double_slash(self):
  348. # urlparse.urlsplit (which tornado.httpserver used to use
  349. # incorrectly) would parse paths beginning with "//" as
  350. # protocol-relative urls.
  351. response = self.fetch("//doubleslash")
  352. self.assertEqual(200, response.code)
  353. self.assertEqual(json_decode(response.body), {})
  354. def test_malformed_body(self):
  355. # parse_qs is pretty forgiving, but it will fail on python 3
  356. # if the data is not utf8.
  357. with ExpectLog(gen_log, "Invalid x-www-form-urlencoded body"):
  358. response = self.fetch(
  359. "/echo",
  360. method="POST",
  361. headers={"Content-Type": "application/x-www-form-urlencoded"},
  362. body=b"\xe9",
  363. )
  364. self.assertEqual(200, response.code)
  365. self.assertEqual(b"{}", response.body)
  366. class HTTPServerRawTest(AsyncHTTPTestCase):
  367. def get_app(self):
  368. return Application([("/echo", EchoHandler)])
  369. def setUp(self):
  370. super(HTTPServerRawTest, self).setUp()
  371. self.stream = IOStream(socket.socket())
  372. self.io_loop.run_sync(
  373. lambda: self.stream.connect(("127.0.0.1", self.get_http_port()))
  374. )
  375. def tearDown(self):
  376. self.stream.close()
  377. super(HTTPServerRawTest, self).tearDown()
  378. def test_empty_request(self):
  379. self.stream.close()
  380. self.io_loop.add_timeout(datetime.timedelta(seconds=0.001), self.stop)
  381. self.wait()
  382. def test_malformed_first_line_response(self):
  383. with ExpectLog(gen_log, ".*Malformed HTTP request line"):
  384. self.stream.write(b"asdf\r\n\r\n")
  385. start_line, headers, response = self.io_loop.run_sync(
  386. lambda: read_stream_body(self.stream)
  387. )
  388. self.assertEqual("HTTP/1.1", start_line.version)
  389. self.assertEqual(400, start_line.code)
  390. self.assertEqual("Bad Request", start_line.reason)
  391. def test_malformed_first_line_log(self):
  392. with ExpectLog(gen_log, ".*Malformed HTTP request line"):
  393. self.stream.write(b"asdf\r\n\r\n")
  394. # TODO: need an async version of ExpectLog so we don't need
  395. # hard-coded timeouts here.
  396. self.io_loop.add_timeout(datetime.timedelta(seconds=0.05), self.stop)
  397. self.wait()
  398. def test_malformed_headers(self):
  399. with ExpectLog(gen_log, ".*Malformed HTTP message.*no colon in header line"):
  400. self.stream.write(b"GET / HTTP/1.0\r\nasdf\r\n\r\n")
  401. self.io_loop.add_timeout(datetime.timedelta(seconds=0.05), self.stop)
  402. self.wait()
  403. def test_chunked_request_body(self):
  404. # Chunked requests are not widely supported and we don't have a way
  405. # to generate them in AsyncHTTPClient, but HTTPServer will read them.
  406. self.stream.write(
  407. b"""\
  408. POST /echo HTTP/1.1
  409. Transfer-Encoding: chunked
  410. Content-Type: application/x-www-form-urlencoded
  411. 4
  412. foo=
  413. 3
  414. bar
  415. 0
  416. """.replace(
  417. b"\n", b"\r\n"
  418. )
  419. )
  420. start_line, headers, response = self.io_loop.run_sync(
  421. lambda: read_stream_body(self.stream)
  422. )
  423. self.assertEqual(json_decode(response), {u"foo": [u"bar"]})
  424. def test_chunked_request_uppercase(self):
  425. # As per RFC 2616 section 3.6, "Transfer-Encoding" header's value is
  426. # case-insensitive.
  427. self.stream.write(
  428. b"""\
  429. POST /echo HTTP/1.1
  430. Transfer-Encoding: Chunked
  431. Content-Type: application/x-www-form-urlencoded
  432. 4
  433. foo=
  434. 3
  435. bar
  436. 0
  437. """.replace(
  438. b"\n", b"\r\n"
  439. )
  440. )
  441. start_line, headers, response = self.io_loop.run_sync(
  442. lambda: read_stream_body(self.stream)
  443. )
  444. self.assertEqual(json_decode(response), {u"foo": [u"bar"]})
  445. @gen_test
  446. def test_invalid_content_length(self):
  447. with ExpectLog(gen_log, ".*Only integer Content-Length is allowed"):
  448. self.stream.write(
  449. b"""\
  450. POST /echo HTTP/1.1
  451. Content-Length: foo
  452. bar
  453. """.replace(
  454. b"\n", b"\r\n"
  455. )
  456. )
  457. yield self.stream.read_until_close()
  458. class XHeaderTest(HandlerBaseTestCase):
  459. class Handler(RequestHandler):
  460. def get(self):
  461. self.set_header("request-version", self.request.version)
  462. self.write(
  463. dict(
  464. remote_ip=self.request.remote_ip,
  465. remote_protocol=self.request.protocol,
  466. )
  467. )
  468. def get_httpserver_options(self):
  469. return dict(xheaders=True, trusted_downstream=["5.5.5.5"])
  470. def test_ip_headers(self):
  471. self.assertEqual(self.fetch_json("/")["remote_ip"], "127.0.0.1")
  472. valid_ipv4 = {"X-Real-IP": "4.4.4.4"}
  473. self.assertEqual(
  474. self.fetch_json("/", headers=valid_ipv4)["remote_ip"], "4.4.4.4"
  475. )
  476. valid_ipv4_list = {"X-Forwarded-For": "127.0.0.1, 4.4.4.4"}
  477. self.assertEqual(
  478. self.fetch_json("/", headers=valid_ipv4_list)["remote_ip"], "4.4.4.4"
  479. )
  480. valid_ipv6 = {"X-Real-IP": "2620:0:1cfe:face:b00c::3"}
  481. self.assertEqual(
  482. self.fetch_json("/", headers=valid_ipv6)["remote_ip"],
  483. "2620:0:1cfe:face:b00c::3",
  484. )
  485. valid_ipv6_list = {"X-Forwarded-For": "::1, 2620:0:1cfe:face:b00c::3"}
  486. self.assertEqual(
  487. self.fetch_json("/", headers=valid_ipv6_list)["remote_ip"],
  488. "2620:0:1cfe:face:b00c::3",
  489. )
  490. invalid_chars = {"X-Real-IP": "4.4.4.4<script>"}
  491. self.assertEqual(
  492. self.fetch_json("/", headers=invalid_chars)["remote_ip"], "127.0.0.1"
  493. )
  494. invalid_chars_list = {"X-Forwarded-For": "4.4.4.4, 5.5.5.5<script>"}
  495. self.assertEqual(
  496. self.fetch_json("/", headers=invalid_chars_list)["remote_ip"], "127.0.0.1"
  497. )
  498. invalid_host = {"X-Real-IP": "www.google.com"}
  499. self.assertEqual(
  500. self.fetch_json("/", headers=invalid_host)["remote_ip"], "127.0.0.1"
  501. )
  502. def test_trusted_downstream(self):
  503. valid_ipv4_list = {"X-Forwarded-For": "127.0.0.1, 4.4.4.4, 5.5.5.5"}
  504. resp = self.fetch("/", headers=valid_ipv4_list)
  505. if resp.headers["request-version"].startswith("HTTP/2"):
  506. # This is a hack - there's nothing that fundamentally requires http/1
  507. # here but tornado_http2 doesn't support it yet.
  508. self.skipTest("requires HTTP/1.x")
  509. result = json_decode(resp.body)
  510. self.assertEqual(result["remote_ip"], "4.4.4.4")
  511. def test_scheme_headers(self):
  512. self.assertEqual(self.fetch_json("/")["remote_protocol"], "http")
  513. https_scheme = {"X-Scheme": "https"}
  514. self.assertEqual(
  515. self.fetch_json("/", headers=https_scheme)["remote_protocol"], "https"
  516. )
  517. https_forwarded = {"X-Forwarded-Proto": "https"}
  518. self.assertEqual(
  519. self.fetch_json("/", headers=https_forwarded)["remote_protocol"], "https"
  520. )
  521. https_multi_forwarded = {"X-Forwarded-Proto": "https , http"}
  522. self.assertEqual(
  523. self.fetch_json("/", headers=https_multi_forwarded)["remote_protocol"],
  524. "http",
  525. )
  526. http_multi_forwarded = {"X-Forwarded-Proto": "http,https"}
  527. self.assertEqual(
  528. self.fetch_json("/", headers=http_multi_forwarded)["remote_protocol"],
  529. "https",
  530. )
  531. bad_forwarded = {"X-Forwarded-Proto": "unknown"}
  532. self.assertEqual(
  533. self.fetch_json("/", headers=bad_forwarded)["remote_protocol"], "http"
  534. )
  535. class SSLXHeaderTest(AsyncHTTPSTestCase, HandlerBaseTestCase):
  536. def get_app(self):
  537. return Application([("/", XHeaderTest.Handler)])
  538. def get_httpserver_options(self):
  539. output = super(SSLXHeaderTest, self).get_httpserver_options()
  540. output["xheaders"] = True
  541. return output
  542. def test_request_without_xprotocol(self):
  543. self.assertEqual(self.fetch_json("/")["remote_protocol"], "https")
  544. http_scheme = {"X-Scheme": "http"}
  545. self.assertEqual(
  546. self.fetch_json("/", headers=http_scheme)["remote_protocol"], "http"
  547. )
  548. bad_scheme = {"X-Scheme": "unknown"}
  549. self.assertEqual(
  550. self.fetch_json("/", headers=bad_scheme)["remote_protocol"], "https"
  551. )
  552. class ManualProtocolTest(HandlerBaseTestCase):
  553. class Handler(RequestHandler):
  554. def get(self):
  555. self.write(dict(protocol=self.request.protocol))
  556. def get_httpserver_options(self):
  557. return dict(protocol="https")
  558. def test_manual_protocol(self):
  559. self.assertEqual(self.fetch_json("/")["protocol"], "https")
  560. @unittest.skipIf(
  561. not hasattr(socket, "AF_UNIX") or sys.platform == "cygwin",
  562. "unix sockets not supported on this platform",
  563. )
  564. class UnixSocketTest(AsyncTestCase):
  565. """HTTPServers can listen on Unix sockets too.
  566. Why would you want to do this? Nginx can proxy to backends listening
  567. on unix sockets, for one thing (and managing a namespace for unix
  568. sockets can be easier than managing a bunch of TCP port numbers).
  569. Unfortunately, there's no way to specify a unix socket in a url for
  570. an HTTP client, so we have to test this by hand.
  571. """
  572. def setUp(self):
  573. super(UnixSocketTest, self).setUp()
  574. self.tmpdir = tempfile.mkdtemp()
  575. self.sockfile = os.path.join(self.tmpdir, "test.sock")
  576. sock = netutil.bind_unix_socket(self.sockfile)
  577. app = Application([("/hello", HelloWorldRequestHandler)])
  578. self.server = HTTPServer(app)
  579. self.server.add_socket(sock)
  580. self.stream = IOStream(socket.socket(socket.AF_UNIX))
  581. self.io_loop.run_sync(lambda: self.stream.connect(self.sockfile))
  582. def tearDown(self):
  583. self.stream.close()
  584. self.io_loop.run_sync(self.server.close_all_connections)
  585. self.server.stop()
  586. shutil.rmtree(self.tmpdir)
  587. super(UnixSocketTest, self).tearDown()
  588. @gen_test
  589. def test_unix_socket(self):
  590. self.stream.write(b"GET /hello HTTP/1.0\r\n\r\n")
  591. response = yield self.stream.read_until(b"\r\n")
  592. self.assertEqual(response, b"HTTP/1.1 200 OK\r\n")
  593. header_data = yield self.stream.read_until(b"\r\n\r\n")
  594. headers = HTTPHeaders.parse(header_data.decode("latin1"))
  595. body = yield self.stream.read_bytes(int(headers["Content-Length"]))
  596. self.assertEqual(body, b"Hello world")
  597. @gen_test
  598. def test_unix_socket_bad_request(self):
  599. # Unix sockets don't have remote addresses so they just return an
  600. # empty string.
  601. with ExpectLog(gen_log, "Malformed HTTP message from"):
  602. self.stream.write(b"garbage\r\n\r\n")
  603. response = yield self.stream.read_until_close()
  604. self.assertEqual(response, b"HTTP/1.1 400 Bad Request\r\n\r\n")
  605. class KeepAliveTest(AsyncHTTPTestCase):
  606. """Tests various scenarios for HTTP 1.1 keep-alive support.
  607. These tests don't use AsyncHTTPClient because we want to control
  608. connection reuse and closing.
  609. """
  610. def get_app(self):
  611. class HelloHandler(RequestHandler):
  612. def get(self):
  613. self.finish("Hello world")
  614. def post(self):
  615. self.finish("Hello world")
  616. class LargeHandler(RequestHandler):
  617. def get(self):
  618. # 512KB should be bigger than the socket buffers so it will
  619. # be written out in chunks.
  620. self.write("".join(chr(i % 256) * 1024 for i in range(512)))
  621. class FinishOnCloseHandler(RequestHandler):
  622. def initialize(self, cleanup_event):
  623. self.cleanup_event = cleanup_event
  624. @gen.coroutine
  625. def get(self):
  626. self.flush()
  627. yield self.cleanup_event.wait()
  628. def on_connection_close(self):
  629. # This is not very realistic, but finishing the request
  630. # from the close callback has the right timing to mimic
  631. # some errors seen in the wild.
  632. self.finish("closed")
  633. self.cleanup_event = Event()
  634. return Application(
  635. [
  636. ("/", HelloHandler),
  637. ("/large", LargeHandler),
  638. (
  639. "/finish_on_close",
  640. FinishOnCloseHandler,
  641. dict(cleanup_event=self.cleanup_event),
  642. ),
  643. ]
  644. )
  645. def setUp(self):
  646. super(KeepAliveTest, self).setUp()
  647. self.http_version = b"HTTP/1.1"
  648. def tearDown(self):
  649. # We just closed the client side of the socket; let the IOLoop run
  650. # once to make sure the server side got the message.
  651. self.io_loop.add_timeout(datetime.timedelta(seconds=0.001), self.stop)
  652. self.wait()
  653. if hasattr(self, "stream"):
  654. self.stream.close()
  655. super(KeepAliveTest, self).tearDown()
  656. # The next few methods are a crude manual http client
  657. @gen.coroutine
  658. def connect(self):
  659. self.stream = IOStream(socket.socket())
  660. yield self.stream.connect(("127.0.0.1", self.get_http_port()))
  661. @gen.coroutine
  662. def read_headers(self):
  663. first_line = yield self.stream.read_until(b"\r\n")
  664. self.assertTrue(first_line.startswith(b"HTTP/1.1 200"), first_line)
  665. header_bytes = yield self.stream.read_until(b"\r\n\r\n")
  666. headers = HTTPHeaders.parse(header_bytes.decode("latin1"))
  667. raise gen.Return(headers)
  668. @gen.coroutine
  669. def read_response(self):
  670. self.headers = yield self.read_headers()
  671. body = yield self.stream.read_bytes(int(self.headers["Content-Length"]))
  672. self.assertEqual(b"Hello world", body)
  673. def close(self):
  674. self.stream.close()
  675. del self.stream
  676. @gen_test
  677. def test_two_requests(self):
  678. yield self.connect()
  679. self.stream.write(b"GET / HTTP/1.1\r\n\r\n")
  680. yield self.read_response()
  681. self.stream.write(b"GET / HTTP/1.1\r\n\r\n")
  682. yield self.read_response()
  683. self.close()
  684. @gen_test
  685. def test_request_close(self):
  686. yield self.connect()
  687. self.stream.write(b"GET / HTTP/1.1\r\nConnection: close\r\n\r\n")
  688. yield self.read_response()
  689. data = yield self.stream.read_until_close()
  690. self.assertTrue(not data)
  691. self.assertEqual(self.headers["Connection"], "close")
  692. self.close()
  693. # keepalive is supported for http 1.0 too, but it's opt-in
  694. @gen_test
  695. def test_http10(self):
  696. self.http_version = b"HTTP/1.0"
  697. yield self.connect()
  698. self.stream.write(b"GET / HTTP/1.0\r\n\r\n")
  699. yield self.read_response()
  700. data = yield self.stream.read_until_close()
  701. self.assertTrue(not data)
  702. self.assertTrue("Connection" not in self.headers)
  703. self.close()
  704. @gen_test
  705. def test_http10_keepalive(self):
  706. self.http_version = b"HTTP/1.0"
  707. yield self.connect()
  708. self.stream.write(b"GET / HTTP/1.0\r\nConnection: keep-alive\r\n\r\n")
  709. yield self.read_response()
  710. self.assertEqual(self.headers["Connection"], "Keep-Alive")
  711. self.stream.write(b"GET / HTTP/1.0\r\nConnection: keep-alive\r\n\r\n")
  712. yield self.read_response()
  713. self.assertEqual(self.headers["Connection"], "Keep-Alive")
  714. self.close()
  715. @gen_test
  716. def test_http10_keepalive_extra_crlf(self):
  717. self.http_version = b"HTTP/1.0"
  718. yield self.connect()
  719. self.stream.write(b"GET / HTTP/1.0\r\nConnection: keep-alive\r\n\r\n\r\n")
  720. yield self.read_response()
  721. self.assertEqual(self.headers["Connection"], "Keep-Alive")
  722. self.stream.write(b"GET / HTTP/1.0\r\nConnection: keep-alive\r\n\r\n")
  723. yield self.read_response()
  724. self.assertEqual(self.headers["Connection"], "Keep-Alive")
  725. self.close()
  726. @gen_test
  727. def test_pipelined_requests(self):
  728. yield self.connect()
  729. self.stream.write(b"GET / HTTP/1.1\r\n\r\nGET / HTTP/1.1\r\n\r\n")
  730. yield self.read_response()
  731. yield self.read_response()
  732. self.close()
  733. @gen_test
  734. def test_pipelined_cancel(self):
  735. yield self.connect()
  736. self.stream.write(b"GET / HTTP/1.1\r\n\r\nGET / HTTP/1.1\r\n\r\n")
  737. # only read once
  738. yield self.read_response()
  739. self.close()
  740. @gen_test
  741. def test_cancel_during_download(self):
  742. yield self.connect()
  743. self.stream.write(b"GET /large HTTP/1.1\r\n\r\n")
  744. yield self.read_headers()
  745. yield self.stream.read_bytes(1024)
  746. self.close()
  747. @gen_test
  748. def test_finish_while_closed(self):
  749. yield self.connect()
  750. self.stream.write(b"GET /finish_on_close HTTP/1.1\r\n\r\n")
  751. yield self.read_headers()
  752. self.close()
  753. # Let the hanging coroutine clean up after itself
  754. self.cleanup_event.set()
  755. @gen_test
  756. def test_keepalive_chunked(self):
  757. self.http_version = b"HTTP/1.0"
  758. yield self.connect()
  759. self.stream.write(
  760. b"POST / HTTP/1.0\r\n"
  761. b"Connection: keep-alive\r\n"
  762. b"Transfer-Encoding: chunked\r\n"
  763. b"\r\n"
  764. b"0\r\n"
  765. b"\r\n"
  766. )
  767. yield self.read_response()
  768. self.assertEqual(self.headers["Connection"], "Keep-Alive")
  769. self.stream.write(b"GET / HTTP/1.0\r\nConnection: keep-alive\r\n\r\n")
  770. yield self.read_response()
  771. self.assertEqual(self.headers["Connection"], "Keep-Alive")
  772. self.close()
  773. class GzipBaseTest(object):
  774. def get_app(self):
  775. return Application([("/", EchoHandler)])
  776. def post_gzip(self, body):
  777. bytesio = BytesIO()
  778. gzip_file = gzip.GzipFile(mode="w", fileobj=bytesio)
  779. gzip_file.write(utf8(body))
  780. gzip_file.close()
  781. compressed_body = bytesio.getvalue()
  782. return self.fetch(
  783. "/",
  784. method="POST",
  785. body=compressed_body,
  786. headers={"Content-Encoding": "gzip"},
  787. )
  788. def test_uncompressed(self):
  789. response = self.fetch("/", method="POST", body="foo=bar")
  790. self.assertEquals(json_decode(response.body), {u"foo": [u"bar"]})
  791. class GzipTest(GzipBaseTest, AsyncHTTPTestCase):
  792. def get_httpserver_options(self):
  793. return dict(decompress_request=True)
  794. def test_gzip(self):
  795. response = self.post_gzip("foo=bar")
  796. self.assertEquals(json_decode(response.body), {u"foo": [u"bar"]})
  797. class GzipUnsupportedTest(GzipBaseTest, AsyncHTTPTestCase):
  798. def test_gzip_unsupported(self):
  799. # Gzip support is opt-in; without it the server fails to parse
  800. # the body (but parsing form bodies is currently just a log message,
  801. # not a fatal error).
  802. with ExpectLog(gen_log, "Unsupported Content-Encoding"):
  803. response = self.post_gzip("foo=bar")
  804. self.assertEquals(json_decode(response.body), {})
  805. class StreamingChunkSizeTest(AsyncHTTPTestCase):
  806. # 50 characters long, and repetitive so it can be compressed.
  807. BODY = b"01234567890123456789012345678901234567890123456789"
  808. CHUNK_SIZE = 16
  809. def get_http_client(self):
  810. # body_producer doesn't work on curl_httpclient, so override the
  811. # configured AsyncHTTPClient implementation.
  812. return SimpleAsyncHTTPClient()
  813. def get_httpserver_options(self):
  814. return dict(chunk_size=self.CHUNK_SIZE, decompress_request=True)
  815. class MessageDelegate(HTTPMessageDelegate):
  816. def __init__(self, connection):
  817. self.connection = connection
  818. def headers_received(self, start_line, headers):
  819. self.chunk_lengths = [] # type: List[int]
  820. def data_received(self, chunk):
  821. self.chunk_lengths.append(len(chunk))
  822. def finish(self):
  823. response_body = utf8(json_encode(self.chunk_lengths))
  824. self.connection.write_headers(
  825. ResponseStartLine("HTTP/1.1", 200, "OK"),
  826. HTTPHeaders({"Content-Length": str(len(response_body))}),
  827. )
  828. self.connection.write(response_body)
  829. self.connection.finish()
  830. def get_app(self):
  831. class App(HTTPServerConnectionDelegate):
  832. def start_request(self, server_conn, request_conn):
  833. return StreamingChunkSizeTest.MessageDelegate(request_conn)
  834. return App()
  835. def fetch_chunk_sizes(self, **kwargs):
  836. response = self.fetch("/", method="POST", **kwargs)
  837. response.rethrow()
  838. chunks = json_decode(response.body)
  839. self.assertEqual(len(self.BODY), sum(chunks))
  840. for chunk_size in chunks:
  841. self.assertLessEqual(
  842. chunk_size, self.CHUNK_SIZE, "oversized chunk: " + str(chunks)
  843. )
  844. self.assertGreater(chunk_size, 0, "empty chunk: " + str(chunks))
  845. return chunks
  846. def compress(self, body):
  847. bytesio = BytesIO()
  848. gzfile = gzip.GzipFile(mode="w", fileobj=bytesio)
  849. gzfile.write(body)
  850. gzfile.close()
  851. compressed = bytesio.getvalue()
  852. if len(compressed) >= len(body):
  853. raise Exception("body did not shrink when compressed")
  854. return compressed
  855. def test_regular_body(self):
  856. chunks = self.fetch_chunk_sizes(body=self.BODY)
  857. # Without compression we know exactly what to expect.
  858. self.assertEqual([16, 16, 16, 2], chunks)
  859. def test_compressed_body(self):
  860. self.fetch_chunk_sizes(
  861. body=self.compress(self.BODY), headers={"Content-Encoding": "gzip"}
  862. )
  863. # Compression creates irregular boundaries so the assertions
  864. # in fetch_chunk_sizes are as specific as we can get.
  865. def test_chunked_body(self):
  866. def body_producer(write):
  867. write(self.BODY[:20])
  868. write(self.BODY[20:])
  869. chunks = self.fetch_chunk_sizes(body_producer=body_producer)
  870. # HTTP chunk boundaries translate to application-visible breaks
  871. self.assertEqual([16, 4, 16, 14], chunks)
  872. def test_chunked_compressed(self):
  873. compressed = self.compress(self.BODY)
  874. self.assertGreater(len(compressed), 20)
  875. def body_producer(write):
  876. write(compressed[:20])
  877. write(compressed[20:])
  878. self.fetch_chunk_sizes(
  879. body_producer=body_producer, headers={"Content-Encoding": "gzip"}
  880. )
  881. class MaxHeaderSizeTest(AsyncHTTPTestCase):
  882. def get_app(self):
  883. return Application([("/", HelloWorldRequestHandler)])
  884. def get_httpserver_options(self):
  885. return dict(max_header_size=1024)
  886. def test_small_headers(self):
  887. response = self.fetch("/", headers={"X-Filler": "a" * 100})
  888. response.rethrow()
  889. self.assertEqual(response.body, b"Hello world")
  890. def test_large_headers(self):
  891. with ExpectLog(gen_log, "Unsatisfiable read", required=False):
  892. try:
  893. self.fetch("/", headers={"X-Filler": "a" * 1000}, raise_error=True)
  894. self.fail("did not raise expected exception")
  895. except HTTPError as e:
  896. # 431 is "Request Header Fields Too Large", defined in RFC
  897. # 6585. However, many implementations just close the
  898. # connection in this case, resulting in a missing response.
  899. if e.response is not None:
  900. self.assertIn(e.response.code, (431, 599))
  901. @skipOnTravis
  902. class IdleTimeoutTest(AsyncHTTPTestCase):
  903. def get_app(self):
  904. return Application([("/", HelloWorldRequestHandler)])
  905. def get_httpserver_options(self):
  906. return dict(idle_connection_timeout=0.1)
  907. def setUp(self):
  908. super(IdleTimeoutTest, self).setUp()
  909. self.streams = [] # type: List[IOStream]
  910. def tearDown(self):
  911. super(IdleTimeoutTest, self).tearDown()
  912. for stream in self.streams:
  913. stream.close()
  914. @gen.coroutine
  915. def connect(self):
  916. stream = IOStream(socket.socket())
  917. yield stream.connect(("127.0.0.1", self.get_http_port()))
  918. self.streams.append(stream)
  919. raise gen.Return(stream)
  920. @gen_test
  921. def test_unused_connection(self):
  922. stream = yield self.connect()
  923. event = Event()
  924. stream.set_close_callback(event.set)
  925. yield event.wait()
  926. @gen_test
  927. def test_idle_after_use(self):
  928. stream = yield self.connect()
  929. event = Event()
  930. stream.set_close_callback(event.set)
  931. # Use the connection twice to make sure keep-alives are working
  932. for i in range(2):
  933. stream.write(b"GET / HTTP/1.1\r\n\r\n")
  934. yield stream.read_until(b"\r\n\r\n")
  935. data = yield stream.read_bytes(11)
  936. self.assertEqual(data, b"Hello world")
  937. # Now let the timeout trigger and close the connection.
  938. yield event.wait()
  939. class BodyLimitsTest(AsyncHTTPTestCase):
  940. def get_app(self):
  941. class BufferedHandler(RequestHandler):
  942. def put(self):
  943. self.write(str(len(self.request.body)))
  944. @stream_request_body
  945. class StreamingHandler(RequestHandler):
  946. def initialize(self):
  947. self.bytes_read = 0
  948. def prepare(self):
  949. if "expected_size" in self.request.arguments:
  950. self.request.connection.set_max_body_size(
  951. int(self.get_argument("expected_size"))
  952. )
  953. if "body_timeout" in self.request.arguments:
  954. self.request.connection.set_body_timeout(
  955. float(self.get_argument("body_timeout"))
  956. )
  957. def data_received(self, data):
  958. self.bytes_read += len(data)
  959. def put(self):
  960. self.write(str(self.bytes_read))
  961. return Application(
  962. [("/buffered", BufferedHandler), ("/streaming", StreamingHandler)]
  963. )
  964. def get_httpserver_options(self):
  965. return dict(body_timeout=3600, max_body_size=4096)
  966. def get_http_client(self):
  967. # body_producer doesn't work on curl_httpclient, so override the
  968. # configured AsyncHTTPClient implementation.
  969. return SimpleAsyncHTTPClient()
  970. def test_small_body(self):
  971. response = self.fetch("/buffered", method="PUT", body=b"a" * 4096)
  972. self.assertEqual(response.body, b"4096")
  973. response = self.fetch("/streaming", method="PUT", body=b"a" * 4096)
  974. self.assertEqual(response.body, b"4096")
  975. def test_large_body_buffered(self):
  976. with ExpectLog(gen_log, ".*Content-Length too long"):
  977. response = self.fetch("/buffered", method="PUT", body=b"a" * 10240)
  978. self.assertEqual(response.code, 400)
  979. @unittest.skipIf(os.name == "nt", "flaky on windows")
  980. def test_large_body_buffered_chunked(self):
  981. # This test is flaky on windows for unknown reasons.
  982. with ExpectLog(gen_log, ".*chunked body too large"):
  983. response = self.fetch(
  984. "/buffered",
  985. method="PUT",
  986. body_producer=lambda write: write(b"a" * 10240),
  987. )
  988. self.assertEqual(response.code, 400)
  989. def test_large_body_streaming(self):
  990. with ExpectLog(gen_log, ".*Content-Length too long"):
  991. response = self.fetch("/streaming", method="PUT", body=b"a" * 10240)
  992. self.assertEqual(response.code, 400)
  993. @unittest.skipIf(os.name == "nt", "flaky on windows")
  994. def test_large_body_streaming_chunked(self):
  995. with ExpectLog(gen_log, ".*chunked body too large"):
  996. response = self.fetch(
  997. "/streaming",
  998. method="PUT",
  999. body_producer=lambda write: write(b"a" * 10240),
  1000. )
  1001. self.assertEqual(response.code, 400)
  1002. def test_large_body_streaming_override(self):
  1003. response = self.fetch(
  1004. "/streaming?expected_size=10240", method="PUT", body=b"a" * 10240
  1005. )
  1006. self.assertEqual(response.body, b"10240")
  1007. def test_large_body_streaming_chunked_override(self):
  1008. response = self.fetch(
  1009. "/streaming?expected_size=10240",
  1010. method="PUT",
  1011. body_producer=lambda write: write(b"a" * 10240),
  1012. )
  1013. self.assertEqual(response.body, b"10240")
  1014. @gen_test
  1015. def test_timeout(self):
  1016. stream = IOStream(socket.socket())
  1017. try:
  1018. yield stream.connect(("127.0.0.1", self.get_http_port()))
  1019. # Use a raw stream because AsyncHTTPClient won't let us read a
  1020. # response without finishing a body.
  1021. stream.write(
  1022. b"PUT /streaming?body_timeout=0.1 HTTP/1.0\r\n"
  1023. b"Content-Length: 42\r\n\r\n"
  1024. )
  1025. with ExpectLog(gen_log, "Timeout reading body"):
  1026. response = yield stream.read_until_close()
  1027. self.assertEqual(response, b"")
  1028. finally:
  1029. stream.close()
  1030. @gen_test
  1031. def test_body_size_override_reset(self):
  1032. # The max_body_size override is reset between requests.
  1033. stream = IOStream(socket.socket())
  1034. try:
  1035. yield stream.connect(("127.0.0.1", self.get_http_port()))
  1036. # Use a raw stream so we can make sure it's all on one connection.
  1037. stream.write(
  1038. b"PUT /streaming?expected_size=10240 HTTP/1.1\r\n"
  1039. b"Content-Length: 10240\r\n\r\n"
  1040. )
  1041. stream.write(b"a" * 10240)
  1042. start_line, headers, response = yield read_stream_body(stream)
  1043. self.assertEqual(response, b"10240")
  1044. # Without the ?expected_size parameter, we get the old default value
  1045. stream.write(
  1046. b"PUT /streaming HTTP/1.1\r\n" b"Content-Length: 10240\r\n\r\n"
  1047. )
  1048. with ExpectLog(gen_log, ".*Content-Length too long"):
  1049. data = yield stream.read_until_close()
  1050. self.assertEqual(data, b"HTTP/1.1 400 Bad Request\r\n\r\n")
  1051. finally:
  1052. stream.close()
  1053. class LegacyInterfaceTest(AsyncHTTPTestCase):
  1054. def get_app(self):
  1055. # The old request_callback interface does not implement the
  1056. # delegate interface, and writes its response via request.write
  1057. # instead of request.connection.write_headers.
  1058. def handle_request(request):
  1059. self.http1 = request.version.startswith("HTTP/1.")
  1060. if not self.http1:
  1061. # This test will be skipped if we're using HTTP/2,
  1062. # so just close it out cleanly using the modern interface.
  1063. request.connection.write_headers(
  1064. ResponseStartLine("", 200, "OK"), HTTPHeaders()
  1065. )
  1066. request.connection.finish()
  1067. return
  1068. message = b"Hello world"
  1069. request.connection.write(
  1070. utf8("HTTP/1.1 200 OK\r\n" "Content-Length: %d\r\n\r\n" % len(message))
  1071. )
  1072. request.connection.write(message)
  1073. request.connection.finish()
  1074. return handle_request
  1075. def test_legacy_interface(self):
  1076. response = self.fetch("/")
  1077. if not self.http1:
  1078. self.skipTest("requires HTTP/1.x")
  1079. self.assertEqual(response.body, b"Hello world")