wisp-python 0.6.1__tar.gz → 0.8.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.
Files changed (27) hide show
  1. wisp_python-0.8.0/LICENSE_third_party.md +296 -0
  2. {wisp_python-0.6.1/src/wisp_python.egg-info → wisp_python-0.8.0}/PKG-INFO +11 -9
  3. {wisp_python-0.6.1 → wisp_python-0.8.0}/README.md +8 -8
  4. {wisp_python-0.6.1 → wisp_python-0.8.0}/pyproject.toml +3 -2
  5. wisp_python-0.8.0/src/wisp/server/__main__.py +4 -0
  6. wisp_python-0.8.0/src/wisp/server/cli.py +89 -0
  7. {wisp_python-0.6.1 → wisp_python-0.8.0}/src/wisp/server/http.py +20 -9
  8. {wisp_python-0.6.1 → wisp_python-0.8.0}/src/wisp/server/net.py +42 -6
  9. {wisp_python-0.6.1 → wisp_python-0.8.0/src/wisp_python.egg-info}/PKG-INFO +11 -9
  10. {wisp_python-0.6.1 → wisp_python-0.8.0}/src/wisp_python.egg-info/SOURCES.txt +2 -6
  11. {wisp_python-0.6.1 → wisp_python-0.8.0}/src/wisp_python.egg-info/requires.txt +1 -0
  12. wisp_python-0.6.1/src/wisp/server/__main__.py +0 -26
  13. wisp_python-0.6.1/src/wisp/server/common.py +0 -30
  14. wisp_python-0.6.1/src/wisp/server/threading/__init__.py +0 -2
  15. wisp_python-0.6.1/src/wisp/server/threading/__main__.py +0 -6
  16. wisp_python-0.6.1/src/wisp/server/threading/connection.py +0 -219
  17. wisp_python-0.6.1/src/wisp/server/threading/http.py +0 -104
  18. wisp_python-0.6.1/src/wisp/server/threading/netsync.py +0 -58
  19. {wisp_python-0.6.1 → wisp_python-0.8.0}/LICENSE +0 -0
  20. {wisp_python-0.6.1 → wisp_python-0.8.0}/setup.cfg +0 -0
  21. {wisp_python-0.6.1 → wisp_python-0.8.0}/src/wisp/__init__.py +0 -0
  22. {wisp_python-0.6.1 → wisp_python-0.8.0}/src/wisp/server/__init__.py +0 -0
  23. {wisp_python-0.6.1 → wisp_python-0.8.0}/src/wisp/server/connection.py +0 -0
  24. {wisp_python-0.6.1 → wisp_python-0.8.0}/src/wisp/server/ratelimit.py +0 -0
  25. {wisp_python-0.6.1 → wisp_python-0.8.0}/src/wisp/util.py +0 -0
  26. {wisp_python-0.6.1 → wisp_python-0.8.0}/src/wisp_python.egg-info/dependency_links.txt +0 -0
  27. {wisp_python-0.6.1 → wisp_python-0.8.0}/src/wisp_python.egg-info/top_level.txt +0 -0
