Path: blob/master/src/java.base/share/classes/java/net/HttpConnectSocketImpl.java
41152 views
/*1* Copyright (c) 2010, 2021, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package java.net;2627import java.io.IOException;28import java.lang.reflect.Field;29import java.lang.reflect.Method;30import java.util.HashMap;31import java.util.Map;32import java.util.Set;3334/**35* Basic SocketImpl that relies on the internal HTTP protocol handler36* implementation to perform the HTTP tunneling and authentication. Once37* connected, all socket operations delegate to a platform SocketImpl.38*39* @since 1.840*/4142/*package*/ @SuppressWarnings("removal") class HttpConnectSocketImpl extends DelegatingSocketImpl {4344private static final String httpURLClazzStr =45"sun.net.www.protocol.http.HttpURLConnection";46private static final String netClientClazzStr = "sun.net.NetworkClient";47private static final String doTunnelingStr = "doTunneling";48private static final Field httpField;49private static final Field serverSocketField;50private static final Method doTunneling;5152private final String server;53private final Socket socket;54private InetSocketAddress external_address;55private HashMap<Integer, Object> optionsMap = new HashMap<>();5657static {58try {59Class<?> httpClazz = Class.forName(httpURLClazzStr, true, null);60httpField = httpClazz.getDeclaredField("http");61doTunneling = httpClazz.getDeclaredMethod(doTunnelingStr);62Class<?> netClientClazz = Class.forName(netClientClazzStr, true, null);63serverSocketField = netClientClazz.getDeclaredField("serverSocket");6465java.security.AccessController.doPrivileged(66new java.security.PrivilegedAction<>() {67public Void run() {68httpField.setAccessible(true);69serverSocketField.setAccessible(true);70return null;71}72});73} catch (ReflectiveOperationException x) {74throw new InternalError("Should not reach here", x);75}76}7778HttpConnectSocketImpl(Proxy proxy, SocketImpl delegate, Socket socket) {79super(delegate);80this.socket = socket;81SocketAddress a = proxy.address();82if ( !(a instanceof InetSocketAddress ad) )83throw new IllegalArgumentException("Unsupported address type");8485server = ad.getHostString();86port = ad.getPort();87}8889@Override90protected void connect(String host, int port) throws IOException {91connect(new InetSocketAddress(host, port), 0);92}9394@Override95protected void connect(InetAddress address, int port) throws IOException {96connect(new InetSocketAddress(address, port), 0);97}9899@Override100protected void connect(SocketAddress endpoint, int timeout)101throws IOException102{103if (!(endpoint instanceof InetSocketAddress epoint))104throw new IllegalArgumentException("Unsupported address type");105String destHost = epoint.isUnresolved() ? epoint.getHostName()106: epoint.getAddress().getHostAddress();107final int destPort = epoint.getPort();108109SecurityManager security = System.getSecurityManager();110if (security != null)111security.checkConnect(destHost, destPort);112113if (destHost.contains(":"))114destHost = "[" + destHost + "]";115116// Connect to the HTTP proxy server117String urlString = "http://" + destHost + ":" + destPort;118Socket httpSocket = privilegedDoTunnel(urlString, timeout);119120// Success!121external_address = epoint;122123// close the original socket impl and release its descriptor124close();125126// update the Sockets impl to the impl from the http Socket127SocketImpl si = httpSocket.impl;128socket.setImpl(si);129130// best effort is made to try and reset options previously set131Set<Map.Entry<Integer,Object>> options = optionsMap.entrySet();132try {133for(Map.Entry<Integer,Object> entry : options) {134si.setOption(entry.getKey(), entry.getValue());135}136} catch (IOException x) { /* gulp! */ }137}138139140@Override141protected void listen(int backlog) {142throw new InternalError("should not get here");143}144145@Override146protected void accept(SocketImpl s) {147throw new InternalError("should not get here");148}149150@Override151void reset() {152throw new InternalError("should not get here");153}154155@Override156public void setOption(int opt, Object val) throws SocketException {157delegate.setOption(opt, val);158159if (external_address != null)160return; // we're connected, just return161162// store options so that they can be re-applied to the impl after connect163optionsMap.put(opt, val);164}165166private Socket privilegedDoTunnel(final String urlString,167final int timeout)168throws IOException169{170try {171return java.security.AccessController.doPrivileged(172new java.security.PrivilegedExceptionAction<>() {173public Socket run() throws IOException {174return doTunnel(urlString, timeout);175}176});177} catch (java.security.PrivilegedActionException pae) {178throw (IOException) pae.getException();179}180}181182private Socket doTunnel(String urlString, int connectTimeout)183throws IOException184{185Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(server, port));186URL destURL = new URL(urlString);187HttpURLConnection conn = (HttpURLConnection) destURL.openConnection(proxy);188conn.setConnectTimeout(connectTimeout);189int timeout = (int) getOption(SocketOptions.SO_TIMEOUT);190if (timeout > 0) {191conn.setReadTimeout(timeout);192}193conn.connect();194doTunneling(conn);195try {196Object httpClient = httpField.get(conn);197return (Socket) serverSocketField.get(httpClient);198} catch (IllegalAccessException x) {199throw new InternalError("Should not reach here", x);200}201}202203private void doTunneling(HttpURLConnection conn) throws IOException {204try {205doTunneling.invoke(conn);206} catch (ReflectiveOperationException x) {207Throwable cause = x.getCause();208if (cause instanceof IOException) {209throw (IOException) cause;210}211throw new InternalError("Should not reach here", x);212}213}214215@Override216protected InetAddress getInetAddress() {217if (external_address != null)218return external_address.getAddress();219else220return delegate.getInetAddress();221}222223@Override224protected int getPort() {225if (external_address != null)226return external_address.getPort();227else228return delegate.getPort();229}230}231232233