| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import base64 |
| 4 |
import binascii |
| 5 |
|
| 6 |
from ..datastructures import Headers, MultipleValuesError |
| 7 |
from ..exceptions import InvalidHeader, InvalidHeaderValue, InvalidUpgrade |
| 8 |
from ..headers import parse_connection, parse_upgrade |
| 9 |
from ..typing import ConnectionOption, UpgradeProtocol |
| 10 |
from ..utils import accept_key as accept, generate_key |
| 11 |
|
| 12 |
|
| 13 |
__all__ = ["build_request", "check_request", "build_response", "check_response"] |
| 14 |
|
| 15 |
|
| 16 |
def build_request(headers: Headers) -> str: |
| 17 |
""" |
| 18 |
Build a handshake request to send to the server. |
| 19 |
|
| 20 |
Update request headers passed in argument. |
| 21 |
|
| 22 |
Args: |
| 23 |
headers: Handshake request headers. |
| 24 |
|
| 25 |
Returns: |
| 26 |
``key`` that must be passed to :func:`check_response`. |
| 27 |
|
| 28 |
""" |
| 29 |
key = generate_key() |
| 30 |
headers["Upgrade"] = "websocket" |
| 31 |
headers["Connection"] = "Upgrade" |
| 32 |
headers["Sec-WebSocket-Key"] = key |
| 33 |
headers["Sec-WebSocket-Version"] = "13" |
| 34 |
return key |
| 35 |
|
| 36 |
|
| 37 |
def check_request(headers: Headers) -> str: |
| 38 |
""" |
| 39 |
Check a handshake request received from the client. |
| 40 |
|
| 41 |
This function doesn't verify that the request is an HTTP/1.1 or higher GET |
| 42 |
request and doesn't perform ``Host`` and ``Origin`` checks. These controls |
| 43 |
are usually performed earlier in the HTTP request handling code. They're |
| 44 |
the responsibility of the caller. |
| 45 |
|
| 46 |
Args: |
| 47 |
headers: Handshake request headers. |
| 48 |
|
| 49 |
Returns: |
| 50 |
``key`` that must be passed to :func:`build_response`. |
| 51 |
|
| 52 |
Raises: |
| 53 |
InvalidHandshake: If the handshake request is invalid. |
| 54 |
Then, the server must return a 400 Bad Request error. |
| 55 |
|
| 56 |
""" |
| 57 |
connection: list[ConnectionOption] = sum( |
| 58 |
[parse_connection(value) for value in headers.get_all("Connection")], [] |
| 59 |
) |
| 60 |
|
| 61 |
if not any(value.lower() == "upgrade" for value in connection): |
| 62 |
raise InvalidUpgrade("Connection", ", ".join(connection)) |
| 63 |
|
| 64 |
upgrade: list[UpgradeProtocol] = sum( |
| 65 |
[parse_upgrade(value) for value in headers.get_all("Upgrade")], [] |
| 66 |
) |
| 67 |
|
| 68 |
# For compatibility with non-strict implementations, ignore case when |
| 69 |
# checking the Upgrade header. The RFC always uses "websocket", except |
| 70 |
# in section 11.2. (IANA registration) where it uses "WebSocket". |
| 71 |
if not (len(upgrade) == 1 and upgrade[0].lower() == "websocket"): |
| 72 |
raise InvalidUpgrade("Upgrade", ", ".join(upgrade)) |
| 73 |
|
| 74 |
try: |
| 75 |
s_w_key = headers["Sec-WebSocket-Key"] |
| 76 |
except KeyError as exc: |
| 77 |
raise InvalidHeader("Sec-WebSocket-Key") from exc |
| 78 |
except MultipleValuesError as exc: |
| 79 |
raise InvalidHeader("Sec-WebSocket-Key", "multiple values") from exc |
| 80 |
|
| 81 |
try: |
| 82 |
raw_key = base64.b64decode(s_w_key.encode(), validate=True) |
| 83 |
except binascii.Error as exc: |
| 84 |
raise InvalidHeaderValue("Sec-WebSocket-Key", s_w_key) from exc |
| 85 |
if len(raw_key) != 16: |
| 86 |
raise InvalidHeaderValue("Sec-WebSocket-Key", s_w_key) |
| 87 |
|
| 88 |
try: |
| 89 |
s_w_version = headers["Sec-WebSocket-Version"] |
| 90 |
except KeyError as exc: |
| 91 |
raise InvalidHeader("Sec-WebSocket-Version") from exc |
| 92 |
except MultipleValuesError as exc: |
| 93 |
raise InvalidHeader("Sec-WebSocket-Version", "multiple values") from exc |
| 94 |
|
| 95 |
if s_w_version != "13": |
| 96 |
raise InvalidHeaderValue("Sec-WebSocket-Version", s_w_version) |
| 97 |
|
| 98 |
return s_w_key |
| 99 |
|
| 100 |
|
| 101 |
def build_response(headers: Headers, key: str) -> None: |
| 102 |
""" |
| 103 |
Build a handshake response to send to the client. |
| 104 |
|
| 105 |
Update response headers passed in argument. |
| 106 |
|
| 107 |
Args: |
| 108 |
headers: Handshake response headers. |
| 109 |
key: Returned by :func:`check_request`. |
| 110 |
|
| 111 |
""" |
| 112 |
headers["Upgrade"] = "websocket" |
| 113 |
headers["Connection"] = "Upgrade" |
| 114 |
headers["Sec-WebSocket-Accept"] = accept(key) |
| 115 |
|
| 116 |
|
| 117 |
def check_response(headers: Headers, key: str) -> None: |
| 118 |
""" |
| 119 |
Check a handshake response received from the server. |
| 120 |
|
| 121 |
This function doesn't verify that the response is an HTTP/1.1 or higher |
| 122 |
response with a 101 status code. These controls are the responsibility of |
| 123 |
the caller. |
| 124 |
|
| 125 |
Args: |
| 126 |
headers: Handshake response headers. |
| 127 |
key: Returned by :func:`build_request`. |
| 128 |
|
| 129 |
Raises: |
| 130 |
InvalidHandshake: If the handshake response is invalid. |
| 131 |
|
| 132 |
""" |
| 133 |
connection: list[ConnectionOption] = sum( |
| 134 |
[parse_connection(value) for value in headers.get_all("Connection")], [] |
| 135 |
) |
| 136 |
|
| 137 |
if not any(value.lower() == "upgrade" for value in connection): |
| 138 |
raise InvalidUpgrade("Connection", " ".join(connection)) |
| 139 |
|
| 140 |
upgrade: list[UpgradeProtocol] = sum( |
| 141 |
[parse_upgrade(value) for value in headers.get_all("Upgrade")], [] |
| 142 |
) |
| 143 |
|
| 144 |
# For compatibility with non-strict implementations, ignore case when |
| 145 |
# checking the Upgrade header. The RFC always uses "websocket", except |
| 146 |
# in section 11.2. (IANA registration) where it uses "WebSocket". |
| 147 |
if not (len(upgrade) == 1 and upgrade[0].lower() == "websocket"): |
| 148 |
raise InvalidUpgrade("Upgrade", ", ".join(upgrade)) |
| 149 |
|
| 150 |
try: |
| 151 |
s_w_accept = headers["Sec-WebSocket-Accept"] |
| 152 |
except KeyError as exc: |
| 153 |
raise InvalidHeader("Sec-WebSocket-Accept") from exc |
| 154 |
except MultipleValuesError as exc: |
| 155 |
raise InvalidHeader("Sec-WebSocket-Accept", "multiple values") from exc |
| 156 |
|
| 157 |
if s_w_accept != accept(key): |
| 158 |
raise InvalidHeaderValue("Sec-WebSocket-Accept", s_w_accept) |