@@ -0,0 +1,296 @@
1
+ # Third Party Licenses
2
+
3
+ ## websockets
4
+
5
+ Link: https://github.com/python-websockets/websockets
6
+
7
+ ```
8
+ Copyright (c) Aymeric Augustin and contributors
9
+
10
+ Redistribution and use in source and binary forms, with or without
11
+ modification, are permitted provided that the following conditions are met:
12
+
13
+ * Redistributions of source code must retain the above copyright notice,
14
+ this list of conditions and the following disclaimer.
15
+ * Redistributions in binary form must reproduce the above copyright notice,
16
+ this list of conditions and the following disclaimer in the documentation
17
+ and/or other materials provided with the distribution.
18
+ * Neither the name of the copyright holder nor the names of its contributors
19
+ may be used to endorse or promote products derived from this software
20
+ without specific prior written permission.
21
+
22
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
23
+ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
24
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
25
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
26
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
28
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
29
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
30
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32
+ ```
33
+
34
+ ## asyncudp
35
+
36
+ Link: https://github.com/eerimoq/asyncudp
37
+
38
+ ```
39
+ The MIT License (MIT)
40
+
41
+ Copyright (c) 2021 Erik Moqvist
42
+
43
+ Permission is hereby granted, free of charge, to any person obtaining a copy
44
+ of this software and associated documentation files (the "Software"), to deal
45
+ in the Software without restriction, including without limitation the rights
46
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
47
+ copies of the Software, and to permit persons to whom the Software is
48
+ furnished to do so, subject to the following conditions:
49
+
50
+ The above copyright notice and this permission notice shall be included in all
51
+ copies or substantial portions of the Software.
52
+
53
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
54
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
55
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
56
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
57
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
58
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
59
+ SOFTWARE.
60
+ ```
61
+
62
+ ## python-socks
63
+
64
+ Link: https://github.com/romis2012/python-socks
65
+
66
+ ```
67
+ Apache License
68
+ Version 2.0, January 2004
69
+ http://www.apache.org/licenses/
70
+
71
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
72
+
73
+ 1. Definitions.
74
+
75
+ "License" shall mean the terms and conditions for use, reproduction,
76
+ and distribution as defined by Sections 1 through 9 of this document.
77
+
78
+ "Licensor" shall mean the copyright owner or entity authorized by
79
+ the copyright owner that is granting the License.
80
+
81
+ "Legal Entity" shall mean the union of the acting entity and all
82
+ other entities that control, are controlled by, or are under common
83
+ control with that entity. For the purposes of this definition,
84
+ "control" means (i) the power, direct or indirect, to cause the
85
+ direction or management of such entity, whether by contract or
86
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
87
+ outstanding shares, or (iii) beneficial ownership of such entity.
88
+
89
+ "You" (or "Your") shall mean an individual or Legal Entity
90
+ exercising permissions granted by this License.
91
+
92
+ "Source" form shall mean the preferred form for making modifications,
93
+ including but not limited to software source code, documentation
94
+ source, and configuration files.
95
+
96
+ "Object" form shall mean any form resulting from mechanical
97
+ transformation or translation of a Source form, including but
98
+ not limited to compiled object code, generated documentation,
99
+ and conversions to other media types.
100
+
101
+ "Work" shall mean the work of authorship, whether in Source or
102
+ Object form, made available under the License, as indicated by a
103
+ copyright notice that is included in or attached to the work
104
+ (an example is provided in the Appendix below).
105
+
106
+ "Derivative Works" shall mean any work, whether in Source or Object
107
+ form, that is based on (or derived from) the Work and for which the
108
+ editorial revisions, annotations, elaborations, or other modifications
109
+ represent, as a whole, an original work of authorship. For the purposes
110
+ of this License, Derivative Works shall not include works that remain
111
+ separable from, or merely link (or bind by name) to the interfaces of,
112
+ the Work and Derivative Works thereof.
113
+
114
+ "Contribution" shall mean any work of authorship, including
115
+ the original version of the Work and any modifications or additions
116
+ to that Work or Derivative Works thereof, that is intentionally
117
+ submitted to Licensor for inclusion in the Work by the copyright owner
118
+ or by an individual or Legal Entity authorized to submit on behalf of
119
+ the copyright owner. For the purposes of this definition, "submitted"
120
+ means any form of electronic, verbal, or written communication sent
121
+ to the Licensor or its representatives, including but not limited to
122
+ communication on electronic mailing lists, source code control systems,
123
+ and issue tracking systems that are managed by, or on behalf of, the
124
+ Licensor for the purpose of discussing and improving the Work, but
125
+ excluding communication that is conspicuously marked or otherwise
126
+ designated in writing by the copyright owner as "Not a Contribution."
127
+
128
+ "Contributor" shall mean Licensor and any individual or Legal Entity
129
+ on behalf of whom a Contribution has been received by Licensor and
130
+ subsequently incorporated within the Work.
131
+
132
+ 2. Grant of Copyright License. Subject to the terms and conditions of
133
+ this License, each Contributor hereby grants to You a perpetual,
134
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
135
+ copyright license to reproduce, prepare Derivative Works of,
136
+ publicly display, publicly perform, sublicense, and distribute the
137
+ Work and such Derivative Works in Source or Object form.
138
+
139
+ 3. Grant of Patent License. Subject to the terms and conditions of
140
+ this License, each Contributor hereby grants to You a perpetual,
141
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
142
+ (except as stated in this section) patent license to make, have made,
143
+ use, offer to sell, sell, import, and otherwise transfer the Work,
144
+ where such license applies only to those patent claims licensable
145
+ by such Contributor that are necessarily infringed by their
146
+ Contribution(s) alone or by combination of their Contribution(s)
147
+ with the Work to which such Contribution(s) was submitted. If You
148
+ institute patent litigation against any entity (including a
149
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
150
+ or a Contribution incorporated within the Work constitutes direct
151
+ or contributory patent infringement, then any patent licenses
152
+ granted to You under this License for that Work shall terminate
153
+ as of the date such litigation is filed.
154
+
155
+ 4. Redistribution. You may reproduce and distribute copies of the
156
+ Work or Derivative Works thereof in any medium, with or without
157
+ modifications, and in Source or Object form, provided that You
158
+ meet the following conditions:
159
+
160
+ (a) You must give any other recipients of the Work or
161
+ Derivative Works a copy of this License; and
162
+
163
+ (b) You must cause any modified files to carry prominent notices
164
+ stating that You changed the files; and
165
+
166
+ (c) You must retain, in the Source form of any Derivative Works
167
+ that You distribute, all copyright, patent, trademark, and
168
+ attribution notices from the Source form of the Work,
169
+ excluding those notices that do not pertain to any part of
170
+ the Derivative Works; and
171
+
172
+ (d) If the Work includes a "NOTICE" text file as part of its
173
+ distribution, then any Derivative Works that You distribute must
174
+ include a readable copy of the attribution notices contained
175
+ within such NOTICE file, excluding those notices that do not
176
+ pertain to any part of the Derivative Works, in at least one
177
+ of the following places: within a NOTICE text file distributed
178
+ as part of the Derivative Works; within the Source form or
179
+ documentation, if provided along with the Derivative Works; or,
180
+ within a display generated by the Derivative Works, if and
181
+ wherever such third-party notices normally appear. The contents
182
+ of the NOTICE file are for informational purposes only and
183
+ do not modify the License. You may add Your own attribution
184
+ notices within Derivative Works that You distribute, alongside
185
+ or as an addendum to the NOTICE text from the Work, provided
186
+ that such additional attribution notices cannot be construed
187
+ as modifying the License.
188
+
189
+ You may add Your own copyright statement to Your modifications and
190
+ may provide additional or different license terms and conditions
191
+ for use, reproduction, or distribution of Your modifications, or
192
+ for any such Derivative Works as a whole, provided Your use,
193
+ reproduction, and distribution of the Work otherwise complies with
194
+ the conditions stated in this License.
195
+
196
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
197
+ any Contribution intentionally submitted for inclusion in the Work
198
+ by You to the Licensor shall be under the terms and conditions of
199
+ this License, without any additional terms or conditions.
200
+ Notwithstanding the above, nothing herein shall supersede or modify
201
+ the terms of any separate license agreement you may have executed
202
+ with Licensor regarding such Contributions.
203
+
204
+ 6. Trademarks. This License does not grant permission to use the trade
205
+ names, trademarks, service marks, or product names of the Licensor,
206
+ except as required for reasonable and customary use in describing the
207
+ origin of the Work and reproducing the content of the NOTICE file.
208
+
209
+ 7. Disclaimer of Warranty. Unless required by applicable law or
210
+ agreed to in writing, Licensor provides the Work (and each
211
+ Contributor provides its Contributions) on an "AS IS" BASIS,
212
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
213
+ implied, including, without limitation, any warranties or conditions
214
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
215
+ PARTICULAR PURPOSE. You are solely responsible for determining the
216
+ appropriateness of using or redistributing the Work and assume any
217
+ risks associated with Your exercise of permissions under this License.
218
+
219
+ 8. Limitation of Liability. In no event and under no legal theory,
220
+ whether in tort (including negligence), contract, or otherwise,
221
+ unless required by applicable law (such as deliberate and grossly
222
+ negligent acts) or agreed to in writing, shall any Contributor be
223
+ liable to You for damages, including any direct, indirect, special,
224
+ incidental, or consequential damages of any character arising as a
225
+ result of this License or out of the use or inability to use the
226
+ Work (including but not limited to damages for loss of goodwill,
227
+ work stoppage, computer failure or malfunction, or any and all
228
+ other commercial damages or losses), even if such Contributor
229
+ has been advised of the possibility of such damages.
230
+
231
+ 9. Accepting Warranty or Additional Liability. While redistributing
232
+ the Work or Derivative Works thereof, You may choose to offer,
233
+ and charge a fee for, acceptance of support, warranty, indemnity,
234
+ or other liability obligations and/or rights consistent with this
235
+ License. However, in accepting such obligations, You may act only
236
+ on Your own behalf and on Your sole responsibility, not on behalf
237
+ of any other Contributor, and only if You agree to indemnify,
238
+ defend, and hold each Contributor harmless for any liability
239
+ incurred by, or claims asserted against, such Contributor by reason
240
+ of your accepting any such warranty or additional liability.
241
+
242
+ END OF TERMS AND CONDITIONS
243
+
244
+ APPENDIX: How to apply the Apache License to your work.
245
+
246
+ To apply the Apache License to your work, attach the following
247
+ boilerplate notice, with the fields enclosed by brackets "{}"
248
+ replaced with your own identifying information. (Don't include
249
+ the brackets!) The text should be enclosed in the appropriate
250
+ comment syntax for the file format. We also recommend that a
251
+ file or class name and description of purpose be included on the
252
+ same "printed page" as the copyright notice for easier
253
+ identification within third-party archives.
254
+
255
+ Copyright {yyyy} {name of copyright owner}
256
+
257
+ Licensed under the Apache License, Version 2.0 (the "License");
258
+ you may not use this file except in compliance with the License.
259
+ You may obtain a copy of the License at
260
+
261
+ http://www.apache.org/licenses/LICENSE-2.0
262
+
263
+ Unless required by applicable law or agreed to in writing, software
264
+ distributed under the License is distributed on an "AS IS" BASIS,
265
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
266
+ See the License for the specific language governing permissions and
267
+ limitations under the License.
268
+ ```
269
+
270
+ ## uvloop
271
+
272
+ Link: https://github.com/MagicStack/uvloop
273
+
274
+ ```
275
+ The MIT License
276
+
277
+ Copyright (C) 2016-present the uvloop authors and contributors.
278
+
279
+ Permission is hereby granted, free of charge, to any person obtaining a copy
280
+ of this software and associated documentation files (the "Software"), to deal
281
+ in the Software without restriction, including without limitation the rights
282
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
283
+ copies of the Software, and to permit persons to whom the Software is
284
+ furnished to do so, subject to the following conditions:
285
+
286
+ The above copyright notice and this permission notice shall be included in
287
+ all copies or substantial portions of the Software.
288
+
289
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
290
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
291
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
292
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
293
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
294
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
295
+ THE SOFTWARE.
296
+ ```
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: wisp-python
3
- Version: 0.6.1
3
+ Version: 0.8.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
@@ -11,8 +11,10 @@ Classifier: Operating System :: OS Independent
11
11
  Requires-Python: >=3.9
