Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/sun/net/NetworkClient.java
38829 views
/*1* Copyright (c) 1994, 2013, 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*/41public class NetworkClient {42/* Default value of read timeout, if not specified (infinity) */43public static final int DEFAULT_READ_TIMEOUT = -1;4445/* Default value of connect timeout, if not specified (infinity) */46public static final int DEFAULT_CONNECT_TIMEOUT = -1;4748protected Proxy proxy = Proxy.NO_PROXY;49/** Socket for communicating with server. */50protected Socket serverSocket = null;5152/** Stream for printing to the server. */53public PrintStream serverOutput;5455/** Buffered stream for reading replies from server. */56public InputStream serverInput;5758protected static int defaultSoTimeout;59protected static int defaultConnectTimeout;6061protected int readTimeout = DEFAULT_READ_TIMEOUT;62protected int connectTimeout = DEFAULT_CONNECT_TIMEOUT;63/* Name of encoding to use for output */64protected static String encoding;6566static {67final int vals[] = {0, 0};68final String encs[] = { null };6970AccessController.doPrivileged(71new PrivilegedAction<Void>() {72public Void run() {73vals[0] = Integer.getInteger("sun.net.client.defaultReadTimeout", 0).intValue();74vals[1] = Integer.getInteger("sun.net.client.defaultConnectTimeout", 0).intValue();75encs[0] = System.getProperty("file.encoding", "ISO8859_1");76return null;77}78});79if (vals[0] != 0) {80defaultSoTimeout = vals[0];81}82if (vals[1] != 0) {83defaultConnectTimeout = vals[1];84}8586encoding = encs[0];87try {88if (!isASCIISuperset (encoding)) {89encoding = "ISO8859_1";90}91} catch (Exception e) {92encoding = "ISO8859_1";93}94}959697/**98* Test the named character encoding to verify that it converts ASCII99* characters correctly. We have to use an ASCII based encoding, or else100* the NetworkClients will not work correctly in EBCDIC based systems.101* However, we cannot just use ASCII or ISO8859_1 universally, because in102* Asian locales, non-ASCII characters may be embedded in otherwise103* ASCII based protocols (eg. HTTP). The specifications (RFC2616, 2398)104* are a little ambiguous in this matter. For instance, RFC2398 [part 2.1]105* says that the HTTP request URI should be escaped using a defined106* mechanism, but there is no way to specify in the escaped string what107* the original character set is. It is not correct to assume that108* UTF-8 is always used (as in URLs in HTML 4.0). For this reason,109* until the specifications are updated to deal with this issue more110* comprehensively, and more importantly, HTTP servers are known to111* support these mechanisms, we will maintain the current behavior112* where it is possible to send non-ASCII characters in their original113* unescaped form.114*/115private static boolean isASCIISuperset (String encoding) throws Exception {116String chkS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"+117"abcdefghijklmnopqrstuvwxyz-_.!~*'();/?:@&=+$,";118119// Expected byte sequence for string above120byte[] chkB = { 48,49,50,51,52,53,54,55,56,57,65,66,67,68,69,70,71,72,12173,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,97,98,99,122100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,123115,116,117,118,119,120,121,122,45,95,46,33,126,42,39,40,41,59,12447,63,58,64,38,61,43,36,44};125126byte[] b = chkS.getBytes (encoding);127return Arrays.equals (b, chkB);128}129130/** Open a connection to the server. */131public void openServer(String server, int port)132throws IOException, UnknownHostException {133if (serverSocket != null)134closeServer();135serverSocket = doConnect (server, port);136try {137serverOutput = new PrintStream(new BufferedOutputStream(138serverSocket.getOutputStream()),139true, encoding);140} catch (UnsupportedEncodingException e) {141throw new InternalError(encoding +"encoding not found", e);142}143serverInput = new BufferedInputStream(serverSocket.getInputStream());144}145146/**147* Return a socket connected to the server, with any148* appropriate options pre-established149*/150protected Socket doConnect (String server, int port)151throws IOException, UnknownHostException {152Socket s;153if (proxy != null) {154if (proxy.type() == Proxy.Type.SOCKS) {155s = AccessController.doPrivileged(156new PrivilegedAction<Socket>() {157public Socket run() {158return new Socket(proxy);159}});160} else if (proxy.type() == Proxy.Type.DIRECT) {161s = createSocket();162} else {163// Still connecting through a proxy164// server & port will be the proxy address and port165s = new Socket(Proxy.NO_PROXY);166}167} else168s = createSocket();169// Instance specific timeouts do have priority, that means170// connectTimeout & readTimeout (-1 means not set)171// Then global default timeouts172// Then no timeout.173if (connectTimeout >= 0) {174s.connect(new InetSocketAddress(server, port), connectTimeout);175} else {176if (defaultConnectTimeout > 0) {177s.connect(new InetSocketAddress(server, port), defaultConnectTimeout);178} else {179s.connect(new InetSocketAddress(server, port));180}181}182if (readTimeout >= 0)183s.setSoTimeout(readTimeout);184else if (defaultSoTimeout > 0) {185s.setSoTimeout(defaultSoTimeout);186}187return s;188}189190/**191* The following method, createSocket, is provided to allow the192* https client to override it so that it may use its socket factory193* to create the socket.194*/195protected Socket createSocket() throws IOException {196return new java.net.Socket();197}198199protected InetAddress getLocalAddress() throws IOException {200if (serverSocket == null)201throw new IOException("not connected");202return AccessController.doPrivileged(203new PrivilegedAction<InetAddress>() {204public InetAddress run() {205return serverSocket.getLocalAddress();206207}208});209}210211/** Close an open connection to the server. */212public void closeServer() throws IOException {213if (! serverIsOpen()) {214return;215}216serverSocket.close();217serverSocket = null;218serverInput = null;219serverOutput = null;220}221222/** Return server connection status */223public boolean serverIsOpen() {224return serverSocket != null;225}226227/** Create connection with host <i>host</i> on port <i>port</i> */228public NetworkClient(String host, int port) throws IOException {229openServer(host, port);230}231232public NetworkClient() {}233234public void setConnectTimeout(int timeout) {235connectTimeout = timeout;236}237238public int getConnectTimeout() {239return connectTimeout;240}241242/**243* Sets the read timeout.244*245* Note: Public URLConnection (and protocol specific implementations)246* protect against negative timeout values being set. This implementation,247* and protocol specific implementations, use -1 to represent the default248* read timeout.249*250* This method may be invoked with the default timeout value when the251* protocol handler is trying to reset the timeout after doing a252* potentially blocking internal operation, e.g. cleaning up unread253* response data, buffering error stream response data, etc254*/255public void setReadTimeout(int timeout) {256if (timeout == DEFAULT_READ_TIMEOUT)257timeout = defaultSoTimeout;258259if (serverSocket != null && timeout >= 0) {260try {261serverSocket.setSoTimeout(timeout);262} catch(IOException e) {263// We tried...264}265}266readTimeout = timeout;267}268269public int getReadTimeout() {270return readTimeout;271}272}273274275