nengo

Java Proxy Server project

Jan 16th, 2012
229
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5.21 KB | None | 0 0
  1. import java.util.*;
  2. import java.net.*;
  3. import java.io.*;
  4.  
  5. class aproxy extends Thread {
  6.  
  7.     Socket socket;
  8.     aproxy(Socket s) {socket = s;}
  9.  
  10.     public static void main(String args[]) {
  11.         try {
  12.            
  13.             ServerSocket ss = new ServerSocket(8080);
  14.             while(true) {
  15.                 System.err.print("-Waiting for Clients \r\n");
  16.                 Socket s = ss.accept();
  17.                 System.err.print("-Client Accepted \r\n");
  18.                 System.err.print(" Number of Active Threads: "+activeCount()+"\r\n");
  19.                 Thread t = new aproxy(s);
  20.                 t.start();
  21.             }
  22.         } catch (IOException e) {}
  23.     }
  24.  
  25.     public void run() {    
  26.         try {
  27.             Scanner in = new Scanner(socket.getInputStream()); // CLIENT-->PROXY
  28.             PrintWriter out = new PrintWriter(socket.getOutputStream(),true); // PROXY-->CLIENT
  29.             if (isGET(in,out))
  30.                 readRequestHead(in,out);
  31.             System.err.print("-Client Gone \r\n");
  32.         } catch (Exception e) {}
  33.     }
  34.    
  35.     public boolean isGET (Scanner in,PrintWriter out) { // Get the input from the client:
  36.         String head = in.next(); //The word 'GET'.
  37.         if ( !head.toUpperCase().equals("GET") ) {
  38.             sendEResponse(out,1,null);
  39.             return false;
  40.             } else
  41.                 return true;
  42.     }
  43.    
  44.     public void sendEResponse (PrintWriter out, int exceptionCase, String targetAddr) { // Send the errors and exceptions:
  45.         try {
  46.         switch (exceptionCase){
  47.        
  48.         case 1:
  49.             //System.err.println("Not an HTTP 'GET' petition!");
  50.             out.print("HTTP/1.1 501 Not Implemented\r\n");
  51.             out.print("Content-Length: xxxx\r\n");
  52.             out.print("Content-Type: xxxx\r\n");
  53.             out.print("Connection: close\r\n");
  54.             out.print("\r\n");
  55.             out.print("<HTML>\n"+"<HEAD><TITLE>Error - Proxy Java</TITLE></HEAD>\n"+"<BODY bgColor=#FF9900><H1>Error HTTP 501</H1>\n"+"<H2> The method you're using is not valid for the HTTP protocol! </H2>\n"+"</BODY>\n"+"</HTML>\r\n\r\n");
  56.             out.flush();
  57.             socket.close();
  58.             break;
  59.            
  60.         case 2:
  61.             //System.err.println("Unknown host!");
  62.             out.print("HTTP/1.1 302 Found\r\n"+"Location: http://www.google.com/search?q="+targetAddr+"\r\n"+"Connection: close\r\n\r\n");
  63.             out.flush();
  64.             socket.close();
  65.             break;
  66.            
  67.         case 3:
  68.             //System.err.println("Connection rejected!");
  69.             out.print("HTTP/1.1 500 Internal Server Error\r\n"+"Content­Length: xxxx\r\n"+"Content­Type: text/html; charset=utf­8\r\n"+"Connection: close\r\n");
  70.             out.print("\r\n");
  71.             out.print("<HTML>\n"+"<HEAD><TITLE>Error - Proxy Java</TITLE></HEAD>\n"+"<BODY bgColor=#FF9900><H1>Error HTTP 500</H1>\n"+"<H2> The server has rejected the request! </H2>\n"+"</BODY>\n"+"<HTML>\r\n\r\n");
  72.             out.flush();
  73.             socket.close();
  74.             break;
  75.         }
  76.         } catch (IOException e) { System.err.println("IO error!"); }
  77.     }
  78.    
  79.     public void readRequestHead (Scanner in,PrintWriter out) { // Get part of the header as the target address to make the socket:
  80.         String path = in.next(); //Full path inside the target host.
  81.         String lineOne = ("GET "+path+" "+in.next()+"\r\n"); //The first line with the 'GET' + the path of the host and the http version.
  82.         String wordHost = (in.next()+" "); //The word 'Host:' of the header and the space.
  83.         String targetAddr = in.next(); //The target host itself.
  84.         String lineTwoEnd = (targetAddr+in.nextLine()+"\r\n"); //The host + the end of the line.
  85.         String lineTwo = (wordHost+lineTwoEnd);
  86.         readNsendRequest(in,out,lineOne,lineTwo,targetAddr);
  87.     }
  88.    
  89.     public void readNsendRequest (Scanner in,PrintWriter out,String lineOne,String lineTwo,String targetAddr) { // Get the remaining part of the header and send it to the target server:
  90.         try {
  91.         Socket tsocket = new Socket(targetAddr, 80); //Socket to the target server the client wants to access.
  92.         PrintWriter tout = new PrintWriter(tsocket.getOutputStream(),true); // PROXY-->SERVER
  93.        
  94.         System.err.println("> Header from the client: \r\n");
  95.         String line;
  96.         System.err.print(lineOne+lineTwo);
  97.         tout.print(lineOne+lineTwo);
  98.         do {
  99.             line = in.nextLine();
  100.  
  101.             if ( ( !line.equals("Connection: keep-alive") ) && ( !line.equals("Proxy-Connection: keep-alive") ) ) {
  102.                 System.err.print(line+"\r\n");
  103.                 tout.print(line+"\r\n");
  104.             } else {
  105.                 System.err.print("Connection: close\r\n");
  106.                 tout.print("Connection: close\r\n");
  107.             }
  108.             } while( !line.equals("") );
  109.         tout.flush();
  110.         getNsendResponse(tsocket);
  111.         } catch (UnknownHostException e) { sendEResponse(out,2,targetAddr); }
  112.         catch (ConnectException e) { sendEResponse(out,3,null); }
  113.         catch (IOException e) { System.err.println("IO error!"); }
  114.     }
  115.    
  116.     public void getNsendResponse (Socket tsocket) { // Send the server output to the client:
  117.         try {
  118.         InputStream streamIn = tsocket.getInputStream(); // SERVER-->PROXY
  119.         OutputStream streamOut = socket.getOutputStream(); // PROXY-->CLIENT
  120.        
  121.         System.err.println(">> Response from the server: \r\n");
  122.         // Buffer:
  123.         int i;
  124.         byte[] b = new byte[1024];
  125.         i = streamIn.read(b);
  126.         while ( (i != 0) && (i != -1) ) { //Loop until the end of the stream.
  127.             System.err.print("--Reading buffer\r\n");
  128.             System.err.print("--Read "+i+" bytes\r\n");
  129.             streamOut.write(b, 0, i);
  130.             System.err.print("--Writing buffer\r\n");
  131.             i = streamIn.read(b);
  132.         }
  133.        
  134.         streamOut.flush();
  135.         streamIn.close();
  136.         streamOut.close();
  137.        
  138.         tsocket.close();
  139.         socket.close();
  140.         } catch (IOException e) { System.err.println("IO error!"); }
  141.     }
  142.  
  143. }
Advertisement
Add Comment
Please, Sign In to add comment