12
12
  Description-Content-Type: text/markdown
13
13
  License-File: LICENSE
14
+ License-File: LICENSE_third_party.md
14
15
  Requires-Dist: websockets
15
16
  Requires-Dist: asyncudp
17
+ Requires-Dist: python-socks[asyncio]
16
18
  Requires-Dist: uvloop; sys_platform != "win32" and sys_platform != "cygwin"
17
19
  Dynamic: license-file
18
20
 
@@ -36,18 +38,14 @@ pip3 install wisp-python
36
38
  ```
37
39
 
38
40
  ## Running the Server:
39
- There are two different versions of the server:
40
- - Async (`wisp.server`) - The default, based on asyncio. It is more stable, but slower.
41
- - 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.
42
-
43
41
  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.
44
42
 
45
- To start the server, run `python3 -m wisp.server` (or `python3 -m wisp.server.threading`). The program accepts the following arguments:
43
+ To start the server, run `python3 -m wisp.server`. The program accepts the following arguments:
46
44
  ```
47
45
  usage: wisp-server-python [-h] [--host HOST] [--port PORT] [--static STATIC] [--limits] [--bandwidth BANDWIDTH] [--connections CONNECTIONS] [--window WINDOW] [--allow-loopback] [--allow-private]
48
- [--log-level LOG_LEVEL]
46
+ [--log-level LOG_LEVEL] [--threads THREADS] [--proxy PROXY]
49
47
 
