1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32 package org.apache.commons.httpclient.server;
33
34 import java.io.IOException;
35 import java.io.InputStream;
36 import java.io.OutputStream;
37 import java.io.OutputStreamWriter;
38 import java.io.UnsupportedEncodingException;
39 import java.io.Writer;
40 import java.net.Socket;
41
42 import org.apache.commons.httpclient.Header;
43 import org.apache.commons.httpclient.HttpConstants;
44 import org.apache.commons.httpclient.HttpURL;
45 import org.apache.commons.httpclient.URI;
46
47 /***
48 * This request handler can handle the CONNECT method. It does
49 * nothing for any other HTTP methods.
50 *
51 * @author Ortwin Glueck
52 */
53 public class TransparentProxyRequestHandler implements HttpRequestHandler {
54
55
56
57
58 public boolean processRequest(SimpleHttpServerConnection conn) throws IOException {
59 RequestLine line = conn.getRequestLine();
60 String method = line.getMethod();
61 if (!"CONNECT".equalsIgnoreCase(method)) return false;
62 URI url = new HttpURL(line.getUri());
63 handshake(conn, url);
64 return true;
65 }
66
67 private void handshake(SimpleHttpServerConnection conn, URI url) throws IOException {
68 Socket targetSocket = new Socket(url.getHost(), url.getPort());
69 InputStream sourceIn = conn.getInputStream();
70 OutputStream sourceOut = conn.getOutputStream();
71 InputStream targetIn = targetSocket.getInputStream();
72 OutputStream targetOut = targetSocket.getOutputStream();
73
74 ResponseWriter out = conn.getWriter();
75 out.println("HTTP/1.1 200 Connection established");
76 out.flush();
77
78 BidiStreamProxy bdsp = new BidiStreamProxy(sourceIn, sourceOut, targetIn, targetOut);
79 bdsp.start();
80 try {
81 bdsp.block();
82 } catch (InterruptedException e) {
83 throw new IOException(e.toString());
84 }
85 }
86
87 private void sendHeaders(Header[] headers, OutputStream os) throws IOException {
88 Writer out;
89 try {
90 out = new OutputStreamWriter(os, HttpConstants.HTTP_ELEMENT_CHARSET);
91 } catch (UnsupportedEncodingException e) {
92 throw new RuntimeException(e.toString());
93 }
94 for (int i=0; i<headers.length; i++) {
95 out.write(headers[i].toExternalForm());
96 }
97 }
98 }