wisp-python 0.6.0__tar.gz → 0.7.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {wisp_python-0.6.0/src/wisp_python.egg-info → wisp_python-0.7.0}/PKG-INFO +10 -10
- {wisp_python-0.6.0 → wisp_python-0.7.0}/README.md +7 -8
- {wisp_python-0.6.0 → wisp_python-0.7.0}/pyproject.toml +2 -2
- wisp_python-0.7.0/src/wisp/server/__main__.py +4 -0
- wisp_python-0.7.0/src/wisp/server/cli.py +86 -0
- {wisp_python-0.6.0 → wisp_python-0.7.0}/src/wisp/server/connection.py +1 -1
- {wisp_python-0.6.0 → wisp_python-0.7.0}/src/wisp/server/http.py +3 -6
- {wisp_python-0.6.0 → wisp_python-0.7.0}/src/wisp/server/net.py +3 -0
- {wisp_python-0.6.0 → wisp_python-0.7.0/src/wisp_python.egg-info}/PKG-INFO +10 -10
- {wisp_python-0.6.0 → wisp_python-0.7.0}/src/wisp_python.egg-info/SOURCES.txt +1 -6
- wisp_python-0.6.0/src/wisp/server/__main__.py +0 -26
- wisp_python-0.6.0/src/wisp/server/common.py +0 -30
- wisp_python-0.6.0/src/wisp/server/threading/__init__.py +0 -2
- wisp_python-0.6.0/src/wisp/server/threading/__main__.py +0 -6
- wisp_python-0.6.0/src/wisp/server/threading/connection.py +0 -216
- wisp_python-0.6.0/src/wisp/server/threading/http.py +0 -104
- wisp_python-0.6.0/src/wisp/server/threading/netsync.py +0 -58
- {wisp_python-0.6.0 → wisp_python-0.7.0}/LICENSE +0 -0
- {wisp_python-0.6.0 → wisp_python-0.7.0}/setup.cfg +0 -0
- {wisp_python-0.6.0 → wisp_python-0.7.0}/src/wisp/__init__.py +0 -0
- {wisp_python-0.6.0 → wisp_python-0.7.0}/src/wisp/server/__init__.py +0 -0
- {wisp_python-0.6.0 → wisp_python-0.7.0}/src/wisp/server/ratelimit.py +0 -0
- {wisp_python-0.6.0 → wisp_python-0.7.0}/src/wisp/util.py +0 -0
- {wisp_python-0.6.0 → wisp_python-0.7.0}/src/wisp_python.egg-info/dependency_links.txt +0 -0
- {wisp_python-0.6.0 → wisp_python-0.7.0}/src/wisp_python.egg-info/requires.txt +0 -0
- {wisp_python-0.6.0 → wisp_python-0.7.0}/src/wisp_python.egg-info/top_level.txt +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
Metadata-Version: 2.
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
2
|
Name: wisp-python
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.7.0
|
|
4
4
|
Summary: An implementation of a Wisp proxy server in Python
|
|
5
5
|
Author: ading2210
|
|
6
6
|
Project-URL: Homepage, https://github.com/MercuryWorkshop/wisp-server-python
|
|
@@ -14,6 +14,7 @@ License-File: LICENSE
|
|
|
14
14
|
Requires-Dist: websockets
|
|
15
15
|
Requires-Dist: asyncudp
|
|
16
16
|
Requires-Dist: uvloop; sys_platform != "win32" and sys_platform != "cygwin"
|
|
17
|
+
Dynamic: license-file
|
|
17
18
|
|
|
18
19
|
# Python Wisp Server
|
|
19
20
|
|
|
@@ -35,18 +36,16 @@ pip3 install wisp-python
|
|
|
35
36
|
```
|
|
36
37
|
|
|
37
38
|
## Running the Server:
|
|
38
|
-
There are two different versions of the server:
|
|
39
|
-
- Async (`wisp.server`) - The default, based on asyncio. It is more stable, but slower.
|
|
40
|
-
- Threading (`wisp.server.threading`) - An faster alternative based on threading. It is about 40-80% faster, but possibly unstable. If you use Python's experimental [free threading](https://docs.python.org/3/howto/free-threading-python.html) builds, performance will scale linearly with your available CPU cores.
|
|
41
|
-
|
|
42
39
|
For the best performance use [CPython](https://github.com/python/cpython) 3.11 or newer. [PyPy](https://github.com/pypy/pypy) is not recommended as it is a lot slower than CPython here.
|
|
43
40
|
|
|
44
|
-
|
|
41
|
+
There used to be an experimental "threading" variant of the server. This has been removed due to its instability and difficulty of maintenance.
|
|
42
|
+
|
|
43
|
+
To start the server, run `python3 -m wisp.server`. The program accepts the following arguments:
|
|
45
44
|
```
|
|
46
|
-
usage: wisp-server-python [-h] [--host HOST] [--port PORT] [--static STATIC] [--limits] [--bandwidth BANDWIDTH] [--connections CONNECTIONS] [--window WINDOW] [--allow-loopback]
|
|
47
|
-
[--log-level LOG_LEVEL]
|
|
45
|
+
usage: wisp-server-python [-h] [--host HOST] [--port PORT] [--static STATIC] [--limits] [--bandwidth BANDWIDTH] [--connections CONNECTIONS] [--window WINDOW] [--allow-loopback]
|
|
46
|
+
[--allow-private] [--log-level LOG_LEVEL] [--threads THREADS]
|
|
48
47
|
|
|
49
|
-
A Wisp server implementation, written in Python (v0.
|
|
48
|
+
A Wisp server implementation, written in Python (v0.7.0)
|
|
50
49
|
|
|
51
50
|
options:
|
|
52
51
|
-h, --help show this help message and exit
|
|
@@ -63,6 +62,7 @@ options:
|
|
|
63
62
|
--allow-private Allow connections to private IP addresses.
|
|
64
63
|
--log-level LOG_LEVEL
|
|
65
64
|
The log level (either debug, info, warning, error, or critical).
|
|
65
|
+
--threads THREADS The number of threads to run the server on. By default it uses all CPU cores.
|
|
66
66
|
```
|
|
67
67
|
|
|
68
68
|
## Roadmap:
|
|
@@ -18,18 +18,16 @@ pip3 install wisp-python
|
|
|
18
18
|
```
|
|
19
19
|
|
|
20
20
|
## Running the Server:
|
|
21
|
-
There are two different versions of the server:
|
|
22
|
-
- Async (`wisp.server`) - The default, based on asyncio. It is more stable, but slower.
|
|
23
|
-
- Threading (`wisp.server.threading`) - An faster alternative based on threading. It is about 40-80% faster, but possibly unstable. If you use Python's experimental [free threading](https://docs.python.org/3/howto/free-threading-python.html) builds, performance will scale linearly with your available CPU cores.
|
|
24
|
-
|
|
25
21
|
For the best performance use [CPython](https://github.com/python/cpython) 3.11 or newer. [PyPy](https://github.com/pypy/pypy) is not recommended as it is a lot slower than CPython here.
|
|
26
22
|
|
|
27
|
-
|
|
23
|
+
There used to be an experimental "threading" variant of the server. This has been removed due to its instability and difficulty of maintenance.
|
|
24
|
+
|
|
25
|
+
To start the server, run `python3 -m wisp.server`. The program accepts the following arguments:
|
|
28
26
|
```
|
|
29
|
-
usage: wisp-server-python [-h] [--host HOST] [--port PORT] [--static STATIC] [--limits] [--bandwidth BANDWIDTH] [--connections CONNECTIONS] [--window WINDOW] [--allow-loopback]
|
|
30
|
-
[--log-level LOG_LEVEL]
|
|
27
|
+
usage: wisp-server-python [-h] [--host HOST] [--port PORT] [--static STATIC] [--limits] [--bandwidth BANDWIDTH] [--connections CONNECTIONS] [--window WINDOW] [--allow-loopback]
|
|
28
|
+
[--allow-private] [--log-level LOG_LEVEL] [--threads THREADS]
|
|
31
29
|
|
|
32
|
-
A Wisp server implementation, written in Python (v0.
|
|
30
|
+
A Wisp server implementation, written in Python (v0.7.0)
|
|
33
31
|
|
|
34
32
|
options:
|
|
35
33
|
-h, --help show this help message and exit
|
|
@@ -46,6 +44,7 @@ options:
|
|
|
46
44
|
--allow-private Allow connections to private IP addresses.
|
|
47
45
|
--log-level LOG_LEVEL
|
|
48
46
|
The log level (either debug, info, warning, error, or critical).
|
|
47
|
+
--threads THREADS The number of threads to run the server on. By default it uses all CPU cores.
|
|
49
48
|
```
|
|
50
49
|
|
|
51
50
|
## Roadmap:
|
|
@@ -6,12 +6,12 @@ requires = ["setuptools>=61.0", "toml"]
|
|
|
6
6
|
build-backend = "setuptools.build_meta"
|
|
7
7
|
|
|
8
8
|
[tool.setuptools]
|
|
9
|
-
packages = ["wisp", "wisp.server"
|
|
9
|
+
packages = ["wisp", "wisp.server"]
|
|
10
10
|
package-dir = {"" = "src"}
|
|
11
11
|
|
|
12
12
|
[project]
|
|
13
13
|
name = "wisp-python"
|
|
14
|
-
version = "0.
|
|
14
|
+
version = "0.7.0"
|
|
15
15
|
authors = [
|
|
16
16
|
{name="ading2210"},
|
|
17
17
|
]
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import argparse
|
|
3
|
+
import pathlib
|
|
4
|
+
import sys
|
|
5
|
+
import logging
|
|
6
|
+
import multiprocessing
|
|
7
|
+
|
|
8
|
+
try:
|
|
9
|
+
import uvloop
|
|
10
|
+
use_uvloop = True
|
|
11
|
+
except ImportError:
|
|
12
|
+
use_uvloop = False
|
|
13
|
+
|
|
14
|
+
import wisp
|
|
15
|
+
from wisp.server import http
|
|
16
|
+
from wisp.server import net
|
|
17
|
+
|
|
18
|
+
def run_async(func, *args, **kwargs):
|
|
19
|
+
try:
|
|
20
|
+
if use_uvloop:
|
|
21
|
+
uvloop.run(func(*args, **kwargs))
|
|
22
|
+
else:
|
|
23
|
+
#uvloop doesn't support windows at all so we don't need to print the error
|
|
24
|
+
if not sys.platform in ("win32", "cygwin"):
|
|
25
|
+
logging.error("Importing uvloop failed. Falling back to asyncio, which is slower.")
|
|
26
|
+
asyncio.run(func(*args, **kwargs))
|
|
27
|
+
except KeyboardInterrupt:
|
|
28
|
+
pass
|
|
29
|
+
|
|
30
|
+
def run_http(args):
|
|
31
|
+
run_async(http.main, args)
|
|
32
|
+
|
|
33
|
+
def main():
|
|
34
|
+
parser = argparse.ArgumentParser(
|
|
35
|
+
prog="wisp-server-python",
|
|
36
|
+
description=f"A Wisp server implementation, written in Python (v{wisp.version})"
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
parser.add_argument("--host", default="127.0.0.1", help="The hostname the server will listen on.")
|
|
40
|
+
parser.add_argument("--port", default=6001, help="The TCP port the server will listen on.")
|
|
41
|
+
parser.add_argument("--static", help="Where static files are served from.")
|
|
42
|
+
parser.add_argument("--limits", action="store_true", help="Enable rate limits.")
|
|
43
|
+
parser.add_argument("--bandwidth", default=1000, help="Bandwidth limit per IP, in kilobytes per second.")
|
|
44
|
+
parser.add_argument("--connections", default=30, help="New connections limit per IP.")
|
|
45
|
+
parser.add_argument("--window", default=60, help="Fixed window length for rate limits, in seconds.")
|
|
46
|
+
parser.add_argument("--allow-loopback", action="store_true", help="Allow connections to loopback IP addresses.")
|
|
47
|
+
parser.add_argument("--allow-private", action="store_true", help="Allow connections to private IP addresses.")
|
|
48
|
+
parser.add_argument("--log-level", default="info", help="The log level (either debug, info, warning, error, or critical).")
|
|
49
|
+
parser.add_argument("--threads", default=0, help="The number of threads to run the server on. By default it uses all CPU cores.")
|
|
50
|
+
args = parser.parse_args()
|
|
51
|
+
|
|
52
|
+
logging.basicConfig(
|
|
53
|
+
format="[%(asctime)s] %(levelname)-8s %(message)s",
|
|
54
|
+
level=getattr(logging, args.log_level.upper()),
|
|
55
|
+
datefmt="%Y/%m/%d - %H:%M:%S"
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
logging.info(f"running wisp-server-python v{wisp.version} (async)")
|
|
59
|
+
if args.static:
|
|
60
|
+
static_path = pathlib.Path(args.static).resolve()
|
|
61
|
+
logging.info(f"serving static files from {static_path}")
|
|
62
|
+
if args.limits:
|
|
63
|
+
logging.info("enabled rate limits")
|
|
64
|
+
logging.info(f"listening on {args.host}:{args.port}")
|
|
65
|
+
|
|
66
|
+
threads = int(args.threads)
|
|
67
|
+
if net.reuse_port_supported():
|
|
68
|
+
if threads == 0:
|
|
69
|
+
threads = multiprocessing.cpu_count()
|
|
70
|
+
logging.info(f"running using {threads} threads")
|
|
71
|
+
|
|
72
|
+
processes = []
|
|
73
|
+
for i in range(0, int(threads)):
|
|
74
|
+
process = multiprocessing.Process(target=run_http, args=(args,), daemon=True)
|
|
75
|
+
processes.append(process)
|
|
76
|
+
process.start()
|
|
77
|
+
try:
|
|
78
|
+
for process in processes:
|
|
79
|
+
process.join()
|
|
80
|
+
except KeyboardInterrupt:
|
|
81
|
+
pass
|
|
82
|
+
|
|
83
|
+
else:
|
|
84
|
+
if threads != 0:
|
|
85
|
+
logging.warn("the --threads option is not supported on this platform")
|
|
86
|
+
run_http(args)
|
|
@@ -128,7 +128,7 @@ class WispConnection:
|
|
|
128
128
|
|
|
129
129
|
#send a CONTINUE packet periodically
|
|
130
130
|
stream["packets_sent"] += 1
|
|
131
|
-
if stream["packets_sent"] % queue_size
|
|
131
|
+
if stream["packets_sent"] % (queue_size // 4) == 0:
|
|
132
132
|
buffer_remaining = stream["queue"].maxsize - stream["queue"].qsize()
|
|
133
133
|
continue_payload = struct.pack(continue_format, buffer_remaining)
|
|
134
134
|
continue_packet = struct.pack(packet_format, 0x03, stream_id) + continue_payload
|
|
@@ -61,18 +61,15 @@ async def static_handler(path, request_headers):
|
|
|
61
61
|
|
|
62
62
|
async def main(args):
|
|
63
63
|
global static_path
|
|
64
|
-
logging.info(f"running wisp-server-python v{wisp.version} (async)")
|
|
65
64
|
|
|
66
65
|
if args.static:
|
|
67
66
|
static_path = pathlib.Path(args.static).resolve()
|
|
68
67
|
request_handler = static_handler
|
|
69
68
|
mimetypes.init()
|
|
70
|
-
logging.info(f"serving static files from {static_path}")
|
|
71
69
|
else:
|
|
72
70
|
request_handler = None
|
|
73
71
|
|
|
74
72
|
if args.limits:
|
|
75
|
-
logging.info("enabled rate limits")
|
|
76
73
|
ratelimit.enabled = True
|
|
77
74
|
ratelimit.connections_limit = int(args.connections)
|
|
78
75
|
ratelimit.bandwidth_limit = float(args.bandwidth)
|
|
@@ -82,10 +79,10 @@ async def main(args):
|
|
|
82
79
|
net.block_private = not args.allow_private
|
|
83
80
|
|
|
84
81
|
limit_task = asyncio.create_task(ratelimit.reset_limits_timer())
|
|
85
|
-
logging.info(f"listening on {args.host}:{args.port}")
|
|
86
|
-
|
|
87
82
|
ws_logger = logging.getLogger("websockets")
|
|
88
83
|
ws_logger.setLevel(logging.WARN)
|
|
89
84
|
|
|
90
|
-
|
|
85
|
+
reuse_port = net.reuse_port_supported()
|
|
86
|
+
|
|
87
|
+
async with serve(connection_handler, args.host, int(args.port), reuse_port=reuse_port, process_request=request_handler, compression=None):
|
|
91
88
|
await asyncio.Future()
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
Metadata-Version: 2.
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
2
|
Name: wisp-python
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.7.0
|
|
4
4
|
Summary: An implementation of a Wisp proxy server in Python
|
|
5
5
|
Author: ading2210
|
|
6
6
|
Project-URL: Homepage, https://github.com/MercuryWorkshop/wisp-server-python
|
|
@@ -14,6 +14,7 @@ License-File: LICENSE
|
|
|
14
14
|
Requires-Dist: websockets
|
|
15
15
|
Requires-Dist: asyncudp
|
|
16
16
|
Requires-Dist: uvloop; sys_platform != "win32" and sys_platform != "cygwin"
|
|
17
|
+
Dynamic: license-file
|
|
17
18
|
|
|
18
19
|
# Python Wisp Server
|
|
19
20
|
|
|
@@ -35,18 +36,16 @@ pip3 install wisp-python
|
|
|
35
36
|
```
|
|
36
37
|
|
|
37
38
|
## Running the Server:
|
|
38
|
-
There are two different versions of the server:
|
|
39
|
-
- Async (`wisp.server`) - The default, based on asyncio. It is more stable, but slower.
|
|
40
|
-
- Threading (`wisp.server.threading`) - An faster alternative based on threading. It is about 40-80% faster, but possibly unstable. If you use Python's experimental [free threading](https://docs.python.org/3/howto/free-threading-python.html) builds, performance will scale linearly with your available CPU cores.
|
|
41
|
-
|
|
42
39
|
For the best performance use [CPython](https://github.com/python/cpython) 3.11 or newer. [PyPy](https://github.com/pypy/pypy) is not recommended as it is a lot slower than CPython here.
|
|
43
40
|
|
|
44
|
-
|
|
41
|
+
There used to be an experimental "threading" variant of the server. This has been removed due to its instability and difficulty of maintenance.
|
|
42
|
+
|
|
43
|
+
To start the server, run `python3 -m wisp.server`. The program accepts the following arguments:
|
|
45
44
|
```
|
|
46
|
-
usage: wisp-server-python [-h] [--host HOST] [--port PORT] [--static STATIC] [--limits] [--bandwidth BANDWIDTH] [--connections CONNECTIONS] [--window WINDOW] [--allow-loopback]
|
|
47
|
-
[--log-level LOG_LEVEL]
|
|
45
|
+
usage: wisp-server-python [-h] [--host HOST] [--port PORT] [--static STATIC] [--limits] [--bandwidth BANDWIDTH] [--connections CONNECTIONS] [--window WINDOW] [--allow-loopback]
|
|
46
|
+
[--allow-private] [--log-level LOG_LEVEL] [--threads THREADS]
|
|
48
47
|
|
|
49
|
-
A Wisp server implementation, written in Python (v0.
|
|
48
|
+
A Wisp server implementation, written in Python (v0.7.0)
|
|
50
49
|
|
|
51
50
|
options:
|
|
52
51
|
-h, --help show this help message and exit
|
|
@@ -63,6 +62,7 @@ options:
|
|
|
63
62
|
--allow-private Allow connections to private IP addresses.
|
|
64
63
|
--log-level LOG_LEVEL
|
|
65
64
|
The log level (either debug, info, warning, error, or critical).
|
|
65
|
+
--threads THREADS The number of threads to run the server on. By default it uses all CPU cores.
|
|
66
66
|
```
|
|
67
67
|
|
|
68
68
|
## Roadmap:
|
|
@@ -5,16 +5,11 @@ src/wisp/__init__.py
|
|
|
5
5
|
src/wisp/util.py
|
|
6
6
|
src/wisp/server/__init__.py
|
|
7
7
|
src/wisp/server/__main__.py
|
|
8
|
-
src/wisp/server/
|
|
8
|
+
src/wisp/server/cli.py
|
|
9
9
|
src/wisp/server/connection.py
|
|
10
10
|
src/wisp/server/http.py
|
|
11
11
|
src/wisp/server/net.py
|
|
12
12
|
src/wisp/server/ratelimit.py
|
|
13
|
-
src/wisp/server/threading/__init__.py
|
|
14
|
-
src/wisp/server/threading/__main__.py
|
|
15
|
-
src/wisp/server/threading/connection.py
|
|
16
|
-
src/wisp/server/threading/http.py
|
|
17
|
-
src/wisp/server/threading/netsync.py
|
|
18
13
|
src/wisp_python.egg-info/PKG-INFO
|
|
19
14
|
src/wisp_python.egg-info/SOURCES.txt
|
|
20
15
|
src/wisp_python.egg-info/dependency_links.txt
|
|
@@ -1,26 +0,0 @@
|
|
|
1
|
-
import argparse
|
|
2
|
-
import asyncio
|
|
3
|
-
import sys
|
|
4
|
-
|
|
5
|
-
try:
|
|
6
|
-
import uvloop
|
|
7
|
-
use_uvloop = True
|
|
8
|
-
except ImportError:
|
|
9
|
-
use_uvloop = False
|
|
10
|
-
|
|
11
|
-
from wisp.server import http
|
|
12
|
-
from wisp.server import common
|
|
13
|
-
|
|
14
|
-
if __name__ == "__main__":
|
|
15
|
-
args = common.setup_main()
|
|
16
|
-
|
|
17
|
-
try:
|
|
18
|
-
if use_uvloop:
|
|
19
|
-
uvloop.run(http.main(args))
|
|
20
|
-
else:
|
|
21
|
-
#uvloop doesn't support windows at all so we don't need to print the error
|
|
22
|
-
if not sys.platform in ("win32", "cygwin"):
|
|
23
|
-
logging.error("Importing uvloop failed. Falling back to asyncio, which is slower.")
|
|
24
|
-
asyncio.run(http.main(args))
|
|
25
|
-
except KeyboardInterrupt:
|
|
26
|
-
pass
|
|
@@ -1,30 +0,0 @@
|
|
|
1
|
-
import argparse
|
|
2
|
-
import logging
|
|
3
|
-
|
|
4
|
-
import wisp
|
|
5
|
-
|
|
6
|
-
def setup_main():
|
|
7
|
-
parser = argparse.ArgumentParser(
|
|
8
|
-
prog="wisp-server-python",
|
|
9
|
-
description=f"A Wisp server implementation, written in Python (v{wisp.version})"
|
|
10
|
-
)
|
|
11
|
-
|
|
12
|
-
parser.add_argument("--host", default="127.0.0.1", help="The hostname the server will listen on.")
|
|
13
|
-
parser.add_argument("--port", default=6001, help="The TCP port the server will listen on.")
|
|
14
|
-
parser.add_argument("--static", help="Where static files are served from.")
|
|
15
|
-
parser.add_argument("--limits", action="store_true", help="Enable rate limits.")
|
|
16
|
-
parser.add_argument("--bandwidth", default=1000, help="Bandwidth limit per IP, in kilobytes per second.")
|
|
17
|
-
parser.add_argument("--connections", default=30, help="New connections limit per IP.")
|
|
18
|
-
parser.add_argument("--window", default=60, help="Fixed window length for rate limits, in seconds.")
|
|
19
|
-
parser.add_argument("--allow-loopback", action="store_true",help="Allow connections to loopback IP addresses.")
|
|
20
|
-
parser.add_argument("--allow-private", action="store_true", help="Allow connections to private IP addresses.")
|
|
21
|
-
parser.add_argument("--log-level", default="info", help="The log level (either debug, info, warning, error, or critical).")
|
|
22
|
-
args = parser.parse_args()
|
|
23
|
-
|
|
24
|
-
logging.basicConfig(
|
|
25
|
-
format="[%(asctime)s] %(levelname)-8s %(message)s",
|
|
26
|
-
level=getattr(logging, args.log_level.upper()),
|
|
27
|
-
datefmt="%Y/%m/%d - %H:%M:%S"
|
|
28
|
-
)
|
|
29
|
-
|
|
30
|
-
return args
|
|
@@ -1,216 +0,0 @@
|
|
|
1
|
-
import struct
|
|
2
|
-
import os
|
|
3
|
-
import logging
|
|
4
|
-
import queue
|
|
5
|
-
import threading
|
|
6
|
-
|
|
7
|
-
from websockets.exceptions import ConnectionClosed
|
|
8
|
-
|
|
9
|
-
from wisp.server import ratelimit
|
|
10
|
-
from wisp.server.threading import netsync
|
|
11
|
-
|
|
12
|
-
queue_size = 128
|
|
13
|
-
static_path = None
|
|
14
|
-
|
|
15
|
-
#wisp packet format definitions
|
|
16
|
-
#see https://docs.python.org/3/library/struct.html for what these characters mean
|
|
17
|
-
packet_format = "<BI"
|
|
18
|
-
connect_format = "<BH"
|
|
19
|
-
continue_format = "<I"
|
|
20
|
-
close_format = "<B"
|
|
21
|
-
|
|
22
|
-
class WSProxyConnection:
|
|
23
|
-
def __init__(self, ws, path, client_ip):
|
|
24
|
-
self.ws = ws
|
|
25
|
-
self.path = path
|
|
26
|
-
self.client_ip = client_ip
|
|
27
|
-
|
|
28
|
-
def setup_connection(self):
|
|
29
|
-
addr_str = self.path.split("/")[-1]
|
|
30
|
-
self.tcp_host, self.tcp_port = addr_str.split(":")
|
|
31
|
-
self.tcp_port = int(self.tcp_port)
|
|
32
|
-
|
|
33
|
-
try:
|
|
34
|
-
self.conn = netsync.TCPConnection(self.tcp_host, self.tcp_port)
|
|
35
|
-
self.conn.connect()
|
|
36
|
-
except Exception as e:
|
|
37
|
-
logging.info(f"Creating a WSProxy stream to {self.tcp_host}:{self.tcp_port} failed: {e}")
|
|
38
|
-
self.ws.close()
|
|
39
|
-
|
|
40
|
-
def handle_ws(self):
|
|
41
|
-
while True:
|
|
42
|
-
try:
|
|
43
|
-
data = self.ws.recv()
|
|
44
|
-
except ConnectionClosed:
|
|
45
|
-
break
|
|
46
|
-
|
|
47
|
-
ratelimit.limit_client_bandwidth_sync(self.client_ip, len(data), "ws")
|
|
48
|
-
self.conn.send(data)
|
|
49
|
-
|
|
50
|
-
self.conn.close()
|
|
51
|
-
|
|
52
|
-
def handle_tcp(self):
|
|
53
|
-
while True:
|
|
54
|
-
data = self.conn.recv()
|
|
55
|
-
if len(data) == 0:
|
|
56
|
-
break #socket closed
|
|
57
|
-
|
|
58
|
-
ratelimit.limit_client_bandwidth_sync(self.client_ip, len(data), "tcp")
|
|
59
|
-
self.ws.send(data)
|
|
60
|
-
|
|
61
|
-
self.ws.close()
|
|
62
|
-
|
|
63
|
-
class WispConnection:
|
|
64
|
-
def __init__(self, ws, path, client_ip, id=None):
|
|
65
|
-
self.ws = ws
|
|
66
|
-
self.path = path
|
|
67
|
-
self.active_streams = {}
|
|
68
|
-
self.client_ip = client_ip
|
|
69
|
-
self.id = id
|
|
70
|
-
|
|
71
|
-
#send the initial CONTINUE packet
|
|
72
|
-
def setup(self):
|
|
73
|
-
continue_payload = struct.pack(continue_format, queue_size)
|
|
74
|
-
continue_packet = struct.pack(packet_format, 0x03, 0) + continue_payload
|
|
75
|
-
self.ws.send(continue_packet)
|
|
76
|
-
|
|
77
|
-
def close(self):
|
|
78
|
-
#close all active streams when the websocket disconnects
|
|
79
|
-
for stream_id in list(self.active_streams.keys()):
|
|
80
|
-
self.close_stream(stream_id)
|
|
81
|
-
self.ws.close()
|
|
82
|
-
|
|
83
|
-
def new_stream(self, stream_id, payload):
|
|
84
|
-
stream_type, destination_port = struct.unpack(connect_format, payload[:3])
|
|
85
|
-
hostname = bytes(payload[3:]).decode()
|
|
86
|
-
logging.debug(f"({self.id}) Creating a new stream to {hostname}:{destination_port}")
|
|
87
|
-
|
|
88
|
-
#rate limited
|
|
89
|
-
stream_count = ratelimit.get_client_attr(self.client_ip, "streams")
|
|
90
|
-
if ratelimit.enabled and stream_count > ratelimit.connections_limit:
|
|
91
|
-
self.send_close_packet(stream_id, 0x49)
|
|
92
|
-
self.close_stream(stream_id)
|
|
93
|
-
return
|
|
94
|
-
|
|
95
|
-
#info looks valid - try to open the connection now
|
|
96
|
-
try:
|
|
97
|
-
if stream_type == 0x01:
|
|
98
|
-
connection = netsync.TCPConnection(hostname, destination_port)
|
|
99
|
-
elif stream_type == 0x02:
|
|
100
|
-
connection = netsync.UDPConnection(hostname, destination_port)
|
|
101
|
-
else:
|
|
102
|
-
raise Exception("Invalid stream type.")
|
|
103
|
-
self.active_streams[stream_id]["conn"] = connection
|
|
104
|
-
connection.connect()
|
|
105
|
-
|
|
106
|
-
except Exception as e:
|
|
107
|
-
logging.warn(f"({self.id}) Creating a new stream to {hostname}:{destination_port} failed: {e}")
|
|
108
|
-
self.send_close_packet(stream_id, 0x42)
|
|
109
|
-
self.close_stream(stream_id)
|
|
110
|
-
return
|
|
111
|
-
|
|
112
|
-
self.active_streams[stream_id]["type"] = stream_type
|
|
113
|
-
threading.Thread(target=self.stream_ws_to_tcp, args=(stream_id,), daemon=True).start()
|
|
114
|
-
threading.Thread(target=self.stream_tcp_to_ws, args=(stream_id,), daemon=True).start()
|
|
115
|
-
ratelimit.inc_client_attr(self.client_ip, "streams")
|
|
116
|
-
|
|
117
|
-
def stream_ws_to_tcp(self, stream_id):
|
|
118
|
-
while True:
|
|
119
|
-
stream = self.active_streams[stream_id]
|
|
120
|
-
data = stream["queue"].get()
|
|
121
|
-
if data is None:
|
|
122
|
-
break
|
|
123
|
-
try:
|
|
124
|
-
stream["conn"].send(data)
|
|
125
|
-
except:
|
|
126
|
-
break
|
|
127
|
-
|
|
128
|
-
#send a CONTINUE packet periodically
|
|
129
|
-
stream["packets_sent"] += 1
|
|
130
|
-
if stream["packets_sent"] % queue_size / 4 == 0:
|
|
131
|
-
buffer_remaining = stream["queue"].maxsize - stream["queue"].qsize()
|
|
132
|
-
continue_payload = struct.pack(continue_format, buffer_remaining)
|
|
133
|
-
continue_packet = struct.pack(packet_format, 0x03, stream_id) + continue_payload
|
|
134
|
-
self.ws.send(continue_packet)
|
|
135
|
-
|
|
136
|
-
def stream_tcp_to_ws(self, stream_id):
|
|
137
|
-
while True:
|
|
138
|
-
stream = self.active_streams[stream_id]
|
|
139
|
-
try:
|
|
140
|
-
data = stream["conn"].recv()
|
|
141
|
-
except Exception as e:
|
|
142
|
-
logging.warn(f"({self.id}) Receiving data from stream failed: {e}")
|
|
143
|
-
self.send_close_packet(stream_id, 0x03)
|
|
144
|
-
self.close_stream(stream_id)
|
|
145
|
-
return
|
|
146
|
-
|
|
147
|
-
if len(data) == 0: #connection closed
|
|
148
|
-
break
|
|
149
|
-
data_header = struct.pack(packet_format, 0x02, stream_id)
|
|
150
|
-
|
|
151
|
-
ratelimit.limit_client_bandwidth_sync(self.client_ip, len(data_header)+len(data), "tcp")
|
|
152
|
-
self.ws.send(data_header + data)
|
|
153
|
-
|
|
154
|
-
self.send_close_packet(stream_id, 0x02)
|
|
155
|
-
self.close_stream(stream_id)
|
|
156
|
-
|
|
157
|
-
def send_close_packet(self, stream_id, reason):
|
|
158
|
-
if not stream_id in self.active_streams:
|
|
159
|
-
return
|
|
160
|
-
close_payload = struct.pack(close_format, reason)
|
|
161
|
-
close_packet = struct.pack(packet_format, 0x04, stream_id) + close_payload
|
|
162
|
-
self.ws.send(close_packet)
|
|
163
|
-
|
|
164
|
-
def close_stream(self, stream_id):
|
|
165
|
-
if not stream_id in self.active_streams:
|
|
166
|
-
return #stream already closed
|
|
167
|
-
stream = self.active_streams[stream_id]
|
|
168
|
-
if stream["conn"]:
|
|
169
|
-
stream["conn"].close()
|
|
170
|
-
|
|
171
|
-
#empty the queue and kill it
|
|
172
|
-
while not stream["queue"].empty():
|
|
173
|
-
stream["queue"].get()
|
|
174
|
-
stream["queue"].put(None)
|
|
175
|
-
del self.active_streams[stream_id]
|
|
176
|
-
|
|
177
|
-
def handle_ws(self):
|
|
178
|
-
while True:
|
|
179
|
-
try:
|
|
180
|
-
data = self.ws.recv()
|
|
181
|
-
except ConnectionClosed:
|
|
182
|
-
break
|
|
183
|
-
except Exception as e:
|
|
184
|
-
logging.warn(f"({self.id}) Receiving data from websocket failed: {e}")
|
|
185
|
-
break
|
|
186
|
-
|
|
187
|
-
if not isinstance(data, bytes):
|
|
188
|
-
continue #ignore non binary frames
|
|
189
|
-
|
|
190
|
-
#implement bandwidth limits
|
|
191
|
-
ratelimit.limit_client_bandwidth_sync(self.client_ip, len(data), "ws")
|
|
192
|
-
|
|
193
|
-
#get basic packet info
|
|
194
|
-
payload = memoryview(data)[5:]
|
|
195
|
-
packet_type, stream_id = struct.unpack(packet_format, data[:5])
|
|
196
|
-
|
|
197
|
-
if packet_type == 0x01: #CONNECT packet
|
|
198
|
-
self.active_streams[stream_id] = {
|
|
199
|
-
"conn": None,
|
|
200
|
-
"type": None,
|
|
201
|
-
"queue": queue.Queue(queue_size),
|
|
202
|
-
"packets_sent": 0
|
|
203
|
-
}
|
|
204
|
-
threading.Thread(target=self.new_stream, args=(stream_id, payload), daemon=True).start()
|
|
205
|
-
|
|
206
|
-
elif packet_type == 0x02: #DATA packet
|
|
207
|
-
stream = self.active_streams.get(stream_id)
|
|
208
|
-
if not stream:
|
|
209
|
-
continue
|
|
210
|
-
stream["queue"].put(payload)
|
|
211
|
-
|
|
212
|
-
elif packet_type == 0x04: #CLOSE packet
|
|
213
|
-
reason = struct.unpack(close_format, payload)[0]
|
|
214
|
-
self.close_stream(stream_id)
|
|
215
|
-
|
|
216
|
-
self.close()
|
|
@@ -1,104 +0,0 @@
|
|
|
1
|
-
import threading
|
|
2
|
-
import multiprocessing
|
|
3
|
-
import pathlib
|
|
4
|
-
import mimetypes
|
|
5
|
-
import logging
|
|
6
|
-
import random
|
|
7
|
-
import sys
|
|
8
|
-
|
|
9
|
-
from websockets.sync.server import serve
|
|
10
|
-
from websockets.http11 import Response, Headers
|
|
11
|
-
|
|
12
|
-
import wisp
|
|
13
|
-
from wisp.server import ratelimit
|
|
14
|
-
from wisp.server import net
|
|
15
|
-
from wisp.server.threading import connection
|
|
16
|
-
|
|
17
|
-
static_path = None
|
|
18
|
-
connections = {}
|
|
19
|
-
|
|
20
|
-
def connection_handler(websocket):
|
|
21
|
-
path = websocket.request.path
|
|
22
|
-
client_ip = websocket.remote_address[0]
|
|
23
|
-
if client_ip == "127.0.0.1" and "X-Real-IP" in websocket.request.headers:
|
|
24
|
-
client_ip = websocket.request.headers["X-Real-IP"]
|
|
25
|
-
origin = websocket.request.headers.get("Origin")
|
|
26
|
-
|
|
27
|
-
conn_id = "".join(random.choices("1234567890abcdef", k=8))
|
|
28
|
-
logging.info(f"({conn_id}) incoming connection on {path} from {client_ip} (origin: {origin})")
|
|
29
|
-
ratelimit.inc_client_attr(client_ip, "streams")
|
|
30
|
-
|
|
31
|
-
if path.endswith("/"):
|
|
32
|
-
wisp_conn = connection.WispConnection(websocket, path, client_ip, conn_id)
|
|
33
|
-
connections[websocket] = wisp_conn
|
|
34
|
-
wisp_conn.setup()
|
|
35
|
-
wisp_conn.handle_ws()
|
|
36
|
-
del connections[websocket]
|
|
37
|
-
|
|
38
|
-
else:
|
|
39
|
-
stream_count = ratelimit.get_client_attr(client_ip, "streams")
|
|
40
|
-
if ratelimit.enabled and stream_count > ratelimit.connections_limit:
|
|
41
|
-
return
|
|
42
|
-
wsproxy_conn = connection.WSProxyConnection(websocket, path, client_ip)
|
|
43
|
-
wsproxy_conn.setup_connection()
|
|
44
|
-
t1 = threading.Thread(target=wsproxy_conn.handle_ws, daemon=True)
|
|
45
|
-
t2 = threading.Thread(target=wsproxy_conn.handle_tcp, daemon=True)
|
|
46
|
-
t1.start(); t2.start()
|
|
47
|
-
t1.join(); t2.join()
|
|
48
|
-
|
|
49
|
-
def static_handler(connection, request):
|
|
50
|
-
if "Upgrade" in request.headers:
|
|
51
|
-
return
|
|
52
|
-
|
|
53
|
-
response_headers = Headers()
|
|
54
|
-
response_headers["Server"] = f"wisp-server-python v{wisp.version}"
|
|
55
|
-
if static_path is None:
|
|
56
|
-
return Response(204, None, response_headers, body=b"")
|
|
57
|
-
|
|
58
|
-
target_path = static_path / request.path[1:]
|
|
59
|
-
|
|
60
|
-
if target_path.is_dir():
|
|
61
|
-
target_path = target_path / "index.html"
|
|
62
|
-
if not target_path.is_relative_to(static_path):
|
|
63
|
-
return Response(403, None, response_headers, body="403 forbidden".encode())
|
|
64
|
-
if not target_path.exists():
|
|
65
|
-
return Response(404, None, response_headers, body="404 not found".encode())
|
|
66
|
-
|
|
67
|
-
mimetype = mimetypes.guess_type(target_path.name)[0]
|
|
68
|
-
response_headers["Content-Type"] = mimetype
|
|
69
|
-
|
|
70
|
-
static_data = target_path.read_bytes()
|
|
71
|
-
return Response(200, None, response_headers, body=static_data)
|
|
72
|
-
|
|
73
|
-
def main(args):
|
|
74
|
-
global static_path
|
|
75
|
-
logging.info(f"running wisp-server-python v{wisp.version} (threading)")
|
|
76
|
-
|
|
77
|
-
if args.static:
|
|
78
|
-
static_path = pathlib.Path(args.static).resolve()
|
|
79
|
-
mimetypes.init()
|
|
80
|
-
logging.info(f"serving static files from {static_path}")
|
|
81
|
-
|
|
82
|
-
if args.limits:
|
|
83
|
-
logging.info("enabled rate limits")
|
|
84
|
-
ratelimit.enabled = True
|
|
85
|
-
ratelimit.connections_limit = int(args.connections)
|
|
86
|
-
ratelimit.bandwidth_limit = float(args.bandwidth)
|
|
87
|
-
ratelimit.window_size = float(args.window)
|
|
88
|
-
|
|
89
|
-
net.block_loopback = not args.allow_loopback
|
|
90
|
-
net.block_private = not args.allow_private
|
|
91
|
-
|
|
92
|
-
threading.Thread(target=ratelimit.reset_limits_timer_sync, daemon=True).start()
|
|
93
|
-
logging.info(f"listening on {args.host}:{args.port}")
|
|
94
|
-
|
|
95
|
-
ws_logger = logging.getLogger("websockets")
|
|
96
|
-
ws_logger.setLevel(logging.WARN)
|
|
97
|
-
|
|
98
|
-
with serve(connection_handler, args.host, int(args.port), process_request=static_handler, compression=None) as server:
|
|
99
|
-
try:
|
|
100
|
-
server.serve_forever()
|
|
101
|
-
except KeyboardInterrupt:
|
|
102
|
-
for connection in connections.values():
|
|
103
|
-
connection.close()
|
|
104
|
-
server.shutdown()
|
|
@@ -1,58 +0,0 @@
|
|
|
1
|
-
import socket
|
|
2
|
-
import ipaddress
|
|
3
|
-
|
|
4
|
-
#various network utilities and wrappers - synchronous version
|
|
5
|
-
|
|
6
|
-
from wisp.server import net
|
|
7
|
-
|
|
8
|
-
def validate_hostname(host, port, stream_type):
|
|
9
|
-
addr_str = net.get_ip(host, port, stream_type)
|
|
10
|
-
net.validate_ip(addr_str)
|
|
11
|
-
return addr_str
|
|
12
|
-
|
|
13
|
-
class TCPConnection:
|
|
14
|
-
def __init__(self, hostname, port):
|
|
15
|
-
self.hostname = hostname
|
|
16
|
-
self.port = port
|
|
17
|
-
self.socket = None
|
|
18
|
-
|
|
19
|
-
def connect(self):
|
|
20
|
-
addr_str = validate_hostname(self.hostname, self.port, 0x01)
|
|
21
|
-
self.socket = socket.socket()
|
|
22
|
-
self.socket.connect((self.hostname, self.port))
|
|
23
|
-
|
|
24
|
-
def recv(self):
|
|
25
|
-
return self.socket.recv(net.tcp_size)
|
|
26
|
-
|
|
27
|
-
def send(self, data):
|
|
28
|
-
self.socket.send(data)
|
|
29
|
-
|
|
30
|
-
def close(self):
|
|
31
|
-
if self.socket is None:
|
|
32
|
-
return
|
|
33
|
-
self.socket.shutdown(socket.SHUT_RDWR)
|
|
34
|
-
self.socket.close()
|
|
35
|
-
|
|
36
|
-
class UDPConnection:
|
|
37
|
-
def __init__(self, hostname, port):
|
|
38
|
-
self.hostname = hostname
|
|
39
|
-
self.port = port
|
|
40
|
-
self.socket = None
|
|
41
|
-
|
|
42
|
-
def connect(self):
|
|
43
|
-
addr_str = validate_hostname(self.hostname, self.port, 0x02)
|
|
44
|
-
self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
|
45
|
-
self.socket.bind((self.hostname, self.port))
|
|
46
|
-
|
|
47
|
-
def recv(self):
|
|
48
|
-
data, addr = self.socket.recvfrom(net.tcp_size)
|
|
49
|
-
return data
|
|
50
|
-
|
|
51
|
-
def send(self, data):
|
|
52
|
-
self.socket.sendto(data, (self.hostname, self.port))
|
|
53
|
-
|
|
54
|
-
def close(self):
|
|
55
|
-
if self.socket is None:
|
|
56
|
-
return
|
|
57
|
-
self.socket.shutdown(socket.SHUT_RDWR)
|
|
58
|
-
self.socket.close()
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|