1 /*
   2  * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  */
  23 
  24 import java.net.*;
  25 import java.io.*;
  26 import java.util.*;
  27 import java.security.*;
  28 
  29 /**
  30  * A minimal proxy server that supports CONNECT tunneling. It does not do
  31  * any header transformations. In future this could be added.
  32  * Two threads are created per client connection. So, it's not
  33  * intended for large numbers of parallel connections.
  34  */
  35 public class ProxyServer extends Thread implements Closeable {
  36 
  37     ServerSocket listener;
  38     int port;
  39     volatile boolean debug;
  40 
  41     /**
  42      * Create proxy on port (zero means don't care). Call getPort()
  43      * to get the assigned port.
  44      */
  45     public ProxyServer(Integer port) throws IOException {
  46         this(port, false);
  47     }
  48 
  49     public ProxyServer(Integer port, Boolean debug) throws IOException {
  50         this.debug = debug;
  51         listener = new ServerSocket();
  52         listener.setReuseAddress(false);
  53         listener.bind(new InetSocketAddress(InetAddress.getLoopbackAddress(), port));
  54         this.port = listener.getLocalPort();
  55         setName("ProxyListener");
  56         setDaemon(true);
  57         connections = new LinkedList<>();
  58         start();
  59     }
  60 
  61     public ProxyServer(String s) {  }
  62 
  63     /**
  64      * Returns the port number this proxy is listening on
  65      */
  66     public int getPort() {
  67         return port;
  68     }
  69 
  70     /**
  71      * Shuts down the proxy, probably aborting any connections
  72      * currently open
  73      */
  74     public void close() throws IOException {
  75         if (debug) System.out.println("Proxy: closing");
  76         done = true;
  77         listener.close();
  78         for (Connection c : connections) {
  79             c.close();
  80         }
  81     }
  82 
  83     List<Connection> connections;
  84 
  85     volatile boolean done;
  86 
  87     public void run() {
  88         if (System.getSecurityManager() == null) {
  89             execute();
  90         } else {
  91             // so calling domain does not need to have socket permission
  92             AccessController.doPrivileged(new PrivilegedAction<Void>() {
  93                 public Void run() {
  94                     execute();
  95                     return null;
  96                 }
  97             });
  98         }
  99     }
 100 
 101     public void execute() {
 102         try {
 103             while(!done) {
 104                 Socket s = listener.accept();
 105                 if (debug)
 106                     System.out.println("Client: " + s);
 107                 Connection c = new Connection(s);
 108                 connections.add(c);
 109             }
 110         } catch(Throwable e) {
 111             if (debug && !done) {
 112                 System.out.println("Fatal error: Listener: " + e);
 113                 e.printStackTrace();
 114             }
 115         }
 116     }
 117 
 118     /**
 119      * Transparently forward everything, once we know what the destination is
 120      */
 121     class Connection {
 122 
 123         Socket clientSocket, serverSocket;
 124         Thread out, in;
 125         volatile InputStream clientIn, serverIn;
 126         volatile OutputStream clientOut, serverOut;
 127 
 128         boolean forwarding = false;
 129 
 130         final static int CR = 13;
 131         final static int LF = 10;
 132 
 133         Connection(Socket s) throws IOException {
 134             this.clientSocket= s;
 135             this.clientIn = new BufferedInputStream(s.getInputStream());
 136             this.clientOut = s.getOutputStream();
 137             init();
 138         }
 139 
 140         byte[] readHeaders(InputStream is) throws IOException {
 141             byte[] outbuffer = new byte[8000];
 142             int crlfcount = 0;
 143             int bytecount = 0;
 144             int c;
 145             while ((c=is.read()) != -1 && bytecount < outbuffer.length) {
 146                 outbuffer[bytecount++] = (byte)c;
 147                 if (debug) System.out.write(c);
 148                 // were looking for CRLFCRLF sequence
 149                 if (c == CR || c == LF) {
 150                     switch(crlfcount) {
 151                         case 0:
 152                             if (c == CR) crlfcount ++;
 153                             break;
 154                         case 1:
 155                             if (c == LF) crlfcount ++;
 156                             break;
 157                         case 2:
 158                             if (c == CR) crlfcount ++;
 159                             break;
 160                         case 3:
 161                             if (c == LF) crlfcount ++;
 162                             break;
 163                     }
 164                 } else {
 165                     crlfcount = 0;
 166                 }
 167                 if (crlfcount == 4) {
 168                     break;
 169                 }
 170             }
 171             byte[] ret = new byte[bytecount];
 172             System.arraycopy(outbuffer, 0, ret, 0, bytecount);
 173             return ret;
 174         }
 175 
 176         boolean running() {
 177             return out.isAlive() || in.isAlive();
 178         }
 179 
 180         private volatile boolean closing;
 181         public synchronized void close() throws IOException {
 182             closing = true;
 183             if (debug) System.out.println("Closing connection (proxy)");
 184             if (serverSocket != null) serverSocket.close();
 185             if (clientSocket != null) clientSocket.close();
 186         }
 187 
 188         int findCRLF(byte[] b) {
 189             for (int i=0; i<b.length-1; i++) {
 190                 if (b[i] == CR && b[i+1] == LF) {
 191                     return i;
 192                 }
 193             }
 194             return -1;
 195         }
 196 
 197         public void init() {
 198             try {
 199                 byte[] buf = readHeaders(clientIn);
 200                 int p = findCRLF(buf);
 201                 if (p == -1) {
 202                     close();
 203                     return;
 204                 }
 205                 String cmd = new String(buf, 0, p, "US-ASCII");
 206                 String[] params = cmd.split(" ");
 207                 if (params[0].equals("CONNECT")) {
 208                     doTunnel(params[1]);
 209                 } else {
 210                     doProxy(params[1], buf, p, cmd);
 211                 }
 212             } catch (Throwable e) {
 213                 if (debug) {
 214                     System.out.println (e);
 215                 }
 216                 try {close(); } catch (IOException e1) {}
 217             }
 218         }
 219 
 220         void doProxy(String dest, byte[] buf, int p, String cmdLine)
 221             throws IOException
 222         {
 223             try {
 224                 URI uri = new URI(dest);
 225                 if (!uri.isAbsolute()) {
 226                     throw new IOException("request URI not absolute");
 227                 }
 228                 dest = uri.getAuthority();
 229                 // now extract the path from the URI and recreate the cmd line
 230                 int sp = cmdLine.indexOf(' ');
 231                 String method = cmdLine.substring(0, sp);
 232                 cmdLine = method + " " + uri.getPath() + " HTTP/1.1";
 233                 int x = cmdLine.length() - 1;
 234                 int i = p;
 235                 while (x >=0) {
 236                     buf[i--] = (byte)cmdLine.charAt(x--);
 237                 }
 238                 i++;
 239 
 240                 commonInit(dest, 80);
 241                 OutputStream sout;
 242                 synchronized (this) {
 243                     if (closing) return;
 244                     sout = serverOut;
 245                 }
 246                 // might fail if we're closing but we don't care.
 247                 sout.write(buf, i, buf.length-i);
 248                 proxyCommon();
 249 
 250             } catch (URISyntaxException e) {
 251                 throw new IOException(e);
 252             }
 253         }
 254 
 255         synchronized void commonInit(String dest, int defaultPort) throws IOException {
 256             if (closing) return;
 257             int port;
 258             String[] hostport = dest.split(":");
 259             if (hostport.length == 1) {
 260                 port = defaultPort;
 261             } else {
 262                 port = Integer.parseInt(hostport[1]);
 263             }
 264             if (debug) System.out.printf("Server: (%s/%d)\n", hostport[0], port);
 265             serverSocket = new Socket(hostport[0], port);
 266             serverOut = serverSocket.getOutputStream();
 267 
 268             serverIn = new BufferedInputStream(serverSocket.getInputStream());
 269         }
 270 
 271         synchronized void proxyCommon() throws IOException {
 272             if (closing) return;
 273             out = new Thread(() -> {
 274                 try {
 275                     byte[] bb = new byte[8000];
 276                     int n;
 277                     while ((n = clientIn.read(bb)) != -1) {
 278                         serverOut.write(bb, 0, n);
 279                     }
 280                     closing = true;
 281                     serverSocket.close();
 282                     clientSocket.close();
 283                 } catch (IOException e) {
 284                     if (debug) {
 285                         System.out.println (e);
 286                     }
 287                 }
 288             });
 289             in = new Thread(() -> {
 290                 try {
 291                     byte[] bb = new byte[8000];
 292                     int n;
 293                     while ((n = serverIn.read(bb)) != -1) {
 294                         clientOut.write(bb, 0, n);
 295                     }
 296                     closing = true;
 297                     serverSocket.close();
 298                     clientSocket.close();
 299                 } catch (IOException e) {
 300                     if (debug) {
 301                         System.out.println(e);
 302                         e.printStackTrace();
 303                     }
 304                 }
 305             });
 306             out.setName("Proxy-outbound");
 307             out.setDaemon(true);
 308             in.setDaemon(true);
 309             in.setName("Proxy-inbound");
 310             out.start();
 311             in.start();
 312         }
 313 
 314         void doTunnel(String dest) throws IOException {
 315             if (closing) return; // no need to go further.
 316             commonInit(dest, 443);
 317             // might fail if we're closing, but we don't care.
 318             clientOut.write("HTTP/1.1 200 OK\r\n\r\n".getBytes());
 319             proxyCommon();
 320         }
 321     }
 322 
 323     public static void main(String[] args) throws Exception {
 324         int port = Integer.parseInt(args[0]);
 325         boolean debug = args.length > 1 && args[1].equals("-debug");
 326         System.out.println("Debugging : " + debug);
 327         ProxyServer ps = new ProxyServer(port, debug);
 328         System.out.println("Proxy server listening on port " + ps.getPort());
 329         while (true) {
 330             Thread.sleep(5000);
 331         }
 332     }
 333 }