50
- A Wisp server implementation, written in Python (v0.5.0)
48
+ A Wisp server implementation, written in Python (v0.8.0)
51
49
 
52
50
  options:
53
51
  -h, --help show this help message and exit
@@ -64,6 +62,8 @@ options:
64
62
  --allow-private Allow connections to private IP addresses.
65
63
  --log-level LOG_LEVEL
66
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. (Linux only)
66
+ --proxy PROXY The url of the socks5h, socks5, sock4a, socks4 or http proxy to use.
67
67
  ```
68
68
 
69
69
  ## Roadmap:
@@ -76,10 +76,12 @@ options:
76
76
  ## Copyright:
77
77
  This repository is licensed under the GNU AGPL v3.
78
78
 
79
+ A few third party libraries are used. See [`LICENSE_third_party.md`](https://github.com/MercuryWorkshop/wisp-server-python/blob/main/LICENSE).
80
+
79
81
  ### Copyright Notice:
80
82
  ```
81
83
  wisp-server-python: a Wisp server implementation written in Python
82
- Copyright (C) 2024 Mercury Workshop
84
+ Copyright (C) 2025 Mercury Workshop
83
85
 
84
86
  This program is free software: you can redistribute it and/or modify
85
87
  it under the terms of the GNU Affero General Public License as published by
