|
| 1 | +import socket, struct, argparse, urllib.parse, time, re, sys, pickle, asyncio, functools, base64, os |
| 2 | + |
| 3 | +CLIENT_TIMEOUT = 10 |
| 4 | +CONNECTION_TIMEOUT = 90 |
| 5 | +AUTH_TIME = 86400*7 |
| 6 | +HTTP_LINE = re.compile('([^ ]+) +(.+?) +([^ ]+)') |
| 7 | + |
| 8 | +def all_stat(stats): |
| 9 | + cmd = sys.stdin.readline() |
| 10 | + print('='*70) |
| 11 | + hstat = {} |
| 12 | + for remote_ip, v in stats.items(): |
| 13 | + if remote_ip == 0: continue |
| 14 | + stat = [0]*6 |
| 15 | + for host_name, v2 in v.items(): |
| 16 | + for h in (stat, hstat.setdefault(host_name, [0]*6)): |
| 17 | + for i in range(6): |
| 18 | + h[i] += v2[i] |
| 19 | + stat = [(f'{i/1024/1024/1024:.1f}G' if i>=1024*1024*1024 else (f'{i/1024/1024:.1f}M' if i>=1024*1024 else f'{i/1024:.1f}K')) for i in stat[:4]] + stat[4:] |
| 20 | + print(remote_ip, f'\tDIRECT: {stat[4]} ({stat[0]},{stat[2]}) PROXY: {stat[5]} ({stat[1]},{stat[3]})') |
| 21 | + print(' '*3+'-'*64) |
| 22 | + hstat = sorted(list(hstat.items()), key=lambda x: sum(x[1]), reverse=True)[:15] |
| 23 | + hlen = max(map(lambda x: len(x[0]), hstat)) if hstat else 0 |
| 24 | + for host_name, stat in hstat: |
| 25 | + stat, conn = (stat[0]+stat[1], stat[2]+stat[3]), stat[4]+stat[5] |
| 26 | + stat = [(f'{i/1024/1024/1024:.1f}G' if i>=1024*1024*1024 else (f'{i/1024/1024:.1f}M' if i>=1024*1024 else f'{i/1024:.1f}K')) for i in stat] |
| 27 | + print(host_name.ljust(hlen+5), f'{stat[0]} / {stat[1]}', f'/ {conn}' if conn else '') |
| 28 | + print('='*70) |
| 29 | + |
| 30 | +async def realtime_stat(stats): |
| 31 | + history = [(stats[:4], time.time())] |
| 32 | + while True: |
| 33 | + await asyncio.sleep(1) |
| 34 | + history.append((stats[:4], time.time())) |
| 35 | + i0, t0, i1, t1 = *history[0], *history[-1] |
| 36 | + stat = [(i1[i]-i0[i])/(t1-t0) for i in range(4)] |
| 37 | + stat = [(f'{i/1024/1024:.1f}M/s' if i>=1024*1024 else f'{i/1024:.1f}K/s') for i in stat] |
| 38 | + sys.stdout.write(f'DIRECT: {stats[4]} ({stat[0]},{stat[2]}) PROXY: {stats[5]} ({stat[1]},{stat[3]})\x1b[0K\r') |
| 39 | + sys.stdout.flush() |
| 40 | + if len(history) >= 10: |
| 41 | + del history[:1] |
| 42 | + |
| 43 | +async def channel(reader, writer, stat_bytes, stat_conn): |
| 44 | + try: |
| 45 | + stat_conn(1) |
| 46 | + while True: |
| 47 | + data = await reader.read(65536) |
| 48 | + if not data: |
| 49 | + break |
| 50 | + stat_bytes(len(data)) |
| 51 | + writer.write(data) |
| 52 | + await writer.drain() |
| 53 | + except Exception: |
| 54 | + pass |
| 55 | + finally: |
| 56 | + stat_conn(-1) |
| 57 | + writer.close() |
| 58 | + |
| 59 | +async def http_channel(reader, writer, stat_bytes): |
| 60 | + try: |
| 61 | + while True: |
| 62 | + lines = await reader.readuntil(b'\r\n\r\n') |
| 63 | + headers = lines[:-4].decode().split('\r\n') |
| 64 | + method, path, ver = HTTP_LINE.fullmatch(headers.pop(0)).groups() |
| 65 | + lines = '\r\n'.join(i for i in headers if not i.startswith('Proxy-')) |
| 66 | + headers = dict(i.split(': ', 1) for i in headers if ': ' in i) |
| 67 | + newpath = urllib.parse.urlparse(path)._replace(netloc='', scheme='').geturl() |
| 68 | + data = f'{method} {newpath} {ver}\r\n{lines}\r\n\r\n'.encode() |
| 69 | + data += await reader.readexactly(int(headers.get('Content-Length', '0'))) |
| 70 | + stat_bytes(len(data)) |
| 71 | + writer.write(data) |
| 72 | + await writer.drain() |
| 73 | + except Exception: |
| 74 | + pass |
| 75 | + finally: |
| 76 | + writer.close() |
| 77 | + |
| 78 | +async def proxy_handler(reader, writer, types, auth, rserver, rtype, rauth, match, block, verbose, stats, auth_tables, **kwargs): |
| 79 | + try: |
| 80 | + initbuf = b'' |
| 81 | + pack2 = lambda s: struct.pack('>H', s) |
| 82 | + unpack2 = lambda s: struct.unpack('>H', s)[0] |
| 83 | + packstr = lambda s: struct.pack('B', len(s)) + s |
| 84 | + read = lambda n: asyncio.wait_for(reader.readexactly(n), timeout=CLIENT_TIMEOUT) |
| 85 | + writer.get_extra_info('socket').setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) |
| 86 | + remote_ip = writer.get_extra_info('peername')[0] |
| 87 | + header = await read(1) |
| 88 | + if 'socks' in types and header == b'\x05': |
| 89 | + methods = await read((await read(1))[0]) |
| 90 | + if auth and (b'\x00' not in methods or time.time() - auth_tables.get(remote_ip, 0) > AUTH_TIME): |
| 91 | + writer.write(b'\x05\x02') |
| 92 | + assert (await read(1))[0] == 1 |
| 93 | + u = await read((await read(1))[0]) |
| 94 | + p = await read((await read(1))[0]) |
| 95 | + if u+b':'+p != auth: |
| 96 | + raise Exception('Unauthorized SOCKS') |
| 97 | + writer.write(b'\x01\x00') |
| 98 | + else: |
| 99 | + writer.write(b'\x05\x00') |
| 100 | + if auth: |
| 101 | + auth_tables[remote_ip] = time.time() |
| 102 | + assert (await read(3)) == b'\x05\x01\x00' |
| 103 | + n = (await read(1))[0] |
| 104 | + if n == 1: |
| 105 | + host_name = socket.inet_ntoa(await read(4)) |
| 106 | + port = unpack2(await read(2)) |
| 107 | + writer.write(b'\x05\x00\x00\x01' + socket.inet_aton(host_name) + pack2(port)) |
| 108 | + elif n == 3: |
| 109 | + host_name = (await read((await read(1))[0])).decode() |
| 110 | + port = unpack2(await read(2)) |
| 111 | + writer.write(b'\x05\x00\x00\x03' + packstr(host_name.encode()) + pack2(port)) |
| 112 | + else: |
| 113 | + raise AssertionError() |
| 114 | + method, path = 'SOCKS', f'{host_name}:{port}' |
| 115 | + elif 'http' in types and header.isalpha(): |
| 116 | + lines = header + (await asyncio.wait_for(reader.readuntil(b'\r\n\r\n'), timeout=CLIENT_TIMEOUT)) |
| 117 | + headers = lines[:-4].decode().split('\r\n') |
| 118 | + method, path, ver = HTTP_LINE.fullmatch(headers.pop(0)).groups() |
| 119 | + lines = '\r\n'.join(i for i in headers if not i.startswith('Proxy-')) |
| 120 | + headers = dict(i.split(': ', 1) for i in headers if ': ' in i) |
| 121 | + if auth: |
| 122 | + pauth = headers.get('Proxy-Authorization', None) |
| 123 | + httpauth = 'Basic ' + base64.b64encode(auth).decode() |
| 124 | + if time.time() - auth_tables.get(remote_ip, 0) > AUTH_TIME and pauth != httpauth: |
| 125 | + writer.write(f'{ver} 407 Proxy Authentication Required\r\nConnection: close\r\nProxy-Authenticate: Basic realm="simple"\r\n\r\n'.encode()) |
| 126 | + raise Exception('Unauthorized HTTP') |
| 127 | + auth_tables[remote_ip] = time.time() |
| 128 | + if method == 'CONNECT': |
| 129 | + host_name, port = path.split(':', 1) |
| 130 | + port = int(port) |
| 131 | + writer.write(f'{ver} 200 OK\r\nConnection: close\r\n\r\n'.encode()) |
| 132 | + else: |
| 133 | + url = urllib.parse.urlparse(path) |
| 134 | + host_name = url.hostname |
| 135 | + port = url.port or 80 |
| 136 | + newpath = url._replace(netloc='', scheme='').geturl() |
| 137 | + initbuf = f'{method} {newpath} {ver}\r\n{lines}\r\n\r\n'.encode() |
| 138 | + initbuf += await read(int(headers.get('Content-Length', '0'))) |
| 139 | + elif 'psocks' in types and (auth and header == auth[:1] or not auth): |
| 140 | + if auth: |
| 141 | + if (await read(len(auth)-1)) != auth[1:]: |
| 142 | + raise Exception('Unauthorized PSOCKS') |
| 143 | + header = await read(1) |
| 144 | + if header == b'\xff': |
| 145 | + host_name = socket.inet_ntoa(await read(4)) |
| 146 | + else: |
| 147 | + host_name = (await read(unpack2(header + (await read(1))))).decode() |
| 148 | + port = unpack2(await read(2)) |
| 149 | + method, path = 'PSOCKS', f'{host_name}:{port}' |
| 150 | + else: |
| 151 | + raise Exception('Unsupported protocol') |
| 152 | + if block and block(host_name): |
| 153 | + raise Exception('BLOCKED ' + host_name) |
| 154 | + host_name_2 = '.'.join(host_name.split('.')[-2:]) if host_name.split('.')[-1].isalpha() else host_name |
| 155 | + tostat = (stats[0], stats.setdefault(remote_ip, {}).setdefault(host_name_2, [0]*6)) |
| 156 | + modstat = lambda i: lambda s: [st.__setitem__(i, st[i] + s) for st in tostat] |
| 157 | + viaproxy = bool(rserver and (not match or match(host_name))) |
| 158 | + if viaproxy: |
| 159 | + if rtype == 'psocks': |
| 160 | + rauth = rauth + pack2(len(host_name.encode())) + host_name.encode() + pack2(port) |
| 161 | + elif rtype == 'socks': |
| 162 | + rauth = (b'\x05\x01\x02\x01' + b''.join(packstr(i) for i in rauth.split(b':', 1)) if rauth else b'\x05\x01\x00') + b'\x05\x01\x00\x03' + packstr(host_name.encode()) + pack2(port) |
| 163 | + elif rtype == 'http': |
| 164 | + rauth = (f'CONNECT {host_name}:{port} HTTP/1.1' + (f'\r\nProxy-Authorization: Basic {base64.b64encode(rauth).decode()}' if rauth else '') + '\r\n\r\n').encode() |
| 165 | + else: |
| 166 | + raise AssertionError() |
| 167 | + initbuf = rauth + initbuf |
| 168 | + verbose(f'{method} {path}') |
| 169 | + else: |
| 170 | + rserver = (host_name, port) |
| 171 | + verbose(f'{method.lower()} {path}') |
| 172 | + try: |
| 173 | + reader_remote, writer_remote = await asyncio.wait_for(asyncio.open_connection(*rserver), timeout=CONNECTION_TIMEOUT) |
| 174 | + except asyncio.TimeoutError: |
| 175 | + raise Exception(f'Connection timeout {rserver}') |
| 176 | + try: |
| 177 | + writer_remote.get_extra_info('socket').setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) |
| 178 | + writer_remote.write(initbuf) |
| 179 | + if viaproxy and rtype == 'socks': |
| 180 | + await asyncio.wait_for(reader_remote.readuntil(b'\x00\x05\x00\x00'), timeout=CLIENT_TIMEOUT) |
| 181 | + readr = lambda n: asyncio.wait_for(reader_remote.readexactly(n), timeout=CLIENT_TIMEOUT) |
| 182 | + await readr(6 if (await readr(1))[0] == 1 else (await readr(1))[0] + 2) |
| 183 | + elif viaproxy and rtype == 'http': |
| 184 | + await asyncio.wait_for(reader_remote.readuntil(b'\r\n\r\n'), timeout=CLIENT_TIMEOUT) |
| 185 | + except Exception: |
| 186 | + writer_remote.close() |
| 187 | + raise Exception('Unknown remote protocol') |
| 188 | + asyncio.ensure_future(channel(reader_remote, writer, modstat(2+viaproxy), modstat(4+viaproxy))) |
| 189 | + if method in ('CONNECT', 'SOCKS', 'PSOCKS'): |
| 190 | + asyncio.ensure_future(channel(reader, writer_remote, modstat(viaproxy), lambda s: None)) |
| 191 | + else: |
| 192 | + asyncio.ensure_future(http_channel(reader, writer_remote, modstat(viaproxy))) |
| 193 | + except Exception as ex: |
| 194 | + verbose(f'{str(ex) or "Unsupported protocol"} from {remote_ip}') |
| 195 | + try: writer.close() |
| 196 | + except Exception: pass |
| 197 | + |
| 198 | +def main(): |
| 199 | + pattern_compile = lambda s: re.compile('|'.join(f'(?:{i.strip()})' for i in open(s) if i.strip() and not i.startswith('#'))).fullmatch |
| 200 | + def addr_compile(s): |
| 201 | + ip, _, port = s.partition(':') |
| 202 | + return (ip, int(port) if port else 18436) |
| 203 | + parser = argparse.ArgumentParser(description='Proxy server that can tunnel by http,socks,psocks protocol.') |
| 204 | + parser.add_argument('-p', dest='port', type=int, default=8080, help='listen port server bound to (default: 8080)') |
| 205 | + parser.add_argument('-t', dest='types', type=lambda s: s.split(','), default=['socks','http'], help='proxy server protocols (default: socks,http)') |
| 206 | + parser.add_argument('-a', dest='auth', type=lambda s: s.encode(), help='authentication requirement') |
| 207 | + parser.add_argument('-rs', dest='rserver', type=addr_compile, help='remote server address (default: direct)') |
| 208 | + parser.add_argument('-rt', dest='rtype', default='psocks', help='remote server type (default: psocks)') |
| 209 | + parser.add_argument('-ra', dest='rauth', default=b'', type=lambda s: s.encode(), help='remote authorization code') |
| 210 | + parser.add_argument('-m', dest='match', type=pattern_compile, help='match pattern file') |
| 211 | + parser.add_argument('-b', dest='block', type=pattern_compile, help='block pattern file') |
| 212 | + parser.add_argument('-v', dest='v', action='store_true', help='print verbose output') |
| 213 | + args = parser.parse_args() |
| 214 | + args.verbose = (lambda s: sys.stdout.write(s+'\x1b[0K\n') and sys.stdout.flush()) if args.v else (lambda s: None) |
| 215 | + args.stats = {0: [0]*6} |
| 216 | + args.auth_tables = pickle.load(open('.auth_tables', 'rb')) if os.path.exists('.auth_tables') else {} |
| 217 | + loop = asyncio.get_event_loop() |
| 218 | + handler = functools.partial(proxy_handler, **vars(args)) |
| 219 | + server = loop.run_until_complete(asyncio.start_server(handler, port=args.port)) |
| 220 | + print(f'Serving on port {args.port} by {",".join(args.types)} (' + (f'REMOTE: {args.rserver[0]} by {args.rtype})' if args.rserver else 'DIRECT)')) |
| 221 | + if args.v: |
| 222 | + loop.create_task(realtime_stat(args.stats[0])) |
| 223 | + loop.add_reader(sys.stdin, functools.partial(all_stat, args.stats)) |
| 224 | + try: |
| 225 | + loop.run_forever() |
| 226 | + except KeyboardInterrupt: |
| 227 | + print('exit') |
| 228 | + if args.auth_tables: |
| 229 | + pickle.dump(args.auth_tables, open('.auth_tables', 'wb'), pickle.HIGHEST_PROTOCOL) |
| 230 | + for task in asyncio.Task.all_tasks(): |
| 231 | + task.cancel() |
| 232 | + server.close() |
| 233 | + loop.run_until_complete(server.wait_closed()) |
| 234 | + loop.close() |
| 235 | + |
| 236 | +if __name__ == '__main__': |
| 237 | + main() |
| 238 | + |
0 commit comments