1 57 58 package org.apache.soap.util.net; 59 60 import java.net.*; 61 import java.io.*; 62 import java.util.*; 63 import javax.net.ssl.*; 64 import java.security.*; 65 66 71 public class SSLUtils { 72 static String tunnelHost; 73 static int tunnelPort; 74 75 76 public static Socket buildSSLSocket(String host, int port, String httpProxyHost, 77 int httpProxyPort) 78 throws IOException, UnknownHostException 79 { 80 SSLSocket sslSocket = null; 81 SSLSocketFactory factory = 82 (SSLSocketFactory)SSLSocketFactory.getDefault(); 83 84 tunnelHost = System.getProperty("https.proxyHost"); 87 tunnelPort = Integer.getInteger("https.proxyPort", 80).intValue(); 88 89 if (tunnelHost==null) { 90 tunnelHost = httpProxyHost; 92 tunnelPort = httpProxyPort; 93 } 94 95 101 102 108 if (tunnelHost==null) { 109 sslSocket = (SSLSocket)factory.createSocket(host, port); 110 } else { 111 Socket tunnel = new Socket(tunnelHost, tunnelPort); 112 doTunnelHandshake(tunnel, host, port); 113 114 sslSocket = (SSLSocket)factory.createSocket(tunnel, host, port, true); 116 } 117 118 129 sslSocket.startHandshake(); 130 131 return sslSocket; 132 133 } 134 135 static private void doTunnelHandshake(Socket tunnel, String host, int port) 136 throws IOException 137 { 138 OutputStream out = tunnel.getOutputStream(); 139 String msg = "CONNECT " + host + ":" + port + " HTTP/1.0\n" 140 + "User-Agent: " 141 + sun.net.www.protocol.http.HttpURLConnection.userAgent 142 + "\r\n\r\n"; 143 byte b[]; 144 try { 145 149 b = msg.getBytes("ASCII7"); 150 } catch (UnsupportedEncodingException ignored) { 151 155 b = msg.getBytes(); 156 } 157 out.write(b); 158 out.flush(); 159 160 164 byte reply[] = new byte[200]; 165 int replyLen = 0; 166 int newlinesSeen = 0; 167 boolean headerDone = false; 168 169 InputStream in = tunnel.getInputStream(); 170 boolean error = false; 171 172 while (newlinesSeen < 2) { 173 int i = in.read(); 174 if (i < 0) { 175 throw new IOException("Unexpected EOF from proxy"); 176 } 177 if (i == '\n') { 178 headerDone = true; 179 ++newlinesSeen; 180 } else if (i != '\r') { 181 newlinesSeen = 0; 182 if (!headerDone && replyLen < reply.length) { 183 reply[replyLen++] = (byte) i; 184 } 185 } 186 } 187 188 193 String replyStr; 194 try { 195 replyStr = new String (reply, 0, replyLen, "ASCII7"); 196 } catch (UnsupportedEncodingException ignored) { 197 replyStr = new String (reply, 0, replyLen); 198 } 199 200 StringTokenizer st = new StringTokenizer(replyStr); 202 st.nextToken(); if (!st.nextToken().startsWith("200")) { 204 throw new IOException("Unable to tunnel through " 205 + tunnelHost + ":" + tunnelPort 206 + ". Proxy returns \"" + replyStr + "\""); 207 } 208 209 210 } 211 } 212 | Popular Tags |