Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
5c7f3c2
lint: fix initial pylint correctness findings
by275 Aug 28, 2026
ef6ab05
refactor: clarify datagram callback ownership
by275 Aug 28, 2026
2bfaa81
refactor: align async backend lifecycle contracts
by275 Aug 28, 2026
6bb9e4f
style: modernize system proxy module
by275 Aug 28, 2026
c0a90af
ci: add scoped pylint checks
by275 Aug 28, 2026
e9b87f8
lint: clarify exception and file boundaries
by275 Aug 28, 2026
69373ba
refactor: declare cipher runtime contracts
by275 Aug 28, 2026
8ec28af
refactor: isolate private transport access
by275 Aug 28, 2026
1d7a4ef
style: document core modules and normalize imports
by275 Aug 28, 2026
7efb95d
refactor: split proxy URI construction stages
by275 Aug 28, 2026
197dd5e
refactor: split CLI and URI lifecycle stages
by275 Aug 28, 2026
612cf4b
refactor: complete TLS transport adapter contract
by275 Aug 28, 2026
b68ade5
style: clarify protocol return contracts
by275 Aug 28, 2026
d350f09
refactor: separate HTTP2 event dispatch
by275 Aug 28, 2026
e71da97
style: document intentional lazy imports
by275 Aug 28, 2026
8e6a69b
style: clarify protocol adapter state
by275 Aug 28, 2026
190118c
docs: document protocol adapter interfaces
by275 Aug 28, 2026
1af971c
docs: document connection lifecycle ownership
by275 Aug 28, 2026
b1d4656
style: document protocol callback exceptions
by275 Aug 28, 2026
7be7a1b
docs: clarify cipher implementation contracts
by275 Aug 28, 2026
7f785ae
style: clarify runtime helper contracts
by275 Aug 28, 2026
df45944
refactor: split stream handler stages
by275 Aug 28, 2026
ccbf097
style: document optional runtime state
by275 Aug 28, 2026
3f42e60
style: classify compatibility naming contracts
by275 Aug 28, 2026
7c2eb59
test: clarify benchmark callback contracts
by275 Aug 28, 2026
4a0d235
docs: label test and benchmark modules
by275 Aug 28, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions .github/workflows/core.yml
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,34 @@ jobs:
pproxy tests
--select E9,F821

- name: Gate selected Pylint correctness messages
run: >-
python -m pylint
--persistent=no
--reports=no
--score=no
--disable=all
--enable=E0102,W0640
pproxy tests

- name: Report Pylint production findings
run: >-
python -m pylint
--persistent=no
--reports=no
--score=no
--exit-zero
pproxy

- name: Report Pylint test and benchmark findings
run: >-
python -m pylint
--persistent=no
--reports=no
--score=no
--exit-zero
tests

- name: Run proxy-level setup smoke benchmark
run: python tests/benchmark_setup.py --connections 10

Expand Down
8 changes: 5 additions & 3 deletions pproxy/__doc__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
"""Package metadata and source-tree version discovery."""

import subprocess
from pathlib import Path

Expand All @@ -18,7 +20,7 @@ def _git_version(root):
text=True,
stderr=subprocess.DEVNULL,
).strip()
except Exception:
except (OSError, subprocess.SubprocessError, ValueError):
return None
dirty = description.endswith('-dirty')
if dirty:
Expand All @@ -41,10 +43,10 @@ def _source_version():
if not (root / '.git').exists():
return None
try:
from setuptools_scm import get_version
from setuptools_scm import get_version # pylint: disable=import-outside-toplevel

return get_version(root=root)
except Exception:
except (ImportError, LookupError, OSError, RuntimeError, ValueError):
return _git_version(root)


Expand Down
7 changes: 4 additions & 3 deletions pproxy/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,10 @@
ProxyFactory = Callable[[str], Any]
RuleFactory = Callable[[str], Callable[[str], Any]]

Connection: ProxyFactory = server.proxies_by_uri
Server: ProxyFactory = server.proxies_by_uri
Rule: RuleFactory = server.compile_rule
# These capitalized aliases are part of the historical public facade.
Connection: ProxyFactory = server.proxies_by_uri # pylint: disable=invalid-name
Server: ProxyFactory = server.proxies_by_uri # pylint: disable=invalid-name
Rule: RuleFactory = server.compile_rule # pylint: disable=invalid-name
DIRECT = server.DIRECT

