Advertisement
Guest User

workingproxy

a guest
Jan 28th, 2015
186
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 7.72 KB | None | 0 0
  1. import java.io.BufferedInputStream;
  2. import java.io.BufferedOutputStream;
  3. import java.io.BufferedReader;
  4. import java.io.ByteArrayOutputStream;
  5. import java.io.IOException;
  6. import java.io.InputStream;
  7. import java.io.InputStreamReader;
  8. import java.io.OutputStream;
  9. import java.io.PrintWriter;
  10. import java.net.InetSocketAddress;
  11. import java.net.ServerSocket;
  12. import java.net.Socket;
  13. import java.nio.ByteBuffer;
  14. import java.nio.charset.Charset;
  15.  
  16. public class WebProxy {
  17.  
  18.     public static void main(String[] args) {
  19.         try {
  20.             // create a socket
  21.             ServerSocket servSocket = new ServerSocket(8000);
  22.             // sockets for client and server communication
  23.             Socket client, server;
  24.             while(true) {
  25.                 System.out.println("Waiting...");
  26.                 client = servSocket.accept();
  27.                
  28.                 System.out.println("Accepted connection : " + client);
  29.                 System.out.println("");
  30.                
  31.                 BufferedInputStream fromClient = new BufferedInputStream(client.getInputStream());
  32.                 BufferedOutputStream toClient = new BufferedOutputStream(client.getOutputStream());
  33.                
  34.                 byte[] request, response;
  35.                 StringBuffer host = new StringBuffer("");
  36.                 int port = 80;
  37.                
  38.                 request = getHTTPData(fromClient, host, true);
  39.                 String hostName = host.toString();
  40.                 server = new Socket();
  41.                 server.connect(new InetSocketAddress(hostName, port));
  42.                
  43.                 BufferedInputStream serverIn = new BufferedInputStream(server.getInputStream());
  44.                 BufferedOutputStream serverOut = new BufferedOutputStream(server.getOutputStream());
  45.                
  46.                 // send the request out
  47.                 serverOut.write(request);
  48.                 serverOut.flush();
  49.                
  50.                 streamHTTPData(serverIn, toClient, true);
  51.                 serverIn.close();
  52.                 serverOut.close();
  53. //              String subRequest = fromClient.readLine();
  54. //              String url = extractUrl(subRequest);
  55. //              String host = url.split("/")[2];
  56. //              subRequest = subRequest.replaceAll("https?://" + host, "");
  57. //              int port = 80;
  58. //              while(!subRequest.equals("")) {
  59. //                  request += subRequest + "\r\n";
  60. //                  subRequest = in.readLine();
  61. //              }
  62. //              System.out.println("The HTTP request is: ");
  63. //              System.out.println(request);
  64. //              // Check if host is blocked.
  65. //             
  66. //              Socket toServer = new Socket();
  67. //              //TODO place a handler for bad hosts
  68. //              toServer.connect(new InetSocketAddress(host, port));
  69. //              System.out.println("Connected: " + url);
  70. //             
  71. //              PrintWriter serverOut = new PrintWriter(toServer.getOutputStream(), true);
  72. //              serverOut.println(request);
  73. //              System.out.println("Request sent");
  74. //             
  75. //              BufferedReader serverIn = new BufferedReader(new InputStreamReader(toServer.getInputStream(), "UTF8"));
  76. //              String response = "";
  77. //              String subResponse;
  78. //              System.out.println("");
  79. //              System.out.println("Response is received");
  80. //              while ((subResponse = serverIn.readLine()) != null) {
  81. //                  System.out.println(subResponse);
  82. //                  response += subResponse + "\r\n";
  83. //              }
  84. //             
  85. //              PrintWriter clientIn = new PrintWriter(fromClient.getOutputStream(), true);
  86. //              clientIn.println(response);
  87. //              System.out.println("Dealt with client");
  88.             }
  89.         }
  90.         catch(Exception e){
  91.             e.printStackTrace();
  92.         }
  93.  
  94.     }
  95.  
  96.  
  97.     private static byte[] getHTTPData (InputStream in, StringBuffer host, boolean waitForDisconnect) {
  98.         // get the HTTP data from an InputStream, and return it as
  99.         // a byte array, and also return the Host entry in the header,
  100.         // if it's specified -- note that we have to use a StringBuffer
  101.         // for the 'host' variable, because a String won't return any
  102.         // information when it's used as a parameter like that
  103.         ByteArrayOutputStream bs = new ByteArrayOutputStream();
  104.         streamHTTPData(in, bs, host, waitForDisconnect);
  105.         return bs.toByteArray();
  106.     }
  107.    
  108.     private static int streamHTTPData (InputStream in, OutputStream out,
  109.                                     StringBuffer host, boolean waitForDisconnect)
  110.     {
  111.         // get the HTTP data from an InputStream, and send it to
  112.         // the designated OutputStream
  113.         StringBuffer header = new StringBuffer("");
  114.         String data = "";
  115.         int responseCode = 200;
  116.         int contentLength = 0;
  117.         int pos = -1;
  118.         int byteCount = 0;
  119.  
  120.         try
  121.         {
  122.             // get the first line of the header, so we know the response code
  123.             data = readLine(in);
  124.             if (data != null)
  125.             {
  126.                 header.append(data + "\r\n");
  127.                 pos = data.indexOf(" ");
  128.                 if ((data.toLowerCase().startsWith("http")) &&
  129.                     (pos >= 0) && (data.indexOf(" ", pos+1) >= 0))
  130.                 {
  131.                     String rcString = data.substring(pos+1, data.indexOf(" ", pos+1));
  132.                     try
  133.                     {
  134.                         responseCode = Integer.parseInt(rcString);
  135.                     }  catch (Exception e)  {
  136. //                      if (debugLevel > 0)
  137. //                          debugOut.println("Error parsing response code " + rcString);
  138.                     }
  139.                 }
  140.             }
  141.             // get the rest of the header info
  142.             while ((data = readLine(in)) != null)
  143.             {
  144.                 // the header ends at the first blank line
  145.                 if (data.length() == 0)
  146.                     break;
  147.                 header.append(data + "\r\n");
  148.                
  149.                 // check for the Host header
  150.                 pos = data.toLowerCase().indexOf("host:");
  151.                 if (pos >= 0)
  152.                 {
  153.                     host.setLength(0);
  154.                     host.append(data.substring(pos + 5).trim());
  155.                 }
  156.                
  157.                 // check for the Content-Length header
  158.                 pos = data.toLowerCase().indexOf("content-length:");
  159.                 if (pos >= 0)
  160.                     contentLength = Integer.parseInt(data.substring(pos + 15).trim());
  161.             }
  162.            
  163.             // add a blank line to terminate the header info
  164.             header.append("\r\n");
  165.            
  166.             // convert the header to a byte array, and write it to our stream
  167.             out.write(header.toString().getBytes(), 0, header.length());
  168.            
  169.             // if the header indicated that this was not a 200 response,
  170.             // just return what we've got if there is no Content-Length,
  171.             // because we may not be getting anything else
  172.             if ((responseCode != 200) && (contentLength == 0))
  173.             {
  174.                 out.flush();
  175.                 return header.length();
  176.             }
  177.  
  178.             // get the body, if any; we try to use the Content-Length header to
  179.             // determine how much data we're supposed to be getting, because
  180.             // sometimes the client/server won't disconnect after sending us
  181.             // information...
  182.             if (contentLength > 0)
  183.                 waitForDisconnect = false;
  184.            
  185.             if ((contentLength > 0) || (waitForDisconnect))
  186.             {
  187.                 try {
  188.                     byte[] buf = new byte[4096];
  189.                     int bytesIn = 0;
  190.                     while ( ((byteCount < contentLength) || (waitForDisconnect))
  191.                             && ((bytesIn = in.read(buf)) >= 0) )
  192.                     {
  193.                         out.write(buf, 0, bytesIn);
  194.                         byteCount += bytesIn;
  195.                     }
  196.                 }  catch (Exception e)  {
  197. //                  String errMsg = "Error getting HTTP body: " + e;
  198. //                  if (debugLevel > 0)
  199. //                      debugOut.println(errMsg);
  200.                     //bs.write(errMsg.getBytes(), 0, errMsg.length());
  201.                 }
  202.             }
  203.         }  catch (Exception e)  {
  204. //          if (debugLevel > 0)
  205. //              debugOut.println("Error getting HTTP data: " + e);
  206.         }
  207.        
  208.         //flush the OutputStream and return
  209.         try  {  out.flush();  }  catch (Exception e)  {}
  210.         return (header.length() + byteCount);
  211.     }
  212.    
  213.    
  214.     private static String readLine (InputStream in)
  215.     {
  216.         // reads a line of text from an InputStream
  217.         StringBuffer data = new StringBuffer("");
  218.         int c;
  219.        
  220.         try
  221.         {
  222.             // if we have nothing to read, just return null
  223.             in.mark(1);
  224.             if (in.read() == -1)
  225.                 return null;
  226.             else
  227.                 in.reset();
  228.            
  229.             while ((c = in.read()) >= 0)
  230.             {
  231.                 // check for an end-of-line character
  232.                 if ((c == 0) || (c == 10) || (c == 13))
  233.                     break;
  234.                 else
  235.                     data.append((char)c);
  236.             }
  237.        
  238.             // deal with the case where the end-of-line terminator is \r\n
  239.             if (c == 13)
  240.             {
  241.                 in.mark(1);
  242.                 if (in.read() != 10)
  243.                     in.reset();
  244.             }
  245.         }  catch (Exception e)  {
  246.         }
  247.        
  248.         // and return what we have
  249.         return data.toString();
  250.     }
  251.  
  252. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement