001: /*
002: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
003: *
004: * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
005: *
006: * The contents of this file are subject to the terms of either the GNU
007: * General Public License Version 2 only ("GPL") or the Common Development
008: * and Distribution License("CDDL") (collectively, the "License"). You
009: * may not use this file except in compliance with the License. You can obtain
010: * a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html
011: * or glassfish/bootstrap/legal/LICENSE.txt. See the License for the specific
012: * language governing permissions and limitations under the License.
013: *
014: * When distributing the software, include this License Header Notice in each
015: * file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
016: * Sun designates this particular file as subject to the "Classpath" exception
017: * as provided by Sun in the GPL Version 2 section of the License file that
018: * accompanied this code. If applicable, add the following below the License
019: * Header, with the fields enclosed by brackets [] replaced by your own
020: * identifying information: "Portions Copyrighted [year]
021: * [name of copyright owner]"
022: *
023: * Contributor(s):
024: *
025: * If you wish your version of this file to be governed by only the CDDL or
026: * only the GPL Version 2, indicate your decision by adding "[Contributor]
027: * elects to include this software in this distribution under the [CDDL or GPL
028: * Version 2] license." If you don't indicate a single choice of license, a
029: * recipient has the option to distribute your version of this file under
030: * either the CDDL, the GPL Version 2 or to extend the choice of license to
031: * its licensees as provided above. However, if you add GPL Version 2 code
032: * and therefore, elected the GPL Version 2 license, then the option applies
033: * only if the new code is made subject to such option by the copyright
034: * holder.
035: */
036:
037: /*
038: * @(#)SocketFetcher.java 1.20 07/05/04
039: */
040:
041: package com.sun.mail.util;
042:
043: import java.security.*;
044: import java.net.*;
045: import java.io.*;
046: import java.lang.reflect.*;
047: import java.util.*;
048: import javax.net.*;
049: import javax.net.ssl.*;
050:
051: /**
052: * This class is used to get Sockets. Depending on the arguments passed
053: * it will either return a plain java.net.Socket or dynamically load
054: * the SocketFactory class specified in the classname param and return
055: * a socket created by that SocketFactory.
056: *
057: * @author Max Spivak
058: * @author Bill Shannon
059: */
060: public class SocketFetcher {
061:
062: // No one should instantiate this class.
063: private SocketFetcher() {
064: }
065:
066: /**
067: * This method returns a Socket. Properties control the use of
068: * socket factories and other socket characteristics. The properties
069: * used are: <p>
070: * <ul>
071: * <li> <i>prefix</i>.socketFactory.class
072: * <li> <i>prefix</i>.socketFactory.fallback
073: * <li> <i>prefix</i>.socketFactory.port
074: * <li> <i>prefix</i>.timeout
075: * <li> <i>prefix</i>.connectiontimeout
076: * <li> <i>prefix</i>.localaddress
077: * <li> <i>prefix</i>.localport
078: * </ul> <p>
079: * If the socketFactory.class property isn't set, the socket
080: * returned is an instance of java.net.Socket connected to the
081: * given host and port. If the socketFactory.class property is set,
082: * it is expected to contain a fully qualified classname of a
083: * javax.net.SocketFactory subclass. In this case, the class is
084: * dynamically instantiated and a socket created by that
085: * SocketFactory is returned. <p>
086: *
087: * If the socketFactory.fallback property is set to false, don't
088: * fall back to using regular sockets if the socket factory fails. <p>
089: *
090: * The socketFactory.port specifies a port to use when connecting
091: * through the socket factory. If unset, the port argument will be
092: * used. <p>
093: *
094: * If the connectiontimeout property is set, we use a separate thread
095: * to make the connection so that we can timeout that connection attempt.
096: * <p>
097: *
098: * If the timeout property is set, it is used to set the socket timeout.
099: * <p>
100: *
101: * If the localaddress property is set, it's used as the local address
102: * to bind to. If the localport property is also set, it's used as the
103: * local port number to bind to.
104: *
105: * @param host The host to connect to
106: * @param port The port to connect to at the host
107: * @param props Properties object containing socket properties
108: * @param prefix Property name prefix, e.g., "mail.imap"
109: * @param useSSL use the SSL socket factory as the default
110: */
111: public static Socket getSocket(String host, int port,
112: Properties props, String prefix, boolean useSSL)
113: throws IOException {
114:
115: if (prefix == null)
116: prefix = "socket";
117: if (props == null)
118: props = new Properties(); // empty
119: String s = props.getProperty(prefix + ".connectiontimeout",
120: null);
121: int cto = -1;
122: if (s != null) {
123: try {
124: cto = Integer.parseInt(s);
125: } catch (NumberFormatException nfex) {
126: }
127: }
128:
129: Socket socket = null;
130: String timeout = props.getProperty(prefix + ".timeout", null);
131: String localaddrstr = props.getProperty(prefix
132: + ".localaddress", null);
133: InetAddress localaddr = null;
134: if (localaddrstr != null)
135: localaddr = InetAddress.getByName(localaddrstr);
136: String localportstr = props.getProperty(prefix + ".localport",
137: null);
138: int localport = 0;
139: if (localportstr != null) {
140: try {
141: localport = Integer.parseInt(localportstr);
142: } catch (NumberFormatException nfex) {
143: }
144: }
145:
146: boolean fb = false;
147: String fallback = props.getProperty(prefix
148: + ".socketFactory.fallback", null);
149: fb = fallback == null || (!fallback.equalsIgnoreCase("false"));
150:
151: String sfClass = props.getProperty(prefix
152: + ".socketFactory.class", null);
153: int sfPort = -1;
154: try {
155: SocketFactory sf = getSocketFactory(sfClass);
156: if (sf != null) {
157: String sfPortStr = props.getProperty(prefix
158: + ".socketFactory.port", null);
159: if (sfPortStr != null) {
160: try {
161: sfPort = Integer.parseInt(sfPortStr);
162: } catch (NumberFormatException nfex) {
163: }
164: }
165:
166: // if port passed in via property isn't valid, use param
167: if (sfPort == -1)
168: sfPort = port;
169: socket = createSocket(localaddr, localport, host,
170: sfPort, cto, sf, useSSL);
171: }
172: } catch (SocketTimeoutException sex) {
173: throw sex;
174: } catch (Exception ex) {
175: if (!fb) {
176: if (ex instanceof InvocationTargetException) {
177: Throwable t = ((InvocationTargetException) ex)
178: .getTargetException();
179: if (t instanceof Exception)
180: ex = (Exception) t;
181: }
182: if (ex instanceof IOException)
183: throw (IOException) ex;
184: IOException ioex = new IOException(
185: "Couldn't connect using \"" + sfClass
186: + "\" socket factory to host, port: "
187: + host + ", " + sfPort
188: + "; Exception: " + ex);
189: ioex.initCause(ex);
190: throw ioex;
191: }
192: }
193:
194: if (socket == null)
195: socket = createSocket(localaddr, localport, host, port,
196: cto, null, useSSL);
197:
198: int to = -1;
199: if (timeout != null) {
200: try {
201: to = Integer.parseInt(timeout);
202: } catch (NumberFormatException nfex) {
203: }
204: }
205: if (to >= 0)
206: socket.setSoTimeout(to);
207:
208: configureSSLSocket(socket, props, prefix);
209: return socket;
210: }
211:
212: public static Socket getSocket(String host, int port,
213: Properties props, String prefix) throws IOException {
214: return getSocket(host, port, props, prefix, false);
215: }
216:
217: /**
218: * Create a socket with the given local address and connected to
219: * the given host and port. Use the specified connection timeout.
220: * If a socket factory is specified, use it. Otherwise, use the
221: * SSLSocketFactory if useSSL is true.
222: */
223: private static Socket createSocket(InetAddress localaddr,
224: int localport, String host, int port, int cto,
225: SocketFactory sf, boolean useSSL) throws IOException {
226: Socket socket;
227:
228: if (sf != null)
229: socket = sf.createSocket();
230: else if (useSSL)
231: socket = SSLSocketFactory.getDefault().createSocket();
232: else
233: socket = new Socket();
234: if (localaddr != null)
235: socket.bind(new InetSocketAddress(localaddr, localport));
236: if (cto >= 0)
237: socket.connect(new InetSocketAddress(host, port), cto);
238: else
239: socket.connect(new InetSocketAddress(host, port));
240: return socket;
241: }
242:
243: /**
244: * Return a socket factory of the specified class.
245: */
246: private static SocketFactory getSocketFactory(String sfClass)
247: throws ClassNotFoundException, NoSuchMethodException,
248: IllegalAccessException, InvocationTargetException {
249: if (sfClass == null || sfClass.length() == 0)
250: return null;
251:
252: // dynamically load the class
253:
254: ClassLoader cl = getContextClassLoader();
255: Class clsSockFact = null;
256: if (cl != null) {
257: try {
258: clsSockFact = cl.loadClass(sfClass);
259: } catch (ClassNotFoundException cex) {
260: }
261: }
262: if (clsSockFact == null)
263: clsSockFact = Class.forName(sfClass);
264: // get & invoke the getDefault() method
265: Method mthGetDefault = clsSockFact.getMethod("getDefault",
266: new Class[] {});
267: SocketFactory sf = (SocketFactory) mthGetDefault.invoke(
268: new Object(), new Object[] {});
269: return sf;
270: }
271:
272: /**
273: * Start TLS on an existing socket.
274: * Supports the "STARTTLS" command in many protocols.
275: * This version for compatibility possible third party code
276: * that might've used this API even though it shouldn't.
277: */
278: public static Socket startTLS(Socket socket) throws IOException {
279: return startTLS(socket, new Properties(), "socket");
280: }
281:
282: /**
283: * Start TLS on an existing socket.
284: * Supports the "STARTTLS" command in many protocols.
285: */
286: public static Socket startTLS(Socket socket, Properties props,
287: String prefix) throws IOException {
288: InetAddress a = socket.getInetAddress();
289: String host = a.getHostName();
290: int port = socket.getPort();
291: //System.out.println("SocketFetcher: startTLS host " + host + ", port " + port);
292:
293: try {
294: SSLSocketFactory ssf;
295: String sfClass = props.getProperty(prefix
296: + ".socketFactory.class", null);
297: SocketFactory sf = getSocketFactory(sfClass);
298: if (sf != null && sf instanceof SSLSocketFactory)
299: ssf = (SSLSocketFactory) sf;
300: else
301: ssf = (SSLSocketFactory) SSLSocketFactory.getDefault();
302: socket = ssf.createSocket(socket, host, port, true);
303: configureSSLSocket(socket, props, prefix);
304: } catch (Exception ex) {
305: if (ex instanceof InvocationTargetException) {
306: Throwable t = ((InvocationTargetException) ex)
307: .getTargetException();
308: if (t instanceof Exception)
309: ex = (Exception) t;
310: }
311: if (ex instanceof IOException)
312: throw (IOException) ex;
313: // wrap anything else before sending it on
314: IOException ioex = new IOException(
315: "Exception in startTLS: host " + host + ", port "
316: + port + "; Exception: " + ex);
317: ioex.initCause(ex);
318: throw ioex;
319: }
320: return socket;
321: }
322:
323: /**
324: * Configure the SSL options for the socket (if it's an SSL socket),
325: * based on the mail.<protocol>.ssl.protocols and
326: * mail.<protocol>.ssl.ciphersuites properties.
327: */
328: private static void configureSSLSocket(Socket socket,
329: Properties props, String prefix) {
330: if (!(socket instanceof SSLSocket))
331: return;
332: SSLSocket sslsocket = (SSLSocket) socket;
333:
334: String protocols = props.getProperty(prefix + ".ssl.protocols",
335: null);
336: if (protocols != null)
337: sslsocket.setEnabledProtocols(stringArray(protocols));
338: else {
339: /*
340: * At least the UW IMAP server insists on only the TLSv1
341: * protocol for STARTTLS, and won't accept the old SSLv2
342: * or SSLv3 protocols. Here we enable only the TLSv1
343: * protocol. XXX - this should probably be parameterized.
344: */
345: sslsocket.setEnabledProtocols(new String[] { "TLSv1" });
346: }
347: String ciphers = props.getProperty(
348: prefix + ".ssl.ciphersuites", null);
349: if (ciphers != null)
350: sslsocket.setEnabledCipherSuites(stringArray(ciphers));
351: /*
352: System.out.println("SSL protocols after " +
353: Arrays.asList(sslsocket.getEnabledProtocols()));
354: System.out.println("SSL ciphers after " +
355: Arrays.asList(sslsocket.getEnabledCipherSuites()));
356: */
357: }
358:
359: /**
360: * Parse a string into whitespace separated tokens
361: * and return the tokens in an array.
362: */
363: private static String[] stringArray(String s) {
364: StringTokenizer st = new StringTokenizer(s);
365: List tokens = new ArrayList();
366: while (st.hasMoreTokens())
367: tokens.add(st.nextToken());
368: return (String[]) tokens.toArray(new String[tokens.size()]);
369: }
370:
371: /**
372: * Convenience method to get our context class loader.
373: * Assert any privileges we might have and then call the
374: * Thread.getContextClassLoader method.
375: */
376: private static ClassLoader getContextClassLoader() {
377: return (ClassLoader) AccessController
378: .doPrivileged(new PrivilegedAction() {
379: public Object run() {
380: ClassLoader cl = null;
381: try {
382: cl = Thread.currentThread()
383: .getContextClassLoader();
384: } catch (SecurityException ex) {
385: }
386: return cl;
387: }
388: });
389: }
390: }
|