refactor(proxies): resolve every --proxy value through one shared entry

This commit is contained in:
imSp4rky
2026-11-27 10:59:53 -07:00
parent dcfd2f66ba
commit f00f8cdc3c
14 changed files with 301 additions and 101 deletions
+1 -1
View File
@@ -988,7 +988,7 @@ Make a remote session for a service and title. Authentication runs asynchronousl
Service CLI options also travel in a nested `service_params` object. When the body has `service_params`, the server reads service options only from it, and a flat key with the same name stays a `dl` value. `profile` at the top level always means the credentials profile, never a service's own `--profile` option. Service CLI options also travel in a nested `service_params` object. When the body has `service_params`, the server reads service options only from it, and a flat key with the same name stays a `dl` value. `profile` at the top level always means the credentials profile, never a service's own `--profile` option.
The `proxy` value must be a full proxy URI, unless the operator gives your API key `server_proxy` in the `serve.users` config. Without `server_proxy`, a proxy URI gets `INVALID_PROXY` when its host is not a public address or is not a plain host name or IP address. Without `server_proxy`, the server does not resolve country codes with its own proxy providers. It rejects the request with `INVALID_PROXY` when no `proxy` is set and the reported `client_region` differs from the server's region. A request that reports no `client_region` is not blocked. Pass `proxy` with your own proxy, or `no_proxy` to accept the server's own connection. With `server_proxy`, the server resolves a country code and picks a proxy for your `client_region` itself. A Control D resolver, `controld://<resolver>@dns.controld.com`, counts as a full proxy URI: the server runs a forwarder for it and needs no Control D configuration of its own. The `proxy` value must be a full proxy URI, unless the operator gives your API key `server_proxy` in the `serve.users` config. Without `server_proxy`, a proxy URI gets `INVALID_PROXY` when its host is not a public address or is not a plain host name or IP address. Without `server_proxy`, the server does not resolve country codes with its own proxy providers. It rejects the request with `INVALID_PROXY` when no `proxy` is set and the reported `client_region` differs from the server's region. A request that reports no `client_region` is not blocked. Pass `proxy` with your own proxy, or `no_proxy` to accept the server's own connection. With `server_proxy`, the server resolves a country code and picks a proxy for your `client_region` itself. A Control D resolver, `controld://<resolver>@dns.controld.com`, counts as a full proxy URI: the server runs a forwarder for it and needs no Control D configuration of its own. A proxy URI needs an `http`, `https` or `socks` scheme: the server answers `INVALID_PROXY` to a `host:port` value, also with `server_proxy`.
=== "Response `200`" === "Response `200`"
+6 -4
View File
@@ -98,7 +98,8 @@ flowchart TD
1. **An explicit URI.** unshackle uses anything shaped like `http://...`, 1. **An explicit URI.** unshackle uses anything shaped like `http://...`,
`https://...`, or a `socks...` URI exactly as you give it. unshackle logs `https://...`, or a `socks...` URI exactly as you give it. unshackle logs
`Using explicit Proxy: ...` and does no lookup. A `host:port` value such as `Using explicit Proxy: ...` and does no lookup. A `host:port` value such as
`localhost:8080` is also an explicit proxy. `localhost:8080` is also an explicit proxy. A server (`--remote` or the REST API)
refuses a proxy that has no `http`, `https` or `socks` scheme.
2. **A provider-prefixed query**: `provider:query`, for example `nordvpn:us` or 2. **A provider-prefixed query**: `provider:query`, for example `nordvpn:us` or
`gluetun:windscribe:us`. unshackle finds the proxy provider whose name matches `gluetun:windscribe:us`. unshackle finds the proxy provider whose name matches
the prefix (case-insensitive). It then asks *only* that proxy provider to find a the prefix (case-insensitive). It then asks *only* that proxy provider to find a
@@ -1055,9 +1056,10 @@ The returned proxy is HTTPS on **port 443**.
providers through `load_proxy_providers()` in `unshackle/core/proxies/resolve.py`. providers through `load_proxy_providers()` in `unshackle/core/proxies/resolve.py`.
The REST API, its download jobs and the remote-service client call it through The REST API, its download jobs and the remote-service client call it through
`initialize_proxy_providers()`, which leaves out Gluetun because Gluetun starts a `initialize_proxy_providers()`, which leaves out Gluetun because Gluetun starts a
local Docker container. All paths accept the same query grammar: a direct URI, a local Docker container. All paths read a value through `resolve_proxy_value()`, which
`provider:query`, a bare query tried against providers in order, or a `controld://` returns the proxy URI with the proxy provider, the query and the log line: a
resolver. `controld://` resolver, a `provider:query` or a bare query tried against providers in
order, or else an explicit proxy URI or `host:port`.
The remote-service client resolves `--proxy` with its own The remote-service client resolves `--proxy` with its own
`resolve_remote_proxy_arg()`. It changes a `controld:` query to a `controld://` `resolve_remote_proxy_arg()`. It changes a `controld:` query to a `controld://`
+51
View File
@@ -0,0 +1,51 @@
"""The dl --proxy block resolves each form through the shared proxy entry and codes its errors."""
from __future__ import annotations
from pathlib import Path
import click
import pytest
from unshackle.core.remote_protocol import APIErrorCode
pytestmark = pytest.mark.unit
def run_dl(monkeypatch: pytest.MonkeyPatch, tmp_path: Path, proxy: str) -> click.Context:
from unshackle.commands import dl as dl_module
monkeypatch.setattr(dl_module.config, "key_vaults", [])
monkeypatch.setattr(dl_module.config, "output_template", {"movies": "{title}"})
monkeypatch.setattr(dl_module.dl, "get_cdm", lambda self, *a, **k: None)
monkeypatch.setattr(dl_module.Services, "get_path", staticmethod(lambda tag: tmp_path))
monkeypatch.setattr(dl_module.dl.cli, "_result_callback", dl_module.dl.cli._result_callback)
ctx = click.Context(dl_module.dl.cli)
ctx.invoked_subcommand = "EXAMPLE"
dl_module.dl(ctx=ctx, no_proxy=False, proxy=proxy, proxy_providers=[])
return ctx
@pytest.mark.usefixtures("example_service")
def test_dl_starts_a_forwarder_for_a_control_d_resolver(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
from unshackle.core.proxies import controld
monkeypatch.setattr(controld, "local_proxy", lambda uri: "http://127.0.0.1:4000")
params = run_dl(monkeypatch, tmp_path, "controld://efgh456@dns.controld.com").params
assert params["proxy"] == "http://127.0.0.1:4000"
assert (params["proxy_query"], params["proxy_provider"]) == (None, None)
@pytest.mark.usefixtures("example_service")
def test_dl_keeps_a_host_and_port_as_given(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
assert run_dl(monkeypatch, tmp_path, "nas:3128").params["proxy"] == "nas:3128"
@pytest.mark.usefixtures("example_service")
@pytest.mark.parametrize("proxy", ["nope:us", "us", "controld://bad id@dns.controld.com"])
def test_a_dl_proxy_error_is_a_proxy_error(monkeypatch: pytest.MonkeyPatch, tmp_path: Path, proxy: str) -> None:
from unshackle.core.run_plan import PlanError
with pytest.raises(PlanError) as raised:
run_dl(monkeypatch, tmp_path, proxy)
assert getattr(raised.value, "error_code", None) == APIErrorCode.INVALID_PROXY
+32
View File
@@ -0,0 +1,32 @@
"""The search command resolves --proxy with the same grammar as dl."""
from __future__ import annotations
from pathlib import Path
import click
import pytest
pytestmark = pytest.mark.unit
SENT = "controld://efgh456@dns.controld.com"
@pytest.mark.usefixtures("example_service")
def test_search_starts_a_forwarder_for_a_control_d_resolver(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
from unshackle.commands import search as search_module
from unshackle.core.proxies import controld
monkeypatch.setattr(controld, "local_proxy", lambda uri: "http://127.0.0.1:4000")
monkeypatch.setattr(search_module, "load_proxy_providers", lambda: [])
monkeypatch.setattr(search_module.Services, "get_path", staticmethod(lambda tag: tmp_path))
ctx = click.Context(search_module.search)
ctx.invoked_subcommand = "EXAMPLE"
ctx.params = {"proxy": SENT, "no_proxy": False}
with ctx:
assert search_module.search.callback
search_module.search.callback(no_proxy=False, proxy=SENT)
assert ctx.params["proxy"] == "http://127.0.0.1:4000"
assert ctx.params["proxy_arg"] == SENT
assert ctx.params.get("proxy_query") is None
+4 -5
View File
@@ -7,7 +7,6 @@ from __future__ import annotations
import base64 import base64
import http.server import http.server
import logging import logging
import re
import socket import socket
import socketserver import socketserver
import threading import threading
@@ -31,7 +30,7 @@ from unshackle.core.proxies.controld import (
local_proxy, local_proxy,
parse_a_records, parse_a_records,
) )
from unshackle.core.proxies.resolve import REGION, resolve_proxy from unshackle.core.proxies.resolve import REGION_QUERY, resolve_proxy, resolve_proxy_value
from unshackle.core.utilities import get_free_port from unshackle.core.utilities import get_free_port
pytestmark = pytest.mark.unit pytestmark = pytest.mark.unit
@@ -462,10 +461,10 @@ def test_a_server_gets_the_typed_proxy_only_when_this_machine_resolved_it_to_loo
@pytest.mark.parametrize("query", ["ca", "us:seattle", "us-ny", "uk1", "yul", "jfk", "res_yyz", "nordvpn:ca"]) @pytest.mark.parametrize("query", ["ca", "us:seattle", "us-ny", "uk1", "yul", "jfk", "res_yyz", "nordvpn:ca"])
def test_a_region_query_matches(query: str) -> None: def test_a_region_query_matches(query: str) -> None:
assert re.fullmatch(rf"(?:[a-z]+:)?{REGION}", query, re.IGNORECASE) assert REGION_QUERY.fullmatch(query)
assert re.fullmatch(rf"(?:[a-z]+:){{0,2}}{REGION}", f"gluetun:{query}", re.IGNORECASE)
@pytest.mark.parametrize("uri", ["nas:3128", "localhost:8080", "proxy.example.com:8080", "1.2.3.4:8080", "us:1080"]) @pytest.mark.parametrize("uri", ["nas:3128", "localhost:8080", "proxy.example.com:8080", "1.2.3.4:8080", "us:1080"])
def test_a_host_and_port_is_never_a_region_query(uri: str) -> None: def test_a_host_and_port_is_never_a_region_query(uri: str) -> None:
assert not re.fullmatch(rf"(?:[a-z]+:){{0,2}}{REGION}", uri, re.IGNORECASE) resolved = resolve_proxy_value(uri, [])
assert resolved.uri == uri and resolved.query is None
+24
View File
@@ -0,0 +1,24 @@
"""An import falls back to the export region for a proxy only when the region is a region code."""
from __future__ import annotations
import logging
from types import SimpleNamespace
import pytest
from unshackle.core import import_service
pytestmark = pytest.mark.unit
@pytest.mark.parametrize(("region", "proxies"), [("ca", {"all": "http://ca.proxy:8080"}), ("localhost:8080", {})])
def test_the_export_region_becomes_a_proxy_only_when_it_is_a_region(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, region: str, proxies: dict
) -> None:
monkeypatch.setattr(import_service, "resolve_proxy_arg", lambda query: f"http://{query}.proxy:8080")
ctx = SimpleNamespace(parent=SimpleNamespace(params={}))
with caplog.at_level(logging.WARNING):
session = import_service.ImportService.build_session(ctx, region) # type: ignore[arg-type]
assert session.proxies == proxies
assert ("continuing without one" in caplog.text) is not proxies
+79 -2
View File
@@ -1,21 +1,24 @@
"""Unit tests for the shared proxy dispatch that dl, search and resolve_proxy use: the provider:query """Unit tests for the shared proxy dispatch that dl, search, the REST API and the remote client use: the
split, the named or bare provider lookup, and the line that reports which proxy provider answered.""" provider:query split, the named or bare provider lookup, and the line that reports which proxy provider answered."""
from __future__ import annotations from __future__ import annotations
import json import json
import logging import logging
from collections.abc import Iterator from collections.abc import Iterator
from contextlib import contextmanager
import pytest import pytest
from unshackle.core.proxies import Basic from unshackle.core.proxies import Basic
from unshackle.core.proxies.proxy import Proxy from unshackle.core.proxies.proxy import Proxy
from unshackle.core.proxies.resolve import ( from unshackle.core.proxies.resolve import (
ResolvedProxy,
Unavailable, Unavailable,
describe_proxy, describe_proxy,
pick_proxy, pick_proxy,
resolve_proxy, resolve_proxy,
resolve_proxy_value,
split_proxy_query, split_proxy_query,
) )
@@ -215,3 +218,77 @@ def test_named_query_passes_a_query_error_on_unchanged() -> None:
with pytest.raises(ValueError, match="^no server for us150$"): with pytest.raises(ValueError, match="^no server for us150$"):
pick_proxy([Strict()], "us150", "strict") pick_proxy([Strict()], "us150", "strict")
class Gluetun(Alpha):
pass
@pytest.mark.parametrize(
("value", "expected"),
[
(
"US",
ResolvedProxy(
"http://a:b@alpha.example:80", None, "us", "Using Alpha Proxy: http://xxxxx:xxxxx@alpha.example:80"
),
),
(
"Beta:CA",
ResolvedProxy("http://c:d@beta-ca.example:80", "Beta", "ca", "Using Beta Proxy via Dallas (server 12)"),
),
(
"alpha:beta:ca",
ResolvedProxy(
"http://a:b@alpha-beta.example:80",
"alpha",
"beta:ca",
"Using Alpha Proxy: http://xxxxx:xxxxx@alpha-beta.example:80",
),
),
(
"http://user:pass@proxy.example:8080",
ResolvedProxy(
"http://user:pass@proxy.example:8080",
None,
None,
"Using explicit Proxy: http://xxxxx:xxxxx@proxy.example:8080",
),
),
("localhost:8080", ResolvedProxy("localhost:8080", None, None, "Using a local proxy on port 8080")),
("1.2.3.4:3128", ResolvedProxy("1.2.3.4:3128", None, None, "Using explicit Proxy: 1.2.3.4:3128")),
("us:1080", ResolvedProxy("us:1080", None, None, "Using explicit Proxy: us:1080")),
],
)
def test_resolve_proxy_value_reads_each_form(providers: list, value: str, expected: ResolvedProxy) -> None:
providers[1].answers["beta:ca"] = "http://a:b@alpha-beta.example:80"
assert resolve_proxy_value(value, providers) == expected
def test_resolve_proxy_value_starts_a_forwarder_for_a_control_d_resolver(monkeypatch: pytest.MonkeyPatch) -> None:
from unshackle.core.proxies import controld
monkeypatch.setattr(controld, "local_proxy", lambda uri: "http://127.0.0.1:4000")
resolved = resolve_proxy_value("controld://efgh456@dns.controld.com", [])
assert resolved == ResolvedProxy("http://127.0.0.1:4000", None, None, "Using a local proxy on port 4000")
@pytest.mark.parametrize(
("value", "message"), [("us", "Getting a Proxy to us..."), ("gluetun:ca", "Connecting to VPN (ca)...")]
)
def test_the_status_wraps_only_the_provider_lookup(providers: list, value: str, message: str) -> None:
shown: list[str] = []
@contextmanager
def status(text: str) -> Iterator[None]:
shown.append(text)
yield
resolve_proxy_value(value, [*providers, Gluetun(ca="http://g.example:8888")], status=status)
resolve_proxy_value("http://proxy.example:8080", providers, status=status)
assert shown == [message]
@pytest.mark.parametrize("value", ["localhost:8080", "1.2.3.4:3128"])
def test_resolve_proxy_passes_a_host_and_port_through(providers: list, value: str) -> None:
assert resolve_proxy(value, providers) == value
+2 -3
View File
@@ -3,7 +3,6 @@
from __future__ import annotations from __future__ import annotations
import datetime import datetime
import re
import socket import socket
import ssl import ssl
import threading import threading
@@ -19,7 +18,7 @@ from cryptography.x509.oid import NameOID
from unshackle.core.proxies import asn, surfsharkvpn from unshackle.core.proxies import asn, surfsharkvpn
from unshackle.core.proxies.nordvpn import NordVPN from unshackle.core.proxies.nordvpn import NordVPN
from unshackle.core.proxies.resolve import REGION from unshackle.core.proxies.resolve import REGION_QUERY
from unshackle.core.proxies.surfsharkvpn import SurfsharkVPN from unshackle.core.proxies.surfsharkvpn import SurfsharkVPN
from unshackle.core.proxies.windscribevpn import WindscribeVPN from unshackle.core.proxies.windscribevpn import WindscribeVPN
from unshackle.core.remote_service import resolve_remote_proxy_arg from unshackle.core.remote_service import resolve_remote_proxy_arg
@@ -54,7 +53,7 @@ def known_networks(monkeypatch: pytest.MonkeyPatch) -> None:
) )
def test_region_grammar_takes_the_selector_but_not_a_uri(value: str, is_query: bool) -> None: def test_region_grammar_takes_the_selector_but_not_a_uri(value: str, is_query: bool) -> None:
"""dl and search send a value to the proxy providers only when it matches; anything else is an explicit URI.""" """dl and search send a value to the proxy providers only when it matches; anything else is an explicit URI."""
assert bool(re.fullmatch(rf"(?:[a-z]+:)?{REGION}", value, re.IGNORECASE)) is is_query assert bool(REGION_QUERY.fullmatch(value)) is is_query
@pytest.mark.parametrize( @pytest.mark.parametrize(
@@ -384,6 +384,23 @@ def test_local_proxy_uri_allowed_with_server_proxy_or_admin(monkeypatch, key):
assert proxy == "http://127.0.0.1:8080" assert proxy == "http://127.0.0.1:8080"
@pytest.mark.parametrize("key", ["plainkey", "proxykey"])
@pytest.mark.parametrize("proxy", ["127.0.0.1:8080", "localhost:3128", "ftp://127.0.0.1:21"])
def test_a_proxy_without_an_http_or_socks_scheme_is_refused(monkeypatch, key, proxy):
monkeypatch.setattr(handlers, "initialize_proxy_providers", lambda **_: [])
with pytest.raises(APIError) as exc_info:
handlers.resolve_handler_proxy({"proxy": proxy}, "EXAMPLE", request(key))
assert exc_info.value.error_code == APIErrorCode.INVALID_PROXY
@pytest.mark.parametrize("client_region", ["localhost:8080", "ftp://127.0.0.1:21", "United States"])
def test_a_client_region_that_is_no_region_code_gets_no_proxy(monkeypatch, client_region):
patch_server_region(monkeypatch, "IN")
monkeypatch.setattr(handlers, "initialize_proxy_providers", lambda **_: [SimpleNamespace(get_proxy=lambda q: None)])
proxy, _ = handlers.resolve_handler_proxy({"client_region": client_region}, "EXAMPLE", request("proxykey"))
assert proxy is None
def test_hostname_resolving_to_a_private_address_refused(monkeypatch): def test_hostname_resolving_to_a_private_address_refused(monkeypatch):
monkeypatch.setattr(handlers.socket, "getaddrinfo", lambda host, port: [(2, 1, 6, "", ("10.0.0.7", 0))]) monkeypatch.setattr(handlers.socket, "getaddrinfo", lambda host, port: [(2, 1, 6, "", ("10.0.0.7", 0))])
with pytest.raises(APIError) as exc_info: with pytest.raises(APIError) as exc_info:
+12 -40
View File
@@ -3,7 +3,6 @@ from __future__ import annotations
import logging import logging
import os import os
import random import random
import re
import shutil import shutil
import subprocess import subprocess
import sys import sys
@@ -65,16 +64,13 @@ from unshackle.core.mux_step import mux_title
from unshackle.core.placement import SAMPLE_DIR, Placement, sample_name from unshackle.core.placement import SAMPLE_DIR, Placement, sample_name
from unshackle.core.providers.tvdb import SEASON_TYPES from unshackle.core.providers.tvdb import SEASON_TYPES
from unshackle.core.proxies.resolve import ( from unshackle.core.proxies.resolve import (
REGION,
describe_explicit_proxy,
describe_proxy,
is_loopback, is_loopback,
load_proxy_providers, load_proxy_providers,
pick_proxy,
require_alone_local_proxy, require_alone_local_proxy,
resolve_proxy, resolve_proxy,
split_proxy_query, resolve_proxy_value,
) )
from unshackle.core.remote_protocol import APIErrorCode, coded
from unshackle.core.run_plan import PlanError, RunOutcome, RunStopped, bitrate_range, check_options from unshackle.core.run_plan import PlanError, RunOutcome, RunStopped, bitrate_range, check_options
from unshackle.core.service import grow_session_pool from unshackle.core.service import grow_session_pool
from unshackle.core.services import ROUTING_PARAMS, Services from unshackle.core.services import ROUTING_PARAMS, Services
@@ -1352,37 +1348,17 @@ class dl:
self.proxy_providers = load_proxy_providers() self.proxy_providers = load_proxy_providers()
keys["proxy_arg"] = proxy keys["proxy_arg"] = proxy
if proxy and proxy.startswith("controld://"):
proxy = ctx.params["proxy"] = resolve_proxy(proxy, [])
if proxy: if proxy:
try: try:
requested_provider, query = split_proxy_query(proxy, self.proxy_providers) resolved = resolve_proxy_value(
except ValueError as e: proxy, self.proxy_providers, status=partial(console.status, spinner="dots")
raise PlanError(str(e)) from None
# Match region codes (us, ca, uk1, us:ny, yul) or provider:region (nordvpn:ca, protonvpn:us:ny).
if re.fullmatch(rf"(?:[a-z]+:)?{REGION}", query, re.IGNORECASE):
# Kept apart from ctx.params["proxy"], which becomes the URI: a service proxy_map keys on it.
proxy_query = query.lower()
status_msg = (
f"Connecting to VPN ({proxy_query})..."
if requested_provider == "gluetun"
else f"Getting a Proxy to {proxy_query}..."
) )
with console.status(status_msg, spinner="dots"): except ValueError as e:
try: raise coded(PlanError(str(e)), APIErrorCode.INVALID_PROXY) from None
proxy_provider, proxy_uri = pick_proxy( ctx.params["proxy"] = resolved.uri
self.proxy_providers, proxy_query, requested_provider self.log.info(resolved.line)
) keys["proxy_query"] = resolved.query
except ValueError as e: keys["proxy_provider"] = resolved.provider
raise click.ClickException(str(e)) from None
ctx.params["proxy"] = proxy_uri
self.log.info(describe_proxy(proxy_provider, proxy_uri, proxy_query))
keys["proxy_query"] = proxy_query
keys["proxy_provider"] = requested_provider
else:
self.log.info(describe_explicit_proxy(ctx.params["proxy"]))
keys["proxy_query"] = None
keys["proxy_provider"] = None
launch( launch(
ctx, ctx,
@@ -1553,13 +1529,9 @@ class dl:
if no_proxy or no_proxy_download: if no_proxy or no_proxy_download:
proxy_download = None proxy_download = None
elif proxy_download and ( else:
proxy_download.startswith("controld://")
or re.fullmatch(rf"(?:[a-z]+:){{0,2}}{REGION}", proxy_download, re.I)
):
# same shapes --proxy resolves against providers (two prefixes for gluetun:nordvpn:ca); else an explicit URI
try: try:
proxy_download = resolve_proxy(proxy_download.lower(), self.proxy_providers) proxy_download = resolve_proxy(proxy_download, self.proxy_providers)
except ValueError as e: except ValueError as e:
raise click.ClickException(f"--proxy-download: {e}") from None raise click.ClickException(f"--proxy-download: {e}") from None
+7 -25
View File
@@ -1,8 +1,8 @@
from __future__ import annotations from __future__ import annotations
import logging import logging
import re
import sys import sys
from functools import partial
from typing import Any from typing import Any
import click import click
@@ -15,15 +15,7 @@ from unshackle.core.console import console
from unshackle.core.constants import context_settings from unshackle.core.constants import context_settings
from unshackle.core.launch import LaunchKeys, launch, load_service_config from unshackle.core.launch import LaunchKeys, launch, load_service_config
from unshackle.core.proxies.proxy import Proxy from unshackle.core.proxies.proxy import Proxy
from unshackle.core.proxies.resolve import ( from unshackle.core.proxies.resolve import load_proxy_providers, require_alone_local_proxy, resolve_proxy_value
REGION,
describe_explicit_proxy,
describe_proxy,
load_proxy_providers,
pick_proxy,
require_alone_local_proxy,
split_proxy_query,
)
from unshackle.core.service import Service from unshackle.core.service import Service
from unshackle.core.services import Services from unshackle.core.services import Services
from unshackle.core.utils.click_types import ContextData from unshackle.core.utils.click_types import ContextData
@@ -104,24 +96,14 @@ def search(
keys["proxy_arg"] = proxy keys["proxy_arg"] = proxy
if proxy: if proxy:
try: try:
requested_provider, query = split_proxy_query(proxy, proxy_providers) resolved = resolve_proxy_value(proxy, proxy_providers, status=partial(console.status, spinner="dots"))
except ValueError as e: except ValueError as e:
log.error(str(e)) log.error(str(e))
sys.exit(1) sys.exit(1)
if re.fullmatch(rf"(?:[a-z]+:)?{REGION}", query, re.IGNORECASE): ctx.params["proxy"] = resolved.uri
query = query.lower() log.info(resolved.line)
with console.status(f"Getting a Proxy to {query}...", spinner="dots"): keys["proxy_query"] = resolved.query
try: keys["proxy_provider"] = resolved.provider
proxy_provider, proxy_uri = pick_proxy(proxy_providers, query, requested_provider)
except ValueError as e:
log.error(str(e))
sys.exit(1)
ctx.params["proxy"] = proxy_uri
log.info(describe_proxy(proxy_provider, proxy_uri, query))
keys["proxy_query"] = query
keys["proxy_provider"] = requested_provider
else:
log.info(describe_explicit_proxy(ctx.params["proxy"]))
launch(ctx, keys, ContextData(config=service_config, cdm=None, proxy_providers=proxy_providers, profile=profile)) launch(ctx, keys, ContextData(config=service_config, cdm=None, proxy_providers=proxy_providers, profile=profile))
+13 -4
View File
@@ -53,7 +53,7 @@ from unshackle.core.drm import WHOLE_FILE_DRM, cbcs, is_null_key, real_kids, who
from unshackle.core.drm.discovery import drm_from_init_segment, ensure_track_drm, fetch_init_segment, track_pssh from unshackle.core.drm.discovery import drm_from_init_segment, ensure_track_drm, fetch_init_segment, track_pssh
from unshackle.core.launch import served_context from unshackle.core.launch import served_context
from unshackle.core.manifests.snapshot import capture from unshackle.core.manifests.snapshot import capture
from unshackle.core.proxies.resolve import initialize_proxy_providers, is_loopback, resolve_proxy from unshackle.core.proxies.resolve import REGION_QUERY, initialize_proxy_providers, is_loopback, resolve_proxy
from unshackle.core.remote_protocol import ( from unshackle.core.remote_protocol import (
HEALTH_ROUTE, HEALTH_ROUTE,
APIErrorCode, APIErrorCode,
@@ -3474,13 +3474,16 @@ async def get_validated_session(session_id: str, request: web.Request | None) ->
return session return session
PROXY_URI = re.compile(r"^(https?://|socks)")
def local_proxy_refusal(proxy: str) -> str | None: def local_proxy_refusal(proxy: str) -> str | None:
"""Why an http(s) or socks proxy URI may reach the server's own machine or network, or None when it cannot. """Why an http(s) or socks proxy URI may reach the server's own machine or network, or None when it cannot.
The host must be a plain DNS name or an IP literal: an HTTP client that follows the WHATWG URL standard The host must be a plain DNS name or an IP literal: an HTTP client that follows the WHATWG URL standard
reads a backslash or a percent-escape in the authority differently from ``urlsplit``. reads a backslash or a percent-escape in the authority differently from ``urlsplit``.
""" """
if not re.match(r"^(https?://|socks)", proxy): if not PROXY_URI.match(proxy):
return None return None
try: try:
host = urlsplit(proxy).hostname or "" host = urlsplit(proxy).hostname or ""
@@ -3524,7 +3527,7 @@ def resolve_handler_proxy(
if ( if (
proxy_param proxy_param
and re.match(r"^(https?://|socks|controld://|tunnel:)", str(proxy_param)) and (PROXY_URI.match(str(proxy_param)) or str(proxy_param).startswith(("controld://", "tunnel:")))
and server_account_for(policy, normalized_service) and server_account_for(policy, normalized_service)
): ):
raise APIError( raise APIError(
@@ -3567,6 +3570,12 @@ def resolve_handler_proxy(
"This server does not resolve country codes into proxies, pass a full proxy URI", "This server does not resolve country codes into proxies, pass a full proxy URI",
details={"service": normalized_service}, details={"service": normalized_service},
) from None ) from None
if not PROXY_URI.match(proxy_param or ""):
raise APIError(
APIErrorCode.INVALID_PROXY,
"Proxy URI has no http, https or socks scheme",
details={"service": normalized_service},
)
client_region = data.get("client_region") client_region = data.get("client_region")
if client_region is not None and not isinstance(client_region, str): if client_region is not None and not isinstance(client_region, str):
@@ -3606,7 +3615,7 @@ def resolve_handler_proxy(
) )
elif in_client_region: elif in_client_region:
log.info(f"Server already in client region '{sanitize_log(client_region)}', no proxy needed") log.info(f"Server already in client region '{sanitize_log(client_region)}', no proxy needed")
else: elif REGION_QUERY.fullmatch(client_region):
try: try:
proxy_param = resolve_proxy(client_region, proxy_providers) proxy_param = resolve_proxy(client_region, proxy_providers)
log.info(f"Using server proxy for client region '{sanitize_log(client_region)}'") log.info(f"Using server proxy for client region '{sanitize_log(client_region)}'")
+4
View File
@@ -21,6 +21,7 @@ from unshackle.core.drm import ClearKey, MonaLisa, real_kids
from unshackle.core.drm.cenc import drm_stub from unshackle.core.drm.cenc import drm_stub
from unshackle.core.drm.discovery import drm_from_init_segment from unshackle.core.drm.discovery import drm_from_init_segment
from unshackle.core.manifests import DASH, HLS, ISM, MissingLanguageError, snapshot from unshackle.core.manifests import DASH, HLS, ISM, MissingLanguageError, snapshot
from unshackle.core.proxies.resolve import REGION_QUERY
from unshackle.core.remote_protocol import APIErrorCode, coded from unshackle.core.remote_protocol import APIErrorCode, coded
from unshackle.core.remote_service import resolve_proxy_arg, segment_uri_filter from unshackle.core.remote_service import resolve_proxy_arg, segment_uri_filter
from unshackle.core.session import failure_response, utf8_text from unshackle.core.session import failure_response, utf8_text
@@ -330,6 +331,9 @@ class ImportService(TitleSource):
if not proxy_query: if not proxy_query:
return session return session
if not explicit and not REGION_QUERY.fullmatch(proxy_query):
log.warning(f"No proxy for export region '{region}', continuing without one")
return session
try: try:
proxy = resolve_proxy_arg(proxy_query) proxy = resolve_proxy_arg(proxy_query)
except Exception as e: except Exception as e:
+49 -17
View File
@@ -6,6 +6,9 @@ import ipaddress
import json import json
import logging import logging
import re import re
from collections.abc import Callable
from contextlib import AbstractContextManager, nullcontext
from dataclasses import dataclass
from typing import Any from typing import Any
from urllib.parse import urlparse from urllib.parse import urlparse
@@ -20,6 +23,7 @@ from unshackle.core.utils.redact import mask_proxy
log = logging.getLogger("proxies") log = logging.getLogger("proxies")
REGION = r"[a-z]{2,4}(?:_[a-z0-9]{2,4})?(?:-[a-z0-9]+|:[a-z][a-z0-9]*)*\d*(?:@-?[a-z0-9][a-z0-9._-]*)?" REGION = r"[a-z]{2,4}(?:_[a-z0-9]{2,4})?(?:-[a-z0-9]+|:[a-z][a-z0-9]*)*\d*(?:@-?[a-z0-9][a-z0-9._-]*)?"
REGION_QUERY = re.compile(rf"(?:[a-z]+:)?{REGION}", re.IGNORECASE)
class Unavailable(Proxy): class Unavailable(Proxy):
@@ -247,30 +251,58 @@ def describe_explicit_proxy(uri: str) -> str:
return f"Using explicit Proxy: {mask_proxy(uri)}" return f"Using explicit Proxy: {mask_proxy(uri)}"
def resolve_proxy(proxy: str, proxy_providers: list[Any]) -> str | None: @dataclass(frozen=True)
"""Change a proxy parameter to a real proxy URI. class ResolvedProxy:
"""A ``--proxy`` value resolved to a proxy URI.
Accepts: *provider* and *query* are the proxy provider that the value names and its lowercase region query.
- Direct URI: "https://...", "socks5://..." Both are None for a proxy URI, a ``host:port`` value or a Control D resolver.
- Country code: "us", "uk"
- Provider:country: "nordvpn:us"
- A Control D resolver sent by a client: "controld://<resolver>@dns.controld.com"
""" """
if not proxy:
return None
if proxy.startswith("controld://"): uri: str
provider: str | None
query: str | None
line: str
def resolve_proxy_value(
value: str,
proxy_providers: list[Any],
allow_debug: bool = True,
status: Callable[[str], AbstractContextManager[Any]] | None = None,
) -> ResolvedProxy:
"""Resolve a ``--proxy`` value: a Control D resolver, a region query for a proxy provider, or a proxy URI.
*status* wraps the proxy provider lookup, for a console spinner. Raises a coded ValueError.
"""
if value.startswith("controld://"):
from unshackle.core.proxies.controld import local_proxy from unshackle.core.proxies.controld import local_proxy
return local_proxy(proxy) uri = local_proxy(value)
return ResolvedProxy(uri, None, None, describe_explicit_proxy(uri))
provider_name, query = split_proxy_query(value, proxy_providers)
if not REGION_QUERY.fullmatch(query):
return ResolvedProxy(value, None, None, describe_explicit_proxy(value))
query = query.lower()
message = (
f"Connecting to VPN ({query})..."
if (provider_name or "").lower() == "gluetun"
else f"Getting a Proxy to {query}..."
)
with status(message) if status else nullcontext():
provider, uri = pick_proxy(proxy_providers, query, provider_name)
line = describe_proxy(provider, uri, query, allow_debug)
return ResolvedProxy(uri, provider_name, query, line)
if re.match(r"^(https?://|socks)", proxy):
return proxy
provider_name, query = split_proxy_query(proxy, proxy_providers) def resolve_proxy(proxy: str | None, proxy_providers: list[Any]) -> str | None:
provider, uri = pick_proxy(proxy_providers, query, provider_name) """Get the proxy URI for a ``--proxy`` value, and log the proxy provider that answered a region query."""
log.info(describe_proxy(provider, uri, query, allow_debug=False)) if not proxy:
return uri return None
resolved = resolve_proxy_value(proxy, proxy_providers, allow_debug=False)
if resolved.query:
log.info(resolved.line)
return resolved.uri
def is_loopback(uri: str) -> bool: def is_loopback(uri: str) -> bool: