1 /*
   2  * Copyright (c) 1994, 2008, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 package sun.net;
  26 
  27 import java.io.*;
  28 import java.net.Socket;
  29 import java.net.InetAddress;
  30 import java.net.InetSocketAddress;
  31 import java.net.UnknownHostException;
  32 import java.net.Proxy;
  33 import java.util.Arrays;
  34 import java.security.AccessController;
  35 import java.security.PrivilegedAction;
  36 
  37 /**
  38  * This is the base class for network clients.
  39  *
  40  * @author      Jonathan Payne
  41  */
  42 public class NetworkClient {






  43     protected Proxy     proxy = Proxy.NO_PROXY;
  44     /** Socket for communicating with server. */
  45     protected Socket    serverSocket = null;
  46 
  47     /** Stream for printing to the server. */
  48     public PrintStream  serverOutput;
  49 
  50     /** Buffered stream for reading replies from server. */
  51     public InputStream  serverInput;
  52 
  53     protected static int defaultSoTimeout;
  54     protected static int defaultConnectTimeout;
  55 
  56     protected int readTimeout = -1;
  57     protected int connectTimeout = -1;
  58     /* Name of encoding to use for output */
  59     protected static String encoding;
  60 
  61     static {
  62         final int vals[] = {0, 0};
  63         final String encs[] = { null };
  64 
  65         AccessController.doPrivileged(
  66                 new PrivilegedAction<Void>() {
  67                     public Void run() {
  68                         vals[0] = Integer.getInteger("sun.net.client.defaultReadTimeout", 0).intValue();
  69                         vals[1] = Integer.getInteger("sun.net.client.defaultConnectTimeout", 0).intValue();
  70                         encs[0] = System.getProperty("file.encoding", "ISO8859_1");
  71                         return null;
  72             }
  73         });
  74         if (vals[0] == 0)
  75             defaultSoTimeout = -1;
  76         else
  77             defaultSoTimeout = vals[0];
  78 
  79         if (vals[1] == 0)
  80             defaultConnectTimeout = -1;
  81         else
  82             defaultConnectTimeout = vals[1];

  83 
  84 
  85         encoding = encs[0];
  86         try {
  87             if (!isASCIISuperset (encoding)) {
  88                 encoding = "ISO8859_1";
  89             }
  90         } catch (Exception e) {
  91             encoding = "ISO8859_1";
  92         }
  93     }
  94 
  95 
  96     /**
  97      * Test the named character encoding to verify that it converts ASCII
  98      * characters correctly. We have to use an ASCII based encoding, or else
  99      * the NetworkClients will not work correctly in EBCDIC based systems.
 100      * However, we cannot just use ASCII or ISO8859_1 universally, because in
 101      * Asian locales, non-ASCII characters may be embedded in otherwise
 102      * ASCII based protocols (eg. HTTP). The specifications (RFC2616, 2398)
 103      * are a little ambiguous in this matter. For instance, RFC2398 [part 2.1]
 104      * says that the HTTP request URI should be escaped using a defined
 105      * mechanism, but there is no way to specify in the escaped string what
 106      * the original character set is. It is not correct to assume that
 107      * UTF-8 is always used (as in URLs in HTML 4.0).  For this reason,
 108      * until the specifications are updated to deal with this issue more
 109      * comprehensively, and more importantly, HTTP servers are known to
 110      * support these mechanisms, we will maintain the current behavior
 111      * where it is possible to send non-ASCII characters in their original
 112      * unescaped form.
 113      */
 114     private static boolean isASCIISuperset (String encoding) throws Exception {
 115         String chkS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"+
 116                         "abcdefghijklmnopqrstuvwxyz-_.!~*'();/?:@&=+$,";
 117 
 118         // Expected byte sequence for string above
 119         byte[] chkB = { 48,49,50,51,52,53,54,55,56,57,65,66,67,68,69,70,71,72,
 120                 73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,97,98,99,
 121                 100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,
 122                 115,116,117,118,119,120,121,122,45,95,46,33,126,42,39,40,41,59,
 123                 47,63,58,64,38,61,43,36,44};
 124 
 125         byte[] b = chkS.getBytes (encoding);
 126         return Arrays.equals (b, chkB);
 127     }
 128 
 129     /** Open a connection to the server. */
 130     public void openServer(String server, int port)
 131         throws IOException, UnknownHostException {
 132         if (serverSocket != null)
 133             closeServer();
 134         serverSocket = doConnect (server, port);
 135         try {
 136             serverOutput = new PrintStream(new BufferedOutputStream(
 137                                         serverSocket.getOutputStream()),
 138                                         true, encoding);
 139         } catch (UnsupportedEncodingException e) {
 140             throw new InternalError(encoding +"encoding not found");
 141         }
 142         serverInput = new BufferedInputStream(serverSocket.getInputStream());
 143     }
 144 
 145     /**
 146      * Return a socket connected to the server, with any
 147      * appropriate options pre-established
 148      */
 149     protected Socket doConnect (String server, int port)
 150     throws IOException, UnknownHostException {
 151         Socket s;
 152         if (proxy != null) {
 153             if (proxy.type() == Proxy.Type.SOCKS) {
 154                 s = AccessController.doPrivileged(
 155                     new PrivilegedAction<Socket>() {
 156                         public Socket run() {
 157                                        return new Socket(proxy);
 158                                    }});
 159             } else if (proxy.type() == Proxy.Type.DIRECT) {
 160                 s = createSocket();
 161             } else {
 162                 // Still connecting through a proxy
 163                 // server & port will be the proxy address and port
 164                 s = new Socket(Proxy.NO_PROXY);
 165             }
 166         } else
 167             s = createSocket();
 168         // Instance specific timeouts do have priority, that means
 169         // connectTimeout & readTimeout (-1 means not set)
 170         // Then global default timeouts
 171         // Then no timeout.
 172         if (connectTimeout >= 0) {
 173             s.connect(new InetSocketAddress(server, port), connectTimeout);
 174         } else {
 175             if (defaultConnectTimeout > 0) {
 176                 s.connect(new InetSocketAddress(server, port), defaultConnectTimeout);
 177             } else {
 178                 s.connect(new InetSocketAddress(server, port));
 179             }
 180         }
 181         if (readTimeout >= 0)
 182             s.setSoTimeout(readTimeout);
 183         else if (defaultSoTimeout > 0) {
 184             s.setSoTimeout(defaultSoTimeout);
 185         }
 186         return s;
 187     }
 188 
 189     /**
 190      * The following method, createSocket, is provided to allow the
 191      * https client to override it so that it may use its socket factory
 192      * to create the socket.
 193      */
 194     protected Socket createSocket() throws IOException {
 195         return new java.net.Socket();
 196     }
 197 
 198     protected InetAddress getLocalAddress() throws IOException {
 199         if (serverSocket == null)
 200             throw new IOException("not connected");
 201         return serverSocket.getLocalAddress();
 202     }
 203 
 204     /** Close an open connection to the server. */
 205     public void closeServer() throws IOException {
 206         if (! serverIsOpen()) {
 207             return;
 208         }
 209         serverSocket.close();
 210         serverSocket = null;
 211         serverInput = null;
 212         serverOutput = null;
 213     }
 214 
 215     /** Return server connection status */
 216     public boolean serverIsOpen() {
 217         return serverSocket != null;
 218     }
 219 
 220     /** Create connection with host <i>host</i> on port <i>port</i> */
 221     public NetworkClient(String host, int port) throws IOException {
 222         openServer(host, port);
 223     }
 224 
 225     public NetworkClient() {}
 226 
 227     public void setConnectTimeout(int timeout) {
 228         connectTimeout = timeout;
 229     }
 230 
 231     public int getConnectTimeout() {
 232         return connectTimeout;
 233     }
 234 













 235     public void setReadTimeout(int timeout) {



 236         if (serverSocket != null && timeout >= 0) {
 237             try {
 238                 serverSocket.setSoTimeout(timeout);
 239             } catch(IOException e) {
 240                 // We tried...
 241             }
 242         }
 243         readTimeout = timeout;
 244     }
 245 
 246     public int getReadTimeout() {
 247         return readTimeout;
 248     }
 249 }
--- EOF ---