Spaces:
Sleeping
Sleeping
Create entrypoint.py
Browse files- entrypoint.py +41 -0
entrypoint.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import asyncio
|
| 2 |
+
import os
|
| 3 |
+
import threading
|
| 4 |
+
import time
|
| 5 |
+
import collections
|
| 6 |
+
|
| 7 |
+
CMD = os.getenv("CMD", "ttyd -p 3000 bash")
|
| 8 |
+
LIMIT, LOG, DEST = 30, collections.defaultdict(list), ('127.0.0.1', 3000)
|
| 9 |
+
|
| 10 |
+
def run():
|
| 11 |
+
print(f"▶ Menjalankan: {CMD}")
|
| 12 |
+
os.system(CMD)
|
| 13 |
+
|
| 14 |
+
threading.Thread(target=run, daemon=True).start()
|
| 15 |
+
|
| 16 |
+
def blocked(ip):
|
| 17 |
+
now = time.time()
|
| 18 |
+
LOG[ip] = [t for t in LOG[ip] if now - t < 60] + [now]
|
| 19 |
+
return len(LOG[ip]) > LIMIT
|
| 20 |
+
|
| 21 |
+
async def proxy(r1, w1):
|
| 22 |
+
ip = w1.get_extra_info("peername")[0]
|
| 23 |
+
if blocked(ip):
|
| 24 |
+
w1.write(b"HTTP/1.1 429 Too Many Requests\r\nConnection: close\r\n\r\n")
|
| 25 |
+
await w1.drain(); w1.close(); return
|
| 26 |
+
try:
|
| 27 |
+
r2, w2 = await asyncio.open_connection(*DEST)
|
| 28 |
+
async def pipe(a, b):
|
| 29 |
+
try:
|
| 30 |
+
while d := await a.read(65536): b.write(d); await b.drain()
|
| 31 |
+
except: pass
|
| 32 |
+
finally: b.close()
|
| 33 |
+
await asyncio.gather(pipe(r1, w2), pipe(r2, w1))
|
| 34 |
+
except: pass
|
| 35 |
+
|
| 36 |
+
async def main():
|
| 37 |
+
server = await asyncio.start_server(proxy, '0.0.0.0', 7860)
|
| 38 |
+
async with server:
|
| 39 |
+
await server.serve_forever()
|
| 40 |
+
|
| 41 |
+
asyncio.run(main())
|