Path: blob/master/src/java.base/share/classes/sun/net/NetworkClient.java
41152 views
/*1* Copyright (c) 1994, 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*/24package sun.net;2526import java.io.*;27import java.net.Socket;28import java.net.InetAddress;29import java.net.InetSocketAddress;30import java.net.UnknownHostException;31import java.net.Proxy;32import java.util.Arrays;33import java.security.AccessController;34import java.security.PrivilegedAction;3536/**37* This is the base class for network clients.38*39* @author Jonathan Payne40*/41@SuppressWarnings("removal")42public class NetworkClient {43/* Default value of read timeout, if not specified (infinity) */44public static final int DEFAULT_READ_TIMEOUT = -1;4546/* Default value of connect timeout, if not specified (infinity) */47public static final int DEFAULT_CONNECT_TIMEOUT = -1;4849protected Proxy proxy = Proxy.NO_PROXY;50/** Socket for communicating with server. */51protected Socket serverSocket = null;5253/** Stream for printing to the server. */54public PrintStream serverOutput;5556/** Buffered stream for reading replies from server. */57public InputStream serverInput;5859protected static int defaultSoTimeout;60protected static int defaultConnectTimeout;6162protected int readTimeout = DEFAULT_READ_TIMEOUT;63protected int connectTimeout = DEFAULT_CONNECT_TIMEOUT;64/* Name of encoding to use for output */65protected static String encoding;6667static {68final int vals[] = {0, 0};69final String encs[] = { null };7071AccessController.doPrivileged(72new PrivilegedAction<>() {73public Void run() {74vals[0] = Integer.getInteger("sun.net.client.defaultReadTimeout", 0).intValue();75vals[1] = Integer.getInteger("sun.net.client.defaultConnectTimeout", 0).intValue();76encs[0] = System.getProperty("file.encoding", "ISO8859_1");77return null;78}79});80if (vals[0] != 0) {81defaultSoTimeout = vals[0];82}83if (vals[1] != 0) {84defaultConnectTimeout = vals[1];85}8687encoding = encs[0];88try {89if (!isASCIISuperset (encoding)) {90encoding = "ISO8859_1";91}92} catch (Exception e) {93encoding = "ISO8859_1";94}95}969798/**99* Test the named character encoding to verify that it converts ASCII100* characters correctly. We have to use an ASCII based encoding, or else101* the NetworkClients will not work correctly in EBCDIC based systems.102* However, we cannot just use ASCII or ISO8859_1 universally, because in103* Asian locales, non-ASCII characters may be embedded in otherwise104* ASCII based protocols (e.g. HTTP). The specifications (RFC2616, 2398)105* are a little ambiguous in this matter. For instance, RFC2398 [part 2.1]106* says that the HTTP request URI should be escaped using a defined107* mechanism, but there is no way to specify in the escaped string what108* the original character set is. It is not correct to assume that109* UTF-8 is always used (as in URLs in HTML 4.0). For this reason,110* until the specifications are updated to deal with this issue more111* comprehensively, and more importantly, HTTP servers are known to112* support these mechanisms, we will maintain the current behavior113* where it is possible to send non-ASCII characters in their original114* unescaped form.115*/116private static boolean isASCIISuperset (String encoding) throws Exception {117String chkS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"+118"abcdefghijklmnopqrstuvwxyz-_.!~*'();/?:@&=+$,";119120// Expected byte sequence for string above121byte[] chkB = { 48,49,50,51,52,53,54,55,56,57,65,66,67,68,69,70,71,72,12273,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,97,98,99,123100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,124115,116,117,118,119,120,121,122,45,95,46,33,126,42,39,40,41,59,12547,63,58,64,38,61,43,36,44};126127byte[] b = chkS.getBytes (encoding);128return Arrays.equals (b, chkB);129}130131/** Open a connection to the server. */132public void openServer(String server, int port)133throws IOException, UnknownHostException {134if (serverSocket != null)135closeServer();136serverSocket = doConnect (server, port);137try {138serverOutput = new PrintStream(new BufferedOutputStream(139serverSocket.getOutputStream()),140true, encoding);141} catch (UnsupportedEncodingException e) {142throw new InternalError(encoding +"encoding not found", e);143}144serverInput = new BufferedInputStream(serverSocket.getInputStream());145}146147/**148* Return a socket connected to the server, with any149* appropriate options pre-established150*/151protected Socket doConnect (String server, int port)152throws IOException, UnknownHostException {153Socket s;154if (proxy != null) {155if (proxy.type() == Proxy.Type.SOCKS) {156s = AccessController.doPrivileged(157new PrivilegedAction<>() {158public Socket run() {159return new Socket(proxy);160}});161} else if (proxy.type() == Proxy.Type.DIRECT) {162s = createSocket();163} else {164// Still connecting through a proxy165// server & port will be the proxy address and port166s = new Socket(Proxy.NO_PROXY);167}168} else {169s = createSocket();170}171172// Instance specific timeouts do have priority, that means173// connectTimeout & readTimeout (-1 means not set)174// Then global default timeouts175// Then no timeout.176if (connectTimeout >= 0) {177s.connect(new InetSocketAddress(server, port), connectTimeout);178} else {179if (defaultConnectTimeout > 0) {180s.connect(new InetSocketAddress(server, port), defaultConnectTimeout);181} else {182s.connect(new InetSocketAddress(server, port));183}184}185if (readTimeout >= 0)186s.setSoTimeout(readTimeout);187else if (defaultSoTimeout > 0) {188s.setSoTimeout(defaultSoTimeout);189}190return s;191}192193/**194* The following method, createSocket, is provided to allow the195* https client to override it so that it may use its socket factory196* to create the socket.197*/198protected Socket createSocket() throws IOException {199return new java.net.Socket(Proxy.NO_PROXY); // direct connection200}201202protected InetAddress getLocalAddress() throws IOException {203if (serverSocket == null)204throw new IOException("not connected");205return AccessController.doPrivileged(206new PrivilegedAction<>() {207public InetAddress run() {208return serverSocket.getLocalAddress();209210}211});212}213214/** Close an open connection to the server. */215public void closeServer() throws IOException {216if (! serverIsOpen()) {217return;218}219serverSocket.close();220serverSocket = null;221serverInput = null;222serverOutput = null;223}224225/** Return server connection status */226public boolean serverIsOpen() {227return serverSocket != null;228}229230/** Create connection with host <i>host</i> on port <i>port</i> */231public NetworkClient(String host, int port) throws IOException {232openServer(host, port);233}234235public NetworkClient() {}236237public void setConnectTimeout(int timeout) {238connectTimeout = timeout;239}240241public int getConnectTimeout() {242return connectTimeout;243}244245/**246* Sets the read timeout.247*248* Note: Public URLConnection (and protocol specific implementations)249* protect against negative timeout values being set. This implementation,250* and protocol specific implementations, use -1 to represent the default251* read timeout.252*253* This method may be invoked with the default timeout value when the254* protocol handler is trying to reset the timeout after doing a255* potentially blocking internal operation, e.g. cleaning up unread256* response data, buffering error stream response data, etc257*/258public void setReadTimeout(int timeout) {259if (timeout == DEFAULT_READ_TIMEOUT)260timeout = defaultSoTimeout;261262if (serverSocket != null && timeout >= 0) {263try {264serverSocket.setSoTimeout(timeout);265} catch(IOException e) {266// We tried...267}268}269readTimeout = timeout;270}271272public int getReadTimeout() {273return readTimeout;274}275}276277278