import java.io.*;
import java.net.*;

class Relay extends Thread{
  private Socket in, out;

  Relay(Socket in, Socket out){
    this.in = in;
    this.out = out;
  }

  /**
  * Relay data of a TCP connection from "in" to "out"
  * and copy them to STDOUT.
  */
  public void run(){
    try{
      InputStream is = in.getInputStream();
      OutputStream os = out.getOutputStream();
      byte[] buf = new byte[4096];

      int nRead;
      while((nRead = is.read(buf, 0, buf.length)) != -1){
        os.write(buf, 0, nRead); os.flush();
        System.out.write(buf, 0, nRead);
      }

      out.shutdownInput();
      in.shutdownOutput();
    }catch(IOException ioe){
      // do nothing
    }
  }

  public static void main(String[] av) throws IOException{
    String rhost = "";
    int rport = 0;
    int lport = 0;
    Socket proxy, browser;

    if(av.length != 2){
      printUsage();
      System.exit(1);
    }

    try{
      int idx = av[1].indexOf(":");
      lport = Integer.parseInt(av[0]);
      rhost = av[1].substring(0, idx);
      rport = Integer.parseInt(av[1].substring(idx + 1));
    }catch(IndexOutOfBoundsException ioobe){
      printUsage();
      System.exit(1);
    }catch(NumberFormatException nfe){
      printUsage();
      System.exit(1);
    }

    ServerSocket ss = new ServerSocket(lport);
    while(true){
      browser = ss.accept();
      proxy = new Socket(rhost, rport);
      new Relay(proxy, browser).start();
      new Relay(browser, proxy).start();
    }
  }

  private static void printUsage(){
    System.err.println("Usage: java Relay <lport> <rhost>:<rport>");
  }
}