@@ -18,18 +18,14 @@ 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
- To start the server, run `python3 -m wisp.server` (or `python3 -m wisp.server.threading`). The program accepts the following arguments:
23
+ To start the server, run `python3 -m wisp.server`. The program accepts the following arguments:
28
24
  ```
29
25
  usage: wisp-server-python [-h] [--host HOST] [--port PORT] [--static STATIC] [--limits] [--bandwidth BANDWIDTH] [--connections CONNECTIONS] [--window WINDOW] [--allow-loopback] [--allow-private]
30
- [--log-level LOG_LEVEL]
26
+ [--log-level LOG_LEVEL] [--threads THREADS] [--proxy PROXY]
31
27
 
32
- A Wisp server implementation, written in Python (v0.5.0)
28
+ A Wisp server implementation, written in Python (v0.8.0)
33
29
 
34
30
  options:
35
31
  -h, --help show this help message and exit
@@ -46,6 +42,8 @@ options:
46
42
  --allow-private Allow connections to private IP addresses.
47
43
  --log-level LOG_LEVEL
48
44
  The log level (either debug, info, warning, error, or critical).
45
+ --threads THREADS The number of threads to run the server on. By default it uses all CPU cores. (Linux only)
46
+ --proxy PROXY The url of the socks5h, socks5, sock4a, socks4 or http proxy to use.
49
47
  ```
50
48
 
51
49
  ## Roadmap:
@@ -58,10 +56,12 @@ options:
58
56
  ## Copyright:
59
57
  This repository is licensed under the GNU AGPL v3.
60
58
 
