|
2 | 2 |
|
3 | 3 | import dataclasses
|
4 | 4 | import urllib.parse
|
| 5 | +import urllib.request |
5 | 6 |
|
6 |
| -from .exceptions import InvalidURI |
| 7 | +from .exceptions import InvalidProxy, InvalidURI |
7 | 8 |
|
8 | 9 |
|
9 | 10 | __all__ = ["parse_uri", "WebSocketURI"]
|
10 | 11 |
|
11 | 12 |
|
| 13 | +# All characters from the gen-delims and sub-delims sets in RFC 3987. |
| 14 | +DELIMS = ":/?#[]@!$&'()*+,;=" |
| 15 | + |
| 16 | + |
12 | 17 | @dataclasses.dataclass
|
13 | 18 | class WebSocketURI:
|
14 | 19 | """
|
@@ -53,10 +58,6 @@ def user_info(self) -> tuple[str, str] | None:
|
53 | 58 | return (self.username, self.password)
|
54 | 59 |
|
55 | 60 |
|
56 |
| -# All characters from the gen-delims and sub-delims sets in RFC 3987. |
57 |
| -DELIMS = ":/?#[]@!$&'()*+,;=" |
58 |
| - |
59 |
| - |
60 | 61 | def parse_uri(uri: str) -> WebSocketURI:
|
61 | 62 | """
|
62 | 63 | Parse and validate a WebSocket URI.
|
@@ -105,3 +106,120 @@ def parse_uri(uri: str) -> WebSocketURI:
|
105 | 106 | password = urllib.parse.quote(password, safe=DELIMS)
|
106 | 107 |
|
107 | 108 | return WebSocketURI(secure, host, port, path, query, username, password)
|
| 109 | + |
| 110 | + |
| 111 | +@dataclasses.dataclass |
| 112 | +class Proxy: |
| 113 | + """ |
| 114 | + Proxy. |
| 115 | +
|
| 116 | + Attributes: |
| 117 | + scheme: ``"socks5h"``, ``"socks5"``, ``"socks4a"``, ``"socks4"``, |
| 118 | + ``"https"``, or ``"http"``. |
| 119 | + host: Normalized to lower case. |
| 120 | + port: Always set even if it's the default. |
| 121 | + username: Available when the proxy address contains `User Information`_. |
| 122 | + password: Available when the proxy address contains `User Information`_. |
| 123 | +
|
| 124 | + .. _User Information: https://datatracker.ietf.org/doc/html/rfc3986#section-3.2.1 |
| 125 | +
|
| 126 | + """ |
| 127 | + |
| 128 | + scheme: str |
| 129 | + host: str |
| 130 | + port: int |
| 131 | + username: str | None = None |
| 132 | + password: str | None = None |
| 133 | + |
| 134 | + @property |
| 135 | + def user_info(self) -> tuple[str, str] | None: |
| 136 | + if self.username is None: |
| 137 | + return None |
| 138 | + assert self.password is not None |
| 139 | + return (self.username, self.password) |
| 140 | + |
| 141 | + |
| 142 | +def parse_proxy(proxy: str) -> Proxy: |
| 143 | + """ |
| 144 | + Parse and validate a proxy. |
| 145 | +
|
| 146 | + Args: |
| 147 | + proxy: proxy. |
| 148 | +
|
| 149 | + Returns: |
| 150 | + Parsed proxy. |
| 151 | +
|
| 152 | + Raises: |
| 153 | + InvalidProxy: If ``proxy`` isn't a valid proxy. |
| 154 | +
|
| 155 | + """ |
| 156 | + parsed = urllib.parse.urlparse(proxy) |
| 157 | + if parsed.scheme not in ["socks5h", "socks5", "socks4a", "socks4", "https", "http"]: |
| 158 | + raise InvalidProxy(proxy, f"scheme {parsed.scheme} isn't supported") |
| 159 | + if parsed.hostname is None: |
| 160 | + raise InvalidProxy(proxy, "hostname isn't provided") |
| 161 | + if parsed.path not in ["", "/"]: |
| 162 | + raise InvalidProxy(proxy, "path is meaningless") |
| 163 | + if parsed.query != "": |
| 164 | + raise InvalidProxy(proxy, "query is meaningless") |
| 165 | + if parsed.fragment != "": |
| 166 | + raise InvalidProxy(proxy, "fragment is meaningless") |
| 167 | + |
| 168 | + scheme = parsed.scheme |
| 169 | + host = parsed.hostname |
| 170 | + port = parsed.port or (443 if parsed.scheme == "https" else 80) |
| 171 | + username = parsed.username |
| 172 | + password = parsed.password |
| 173 | + # urllib.parse.urlparse accepts URLs with a username but without a |
| 174 | + # password. This doesn't make sense for HTTP Basic Auth credentials. |
| 175 | + if username is not None and password is None: |
| 176 | + raise InvalidProxy(proxy, "username provided without password") |
| 177 | + |
| 178 | + try: |
| 179 | + proxy.encode("ascii") |
| 180 | + except UnicodeEncodeError: |
| 181 | + # Input contains non-ASCII characters. |
| 182 | + # It must be an IRI. Convert it to a URI. |
| 183 | + host = host.encode("idna").decode() |
| 184 | + if username is not None: |
| 185 | + assert password is not None |
| 186 | + username = urllib.parse.quote(username, safe=DELIMS) |
| 187 | + password = urllib.parse.quote(password, safe=DELIMS) |
| 188 | + |
| 189 | + return Proxy(scheme, host, port, username, password) |
| 190 | + |
| 191 | + |
| 192 | +def get_proxy(uri: WebSocketURI) -> str | None: |
| 193 | + """ |
| 194 | + Return the proxy to use for connecting to the given WebSocket URI, if any. |
| 195 | +
|
| 196 | + """ |
| 197 | + if urllib.request.proxy_bypass(f"{uri.host}:{uri.port}"): |
| 198 | + return None |
| 199 | + |
| 200 | + # According to the _Proxy Usage_ section of RFC 6455, use a SOCKS5 proxy if |
| 201 | + # available, else favor the proxy for HTTPS connections over the proxy for |
| 202 | + # HTTP connections. |
| 203 | + |
| 204 | + # The priority of a proxy for WebSocket connections is unspecified. We give |
| 205 | + # it the highest priority. This makes it easy to configure a specific proxy |
| 206 | + # for websockets. |
| 207 | + |
| 208 | + # getproxies() may return SOCKS proxies as {"socks": "http://host:port"} or |
| 209 | + # as {"https": "socks5h://host:port"} depending on whether they're declared |
| 210 | + # in the operating system or in environment variables. |
| 211 | + |
| 212 | + proxies = urllib.request.getproxies() |
| 213 | + if uri.secure: |
| 214 | + schemes = ["wss", "socks", "https"] |
| 215 | + else: |
| 216 | + schemes = ["ws", "socks", "https", "http"] |
| 217 | + |
| 218 | + for scheme in schemes: |
| 219 | + proxy = proxies.get(scheme) |
| 220 | + if proxy is not None: |
| 221 | + if scheme == "socks" and proxy.startswith("http://"): |
| 222 | + proxy = "socks5h://" + proxy[7:] |
| 223 | + return proxy |
| 224 | + else: |
| 225 | + return None |
0 commit comments