|
1 | | -""" |
2 | | -This file provides remote port forwarding functionality using paramiko package, |
3 | | -Inspired by: https://github.com/paramiko/paramiko/blob/master/demos/rforward.py |
4 | | -""" |
5 | | - |
6 | | -import select |
7 | | -import socket |
8 | | -import sys |
9 | | -import threading |
10 | | -import warnings |
11 | | -from io import StringIO |
12 | | - |
13 | | -from cryptography.utils import CryptographyDeprecationWarning |
14 | | - |
15 | | -with warnings.catch_warnings(): |
16 | | - warnings.filterwarnings("ignore", category=CryptographyDeprecationWarning) |
17 | | - import paramiko |
18 | | - |
19 | | - |
20 | | -def handler(chan, host, port): |
21 | | - sock = socket.socket() |
22 | | - try: |
23 | | - sock.connect((host, port)) |
24 | | - except Exception as e: |
25 | | - verbose(f"Forwarding request to {host}:{port} failed: {e}") |
26 | | - return |
27 | | - |
28 | | - verbose( |
29 | | - "Connected! Tunnel open " |
30 | | - f"{chan.origin_addr} -> {chan.getpeername()} -> {(host, port)}" |
31 | | - ) |
32 | | - |
33 | | - while True: |
34 | | - r, w, x = select.select([sock, chan], [], []) |
35 | | - if sock in r: |
36 | | - data = sock.recv(1024) |
37 | | - if len(data) == 0: |
38 | | - break |
39 | | - chan.send(data) |
40 | | - if chan in r: |
41 | | - data = chan.recv(1024) |
42 | | - if len(data) == 0: |
43 | | - break |
44 | | - sock.send(data) |
45 | | - chan.close() |
46 | | - sock.close() |
47 | | - verbose(f"Tunnel closed from {chan.origin_addr}") |
48 | | - |
49 | | - |
50 | | -def reverse_forward_tunnel(server_port, remote_host, remote_port, transport): |
51 | | - transport.request_port_forward("", server_port) |
52 | | - while True: |
53 | | - chan = transport.accept(1000) |
54 | | - if chan is None: |
55 | | - continue |
56 | | - thr = threading.Thread(target=handler, args=(chan, remote_host, remote_port)) |
57 | | - thr.setDaemon(True) |
58 | | - thr.start() |
59 | | - |
60 | | - |
61 | | -def verbose(s, debug_mode=False): |
62 | | - if debug_mode: |
63 | | - print(s) |
64 | | - |
65 | | - |
66 | | -def create_tunnel(payload, local_server, local_server_port): |
67 | | - client = paramiko.SSHClient() |
68 | | - client.set_missing_host_key_policy(paramiko.WarningPolicy()) |
69 | | - |
70 | | - verbose(f'Conecting to ssh host {payload["host"]}:{payload["port"]} ...') |
71 | | - try: |
72 | | - with warnings.catch_warnings(): |
73 | | - warnings.simplefilter("ignore") |
74 | | - client.connect( |
75 | | - hostname=payload["host"], |
76 | | - port=int(payload["port"]), |
77 | | - username=payload["user"], |
78 | | - pkey=paramiko.RSAKey.from_private_key(StringIO(payload["key"])), |
79 | | - ) |
80 | | - except Exception as e: |
81 | | - print(f'*** Failed to connect to {payload["host"]}:{payload["port"]}: {e}') |
82 | | - sys.exit(1) |
83 | | - |
84 | | - verbose( |
85 | | - f'Now forwarding remote port {payload["remote_port"]}' |
86 | | - f"to {local_server}:{local_server_port} ..." |
87 | | - ) |
88 | | - |
89 | | - thread = threading.Thread( |
90 | | - target=reverse_forward_tunnel, |
91 | | - args=( |
92 | | - int(payload["remote_port"]), |
93 | | - local_server, |
94 | | - local_server_port, |
95 | | - client.get_transport(), |
96 | | - ), |
97 | | - daemon=True, |
98 | | - ) |
99 | | - thread.start() |
100 | | - |
101 | | - return payload["share_url"] |
| 1 | +import atexit |
| 2 | +import os |
| 3 | +import platform |
| 4 | +import re |
| 5 | +import subprocess |
| 6 | +from typing import List |
| 7 | + |
| 8 | +VERSION = "0.1" |
| 9 | +CURRENT_TUNNELS: List["Tunnel"] = [] |
| 10 | + |
| 11 | + |
| 12 | +class Tunnel: |
| 13 | + def __init__(self, remote_host, remote_port, local_host, local_port): |
| 14 | + self.proc = None |
| 15 | + self.url = None |
| 16 | + self.remote_host = remote_host |
| 17 | + self.remote_port = remote_port |
| 18 | + self.local_host = local_host |
| 19 | + self.local_port = local_port |
| 20 | + |
| 21 | + @staticmethod |
| 22 | + def download_binary(): |
| 23 | + machine = platform.machine() |
| 24 | + if machine == "x86_64": |
| 25 | + machine = "amd64" |
| 26 | + |
| 27 | + # Check if the file exist |
| 28 | + binary_name = f"frpc_{platform.system().lower()}_{machine.lower()}" |
| 29 | + binary_path = os.path.join(os.path.dirname(__file__), binary_name) |
| 30 | + |
| 31 | + extension = ".exe" if os.name == "nt" else "" |
| 32 | + |
| 33 | + if not os.path.exists(binary_path): |
| 34 | + import stat |
| 35 | + |
| 36 | + import requests |
| 37 | + |
| 38 | + binary_url = f"https://cdn-media.huggingface.co/frpc-gradio-{VERSION}/{binary_name}{extension}" |
| 39 | + resp = requests.get(binary_url) |
| 40 | + |
| 41 | + if resp.status_code == 403: |
| 42 | + raise OSError( |
| 43 | + f"Cannot set up a share link as this platform is incompatible. Please " |
| 44 | + f"create a GitHub issue with information about your platform: {platform.uname()}" |
| 45 | + ) |
| 46 | + |
| 47 | + resp.raise_for_status() |
| 48 | + |
| 49 | + # Save file data to local copy |
| 50 | + with open(binary_path, "wb") as file: |
| 51 | + file.write(resp.content) |
| 52 | + st = os.stat(binary_path) |
| 53 | + os.chmod(binary_path, st.st_mode | stat.S_IEXEC) |
| 54 | + |
| 55 | + return binary_path |
| 56 | + |
| 57 | + def start_tunnel(self) -> str: |
| 58 | + binary_path = self.download_binary() |
| 59 | + self.url = self._start_tunnel(binary_path) |
| 60 | + return self.url |
| 61 | + |
| 62 | + def kill(self): |
| 63 | + if self.proc is not None: |
| 64 | + print(f"Killing tunnel {self.local_host}:{self.local_port} <> {self.url}") |
| 65 | + self.proc.terminate() |
| 66 | + self.proc = None |
| 67 | + |
| 68 | + def _start_tunnel(self, binary: str) -> str: |
| 69 | + CURRENT_TUNNELS.append(self) |
| 70 | + command = [ |
| 71 | + binary, |
| 72 | + "http", |
| 73 | + "-n", |
| 74 | + "random", |
| 75 | + "-l", |
| 76 | + str(self.local_port), |
| 77 | + "-i", |
| 78 | + self.local_host, |
| 79 | + "--uc", |
| 80 | + "--sd", |
| 81 | + "random", |
| 82 | + "--ue", |
| 83 | + "--server_addr", |
| 84 | + f"{self.remote_host}:{self.remote_port}", |
| 85 | + "--disable_log_color", |
| 86 | + ] |
| 87 | + |
| 88 | + self.proc = subprocess.Popen( |
| 89 | + command, stdout=subprocess.PIPE, stderr=subprocess.PIPE |
| 90 | + ) |
| 91 | + atexit.register(self.kill) |
| 92 | + url = "" |
| 93 | + while url == "": |
| 94 | + line = self.proc.stdout.readline() |
| 95 | + line = line.decode("utf-8") |
| 96 | + if "start proxy success" in line: |
| 97 | + url = re.search("start proxy success: (.+)\n", line).group(1) |
| 98 | + return url |
0 commit comments