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.HttpURL;
44 import org.apache.commons.httpclient.URI;
45
46 /***
47 * This request handler can handle the CONNECT method. It does nothing for any
48 * other HTTP methods.
49 *
50 * @author Ortwin Glueck
51 */
52 public class TransparentProxyRequestHandler implements HttpRequestHandler {
53
54
55
56
57
58
59 public boolean processRequest(
60 final SimpleHttpServerConnection conn,
61 final SimpleRequest request) throws IOException
62 {
63 RequestLine line = request.getRequestLine();
64 String method = line.getMethod();
65 if (!"CONNECT".equalsIgnoreCase(method))
66 return false;
67 URI url = new HttpURL(line.getUri());
68 handshake(conn, url);
69 return true;
70 }
71
72 private void handshake(SimpleHttpServerConnection conn, URI url) throws IOException {
73 Socket targetSocket = new Socket(url.getHost(), url.getPort());
74 InputStream sourceIn = conn.getInputStream();
75 OutputStream sourceOut = conn.getOutputStream();
76 InputStream targetIn = targetSocket.getInputStream();
77 OutputStream targetOut = targetSocket.getOutputStream();
78
79 ResponseWriter out = conn.getWriter();
80 out.println("HTTP/1.1 200 Connection established");
81 out.flush();
82
83 BidiStreamProxy bdsp = new BidiStreamProxy(sourceIn, sourceOut, targetIn, targetOut);
84 bdsp.start();
85 try {
86 bdsp.block();
87 } catch (InterruptedException e) {
88 throw new IOException(e.toString());
89 }
90 }
91
92 private void sendHeaders(Header[] headers, OutputStream os) throws IOException {
93 Writer out;
94 try {
95 out = new OutputStreamWriter(os, "US-ASCII");
96 } catch (UnsupportedEncodingException e) {
97 throw new RuntimeException(e.toString());
98 }
99 for (int i = 0; i < headers.length; i++) {
100 out.write(headers[i].toExternalForm());
101 }
102 }
103 }