__all__ = [
Expand Down
2 changes: 2 additions & 0 deletions pproxy/__main__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
"""Module entry point for ``python -m pproxy``."""

if __name__ == '__main__':
from .server import main
main()
11 changes: 10 additions & 1 deletion pproxy/admin.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
"""Minimal HTTP administration handlers for runtime reload support."""

import json

from .runtime import ADMIN_BODY_LIMIT
Expand All @@ -7,10 +9,16 @@


async def reply_http(reply, ver, code, content):
await reply(code, f'{ver} {code}\r\nConnection: close\r\nContent-Type: text/plain\r\nCache-Control: max-age=900\r\nContent-Length: {len(content)}\r\n\r\n'.encode(), content, True)
"""Write a complete plain-text HTTP response through a protocol callback."""
headers = (
f'{ver} {code}\r\nConnection: close\r\nContent-Type: text/plain\r\n'
f'Cache-Control: max-age=900\r\nContent-Length: {len(content)}\r\n\r\n'
)
await reply(code, headers.encode(), content, True)


async def status_handler(reply, **kwarg):
"""Return the administration endpoint health status."""
method = kwarg.get('method')
if method == 'GET':
data = {"status": "ok"}
Expand All @@ -20,6 +28,7 @@ async def status_handler(reply, **kwarg):


async def configs_handler(reply, **kwarg):
"""Read or schedule supported runtime configuration actions."""
method = kwarg.get('method')
ver = kwarg.get('ver')

Expand Down
173 changes: 112 additions & 61 deletions pproxy/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,12 @@

from . import admin
from . import server as runtime
from . import verbose as verbose_runtime
from .__doc__ import __description__, __url__, __version__


def main(args=None):
"""Parse CLI arguments, start configured servers, and own shutdown."""
origin_argv = sys.argv[1:] if args is None else args

def _build_parser():
"""Create the command-line parser used by the legacy CLI."""
parser = argparse.ArgumentParser(
description=__description__
+ '\nSupported protocols: http,socks4,socks5,shadowsocks,shadowsocksr,redirect,pf,tunnel,ws,cfp',
Expand All @@ -36,19 +35,11 @@ def main(args=None):
parser.add_argument('--daemon', dest='daemon', action='store_true', help='run as a daemon (Linux only)')
parser.add_argument('--test', help='test this url for all remote proxies and exit')
parser.add_argument('--version', action='version', version=f'%(prog)s {__version__}')
args = parser.parse_args(args)
if args.sslfile:
sslfile = args.sslfile.split(',')
for context in runtime.sslcontexts:
context.load_cert_chain(*sslfile)
elif any(o.sslclient or isinstance(o, runtime.ProxyQUIC) for o in args.listen + args.ulisten):
print('You must specify --ssl to listen in ssl mode')
return
if args.test:
asyncio.run(runtime.test_url(args.test, args.rserver))
return
if not args.listen and not args.ulisten:
args.listen.append(runtime.proxies_by_uri(runtime.DEFAULT_LISTENER_URI))
return parser


def _load_http_payloads(args):
"""Build PAC and custom HTTP payloads from parsed CLI options."""
args.httpget = {}
if args.pac:
pactext = 'function FindProxyForURL(u,h){' + (f'var b=/^(:?{args.block.__self__.pattern})$/i;if(b.test(h))return "";' if args.block else '')
Expand All @@ -61,67 +52,134 @@ def main(args=None):
path, filename = gets.split(',', 1)
with open(filename, 'rb') as file:
args.httpget[path] = file.read()
if args.daemon:
try:
__import__('daemon').DaemonContext().open()
except ModuleNotFoundError:
print('Missing library: pip3 install python-daemon')
return
try:
__import__('uvloop').install()
print('Using uvloop')
except ModuleNotFoundError:
pass
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
if args.v:
from . import verbose

verbose.setup(loop, args)
servers = []
admin.config.update({'argv': origin_argv, 'servers': servers, 'args': args, 'loop': loop})

def print_fn(option, bind=None):
if runtime.is_unauthenticated_wildcard(option):
print('WARNING: wildcard listener has no authentication; use loopback or configure credentials')
print('Serving on', (bind or option.bind), 'by', ','.join(i.name for i in option.protos) + ('(SSL)' if option.sslclient else ''), '({}{})'.format(option.cipher.name, ' ' + ','.join(i.name() for i in option.cipher.plugins) if option.cipher and option.cipher.plugins else '') if option.cipher else '')
def _cipher_label(option, include_plugins=False):
"""Format an optional cipher and, when requested, its plugin names."""
if not option.cipher:
return ''
suffix = ''
if include_plugins and option.cipher.plugins:
suffix = ' ' + ','.join(plugin.name() for plugin in option.cipher.plugins)
return f'({option.cipher.name}{suffix})'


def _print_tcp_server(option, bind=None):
"""Print the address and protocol set for a TCP listener."""
if runtime.is_unauthenticated_wildcard(option):
print('WARNING: wildcard listener has no authentication; use loopback or configure credentials')
protocols = ','.join(i.name for i in option.protos) + ('(SSL)' if option.sslclient else '')
print('Serving on', (bind or option.bind), 'by', protocols, _cipher_label(option, include_plugins=True))


def _print_udp_server(option, bind=None):
"""Print the address and protocol set for a UDP listener."""
protocols = ','.join(i.name for i in option.protos)
print('Serving on UDP', (bind or option.bind), 'by', protocols, _cipher_label(option))


def _print_backward_server(option, bind=None):
"""Print the address and protocol set for a backward listener."""
protocols = ','.join(i.name for i in option.protos) + ('(SSL)' if option.sslclient else '')
print('Serving on', (bind or option.bind), 'backward by', protocols, _cipher_label(option, include_plugins=True))


def _start_tcp_servers(loop, args, servers):
"""Start TCP listeners while isolating failures between configurations."""
for option in args.listen:
try:
handler = loop.run_until_complete(option.start_server(vars(args)))
runtime.print_server_started(option, handler, print_fn)
runtime.print_server_started(option, handler, _print_tcp_server)
servers.append(handler)
except Exception as ex: # noqa: BLE001 - preserve CLI startup reporting
print_fn(option)
except Exception as ex: # pylint: disable=broad-exception-caught # keep starting other listeners
_print_tcp_server(option)
print('Start server failed.\n\t==>', ex)

def print_fn(option, bind=None):
print('Serving on UDP', (bind or option.bind), 'by', ','.join(i.name for i in option.protos), f'({option.cipher.name})' if option.cipher else '')

def _start_udp_servers(loop, args, servers):
"""Start UDP listeners while isolating failures between configurations."""
for option in args.ulisten:
try:
handler, _protocol = loop.run_until_complete(option.udp_start_server(vars(args)))
runtime.print_server_started(option, handler, print_fn)
runtime.print_server_started(option, handler, _print_udp_server)
servers.append(handler)
except Exception as ex: # noqa: BLE001 - preserve CLI startup reporting
print_fn(option)
except Exception as ex: # pylint: disable=broad-exception-caught # keep starting other listeners
_print_udp_server(option)
print('Start server failed.\n\t==>', ex)

def print_fn(option, bind=None):
print('Serving on', (bind or option.bind), 'backward by', ','.join(i.name for i in option.protos) + ('(SSL)' if option.sslclient else ''), '({}{})'.format(option.cipher.name, ' ' + ','.join(i.name() for i in option.cipher.plugins) if option.cipher and option.cipher.plugins else '') if option.cipher else '')

def _start_backward_servers(loop, args, servers):
"""Start backward listeners while isolating failures between configurations."""
for option in args.rserver:
if isinstance(option, runtime.ProxyBackward):
try:
handler = loop.run_until_complete(option.start_backward_client(vars(args)))
runtime.print_server_started(option, handler, print_fn)
runtime.print_server_started(option, handler, _print_backward_server)
servers.append(handler)
except Exception as ex: # noqa: BLE001 - preserve CLI startup reporting
print_fn(option)
except Exception as ex: # pylint: disable=broad-exception-caught # keep starting other listeners
_print_backward_server(option)
print('Start server failed.\n\t==>', ex)


def _start_servers(loop, args, servers):
"""Start all configured listener types in their historical order."""
_start_tcp_servers(loop, args, servers)
_start_udp_servers(loop, args, servers)
_start_backward_servers(loop, args, servers)


def _shutdown_servers(loop, servers):
"""Cancel tasks and close listeners before the event loop is closed."""
for task in asyncio.all_tasks(loop):
task.cancel()
for handler in servers:
handler.close()
for handler in servers:
if hasattr(handler, 'wait_closed'):
loop.run_until_complete(handler.wait_closed())
loop.run_until_complete(loop.shutdown_asyncgens())


def main(args=None): # pylint: disable=too-many-branches # CLI lifecycle has independent modes
"""Parse CLI arguments, start configured servers, and own shutdown."""
origin_argv = sys.argv[1:] if args is None else args

parser = _build_parser()
args = parser.parse_args(args)
if args.sslfile:
sslfile = args.sslfile.split(',')
for context in runtime.sslcontexts:
context.load_cert_chain(*sslfile)
elif any(o.sslclient or isinstance(o, runtime.ProxyQUIC) for o in args.listen + args.ulisten):
print('You must specify --ssl to listen in ssl mode')
return
if args.test:
asyncio.run(runtime.test_url(args.test, args.rserver))
return
if not args.listen and not args.ulisten:
args.listen.append(runtime.proxies_by_uri(runtime.DEFAULT_LISTENER_URI))
_load_http_payloads(args)
if args.daemon:
try:
__import__('daemon').DaemonContext().open()
except ModuleNotFoundError:
print('Missing library: pip3 install python-daemon')
return
try:
__import__('uvloop').install()
print('Using uvloop')
except ModuleNotFoundError:
pass
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
if args.v:
verbose_runtime.setup(loop, args)
servers = []
admin.config.update({'argv': origin_argv, 'servers': servers, 'args': args, 'loop': loop})
_start_servers(loop, args, servers)
if servers:
if args.sys:
from . import sysproxy
from . import sysproxy # pylint: disable=import-outside-toplevel

args.sys = sysproxy.setup(args)
if args.alived > 0 and args.rserver:
Expand All @@ -132,14 +190,7 @@ def print_fn(option, bind=None):
print('exit')
if args.sys:
args.sys.clear()
for task in asyncio.all_tasks(loop):
task.cancel()
for handler in servers:
handler.close()
for handler in servers:
if hasattr(handler, 'wait_closed'):
loop.run_until_complete(handler.wait_closed())
loop.run_until_complete(loop.shutdown_asyncgens())
_shutdown_servers(loop, servers)
if admin.config.get('reload', False):
admin.config['reload'] = False
main(admin.config['argv'])
Expand Down
Loading