1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765
|
import errno
from http import client as httplib
import logging
import multiprocessing
import os
import signal
import socket
import string
import subprocess
import sys
import time
import unittest
from waitress import server
from waitress.compat import WIN
from waitress.utilities import cleanup_unix_socket
dn = os.path.dirname
here = dn(__file__)
class NullHandler(logging.Handler): # pragma: no cover
"""A logging handler that swallows all emitted messages."""
def emit(self, record):
pass
def start_server(app, svr, queue, **kwargs): # pragma: no cover
"""Run a fixture application."""
logging.getLogger("waitress").addHandler(NullHandler())
svr(app, queue, **kwargs).run()
class FixtureTcpWSGIServer(server.TcpWSGIServer):
"""A version of TcpWSGIServer that relays back what it's bound to."""
family = socket.AF_INET # Testing
def __init__(self, application, queue, **kw): # pragma: no cover
# Coverage doesn't see this as it's ran in a separate process.
kw["host"] = "127.0.0.1"
kw["port"] = 0 # Bind to any available port.
super().__init__(application, **kw)
host, port = self.socket.getsockname()
if os.name == "nt":
host = "127.0.0.1"
queue.put((host, port))
class SubprocessTests:
exe = sys.executable
server = None
def start_subprocess(self, target, **kw):
# Spawn a server process.
self.queue = multiprocessing.Queue()
if "COVERAGE_RCFILE" in os.environ:
os.environ["COVERAGE_PROCESS_START"] = os.environ["COVERAGE_RCFILE"]
if not WIN:
ctx = multiprocessing.get_context("fork")
else:
ctx = multiprocessing.get_context("spawn")
self.proc = ctx.Process(
target=start_server,
args=(target, self.server, self.queue),
kwargs=kw,
)
self.proc.start()
if self.proc.exitcode is not None: # pragma: no cover
raise RuntimeError("%s didn't start" % str(target))
# Get the socket the server is listening on.
self.bound_to = self.queue.get(timeout=5)
self.sock = self.create_socket()
def stop_subprocess(self):
if self.proc.exitcode is None:
self.proc.terminate()
self.sock.close()
# This give us one FD back ...
self.proc.join()
self.proc.close()
self.queue.close()
self.queue.join_thread()
# The following is for the benefit of PyPy 3, for some reason it is
# holding on to some resources way longer than necessary causing tests
# to fail with file descriptor exceeded errors on macOS which defaults
# to 256 file descriptors per process. While we could use ulimit to
# increase the limits before running tests, this works as well and
# means we don't need to remember to do that.
import gc
gc.collect()
def assertline(self, line, status, reason, version):
v, s, r = (x.strip() for x in line.split(None, 2))
self.assertEqual(s, status.encode("latin-1"))
self.assertEqual(r, reason.encode("latin-1"))
self.assertEqual(v, version.encode("latin-1"))
def create_socket(self):
return socket.socket(self.server.family, socket.SOCK_STREAM)
def connect(self):
self.sock.connect(self.bound_to)
def make_http_connection(self):
raise NotImplementedError # pragma: no cover
def send_check_error(self, to_send):
self.sock.send(to_send)
class TcpTests(SubprocessTests):
server = FixtureTcpWSGIServer
def make_http_connection(self):
return httplib.HTTPConnection(*self.bound_to)
class SleepyThreadTests(TcpTests, unittest.TestCase):
# test that sleepy thread doesnt block other requests
def setUp(self):
from tests.fixtureapps import sleepy
self.start_subprocess(sleepy.app)
def tearDown(self):
self.stop_subprocess()
def test_it(self):
getline = os.path.join(here, "fixtureapps", "getline.py")
cmds = (
[self.exe, getline, "http://%s:%d/sleepy" % self.bound_to],
[self.exe, getline, "http://%s:%d/" % self.bound_to],
)
r, w = os.pipe()
procs = []
for cmd in cmds:
procs.append(subprocess.Popen(cmd, stdout=w))
time.sleep(3)
for proc in procs:
if proc.returncode is not None: # pragma: no cover
proc.terminate()
proc.wait()
# the notsleepy response should always be first returned (it sleeps
# for 2 seconds, then returns; the notsleepy response should be
# processed in the meantime)
result = os.read(r, 10000)
os.close(r)
os.close(w)
self.assertEqual(result, b"notsleepy returnedsleepy returned")
class EchoTests:
def setUp(self):
from tests.fixtureapps import echo
self.start_subprocess(
echo.app,
trusted_proxy="*",
trusted_proxy_count=1,
trusted_proxy_headers={"x-forwarded-for", "x-forwarded-proto"},
clear_untrusted_proxy_headers=True,
)
def tearDown(self):
self.stop_subprocess()
def _read_echo(self, fp):
from tests.fixtureapps import echo
line, headers, body = read_http(fp)
return line, headers, echo.parse_response(body)
def test_date_and_server(self):
to_send = b"GET / HTTP/1.0\r\nContent-Length: 0\r\n\r\n"
self.connect()
self.sock.send(to_send)
with self.sock.makefile("rb", 0) as fp:
line, headers, echo = self._read_echo(fp)
self.assertline(line, "200", "OK", "HTTP/1.0")
self.assertEqual(headers.get("server"), "waitress")
self.assertTrue(headers.get("date"))
def test_bad_host_header(self):
# https://corte.si/posts/code/pathod/pythonservers/index.html
to_send = b"GET / HTTP/1.0\r\n Host: 0\r\n\r\n"
self.connect()
self.sock.send(to_send)
with self.sock.makefile("rb", 0) as fp:
line, headers, response_body = read_http(fp)
self.assertline(line, "400", "Bad Request", "HTTP/1.0")
self.assertEqual(headers.get("server"), "waitress")
self.assertTrue(headers.get("date"))
def test_send_with_body(self):
to_send = b"GET / HTTP/1.0\r\nContent-Length: 5\r\n\r\n"
to_send += b"hello"
self.connect()
self.sock.send(to_send)
with self.sock.makefile("rb", 0) as fp:
line, headers, echo = self._read_echo(fp)
self.assertline(line, "200", "OK", "HTTP/1.0")
self.assertEqual(echo.content_length, "5")
self.assertEqual(echo.body, b"hello")
def test_send_empty_body(self):
to_send = b"GET / HTTP/1.0\r\nContent-Length: 0\r\n\r\n"
self.connect()
self.sock.send(to_send)
with self.sock.makefile("rb", 0) as fp:
line, headers, echo = self._read_echo(fp)
self.assertline(line, "200", "OK", "HTTP/1.0")
self.assertEqual(echo.content_length, "0")
self.assertEqual(echo.body, b"")
def test_multiple_requests_with_body(self):
orig_sock = self.sock
for x in range(3):
self.sock = self.create_socket()
self.test_send_with_body()
self.sock.close()
self.sock = orig_sock
def test_multiple_requests_without_body(self):
orig_sock = self.sock
for x in range(3):
self.sock = self.create_socket()
self.test_send_empty_body()
self.sock.close()
self.sock = orig_sock
def test_without_crlf(self):
data = b"Echo\r\nthis\r\nplease"
s = (
b"GET / HTTP/1.0\r\n"
b"Connection: close\r\n"
b"Content-Length: %d\r\n"
b"\r\n"
b"%s" % (len(data), data)
)
self.connect()
self.sock.send(s)
with self.sock.makefile("rb", 0) as fp:
line, headers, echo = self._read_echo(fp)
self.assertline(line, "200", "OK", "HTTP/1.0")
self.assertEqual(int(echo.content_length), len(data))
self.assertEqual(len(echo.body), len(data))
self.assertEqual(echo.body, (data))
def test_large_body(self):
# 1024 characters.
body = b"This string has 32 characters.\r\n" * 32
s = b"GET / HTTP/1.0\r\nContent-Length: %d\r\n\r\n%s" % (len(body), body)
self.connect()
self.sock.send(s)
with self.sock.makefile("rb", 0) as fp:
line, headers, echo = self._read_echo(fp)
self.assertline(line, "200", "OK", "HTTP/1.0")
self.assertEqual(echo.content_length, "1024")
self.assertEqual(echo.body, body)
def test_many_clients(self):
conns = []
for n in range(50):
h = self.make_http_connection()
h.request("GET", "/", headers={"Accept": "text/plain"})
conns.append(h)
responses = []
for h in conns:
response = h.getresponse()
self.assertEqual(response.status, 200)
responses.append(response)
for response in responses:
response.read()
for h in conns:
h.close()
def test_chunking_request_without_content(self):
header = b"GET / HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n"
self.connect()
self.sock.send(header)
self.sock.send(b"0\r\n\r\n")
with self.sock.makefile("rb", 0) as fp:
line, headers, echo = self._read_echo(fp)
self.assertline(line, "200", "OK", "HTTP/1.1")
self.assertEqual(echo.body, b"")
self.assertEqual(echo.content_length, "0")
self.assertNotIn("transfer-encoding", headers)
def test_chunking_request_with_content(self):
control_line = b"20\r\n" # 20 hex = 32 dec
s = b"This string has 32 characters.\r\n"
expected = s * 12
header = b"GET / HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n"
self.connect()
self.sock.send(header)
with self.sock.makefile("rb", 0) as fp:
for n in range(12):
self.sock.send(control_line)
self.sock.send(s)
self.sock.send(b"\r\n") # End the chunk
self.sock.send(b"0\r\n\r\n")
line, headers, echo = self._read_echo(fp)
self.assertline(line, "200", "OK", "HTTP/1.1")
self.assertEqual(echo.body, expected)
self.assertEqual(echo.content_length, str(len(expected)))
self.assertNotIn("transfer-encoding", headers)
def test_broken_chunked_encoding(self):
control_line = b"20\r\n" # 20 hex = 32 dec
s = b"This string has 32 characters.\r\n"
to_send = b"GET / HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n"
to_send += control_line + s + b"\r\n"
# garbage in input
to_send += b"garbage\r\n"
self.connect()
self.sock.send(to_send)
with self.sock.makefile("rb", 0) as fp:
line, headers, response_body = read_http(fp)
# receiver caught garbage and turned it into a 400
self.assertline(line, "400", "Bad Request", "HTTP/1.1")
cl = int(headers["content-length"])
self.assertEqual(cl, len(response_body))
self.assertEqual(
sorted(headers.keys()),
["connection", "content-length", "content-type", "date", "server"],
)
self.assertEqual(headers["content-type"], "text/plain; charset=utf-8")
# connection has been closed
self.send_check_error(to_send)
self.assertRaises(ConnectionClosed, read_http, fp)
def test_broken_chunked_encoding_invalid_hex(self):
control_line = b"0x20\r\n" # 20 hex = 32 dec
s = b"This string has 32 characters.\r\n"
to_send = b"GET / HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n"
to_send += control_line + s + b"\r\n"
self.connect()
self.sock.send(to_send)
with self.sock.makefile("rb", 0) as fp:
line, headers, response_body = read_http(fp)
self.assertline(line, "400", "Bad Request", "HTTP/1.1")
cl = int(headers["content-length"])
self.assertEqual(cl, len(response_body))
self.assertIn(b"Invalid chunk size", response_body)
self.assertEqual(
sorted(headers.keys()),
["connection", "content-length", "content-type", "date", "server"],
)
self.assertEqual(headers["content-type"], "text/plain; charset=utf-8")
# connection has been closed
self.send_check_error(to_send)
self.assertRaises(ConnectionClosed, read_http, fp)
def test_broken_chunked_encoding_invalid_extension(self):
control_line = b"20;invalid=\r\n" # 20 hex = 32 dec
s = b"This string has 32 characters.\r\n"
to_send = b"GET / HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n"
to_send += control_line + s + b"\r\n"
self.connect()
self.sock.send(to_send)
with self.sock.makefile("rb", 0) as fp:
line, headers, response_body = read_http(fp)
self.assertline(line, "400", "Bad Request", "HTTP/1.1")
cl = int(headers["content-length"])
self.assertEqual(cl, len(response_body))
self.assertIn(b"Invalid chunk extension", response_body)
self.assertEqual(
sorted(headers.keys()),
["connection", "content-length", "content-type", "date", "server"],
)
self.assertEqual(headers["content-type"], "text/plain; charset=utf-8")
# connection has been closed
self.send_check_error(to_send)
self.assertRaises(ConnectionClosed, read_http, fp)
def test_broken_chunked_encoding_missing_chunk_end(self):
control_line = b"20\r\n" # 20 hex = 32 dec
s = b"This string has 32 characters.\r\n"
to_send = b"GET / HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n"
to_send += control_line + s
# garbage in input
to_send += b"garbage"
self.connect()
self.sock.send(to_send)
with self.sock.makefile("rb", 0) as fp:
line, headers, response_body = read_http(fp)
# receiver caught garbage and turned it into a 400
self.assertline(line, "400", "Bad Request", "HTTP/1.1")
cl = int(headers["content-length"])
self.assertEqual(cl, len(response_body))
self.assertIn(b"Chunk not properly terminated", response_body)
self.assertEqual(
sorted(headers.keys()),
["connection", "content-length", "content-type", "date", "server"],
)
self.assertEqual(headers["content-type"], "text/plain; charset=utf-8")
# connection has been closed
self.send_check_error(to_send)
self.assertRaises(ConnectionClosed, read_http, fp)
def test_keepalive_http_10(self):
# Handling of Keep-Alive within HTTP 1.0
data = b"Default: Don't keep me alive"
s = b"GET / HTTP/1.0\r\nContent-Length: %d\r\n\r\n%s" % (len(data), data)
self.connect()
self.sock.send(s)
response = httplib.HTTPResponse(self.sock)
response.begin()
self.assertEqual(int(response.status), 200)
connection = response.getheader("Connection", "")
# We sent no Connection: Keep-Alive header
# Connection: close (or no header) is default.
self.assertNotEqual(connection, "Keep-Alive")
def test_keepalive_http10_explicit(self):
# If header Connection: Keep-Alive is explicitly sent,
# we want to keept the connection open, we also need to return
# the corresponding header
data = b"Keep me alive"
s = (
b"GET / HTTP/1.0\r\n"
b"Connection: Keep-Alive\r\n"
b"Content-Length: %d\r\n"
b"\r\n"
b"%s" % (len(data), data)
)
self.connect()
self.sock.send(s)
response = httplib.HTTPResponse(self.sock)
response.begin()
self.assertEqual(int(response.status), 200)
connection = response.getheader("Connection", "")
self.assertEqual(connection, "Keep-Alive")
def test_keepalive_http_11(self):
# Handling of Keep-Alive within HTTP 1.1
# All connections are kept alive, unless stated otherwise
data = b"Default: Keep me alive"
s = b"GET / HTTP/1.1\r\nContent-Length: %d\r\n\r\n%s" % (len(data), data)
self.connect()
self.sock.send(s)
response = httplib.HTTPResponse(self.sock)
response.begin()
self.assertEqual(int(response.status), 200)
self.assertNotEqual(response.getheader("connection"), "close")
def test_keepalive_http11_explicit(self):
# Explicitly set keep-alive
data = b"Default: Keep me alive"
s = (
b"GET / HTTP/1.1\r\n"
b"Connection: keep-alive\r\n"
b"Content-Length: %d\r\n"
b"\r\n"
b"%s" % (len(data), data)
)
self.connect()
self.sock.send(s)
response = httplib.HTTPResponse(self.sock)
response.begin()
self.assertEqual(int(response.status), 200)
self.assertNotEqual(response.getheader("connection"), "close")
def test_keepalive_http11_connclose(self):
# specifying Connection: close explicitly
data = b"Don't keep me alive"
s = (
b"GET / HTTP/1.1\r\n"
b"Connection: close\r\n"
b"Content-Length: %d\r\n"
b"\r\n"
b"%s" % (len(data), data)
)
self.connect()
self.sock.send(s)
response = httplib.HTTPResponse(self.sock)
response.begin()
self.assertEqual(int(response.status), 200)
self.assertEqual(response.getheader("connection"), "close")
def test_proxy_headers(self):
to_send = (
b"GET / HTTP/1.0\r\n"
b"Content-Length: 0\r\n"
b"Host: www.google.com:8080\r\n"
b"X-Forwarded-For: 192.168.1.1\r\n"
b"X-Forwarded-Proto: https\r\n"
b"X-Forwarded-Port: 5000\r\n\r\n"
)
self.connect()
self.sock.send(to_send)
with self.sock.makefile("rb", 0) as fp:
line, headers, echo = self._read_echo(fp)
self.assertline(line, "200", "OK", "HTTP/1.0")
self.assertEqual(headers.get("server"), "waitress")
self.assertTrue(headers.get("date"))
self.assertIsNone(echo.headers.get("X_FORWARDED_PORT"))
self.assertEqual(echo.headers["HOST"], "www.google.com:8080")
self.assertEqual(echo.scheme, "https")
self.assertEqual(echo.remote_addr, "192.168.1.1")
self.assertEqual(echo.remote_host, "192.168.1.1")
class PipeliningTests:
def setUp(self):
from tests.fixtureapps import echo
self.start_subprocess(echo.app_body_only)
def tearDown(self):
self.stop_subprocess()
def test_pipelining(self):
s = (
b"GET / HTTP/1.0\r\n"
b"Connection: %s\r\n"
b"Content-Length: %d\r\n"
b"\r\n"
b"%s"
)
to_send = b""
count = 25
for n in range(count):
body = b"Response #%d\r\n" % (n + 1)
if n + 1 < count:
conn = b"keep-alive"
else:
conn = b"close"
to_send += s % (conn, len(body), body)
self.connect()
self.sock.send(to_send)
with self.sock.makefile("rb", 0) as fp:
for n in range(count):
expect_body = b"Response #%d\r\n" % (n + 1)
line = fp.readline() # status line
version, status, reason = (x.strip() for x in line.split(None, 2))
headers = parse_headers(fp)
length = int(headers.get("content-length")) or None
response_body = fp.read(length)
self.assertEqual(int(status), 200)
self.assertEqual(length, len(response_body))
self.assertEqual(response_body, expect_body)
class ExpectContinueTests:
def setUp(self):
from tests.fixtureapps import echo
self.start_subprocess(echo.app_body_only)
def tearDown(self):
self.stop_subprocess()
def test_expect_continue(self):
# specifying Connection: close explicitly
data = b"I have expectations"
to_send = (
b"GET / HTTP/1.1\r\n"
b"Connection: close\r\n"
b"Content-Length: %d\r\n"
b"Expect: 100-continue\r\n"
b"\r\n"
b"%s" % (len(data), data)
)
self.connect()
self.sock.send(to_send)
with self.sock.makefile("rb", 0) as fp:
line = fp.readline() # continue status line
version, status, reason = (x.strip() for x in line.split(None, 2))
self.assertEqual(int(status), 100)
self.assertEqual(reason, b"Continue")
self.assertEqual(version, b"HTTP/1.1")
fp.readline() # blank line
line = fp.readline() # next status line
version, status, reason = (x.strip() for x in line.split(None, 2))
headers = parse_headers(fp)
length = int(headers.get("content-length")) or None
response_body = fp.read(length)
self.assertEqual(int(status), 200)
self.assertEqual(length, len(response_body))
self.assertEqual(response_body, data)
class BadContentLengthTests:
def setUp(self):
from tests.fixtureapps import badcl
self.start_subprocess(badcl.app)
def tearDown(self):
self.stop_subprocess()
def test_short_body(self):
# check to see if server closes connection when body is too short
# for cl header
to_send = (
b"GET /short_body HTTP/1.0\r\n"
b"Connection: Keep-Alive\r\n"
b"Content-Length: 0\r\n"
b"\r\n"
)
self.connect()
self.sock.send(to_send)
with self.sock.makefile("rb", 0) as fp:
line = fp.readline() # status line
version, status, reason = (x.strip() for x in line.split(None, 2))
headers = parse_headers(fp)
content_length = int(headers.get("content-length"))
response_body = fp.read(content_length)
self.assertEqual(int(status), 200)
self.assertNotEqual(content_length, len(response_body))
self.assertEqual(len(response_body), content_length - 1)
self.assertEqual(response_body, b"abcdefghi")
# remote closed connection (despite keepalive header); not sure why
# first send succeeds
self.send_check_error(to_send)
self.assertRaises(ConnectionClosed, read_http, fp)
def test_long_body(self):
# check server doesnt close connection when body is too short
# for cl header
to_send = (
b"GET /long_body HTTP/1.0\r\n"
b"Connection: Keep-Alive\r\n"
b"Content-Length: 0\r\n"
b"\r\n"
)
self.connect()
self.sock.send(to_send)
with self.sock.makefile("rb", 0) as fp:
line = fp.readline() # status line
version, status, reason = (x.strip() for x in line.split(None, 2))
headers = parse_headers(fp)
content_length = int(headers.get("content-length")) or None
response_body = fp.read(content_length)
self.assertEqual(int(status), 200)
self.assertEqual(content_length, len(response_body))
self.assertEqual(response_body, b"abcdefgh")
# remote does not close connection (keepalive header)
self.sock.send(to_send)
with self.sock.makefile("rb", 0) as fp:
line = fp.readline() # status line
version, status, reason = (x.strip() for x in line.split(None, 2))
headers = parse_headers(fp)
content_length = int(headers.get("content-length")) or None
response_body = fp.read(content_length)
self.assertEqual(int(status), 200)
class NoContentLengthTests:
def setUp(self):
from tests.fixtureapps import nocl
self.start_subprocess(nocl.app)
def tearDown(self):
self.stop_subprocess()
def test_http10_generator(self):
body = string.ascii_letters.encode("latin-1")
to_send = (
b"GET / HTTP/1.0\r\n"
b"Connection: Keep-Alive\r\n"
b"Content-Length: %d\r\n\r\n" % len(body)
)
to_send += body
self.connect()
self.sock.send(to_send)
with self.sock.makefile("rb", 0) as fp:
line, headers, response_body = read_http(fp)
self.assertline(line, "200", "OK", "HTTP/1.0")
self.assertIsNone(headers.get("content-length"))
self.assertEqual(headers.get("connection"), "close")
self.assertEqual(response_body, body)
# remote closed connection (despite keepalive header), because
# generators cannot have a content-length divined
self.send_check_error(to_send)
self.assertRaises(ConnectionClosed, read_http, fp)
def test_http10_list(self):
body = string.ascii_letters.encode("latin-1")
to_send = (
b"GET /list HTTP/1.0\r\n"
b"Connection: Keep-Alive\r\n"
b"Content-Length: %d\r\n\r\n" % len(body)
)
to_send += body
self.connect()
self.sock.send(to_send)
with self.sock.makefile("rb", 0) as fp:
line, headers, response_body = read_http(fp)
self.assertline(line, "200", "OK", "HTTP/1.0")
self.assertEqual(headers["content-length"], str(len(body)))
self.assertEqual(headers.get("connection"), "Keep-Alive")
self.assertEqual(response_body, body)
# remote keeps connection open because it divined the content length
# from a length-1 list
self.sock.send(to_send)
line, headers, response_body = read_http(fp)
self.assertline(line, "200", "OK", "HTTP/1.0")
def test_http10_listlentwo(self):
body = string.ascii_letters.encode("latin-1")
to_send = (
b"GET /list_lentwo HTTP/1.0\r\n"
b"Connection: Keep-Alive\r\n"
b"Content-Length: %d\r\n\r\n" % len(body)
)
to_send += body
self.connect()
self.sock.send(to_send)
with self.sock.makefile("rb", 0) as fp:
line, headers, response_body = read_http(fp)
self.assertline(line, "200", "OK", "HTTP/1.0")
self.assertIsNone(headers.get("content-length"))
self.assertEqual(headers.get("connection"), "close")
self.assertEqual(response_body, body)
# remote closed connection (despite keepalive header), because
# lists of length > 1 cannot have their content length divined
self.send_check_error(to_send)
self.assertRaises(ConnectionClosed, read_http, fp)
def test_http11_generator(self):
body = string.ascii_letters
body = body.encode("latin-1")
to_send = b"GET / HTTP/1.1\r\nContent-Length: %d\r\n\r\n" % len(body)
to_send += body
self.connect()
self.sock.send(to_send)
with self.sock.makefile("rb") as fp:
line, headers, response_body = read_http(fp)
self.assertline(line, "200", "OK", "HTTP/1.1")
expected = b""
for chunk in chunks(body, 10):
expected += b"%s\r\n%s\r\n" % (
hex(len(chunk))[2:].upper().encode("latin-1"),
chunk,
)
expected += b"0\r\n\r\n"
self.assertEqual(response_body, expected)
# connection is always closed at the end of a chunked response
self.send_check_error(to_send)
self.assertRaises(ConnectionClosed, read_http, fp)
def test_http11_list(self):
body = string.ascii_letters.encode("latin-1")
to_send = b"GET /list HTTP/1.1\r\nContent-Length: %d\r\n\r\n" % len(body)
to_send += body
self.connect()
self.sock.send(to_send)
with self.sock.makefile("rb", 0) as fp:
line, headers, response_body = read_http(fp)
self.assertline(line, "200", "OK", "HTTP/1.1")
self.assertEqual(headers["content-length"], str(len(body)))
self.assertEqual(response_body, body)
# remote keeps connection open because it divined the content length
# from a length-1 list
self.sock.send(to_send)
line, headers, response_body = read_http(fp)
self.assertline(line, "200", "OK", "HTTP/1.1")
def test_http11_listlentwo(self):
body = string.ascii_letters.encode("latin-1")
to_send = b"GET /list_lentwo HTTP/1.1\r\nContent-Length: %d\r\n\r\n" % len(body)
to_send += body
self.connect()
self.sock.send(to_send)
with self.sock.makefile("rb") as fp:
line, headers, response_body = read_http(fp)
self.assertline(line, "200", "OK", "HTTP/1.1")
expected = b""
for chunk in (body[:1], body[1:]):
expected += b"%s\r\n%s\r\n" % (
(hex(len(chunk))[2:].upper().encode("latin-1")),
chunk,
)
expected += b"0\r\n\r\n"
self.assertEqual(response_body, expected)
# connection is always closed at the end of a chunked response
self.send_check_error(to_send)
self.assertRaises(ConnectionClosed, read_http, fp)
class WriteCallbackTests:
def setUp(self):
from tests.fixtureapps import writecb
self.start_subprocess(writecb.app)
def tearDown(self):
self.stop_subprocess()
def test_short_body(self):
# check to see if server closes connection when body is too short
# for cl header
to_send = (
b"GET /short_body HTTP/1.0\r\n"
b"Connection: Keep-Alive\r\n"
b"Content-Length: 0\r\n"
b"\r\n"
)
self.connect()
self.sock.send(to_send)
with self.sock.makefile("rb", 0) as fp:
line, headers, response_body = read_http(fp)
# server trusts the content-length header (5)
self.assertline(line, "200", "OK", "HTTP/1.0")
cl = int(headers["content-length"])
self.assertEqual(cl, 9)
self.assertNotEqual(cl, len(response_body))
self.assertEqual(len(response_body), cl - 1)
self.assertEqual(response_body, b"abcdefgh")
# remote closed connection (despite keepalive header)
self.send_check_error(to_send)
self.assertRaises(ConnectionClosed, read_http, fp)
def test_long_body(self):
# check server doesnt close connection when body is too long
# for cl header
to_send = (
b"GET /long_body HTTP/1.0\r\n"
b"Connection: Keep-Alive\r\n"
b"Content-Length: 0\r\n"
b"\r\n"
)
self.connect()
self.sock.send(to_send)
with self.sock.makefile("rb", 0) as fp:
line, headers, response_body = read_http(fp)
content_length = int(headers.get("content-length")) or None
self.assertEqual(content_length, 9)
self.assertEqual(content_length, len(response_body))
self.assertEqual(response_body, b"abcdefghi")
# remote does not close connection (keepalive header)
self.sock.send(to_send)
with self.sock.makefile("rb", 0) as fp:
line, headers, response_body = read_http(fp)
self.assertline(line, "200", "OK", "HTTP/1.0")
def test_equal_body(self):
# check server doesnt close connection when body is equal to
# cl header
to_send = (
b"GET /equal_body HTTP/1.0\r\n"
b"Connection: Keep-Alive\r\n"
b"Content-Length: 0\r\n"
b"\r\n"
)
self.connect()
self.sock.send(to_send)
with self.sock.makefile("rb", 0) as fp:
line, headers, response_body = read_http(fp)
content_length = int(headers.get("content-length")) or None
self.assertEqual(content_length, 9)
self.assertline(line, "200", "OK", "HTTP/1.0")
self.assertEqual(content_length, len(response_body))
self.assertEqual(response_body, b"abcdefghi")
# remote does not close connection (keepalive header)
self.sock.send(to_send)
with self.sock.makefile("rb", 0) as fp:
line, headers, response_body = read_http(fp)
self.assertline(line, "200", "OK", "HTTP/1.0")
def test_no_content_length(self):
# wtf happens when there's no content-length
to_send = (
b"GET /no_content_length HTTP/1.0\r\n"
b"Connection: Keep-Alive\r\n"
b"Content-Length: 0\r\n"
b"\r\n"
)
self.connect()
self.sock.send(to_send)
with self.sock.makefile("rb", 0) as fp:
line = fp.readline() # status line
line, headers, response_body = read_http(fp)
content_length = headers.get("content-length")
self.assertIsNone(content_length)
self.assertEqual(response_body, b"abcdefghi")
# remote closed connection (despite keepalive header)
self.send_check_error(to_send)
self.assertRaises(ConnectionClosed, read_http, fp)
class TooLargeTests:
toobig = 1050
def setUp(self):
from tests.fixtureapps import toolarge
self.start_subprocess(
toolarge.app, max_request_header_size=1000, max_request_body_size=1000
)
def tearDown(self):
self.stop_subprocess()
def test_request_headers_too_large_http11(self):
body = b""
bad_headers = b"X-Random-Header: 100\r\n" * int(self.toobig / 20)
to_send = b"GET / HTTP/1.1\r\nContent-Length: 0\r\n"
to_send += bad_headers
to_send += b"\r\n\r\n"
to_send += body
self.connect()
self.sock.send(to_send)
with self.sock.makefile("rb") as fp:
response_line, headers, response_body = read_http(fp)
self.assertline(
response_line, "431", "Request Header Fields Too Large", "HTTP/1.0"
)
self.assertEqual(headers["connection"], "close")
def test_request_body_too_large_with_wrong_cl_http10(self):
body = b"a" * self.toobig
to_send = b"GET / HTTP/1.0\r\nContent-Length: 5\r\n\r\n"
to_send += body
self.connect()
self.sock.send(to_send)
with self.sock.makefile("rb") as fp:
# first request succeeds (content-length 5)
line, headers, response_body = read_http(fp)
self.assertline(line, "200", "OK", "HTTP/1.0")
cl = int(headers["content-length"])
self.assertEqual(cl, len(response_body))
# server trusts the content-length header; no pipelining,
# so request fulfilled, extra bytes are thrown away
# connection has been closed
self.send_check_error(to_send)
self.assertRaises(ConnectionClosed, read_http, fp)
def test_request_body_too_large_with_wrong_cl_http10_keepalive(self):
body = b"a" * self.toobig
to_send = (
b"GET / HTTP/1.0\r\nContent-Length: 5\r\nConnection: Keep-Alive\r\n\r\n"
)
to_send += body
self.connect()
self.sock.send(to_send)
with self.sock.makefile("rb") as fp:
# first request succeeds (content-length 5)
line, headers, response_body = read_http(fp)
self.assertline(line, "200", "OK", "HTTP/1.0")
cl = int(headers["content-length"])
self.assertEqual(cl, len(response_body))
line, headers, response_body = read_http(fp)
self.assertline(line, "431", "Request Header Fields Too Large", "HTTP/1.0")
cl = int(headers["content-length"])
self.assertEqual(cl, len(response_body))
# connection has been closed
self.send_check_error(to_send)
self.assertRaises(ConnectionClosed, read_http, fp)
def test_request_body_too_large_with_no_cl_http10(self):
body = b"a" * self.toobig
to_send = b"GET / HTTP/1.0\r\n\r\n"
to_send += body
self.connect()
self.sock.send(to_send)
with self.sock.makefile("rb", 0) as fp:
line, headers, response_body = read_http(fp)
self.assertline(line, "200", "OK", "HTTP/1.0")
cl = int(headers["content-length"])
self.assertEqual(cl, len(response_body))
# extra bytes are thrown away (no pipelining), connection closed
self.send_check_error(to_send)
self.assertRaises(ConnectionClosed, read_http, fp)
def test_request_body_too_large_with_no_cl_http10_keepalive(self):
body = b"a" * self.toobig
to_send = b"GET / HTTP/1.0\r\nConnection: Keep-Alive\r\n\r\n"
to_send += body
self.connect()
self.sock.send(to_send)
with self.sock.makefile("rb", 0) as fp:
line, headers, response_body = read_http(fp)
# server trusts the content-length header (assumed zero)
self.assertline(line, "200", "OK", "HTTP/1.0")
cl = int(headers["content-length"])
self.assertEqual(cl, len(response_body))
line, headers, response_body = read_http(fp)
# next response overruns because the extra data appears to be
# header data
self.assertline(line, "431", "Request Header Fields Too Large", "HTTP/1.0")
cl = int(headers["content-length"])
self.assertEqual(cl, len(response_body))
# connection has been closed
self.send_check_error(to_send)
self.assertRaises(ConnectionClosed, read_http, fp)
def test_request_body_too_large_with_wrong_cl_http11(self):
body = b"a" * self.toobig
to_send = b"GET / HTTP/1.1\r\nContent-Length: 5\r\n\r\n"
to_send += body
self.connect()
self.sock.send(to_send)
with self.sock.makefile("rb") as fp:
# first request succeeds (content-length 5)
line, headers, response_body = read_http(fp)
self.assertline(line, "200", "OK", "HTTP/1.1")
cl = int(headers["content-length"])
self.assertEqual(cl, len(response_body))
# second response is an error response
line, headers, response_body = read_http(fp)
self.assertline(line, "431", "Request Header Fields Too Large", "HTTP/1.0")
cl = int(headers["content-length"])
self.assertEqual(cl, len(response_body))
# connection has been closed
self.send_check_error(to_send)
self.assertRaises(ConnectionClosed, read_http, fp)
def test_request_body_too_large_with_wrong_cl_http11_connclose(self):
body = b"a" * self.toobig
to_send = b"GET / HTTP/1.1\r\nContent-Length: 5\r\nConnection: close\r\n\r\n"
to_send += body
self.connect()
self.sock.send(to_send)
with self.sock.makefile("rb", 0) as fp:
line, headers, response_body = read_http(fp)
# server trusts the content-length header (5)
self.assertline(line, "200", "OK", "HTTP/1.1")
cl = int(headers["content-length"])
self.assertEqual(cl, len(response_body))
# connection has been closed
self.send_check_error(to_send)
self.assertRaises(ConnectionClosed, read_http, fp)
def test_request_body_too_large_with_no_cl_http11(self):
body = b"a" * self.toobig
to_send = b"GET / HTTP/1.1\r\n\r\n"
to_send += body
self.connect()
self.sock.send(to_send)
with self.sock.makefile("rb") as fp:
# server trusts the content-length header (assumed 0)
line, headers, response_body = read_http(fp)
self.assertline(line, "200", "OK", "HTTP/1.1")
cl = int(headers["content-length"])
self.assertEqual(cl, len(response_body))
# server assumes pipelined requests due to http/1.1, and the first
# request was assumed c-l 0 because it had no content-length header,
# so entire body looks like the header of the subsequent request
# second response is an error response
line, headers, response_body = read_http(fp)
self.assertline(line, "431", "Request Header Fields Too Large", "HTTP/1.0")
cl = int(headers["content-length"])
self.assertEqual(cl, len(response_body))
# connection has been closed
self.send_check_error(to_send)
self.assertRaises(ConnectionClosed, read_http, fp)
def test_request_body_too_large_with_no_cl_http11_connclose(self):
body = b"a" * self.toobig
to_send = b"GET / HTTP/1.1\r\nConnection: close\r\n\r\n"
to_send += body
self.connect()
self.sock.send(to_send)
with self.sock.makefile("rb", 0) as fp:
line, headers, response_body = read_http(fp)
# server trusts the content-length header (assumed 0)
self.assertline(line, "200", "OK", "HTTP/1.1")
cl = int(headers["content-length"])
self.assertEqual(cl, len(response_body))
# connection has been closed
self.send_check_error(to_send)
self.assertRaises(ConnectionClosed, read_http, fp)
def test_request_body_too_large_chunked_encoding(self):
control_line = b"20;\r\n" # 20 hex = 32 dec
s = b"This string has 32 characters.\r\n"
to_send = b"GET / HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n"
repeat = control_line + s
to_send += repeat * ((self.toobig // len(repeat)) + 1)
self.connect()
self.sock.send(to_send)
with self.sock.makefile("rb", 0) as fp:
line, headers, response_body = read_http(fp)
# body bytes counter caught a max_request_body_size overrun
self.assertline(line, "413", "Request Entity Too Large", "HTTP/1.1")
cl = int(headers["content-length"])
self.assertEqual(cl, len(response_body))
self.assertEqual(headers["content-type"], "text/plain; charset=utf-8")
# connection has been closed
self.send_check_error(to_send)
self.assertRaises(ConnectionClosed, read_http, fp)
class InternalServerErrorTests:
def setUp(self):
from tests.fixtureapps import error
self.start_subprocess(error.app, expose_tracebacks=True)
def tearDown(self):
self.stop_subprocess()
def test_before_start_response_http_10(self):
to_send = b"GET /before_start_response HTTP/1.0\r\n\r\n"
self.connect()
self.sock.send(to_send)
with self.sock.makefile("rb", 0) as fp:
line, headers, response_body = read_http(fp)
self.assertline(line, "500", "Internal Server Error", "HTTP/1.0")
cl = int(headers["content-length"])
self.assertEqual(cl, len(response_body))
self.assertTrue(response_body.startswith(b"Internal Server Error"))
self.assertEqual(headers["connection"], "close")
# connection has been closed
self.send_check_error(to_send)
self.assertRaises(ConnectionClosed, read_http, fp)
def test_before_start_response_http_11(self):
to_send = b"GET /before_start_response HTTP/1.1\r\n\r\n"
self.connect()
self.sock.send(to_send)
with self.sock.makefile("rb", 0) as fp:
line, headers, response_body = read_http(fp)
self.assertline(line, "500", "Internal Server Error", "HTTP/1.1")
cl = int(headers["content-length"])
self.assertEqual(cl, len(response_body))
self.assertTrue(response_body.startswith(b"Internal Server Error"))
self.assertEqual(
sorted(headers.keys()),
["connection", "content-length", "content-type", "date", "server"],
)
# connection has been closed
self.send_check_error(to_send)
self.assertRaises(ConnectionClosed, read_http, fp)
def test_before_start_response_http_11_close(self):
to_send = b"GET /before_start_response HTTP/1.1\r\nConnection: close\r\n\r\n"
self.connect()
self.sock.send(to_send)
with self.sock.makefile("rb", 0) as fp:
line, headers, response_body = read_http(fp)
self.assertline(line, "500", "Internal Server Error", "HTTP/1.1")
cl = int(headers["content-length"])
self.assertEqual(cl, len(response_body))
self.assertTrue(response_body.startswith(b"Internal Server Error"))
self.assertEqual(
sorted(headers.keys()),
["connection", "content-length", "content-type", "date", "server"],
)
self.assertEqual(headers["connection"], "close")
# connection has been closed
self.send_check_error(to_send)
self.assertRaises(ConnectionClosed, read_http, fp)
def test_after_start_response_http10(self):
to_send = b"GET /after_start_response HTTP/1.0\r\n\r\n"
self.connect()
self.sock.send(to_send)
with self.sock.makefile("rb", 0) as fp:
line, headers, response_body = read_http(fp)
self.assertline(line, "500", "Internal Server Error", "HTTP/1.0")
cl = int(headers["content-length"])
self.assertEqual(cl, len(response_body))
self.assertTrue(response_body.startswith(b"Internal Server Error"))
self.assertEqual(
sorted(headers.keys()),
["connection", "content-length", "content-type", "date", "server"],
)
self.assertEqual(headers["connection"], "close")
# connection has been closed
self.send_check_error(to_send)
self.assertRaises(ConnectionClosed, read_http, fp)
def test_after_start_response_http11(self):
to_send = b"GET /after_start_response HTTP/1.1\r\n\r\n"
self.connect()
self.sock.send(to_send)
with self.sock.makefile("rb", 0) as fp:
line, headers, response_body = read_http(fp)
self.assertline(line, "500", "Internal Server Error", "HTTP/1.1")
cl = int(headers["content-length"])
self.assertEqual(cl, len(response_body))
self.assertTrue(response_body.startswith(b"Internal Server Error"))
self.assertEqual(
sorted(headers.keys()),
["connection", "content-length", "content-type", "date", "server"],
)
# connection has been closed
self.send_check_error(to_send)
self.assertRaises(ConnectionClosed, read_http, fp)
def test_after_start_response_http11_close(self):
to_send = b"GET /after_start_response HTTP/1.1\r\nConnection: close\r\n\r\n"
self.connect()
self.sock.send(to_send)
with self.sock.makefile("rb", 0) as fp:
line, headers, response_body = read_http(fp)
self.assertline(line, "500", "Internal Server Error", "HTTP/1.1")
cl = int(headers["content-length"])
self.assertEqual(cl, len(response_body))
self.assertTrue(response_body.startswith(b"Internal Server Error"))
self.assertEqual(
sorted(headers.keys()),
["connection", "content-length", "content-type", "date", "server"],
)
self.assertEqual(headers["connection"], "close")
# connection has been closed
self.send_check_error(to_send)
self.assertRaises(ConnectionClosed, read_http, fp)
def test_after_write_cb(self):
to_send = b"GET /after_write_cb HTTP/1.1\r\n\r\n"
self.connect()
self.sock.send(to_send)
with self.sock.makefile("rb", 0) as fp:
line, headers, response_body = read_http(fp)
self.assertline(line, "200", "OK", "HTTP/1.1")
self.assertEqual(response_body, b"")
# connection has been closed
self.send_check_error(to_send)
self.assertRaises(ConnectionClosed, read_http, fp)
def test_in_generator(self):
to_send = b"GET /in_generator HTTP/1.1\r\n\r\n"
self.connect()
self.sock.send(to_send)
with self.sock.makefile("rb", 0) as fp:
line, headers, response_body = read_http(fp)
self.assertline(line, "200", "OK", "HTTP/1.1")
self.assertEqual(response_body, b"")
# connection has been closed
self.send_check_error(to_send)
self.assertRaises(ConnectionClosed, read_http, fp)
class InternalServerErrorTestsWithTraceback:
def setUp(self):
from tests.fixtureapps import error_traceback
self.start_subprocess(error_traceback.app, expose_tracebacks=True)
def tearDown(self):
self.stop_subprocess()
def test_expose_tracebacks_http_10(self):
to_send = b"GET / HTTP/1.0\r\n\r\n"
self.connect()
self.sock.send(to_send)
with self.sock.makefile("rb", 0) as fp:
line, headers, response_body = read_http(fp)
self.assertline(line, "500", "Internal Server Error", "HTTP/1.0")
cl = int(headers["content-length"])
self.assertEqual(cl, len(response_body))
self.assertTrue(response_body.startswith(b"Internal Server Error"))
self.assertEqual(headers["connection"], "close")
# connection has been closed
self.send_check_error(to_send)
self.assertRaises(ConnectionClosed, read_http, fp)
def test_expose_tracebacks_http_11(self):
to_send = b"GET / HTTP/1.1\r\n\r\n"
self.connect()
self.sock.send(to_send)
with self.sock.makefile("rb", 0) as fp:
line, headers, response_body = read_http(fp)
self.assertline(line, "500", "Internal Server Error", "HTTP/1.1")
cl = int(headers["content-length"])
self.assertEqual(cl, len(response_body))
self.assertTrue(response_body.startswith(b"Internal Server Error"))
self.assertEqual(
sorted(headers.keys()),
["connection", "content-length", "content-type", "date", "server"],
)
# connection has been closed
self.send_check_error(to_send)
self.assertRaises(ConnectionClosed, read_http, fp)
class FileWrapperTests:
def setUp(self):
from tests.fixtureapps import filewrapper
self.start_subprocess(filewrapper.app)
def tearDown(self):
self.stop_subprocess()
def test_filelike_http11(self):
to_send = b"GET /filelike HTTP/1.1\r\n\r\n"
self.connect()
for t in range(0, 2):
self.sock.send(to_send)
with self.sock.makefile("rb", 0) as fp:
line, headers, response_body = read_http(fp)
self.assertline(line, "200", "OK", "HTTP/1.1")
cl = int(headers["content-length"])
self.assertEqual(cl, len(response_body))
ct = headers["content-type"]
self.assertEqual(ct, "image/jpeg")
self.assertIn(b"\377\330\377", response_body)
# connection has not been closed
def test_filelike_nocl_http11(self):
to_send = b"GET /filelike_nocl HTTP/1.1\r\n\r\n"
self.connect()
for t in range(0, 2):
self.sock.send(to_send)
with self.sock.makefile("rb", 0) as fp:
line, headers, response_body = read_http(fp)
self.assertline(line, "200", "OK", "HTTP/1.1")
cl = int(headers["content-length"])
self.assertEqual(cl, len(response_body))
ct = headers["content-type"]
self.assertEqual(ct, "image/jpeg")
self.assertIn(b"\377\330\377", response_body)
# connection has not been closed
def test_filelike_shortcl_http11(self):
to_send = b"GET /filelike_shortcl HTTP/1.1\r\n\r\n"
self.connect()
for t in range(0, 2):
self.sock.send(to_send)
with self.sock.makefile("rb", 0) as fp:
line, headers, response_body = read_http(fp)
self.assertline(line, "200", "OK", "HTTP/1.1")
cl = int(headers["content-length"])
self.assertEqual(cl, 1)
self.assertEqual(cl, len(response_body))
ct = headers["content-type"]
self.assertEqual(ct, "image/jpeg")
self.assertIn(b"\377", response_body)
# connection has not been closed
def test_filelike_longcl_http11(self):
to_send = b"GET /filelike_longcl HTTP/1.1\r\n\r\n"
self.connect()
for t in range(0, 2):
self.sock.send(to_send)
with self.sock.makefile("rb", 0) as fp:
line, headers, response_body = read_http(fp)
self.assertline(line, "200", "OK", "HTTP/1.1")
cl = int(headers["content-length"])
self.assertEqual(cl, len(response_body))
ct = headers["content-type"]
self.assertEqual(ct, "image/jpeg")
self.assertIn(b"\377\330\377", response_body)
# connection has not been closed
def test_notfilelike_http11(self):
to_send = b"GET /notfilelike HTTP/1.1\r\n\r\n"
self.connect()
for t in range(0, 2):
self.sock.send(to_send)
with self.sock.makefile("rb", 0) as fp:
line, headers, response_body = read_http(fp)
self.assertline(line, "200", "OK", "HTTP/1.1")
cl = int(headers["content-length"])
self.assertEqual(cl, len(response_body))
ct = headers["content-type"]
self.assertEqual(ct, "image/jpeg")
self.assertIn(b"\377\330\377", response_body)
# connection has not been closed
def test_notfilelike_iobase_http11(self):
to_send = b"GET /notfilelike_iobase HTTP/1.1\r\n\r\n"
self.connect()
for t in range(0, 2):
self.sock.send(to_send)
with self.sock.makefile("rb", 0) as fp:
line, headers, response_body = read_http(fp)
self.assertline(line, "200", "OK", "HTTP/1.1")
cl = int(headers["content-length"])
self.assertEqual(cl, len(response_body))
ct = headers["content-type"]
self.assertEqual(ct, "image/jpeg")
self.assertIn(b"\377\330\377", response_body)
# connection has not been closed
def test_notfilelike_nocl_http11(self):
to_send = b"GET /notfilelike_nocl HTTP/1.1\r\n\r\n"
self.connect()
self.sock.send(to_send)
with self.sock.makefile("rb", 0) as fp:
line, headers, response_body = read_http(fp)
self.assertline(line, "200", "OK", "HTTP/1.1")
ct = headers["content-type"]
self.assertEqual(ct, "image/jpeg")
self.assertIn(b"\377\330\377", response_body)
# connection has been closed (no content-length)
self.send_check_error(to_send)
self.assertRaises(ConnectionClosed, read_http, fp)
def test_notfilelike_shortcl_http11(self):
to_send = b"GET /notfilelike_shortcl HTTP/1.1\r\n\r\n"
self.connect()
for t in range(0, 2):
self.sock.send(to_send)
with self.sock.makefile("rb", 0) as fp:
line, headers, response_body = read_http(fp)
self.assertline(line, "200", "OK", "HTTP/1.1")
cl = int(headers["content-length"])
self.assertEqual(cl, 1)
self.assertEqual(cl, len(response_body))
ct = headers["content-type"]
self.assertEqual(ct, "image/jpeg")
self.assertIn(b"\377", response_body)
# connection has not been closed
def test_notfilelike_longcl_http11(self):
to_send = b"GET /notfilelike_longcl HTTP/1.1\r\n\r\n"
self.connect()
self.sock.send(to_send)
with self.sock.makefile("rb", 0) as fp:
line, headers, response_body = read_http(fp)
self.assertline(line, "200", "OK", "HTTP/1.1")
cl = int(headers["content-length"])
self.assertEqual(cl, len(response_body) + 10)
ct = headers["content-type"]
self.assertEqual(ct, "image/jpeg")
self.assertIn(b"\377\330\377", response_body)
# connection has been closed
self.send_check_error(to_send)
self.assertRaises(ConnectionClosed, read_http, fp)
def test_filelike_http10(self):
to_send = b"GET /filelike HTTP/1.0\r\n\r\n"
self.connect()
self.sock.send(to_send)
with self.sock.makefile("rb", 0) as fp:
line, headers, response_body = read_http(fp)
self.assertline(line, "200", "OK", "HTTP/1.0")
cl = int(headers["content-length"])
self.assertEqual(cl, len(response_body))
ct = headers["content-type"]
self.assertEqual(ct, "image/jpeg")
self.assertIn(b"\377\330\377", response_body)
# connection has been closed
self.send_check_error(to_send)
self.assertRaises(ConnectionClosed, read_http, fp)
def test_filelike_nocl_http10(self):
to_send = b"GET /filelike_nocl HTTP/1.0\r\n\r\n"
self.connect()
self.sock.send(to_send)
with self.sock.makefile("rb", 0) as fp:
line, headers, response_body = read_http(fp)
self.assertline(line, "200", "OK", "HTTP/1.0")
cl = int(headers["content-length"])
self.assertEqual(cl, len(response_body))
ct = headers["content-type"]
self.assertEqual(ct, "image/jpeg")
self.assertIn(b"\377\330\377", response_body)
# connection has been closed
self.send_check_error(to_send)
self.assertRaises(ConnectionClosed, read_http, fp)
def test_notfilelike_http10(self):
to_send = b"GET /notfilelike HTTP/1.0\r\n\r\n"
self.connect()
self.sock.send(to_send)
with self.sock.makefile("rb", 0) as fp:
line, headers, response_body = read_http(fp)
self.assertline(line, "200", "OK", "HTTP/1.0")
cl = int(headers["content-length"])
self.assertEqual(cl, len(response_body))
ct = headers["content-type"]
self.assertEqual(ct, "image/jpeg")
self.assertIn(b"\377\330\377", response_body)
# connection has been closed
self.send_check_error(to_send)
self.assertRaises(ConnectionClosed, read_http, fp)
def test_notfilelike_nocl_http10(self):
to_send = b"GET /notfilelike_nocl HTTP/1.0\r\n\r\n"
self.connect()
self.sock.send(to_send)
with self.sock.makefile("rb", 0) as fp:
line, headers, response_body = read_http(fp)
self.assertline(line, "200", "OK", "HTTP/1.0")
ct = headers["content-type"]
self.assertEqual(ct, "image/jpeg")
self.assertIn(b"\377\330\377", response_body)
# connection has been closed (no content-length)
self.send_check_error(to_send)
self.assertRaises(ConnectionClosed, read_http, fp)
class TcpEchoTests(EchoTests, TcpTests, unittest.TestCase):
pass
class TcpPipeliningTests(PipeliningTests, TcpTests, unittest.TestCase):
pass
class TcpExpectContinueTests(ExpectContinueTests, TcpTests, unittest.TestCase):
pass
class TcpBadContentLengthTests(BadContentLengthTests, TcpTests, unittest.TestCase):
pass
class TcpNoContentLengthTests(NoContentLengthTests, TcpTests, unittest.TestCase):
pass
class TcpWriteCallbackTests(WriteCallbackTests, TcpTests, unittest.TestCase):
pass
class TcpTooLargeTests(TooLargeTests, TcpTests, unittest.TestCase):
pass
class TcpInternalServerErrorTests(
InternalServerErrorTests, TcpTests, unittest.TestCase
):
pass
class TcpInternalServerErrorTestsWithTraceback(
InternalServerErrorTestsWithTraceback, TcpTests, unittest.TestCase
):
pass
class TcpFileWrapperTests(FileWrapperTests, TcpTests, unittest.TestCase):
pass
if hasattr(socket, "AF_UNIX"):
class FixtureUnixWSGIServer(server.UnixWSGIServer):
"""A version of UnixWSGIServer that relays back what it's bound to."""
family = socket.AF_UNIX # Testing
def __init__(self, application, queue, **kw): # pragma: no cover
# Coverage doesn't see this as it's ran in a separate process.
# To permit parallel testing, use a PID-dependent socket.
kw["unix_socket"] = "/tmp/waitress.test-%d.sock" % os.getpid()
super().__init__(application, **kw)
queue.put(self.socket.getsockname())
class UnixTests(SubprocessTests):
server = FixtureUnixWSGIServer
def make_http_connection(self):
return UnixHTTPConnection(self.bound_to)
def stop_subprocess(self):
super().stop_subprocess()
cleanup_unix_socket(self.bound_to)
def send_check_error(self, to_send):
# Unlike inet domain sockets, Unix domain sockets can trigger a
# 'Broken pipe' error when the socket it closed.
try:
self.sock.send(to_send)
except OSError as exc:
valid_errors = {errno.EPIPE, errno.ENOTCONN}
self.assertIn(get_errno(exc), valid_errors)
class UnixEchoTests(EchoTests, UnixTests, unittest.TestCase):
pass
class UnixPipeliningTests(PipeliningTests, UnixTests, unittest.TestCase):
pass
class UnixExpectContinueTests(ExpectContinueTests, UnixTests, unittest.TestCase):
pass
class UnixBadContentLengthTests(
BadContentLengthTests, UnixTests, unittest.TestCase
):
pass
class UnixNoContentLengthTests(NoContentLengthTests, UnixTests, unittest.TestCase):
pass
class UnixWriteCallbackTests(WriteCallbackTests, UnixTests, unittest.TestCase):
pass
class UnixTooLargeTests(TooLargeTests, UnixTests, unittest.TestCase):
pass
class UnixInternalServerErrorTests(
InternalServerErrorTests, UnixTests, unittest.TestCase
):
pass
class UnixInternalServerErrorTestsWithTraceback(
InternalServerErrorTestsWithTraceback, UnixTests, unittest.TestCase
):
pass
class UnixFileWrapperTests(FileWrapperTests, UnixTests, unittest.TestCase):
pass
def parse_headers(fp):
"""Parses only RFC2822 headers from a file pointer."""
headers = {}
while True:
line = fp.readline()
if line in (b"\r\n", b"\n", b""):
break
line = line.decode("iso-8859-1")
name, value = line.strip().split(":", 1)
headers[name.lower().strip()] = value.lower().strip()
return headers
class UnixHTTPConnection(httplib.HTTPConnection):
"""Patched version of HTTPConnection that uses Unix domain sockets."""
def __init__(self, path):
httplib.HTTPConnection.__init__(self, "localhost")
self.path = path
def connect(self):
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.connect(self.path)
self.sock = sock
def close(self):
self.sock.close()
class ConnectionClosed(Exception):
pass
# stolen from gevent
def read_http(fp): # pragma: no cover
try:
response_line = fp.readline()
except OSError as exc:
fp.close()
# errno 104 is ENOTRECOVERABLE, In WinSock 10054 is ECONNRESET
if get_errno(exc) in (errno.ECONNABORTED, errno.ECONNRESET, 104, 10054):
raise ConnectionClosed
raise
if not response_line:
raise ConnectionClosed
header_lines = []
while True:
line = fp.readline()
if line in (b"\r\n", b"\r\n", b""):
break
else:
header_lines.append(line)
headers = dict()
for x in header_lines:
x = x.strip()
if not x:
continue
key, value = x.split(b": ", 1)
key = key.decode("iso-8859-1").lower()
value = value.decode("iso-8859-1")
assert key not in headers, "%s header duplicated" % key
headers[key] = value
if "content-length" in headers:
num = int(headers["content-length"])
body = b""
left = num
while left > 0:
data = fp.read(left)
if not data:
break
body += data
left -= len(data)
else:
# read until EOF
body = fp.read()
return response_line, headers, body
# stolen from gevent
def get_errno(exc): # pragma: no cover
"""Get the error code out of socket.error objects.
socket.error in <2.5 does not have errno attribute
socket.error in 3.x does not allow indexing access
e.args[0] works for all.
There are cases when args[0] is not errno.
i.e. http://bugs.python.org/issue6471
Maybe there are cases when errno is set, but it is not the first argument?
"""
try:
if exc.errno is not None:
return exc.errno
except AttributeError:
pass
try:
return exc.args[0]
except IndexError:
return None
def chunks(l, n):
"""Yield successive n-sized chunks from l."""
for i in range(0, len(l), n):
yield l[i : i + n]
|