59
+ A few third party libraries are used. See [`LICENSE_third_party.md`](https://github.com/MercuryWorkshop/wisp-server-python/blob/main/LICENSE).
60
+
61
61
  ### Copyright Notice:
62
62
  ```
63
63
  wisp-server-python: a Wisp server implementation written in Python
64
- Copyright (C) 2024 Mercury Workshop
64
+ Copyright (C) 2025 Mercury Workshop
65
65
 
66
66
  This program is free software: you can redistribute it and/or modify
67
67
  it under the terms of the GNU Affero General Public License as published by
@@ -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", "wisp.server.threading"]
9
+ packages = ["wisp", "wisp.server"]
10
10
  package-dir = {"" = "src"}
11
11
 
12
12
  [project]
13
13
  name = "wisp-python"
14
- version = "0.6.1"
14
+ version = "0.8.0"
15
15
  authors = [
16
16
  {name="ading2210"},
17
17
  ]
@@ -26,6 +26,7 @@ classifiers = [
26
26
  dependencies = [
27
27
  "websockets",
28
28
  "asyncudp",
29
+ "python-socks[asyncio]",
29
30
  "uvloop; sys_platform != 'win32' and sys_platform != 'cygwin'"
30
31
  ]
31
32
 
@@ -0,0 +1,4 @@
1
+ from wisp.server import cli
2
+
3
+ if __name__ == "__main__":
4
+ cli.main()
@@ -0,0 +1,89 @@
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. (Linux only)")
50
+ parser.add_argument("--proxy", default=None, help="The url of the socks5h, socks5, sock4a, socks4 or http proxy to use.")
51
+ args = parser.parse_args()
52
+
53
+ logging.basicConfig(
54
+ format="[%(asctime)s] %(levelname)-8s %(message)s",
55
+ level=getattr(logging, args.log_level.upper()),
56
+ datefmt="%Y/%m/%d - %H:%M:%S"
57
+ )
58
+
59
+ logging.info(f"running wisp-server-python v{wisp.version} (async)")
60
+ if args.static:
61
+ static_path = pathlib.Path(args.static).resolve()
62
+ logging.info(f"serving static files from {static_path}")
63
+ if args.limits:
64
+ logging.info("enabled rate limits")
65
+ if args.proxy:
66
+ logging.info(f"proxy enabled: {args.proxy}")
67
+ logging.info(f"listening on {args.host}:{args.port}")
68
+
69
+ threads = int(args.threads)
70
+ if net.reuse_port_supported():
71
+ if threads == 0:
72
+ threads = multiprocessing.cpu_count()
73
+ logging.info(f"running using {threads} threads")
74
+
75
+ processes = []
76
+ for i in range(0, int(threads)):
77
+ process = multiprocessing.Process(target=run_http, args=(args,), daemon=True)
78
+ processes.append(process)
79
+ process.start()
80
+ try:
81
+ for process in processes:
82
+ process.join()
83
+ except KeyboardInterrupt:
84
+ pass
85
+
86
+ else:
87
+ if threads != 0:
88
+ logging.warn("the --threads option is not supported on this platform")
89
+ run_http(args)
@@ -41,9 +41,7 @@ async def static_handler(path, request_headers):
41
41
  if "Upgrade" in request_headers:
42
42
  return
43
43
 
44
- response_headers = [
45
- ("Server", f"wisp-server-python v{wisp.version}")
46
- ]
44
+ response_headers = []
47
45
  target_path = static_path / path[1:]
48
46
 
49
47
  if target_path.is_dir():
@@ -61,31 +59,44 @@ async def static_handler(path, request_headers):
61
59
 
62
60
  async def main(args):
63
61
  global static_path
64
- logging.info(f"running wisp-server-python v{wisp.version} (async)")
65
62
 
66
63
  if args.static:
67
64
  static_path = pathlib.Path(args.static).resolve()
68
65
  request_handler = static_handler
69
66
  mimetypes.init()
70
- logging.info(f"serving static files from {static_path}")
71
67
  else:
72
68
  request_handler = None
73
69
 
74
70
  if args.limits:
75
- logging.info("enabled rate limits")
76
71
  ratelimit.enabled = True
77
72
  ratelimit.connections_limit = int(args.connections)
78
73
  ratelimit.bandwidth_limit = float(args.bandwidth)
79
74
  ratelimit.window_size = float(args.window)
75
+
76
+ if args.proxy:
77
+ if args.proxy.startswith("socks5h:"):
78
+ net.proxy_url = args.proxy.replace("socks5h:", "socks5:", 1)
79
+ net.proxy_dns = True
80
+ elif args.proxy.startswith("socks4a:"):
81
+ net.proxy_url = args.proxy.replace("socks4a:", "socks4:", 1)
82
+ net.proxy_dns = True
83
+ else:
84
+ net.proxy_url = args.proxy
85
+ net.proxy_dns = False
80
86
 
81
87
  net.block_loopback = not args.allow_loopback
82
88
  net.block_private = not args.allow_private
83
89
 
84
90
  limit_task = asyncio.create_task(ratelimit.reset_limits_timer())
85
- logging.info(f"listening on {args.host}:{args.port}")
86
-
87
91
  ws_logger = logging.getLogger("websockets")
88
92
  ws_logger.setLevel(logging.WARN)
89
93
 
90
- async with serve(connection_handler, args.host, int(args.port), process_request=request_handler, compression=None):
94
+ reuse_port = net.reuse_port_supported()
95
+ server_header = f"wisp-server-python v{wisp.version}"
96
+
97
+ async with serve(
98
+ connection_handler, args.host, int(args.port),
99
+ reuse_port=reuse_port, process_request=request_handler,
100
+ compression=None, server_header=server_header
101
+ ):
91
102
  await asyncio.Future()
@@ -1,14 +1,29 @@
1
- import asyncudp
2
1
  import asyncio
3
2
  import socket
4
3
  import ipaddress
5
4
 
5
+ import asyncudp
6
+ from python_socks.async_.asyncio import Proxy
7
+
6
8
  #various network utilities and wrappers
7
9
 
8
10
  tcp_size = 64*1024
9
11
  block_loopback = False
10
12
  block_private = False
11
13
 
14
+ proxy_url = None
15
+ proxy_dns = False
16
+
17
+ def reuse_port_supported():
18
+ return hasattr(socket, "SO_REUSEPORT")
19
+
20
+ def is_ip(addr_str):
21
+ try:
22
+ ipaddress.ip_address(addr_str)
23
+ return True
24
+ except:
25
+ return False
26
+
12
27
  def get_ip(host, port, stream_type):
13
28
  if stream_type == 0x01:
14
29
  proto = socket.IPPROTO_TCP
@@ -21,7 +36,7 @@ async def get_ip_async(host, port, stream_type):
21
36
  loop = asyncio.get_running_loop()
22
37
  return await loop.run_in_executor(None, get_ip, host, port, stream_type)
23
38
 
24
- def validate_ip(addr_str):
39
+ def validate_ip(addr_str):
25
40
  ip_addr = ipaddress.ip_address(addr_str)
26
41
  if block_loopback and ip_addr.is_loopback:
27
42
  raise TypeError("Connection to loopback ip address blocked.")
@@ -29,9 +44,15 @@ def validate_ip(addr_str):
29
44
  raise TypeError("Connection to private ip address blocked.")
30
45
 
31
46
  async def validate_hostname(host, port, stream_type):
32
- addr_str = await get_ip_async(host, port, stream_type)
33
- validate_ip(addr_str)
34
- return addr_str
47
+ if is_ip(host):
48
+ return validate_ip(host)
49
+ #don't do a dns lookup when we're on a proxy and using remote dns
50
+ elif proxy_url and proxy_dns:
51
+ return None
52
+ else:
53
+ addr_str = await get_ip_async(host, port, stream_type)
54
+ validate_ip(addr_str)
55
+ return addr_str
35
56
 
36
57
  class TCPConnection:
37
58
  def __init__(self, hostname, port):
@@ -42,7 +63,20 @@ class TCPConnection:
42
63
 
43
64
  async def connect(self):
44
65
  addr_str = await validate_hostname(self.hostname, self.port, 0x01)
45
- self.tcp_reader, self.tcp_writer = await asyncio.open_connection(host=addr_str, port=self.port, limit=tcp_size)
66
+ if proxy_url:
67
+ proxy = Proxy.from_url(proxy_url, rdns=proxy_dns)
68
+ proxy_dest = self.hostname if proxy_dns else addr_str
69
+ sock = await proxy.connect(dest_host=proxy_dest, dest_port=self.port)
70
+ self.tcp_reader, self.tcp_writer = await asyncio.open_connection(
71
+ limit=tcp_size,
72
+ sock=sock
73
+ )
74
+ else:
75
+ self.tcp_reader, self.tcp_writer = await asyncio.open_connection(
76
+ host=addr_str,
77
+ port=self.port,
78
+ limit=tcp_size,
79
+ )
46
80
 
47
81
  async def recv(self):
48
82
  return await self.tcp_reader.read(tcp_size)
@@ -65,6 +99,8 @@ class UDPConnection:
65
99
  self.socket = None
66
100
 
67
101
  async def connect(self):
102
+ if proxy_url:
103
+ raise NotImplementedError("SOCKS/HTTP proxy is not supported for UDP.")
68
104
  addr_str = await validate_hostname(self.hostname, self.port, 0x02)
69
105
  self.socket = await asyncudp.create_socket(remote_addr=(addr_str, self.port))
70
106
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: wisp-python
3
- Version: 0.6.1
3
+ Version: 0.8.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
@@ -11,8 +11,10 @@ Classifier: Operating System :: OS Independent
11
11
  Requires-Python: >=3.9
12
12
  Description-Content-Type: text/markdown
13
13
  License-File: LICENSE
14
+ License-File: LICENSE_third_party.md
14
15
  Requires-Dist: websockets
15
16
  Requires-Dist: asyncudp
17
+ Requires-Dist: python-socks[asyncio]
16
18
  Requires-Dist: uvloop; sys_platform != "win32" and sys_platform != "cygwin"
17
19
  Dynamic: license-file
18
20
 
@@ -36,18 +38,14 @@ pip3 install wisp-python
36
38
  ```
37
39
 
38
40
  ## Running the Server:
39
- There are two different versions of the server:
40
- - Async (`wisp.server`) - The default, based on asyncio. It is more stable, but slower.
41
- - 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.
42
-
43
41
  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.
44
42
 
45
- To start the server, run `python3 -m wisp.server` (or `python3 -m wisp.server.threading`). The program accepts the following arguments:
43
+ To start the server, run `python3 -m wisp.server`. The program accepts the following arguments:
46
44
  ```
47
45
  usage: wisp-server-python [-h] [--host HOST] [--port PORT] [--static STATIC] [--limits] [--bandwidth BANDWIDTH] [--connections CONNECTIONS] [--window WINDOW] [--allow-loopback] [--allow-private]
48
- [--log-level LOG_LEVEL]
46
+ [--log-level LOG_LEVEL] [--threads THREADS] [--proxy PROXY]
49
47
 
50
- A Wisp server implementation, written in Python (v0.5.0)
48
+ A Wisp server implementation, written in Python (v0.8.0)
51
49
 
52
50
  options:
53
51
  -h, --help show this help message and exit
@@ -64,6 +62,8 @@ options:
64
62
  --allow-private Allow connections to private IP addresses.
65
63
  --log-level LOG_LEVEL
66
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. (Linux only)
66
+ --proxy PROXY The url of the socks5h, socks5, sock4a, socks4 or http proxy to use.
67
67
  ```
68
68
 
69
69
  ## Roadmap:
@@ -76,10 +76,12 @@ options:
76
76
  ## Copyright:
77
77
  This repository is licensed under the GNU AGPL v3.
78
78
 
79
+ A few third party libraries are used. See [`LICENSE_third_party.md`](https://github.com/MercuryWorkshop/wisp-server-python/blob/main/LICENSE).
80
+
79
81
  ### Copyright Notice:
80
82
  ```
81
83
  wisp-server-python: a Wisp server implementation written in Python
82
- Copyright (C) 2024 Mercury Workshop
84
+ Copyright (C) 2025 Mercury Workshop
83
85
 
84
86
  This program is free software: you can redistribute it and/or modify
85
87
  it under the terms of the GNU Affero General Public License as published by
@@ -1,20 +1,16 @@
1
1
  LICENSE
2
+ LICENSE_third_party.md
2
3
  README.md
3
4
  pyproject.toml
4
5
  src/wisp/__init__.py
5
6
  src/wisp/util.py
6
7
  src/wisp/server/__init__.py
7
8
  src/wisp/server/__main__.py
8
- src/wisp/server/common.py
9
+ src/wisp/server/cli.py
9
10
  src/wisp/server/connection.py
10
11
  src/wisp/server/http.py
11
12
  src/wisp/server/net.py
12
13
  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
14
  src/wisp_python.egg-info/PKG-INFO
19
15
  src/wisp_python.egg-info/SOURCES.txt
20
16
  src/wisp_python.egg-info/dependency_links.txt
@@ -1,5 +1,6 @@
1
1
  websockets
2
2
  asyncudp
3
+ python-socks[asyncio]
3
4
 
4
5
  [:sys_platform != "win32" and sys_platform != "cygwin"]
5
6
  uvloop
@@ -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,2 +0,0 @@
1
- from wisp.server.threading.connection import WispConnection
2
- from wisp.server.threading.connection import WSProxyConnection
@@ -1,6 +0,0 @@
1
- from wisp.server.threading import http
2
- from wisp.server import common
3
-
4
- if __name__ == "__main__":
5
- args = common.setup_main()
6
- http.main(args)
@@ -1,219 +0,0 @@
1
- import struct
2
- import os
3
- import logging
4
- import queue
5
- import threading
6
-
7
- from websockets.exceptions import ConnectionClosed, ConnectionClosedError
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, ConnectionClosedError) as e:
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
- try:
153
- self.ws.send(data_header + data)
154
- except (ConnectionClosed, ConnectionClosedError) as e:
155
- return
156
-
157
- self.send_close_packet(stream_id, 0x02)
158
- self.close_stream(stream_id)
159
-
160
- def send_close_packet(self, stream_id, reason):
161
- if not stream_id in self.active_streams:
162
- return
163
- close_payload = struct.pack(close_format, reason)
164
- close_packet = struct.pack(packet_format, 0x04, stream_id) + close_payload
165
- self.ws.send(close_packet)
166
-
167
- def close_stream(self, stream_id):
168
- if not stream_id in self.active_streams:
169
- return #stream already closed
170
- stream = self.active_streams[stream_id]
171
- if stream["conn"]:
172
- stream["conn"].close()
173
-
174
- #empty the queue and kill it
175
- while not stream["queue"].empty():
176
- stream["queue"].get()
177
- stream["queue"].put(None)
178
- del self.active_streams[stream_id]
179
-
180
- def handle_ws(self):
181
- while True:
182
- try:
183
- data = self.ws.recv()
184
- except (ConnectionClosed, ConnectionClosedError):
185
- break
186
- except Exception as e:
187
- logging.warn(f"({self.id}) Receiving data from websocket failed: {e}")
188
- break
189
-
190
- if not isinstance(data, bytes):
191
- continue #ignore non binary frames
192
-
193
- #implement bandwidth limits
194
- ratelimit.limit_client_bandwidth_sync(self.client_ip, len(data), "ws")
195
-
196
- #get basic packet info
197
- payload = memoryview(data)[5:]
198
- packet_type, stream_id = struct.unpack(packet_format, data[:5])
199
-
200
- if packet_type == 0x01: #CONNECT packet
201
- self.active_streams[stream_id] = {
202
- "conn": None,
203
- "type": None,
204
- "queue": queue.Queue(queue_size),
205
- "packets_sent": 0
206
- }
207
- threading.Thread(target=self.new_stream, args=(stream_id, payload), daemon=True).start()
208
-
209
- elif packet_type == 0x02: #DATA packet
210
- stream = self.active_streams.get(stream_id)
211
- if not stream:
212
- continue
213
- stream["queue"].put(payload)
214
-
215
- elif packet_type == 0x04: #CLOSE packet
216
- reason = struct.unpack(close_format, payload)[0]
217
- self.close_stream(stream_id)
218
-
219
- 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