#!/usr/bin/env python3
"""127.0.0.1:15555 -> the one device Standa allowed, through the system nc (macOS lets only it reach the local network)."""
import socket, subprocess, threading
HOST, PORT = '192.168.0.14', 5555
srv = socket.socket(); srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1); srv.bind(('127.0.0.1', 15555)); srv.listen(8)
def pipe(a, b):
    try:
        while True:
            d = a(65536)
            if not d: break
            b(d)
    except OSError: pass
def serve(c):
    p = subprocess.Popen(['/usr/bin/nc', HOST, str(PORT)], stdin=subprocess.PIPE, stdout=subprocess.PIPE, bufsize=0)
    def down():
        pipe(lambda n: p.stdout.read1(n) if hasattr(p.stdout,'read1') else p.stdout.read(n), c.sendall)
        try: c.shutdown(socket.SHUT_RDWR)
        except OSError: pass
    threading.Thread(target=down, daemon=True).start()
    def up(d):
        p.stdin.write(d); p.stdin.flush()
    pipe(c.recv, up)
    p.terminate(); c.close()
while True:
    c, _ = srv.accept()
    threading.Thread(target=serve, args=(c,), daemon=True).start()
