You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@synapse.apache.org by hi...@apache.org on 2013/07/12 00:18:48 UTC

svn commit: r1502386 [3/7] - in /synapse/trunk/java: modules/core/src/main/java/org/apache/synapse/ modules/core/src/main/java/org/apache/synapse/config/xml/ modules/core/src/main/java/org/apache/synapse/config/xml/endpoints/ modules/core/src/main/java...

Added: synapse/trunk/java/modules/transports/core/nhttp/src/main/java/org/apache/synapse/transport/passthru/HostnameVerifier.java
URL: http://svn.apache.org/viewvc/synapse/trunk/java/modules/transports/core/nhttp/src/main/java/org/apache/synapse/transport/passthru/HostnameVerifier.java?rev=1502386&view=auto
==============================================================================
--- synapse/trunk/java/modules/transports/core/nhttp/src/main/java/org/apache/synapse/transport/passthru/HostnameVerifier.java (added)
+++ synapse/trunk/java/modules/transports/core/nhttp/src/main/java/org/apache/synapse/transport/passthru/HostnameVerifier.java Thu Jul 11 22:18:46 2013
@@ -0,0 +1,577 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+
+
+/**
+ * ************************************************************************
+ * Copied from the not-yet-commons-ssl project at http://juliusdavies.ca/commons-ssl/
+ * As the above project is accepted into Apache and its JARs become available in
+ * the Maven 2 repos, we will have to switch to using the JARs instead
+ * ************************************************************************
+ * <p/>
+ * Interface for checking if a hostname matches the names stored inside the
+ * server's X.509 certificate.  Correctly implements
+ * javax.net.ssl.HostnameVerifier, but that interface is not recommended.
+ * Instead we added several check() methods that take SSLSocket,
+ * or X509Certificate, or ultimately (they all end up calling this one),
+ * String.  (It's easier to supply JUnit with Strings instead of mock
+ * SSLSession objects!)
+ * </p><p>Our check() methods throw exceptions if the name is
+ * invalid, whereas javax.net.ssl.HostnameVerifier just returns true/false.
+ * <p/>
+ * We provide the HostnameVerifier.DEFAULT, HostnameVerifier.STRICT, and
+ * HostnameVerifier.ALLOW_ALL implementations.  We also provide the more
+ * specialized HostnameVerifier.DEFAULT_AND_LOCALHOST, as well as
+ * HostnameVerifier.STRICT_IE6.  But feel free to define your own
+ * implementations!
+ * <p/>
+ * Inspired by Sebastian Hauer's original StrictSSLProtocolSocketFactory in the
+ * HttpClient "contrib" repository.
+ *
+ * @author Julius Davies
+ * @author <a href="mailto:hauer@psicode.com">Sebastian Hauer</a>
+ * @since 8-Dec-2006
+ */
+
+package org.apache.synapse.transport.passthru;
+
+import javax.net.ssl.SSLException;
+import javax.net.ssl.SSLPeerUnverifiedException;
+import javax.net.ssl.SSLSession;
+import javax.net.ssl.SSLSocket;
+import java.io.IOException;
+import java.io.InputStream;
+import java.security.cert.Certificate;
+import java.security.cert.CertificateParsingException;
+import java.security.cert.X509Certificate;
+import java.util.*;
+
+public interface HostnameVerifier extends javax.net.ssl.HostnameVerifier {
+
+    boolean verify(String host, SSLSession session);
+
+    void check(String host, SSLSocket ssl) throws IOException;
+
+    void check(String host, X509Certificate cert) throws SSLException;
+
+    void check(String host, String[] cns, String[] subjectAlts)
+        throws SSLException;
+
+    void check(String[] hosts, SSLSocket ssl) throws IOException;
+
+    void check(String[] hosts, X509Certificate cert) throws SSLException;
+
+
+    /**
+     * Checks to see if the supplied hostname matches any of the supplied CNs
+     * or "DNS" Subject-Alts.  Most implementations only look at the first CN,
+     * and ignore any additional CNs.  Most implementations do look at all of
+     * the "DNS" Subject-Alts. The CNs or Subject-Alts may contain wildcards
+     * according to RFC 2818.
+     *
+     * @param cns         CN fields, in order, as extracted from the X.509
+     *                    certificate.
+     * @param subjectAlts Subject-Alt fields of type 2 ("DNS"), as extracted
+     *                    from the X.509 certificate.
+     * @param hosts       The array of hostnames to verify.
+     * @throws SSLException If verification failed.
+     */
+    void check(String[] hosts, String[] cns, String[] subjectAlts)
+        throws SSLException;
+
+
+    /**
+     * The DEFAULT HostnameVerifier works the same way as Curl and Firefox.
+     * <p/>
+     * The hostname must match either the first CN, or any of the subject-alts.
+     * A wildcard can occur in the CN, and in any of the subject-alts.
+     * <p/>
+     * The only difference between DEFAULT and STRICT is that a wildcard (such
+     * as "*.foo.com") with DEFAULT matches all subdomains, including
+     * "a.b.foo.com".
+     */
+    public final static HostnameVerifier DEFAULT =
+        new AbstractVerifier() {
+            public final void check(final String[] hosts, final String[] cns,
+                final String[] subjectAlts)
+                throws SSLException {
+                check(hosts, cns, subjectAlts, false, false);
+            }
+
+            public final String toString() {
+                return "DEFAULT";
+            }
+        };
+
+
+    /**
+     * The DEFAULT_AND_LOCALHOST HostnameVerifier works like the DEFAULT
+     * one with one additional relaxation:  a host of "localhost",
+     * "localhost.localdomain", "127.0.0.1", "::1" will always pass, no matter
+     * what is in the server's certificate.
+     */
+    public final static HostnameVerifier DEFAULT_AND_LOCALHOST =
+        new AbstractVerifier() {
+            public final void check(final String[] hosts, final String[] cns,
+                final String[] subjectAlts)
+                throws SSLException {
+                if (isLocalhost(hosts[0])) {
+                    return;
+                }
+                check(hosts, cns, subjectAlts, false, false);
+            }
+
+            public final String toString() {
+                return "DEFAULT_AND_LOCALHOST";
+            }
+        };
+
+    /**
+     * The STRICT HostnameVerifier works the same way as java.net.URL in Sun
+     * Java 1.4, Sun Java 5, Sun Java 6.  It's also pretty close to IE6.
+     * This implementation appears to be compliant with RFC 2818 for dealing
+     * with wildcards.
+     * <p/>
+     * The hostname must match either the first CN, or any of the subject-alts.
+     * A wildcard can occur in the CN, and in any of the subject-alts.  The
+     * one divergence from IE6 is how we only check the first CN.  IE6 allows
+     * a match against any of the CNs present.  We decided to follow in
+     * Sun Java 1.4's footsteps and only check the first CN.
+     * <p/>
+     * A wildcard such as "*.foo.com" matches only subdomains in the same
+     * level, for example "a.foo.com".  It does not match deeper subdomains
+     * such as "a.b.foo.com".
+     */
+    public final static HostnameVerifier STRICT =
+        new AbstractVerifier() {
+            public final void check(final String[] host, final String[] cns,
+                final String[] subjectAlts)
+                throws SSLException {
+                check(host, cns, subjectAlts, false, true);
+            }
+
+            public final String toString() {
+                return "STRICT";
+            }
+        };
+
+    /**
+     * The STRICT_IE6 HostnameVerifier works just like the STRICT one with one
+     * minor variation:  the hostname can match against any of the CN's in the
+     * server's certificate, not just the first one.  This behaviour is
+     * identical to IE6's behaviour.
+     */
+    public final static HostnameVerifier STRICT_IE6 =
+        new AbstractVerifier() {
+            public final void check(final String[] host, final String[] cns,
+                final String[] subjectAlts)
+                throws SSLException {
+                check(host, cns, subjectAlts, true, true);
+            }
+
+            public final String toString() {
+                return "STRICT_IE6";
+            }
+        };
+
+    /**
+     * The ALLOW_ALL HostnameVerifier essentially turns hostname verification
+     * off.  This implementation is a no-op, and never throws the SSLException.
+     */
+    public final static HostnameVerifier ALLOW_ALL =
+        new AbstractVerifier() {
+            public final void check(final String[] host, final String[] cns,
+                final String[] subjectAlts) {
+                // Allow everything - so never blowup.
+            }
+
+            public final String toString() {
+                return "ALLOW_ALL";
+            }
+        };
+
+    abstract class AbstractVerifier implements HostnameVerifier {
+
+        /**
+         * This contains a list of 2nd-level domains that aren't allowed to
+         * have wildcards when combined with country-codes.
+         * For example: [*.co.uk].
+         * <p/>
+         * The [*.co.uk] problem is an interesting one.  Should we just hope
+         * that CA's would never foolishly allow such a certificate to happen?
+         * Looks like we're the only implementation guarding against this.
+         * Firefox, Curl, Sun Java 1.4, 5, 6 don't bother with this check.
+         */
+        private final static String[] BAD_COUNTRY_2LDS =
+            {"ac", "co", "com", "ed", "edu", "go", "gouv", "gov", "info",
+                "lg", "ne", "net", "or", "org"};
+
+        private final static String[] LOCALHOSTS = {"::1", "127.0.0.1",
+            "localhost",
+            "localhost.localdomain"};
+
+
+        static {
+            // Just in case developer forgot to manually sort the array.  :-)
+            Arrays.sort(BAD_COUNTRY_2LDS);
+            Arrays.sort(LOCALHOSTS);
+        }
+
+        protected AbstractVerifier() {
+        }
+
+        /**
+         * The javax.net.ssl.HostnameVerifier contract.
+         *
+         * @param host    'hostname' we used to create our socket
+         * @param session SSLSession with the remote server
+         * @return true if the host matched the one in the certificate.
+         */
+        public boolean verify(String host, SSLSession session) {
+            try {
+                Certificate[] certs = session.getPeerCertificates();
+                X509Certificate x509 = (X509Certificate) certs[0];
+                check(new String[]{host}, x509);
+                return true;
+            }
+            catch (SSLException e) {
+                return false;
+            }
+        }
+
+        public void check(String host, SSLSocket ssl) throws IOException {
+            check(new String[]{host}, ssl);
+        }
+
+        public void check(String host, X509Certificate cert)
+            throws SSLException {
+            check(new String[]{host}, cert);
+        }
+
+        public void check(String host, String[] cns, String[] subjectAlts)
+            throws SSLException {
+            check(new String[]{host}, cns, subjectAlts);
+        }
+
+        public void check(String host[], SSLSocket ssl)
+            throws IOException {
+            if (host == null) {
+                throw new NullPointerException("host to verify is null");
+            }
+
+            SSLSession session = ssl.getSession();
+            if (session == null) {
+                // In our experience this only happens under IBM 1.4.x when
+                // spurious (unrelated) certificates show up in the server'
+                // chain.  Hopefully this will unearth the real problem:
+                InputStream in = ssl.getInputStream();
+                in.available();
+                /*
+                  If you're looking at the 2 lines of code above because
+                  you're running into a problem, you probably have two
+                  options:
+
+                    #1.  Clean up the certificate chain that your server
+                         is presenting (e.g. edit "/etc/apache2/server.crt"
+                         or wherever it is your server's certificate chain
+                         is defined).
+
+                                               OR
+
+                    #2.   Upgrade to an IBM 1.5.x or greater JVM, or switch
+                          to a non-IBM JVM.
+                */
+
+                // If ssl.getInputStream().available() didn't cause an
+                // exception, maybe at least now the session is available?
+                session = ssl.getSession();
+                if (session == null) {
+                    // If it's still null, probably a startHandshake() will
+                    // unearth the real problem.
+                    ssl.startHandshake();
+
+                    // Okay, if we still haven't managed to cause an exception,
+                    // might as well go for the NPE.  Or maybe we're okay now?
+                    session = ssl.getSession();
+                }
+            }
+            Certificate[] certs;
+            try {
+                certs = session.getPeerCertificates();
+            } catch (SSLPeerUnverifiedException spue) {
+                InputStream in = ssl.getInputStream();
+                in.available();
+                // Didn't trigger anything interesting?  Okay, just throw
+                // original.
+                throw spue;
+            }
+            X509Certificate x509 = (X509Certificate) certs[0];
+            check(host, x509);
+        }
+
+        public void check(String[] host, X509Certificate cert)
+            throws SSLException {
+
+            String[] cns = Certificates.getCNs(cert);
+            String[] subjectAlts = Certificates.getDNSSubjectAlts(cert);
+            check(host, cns, subjectAlts);
+
+        }
+
+        public void check(final String[] hosts, final String[] cns,
+            final String[] subjectAlts, final boolean ie6,
+            final boolean strictWithSubDomains)
+            throws SSLException {
+            // Build up lists of allowed hosts For logging/debugging purposes.
+            StringBuffer buf = new StringBuffer(32);
+            buf.append('<');
+            for (int i = 0; i < hosts.length; i++) {
+                String h = hosts[i];
+                h = h != null ? h.trim().toLowerCase() : "";
+                hosts[i] = h;
+                if (i > 0) {
+                    buf.append('/');
+                }
+                buf.append(h);
+            }
+            buf.append('>');
+            String hostnames = buf.toString();
+            // Build the list of names we're going to check.  Our DEFAULT and
+            // STRICT implementations of the HostnameVerifier only use the
+            // first CN provided.  All other CNs are ignored.
+            // (Firefox, wget, curl, Sun Java 1.4, 5, 6 all work this way).
+            TreeSet names = new TreeSet();
+            if (cns != null && cns.length > 0 && cns[0] != null) {
+                names.add(cns[0]);
+                if (ie6) {
+                    for (int i = 1; i < cns.length; i++) {
+                        names.add(cns[i]);
+                    }
+                }
+            }
+            if (subjectAlts != null) {
+                for (int i = 0; i < subjectAlts.length; i++) {
+                    if (subjectAlts[i] != null) {
+                        names.add(subjectAlts[i]);
+                    }
+                }
+            }
+            if (names.isEmpty()) {
+                String msg = "Certificate for " + hosts[0] + " doesn't contain CN or DNS subjectAlt";
+                throw new SSLException(msg);
+            }
+
+            // StringBuffer for building the error message.
+            buf = new StringBuffer();
+
+            boolean match = false;
+            out:
+            for (Iterator it = names.iterator(); it.hasNext();) {
+                // Don't trim the CN, though!
+                String cn = (String) it.next();
+                cn = cn.toLowerCase();
+                // Store CN in StringBuffer in case we need to report an error.
+                buf.append(" <");
+                buf.append(cn);
+                buf.append('>');
+                if (it.hasNext()) {
+                    buf.append(" OR");
+                }
+
+                // The CN better have at least two dots if it wants wildcard
+                // action.  It also can't be [*.co.uk] or [*.co.jp] or
+                // [*.org.uk], etc...
+                boolean doWildcard = cn.startsWith("*.") &&
+                    cn.lastIndexOf('.') >= 0 &&
+                    !isIP4Address(cn) &&
+                    acceptableCountryWildcard(cn);
+
+                for (int i = 0; i < hosts.length; i++) {
+                    final String hostName = hosts[i].trim().toLowerCase();
+                    if (doWildcard) {
+                        match = hostName.endsWith(cn.substring(1));
+                        if (match && strictWithSubDomains) {
+                            // If we're in strict mode, then [*.foo.com] is not
+                            // allowed to match [a.b.foo.com]
+                            match = countDots(hostName) == countDots(cn);
+                        }
+                    } else {
+                        match = hostName.equals(cn);
+                    }
+                    if (match) {
+                        break out;
+                    }
+                }
+            }
+            if (!match) {
+                throw new SSLException("hostname in certificate didn't match: " + hostnames + " !=" + buf);
+            }
+        }
+
+        public static boolean isIP4Address(final String cn) {
+            boolean isIP4 = true;
+            String tld = cn;
+            int x = cn.lastIndexOf('.');
+            // We only bother analyzing the characters after the final dot
+            // in the name.
+            if (x >= 0 && x + 1 < cn.length()) {
+                tld = cn.substring(x + 1);
+            }
+            for (int i = 0; i < tld.length(); i++) {
+                if (!Character.isDigit(tld.charAt(0))) {
+                    isIP4 = false;
+                    break;
+                }
+            }
+            return isIP4;
+        }
+
+        public static boolean acceptableCountryWildcard(final String cn) {
+            int cnLen = cn.length();
+            if (cnLen >= 7 && cnLen <= 9) {
+                // Look for the '.' in the 3rd-last position:
+                if (cn.charAt(cnLen - 3) == '.') {
+                    // Trim off the [*.] and the [.XX].
+                    String s = cn.substring(2, cnLen - 3);
+                    // And test against the sorted array of bad 2lds:
+                    int x = Arrays.binarySearch(BAD_COUNTRY_2LDS, s);
+                    return x < 0;
+                }
+            }
+            return true;
+        }
+
+        public static boolean isLocalhost(String host) {
+            host = host != null ? host.trim().toLowerCase() : "";
+            if (host.startsWith("::1")) {
+                int x = host.lastIndexOf('%');
+                if (x >= 0) {
+                    host = host.substring(0, x);
+                }
+            }
+            int x = Arrays.binarySearch(LOCALHOSTS, host);
+            return x >= 0;
+        }
+
+        /**
+         * Counts the number of dots "." in a string.
+         *
+         * @param s string to count dots from
+         * @return number of dots
+         */
+        public static int countDots(final String s) {
+            int count = 0;
+            for (int i = 0; i < s.length(); i++) {
+                if (s.charAt(i) == '.') {
+                    count++;
+                }
+            }
+            return count;
+        }
+    }
+
+    class Certificates {
+        public static String[] getCNs(X509Certificate cert) {
+            LinkedList cnList = new LinkedList();
+            /*
+           Sebastian Hauer's original StrictSSLProtocolSocketFactory used
+           getName() and had the following comment:
+
+              Parses a X.500 distinguished name for the value of the
+              "Common Name" field.  This is done a bit sloppy right
+              now and should probably be done a bit more according to
+              <code>RFC 2253</code>.
+
+            I've noticed that toString() seems to do a better job than
+            getName() on these X500Principal objects, so I'm hoping that
+            addresses Sebastian's concern.
+
+            For example, getName() gives me this:
+            1.2.840.113549.1.9.1=#16166a756c6975736461766965734063756362632e636f6d
+
+            whereas toString() gives me this:
+            EMAILADDRESS=juliusdavies@cucbc.com
+
+            Looks like toString() even works with non-ascii domain names!
+            I tested it with "&#x82b1;&#x5b50;.co.jp" and it worked fine.
+           */
+            String subjectPrincipal = cert.getSubjectX500Principal().toString();
+            StringTokenizer st = new StringTokenizer(subjectPrincipal, ",");
+            while (st.hasMoreTokens()) {
+                String tok = st.nextToken();
+                int x = tok.indexOf("CN=");
+                if (x >= 0) {
+                    cnList.add(tok.substring(x + 3));
+                }
+            }
+            if (!cnList.isEmpty()) {
+                String[] cns = new String[cnList.size()];
+                cnList.toArray(cns);
+                return cns;
+            } else {
+                return null;
+            }
+        }
+
+        /**
+         * Extracts the array of SubjectAlt DNS names from an X509Certificate.
+         * Returns null if there aren't any.
+         * <p/>
+         * Note:  Java doesn't appear able to extract international characters
+         * from the SubjectAlts.  It can only extract international characters
+         * from the CN field.
+         * <p/>
+         * (Or maybe the version of OpenSSL I'm using to test isn't storing the
+         * international characters correctly in the SubjectAlts?).
+         *
+         * @param cert X509Certificate
+         * @return Array of SubjectALT DNS names stored in the certificate.
+         */
+        public static String[] getDNSSubjectAlts(X509Certificate cert) {
+            LinkedList subjectAltList = new LinkedList();
+            Collection c = null;
+            try {
+                c = cert.getSubjectAlternativeNames();
+            }
+            catch (CertificateParsingException cpe) {
+                // Should probably log.debug() this?
+                cpe.printStackTrace();
+            }
+            if (c != null) {
+                Iterator it = c.iterator();
+                while (it.hasNext()) {
+                    List list = (List) it.next();
+                    int type = ((Integer) list.get(0)).intValue();
+                    // If type is 2, then we've got a dNSName
+                    if (type == 2) {
+                        String s = (String) list.get(1);
+                        subjectAltList.add(s);
+                    }
+                }
+            }
+            if (!subjectAltList.isEmpty()) {
+                String[] subjectAlts = new String[subjectAltList.size()];
+                subjectAltList.toArray(subjectAlts);
+                return subjectAlts;
+            } else {
+                return null;
+            }
+        }
+    }
+}

Added: synapse/trunk/java/modules/transports/core/nhttp/src/main/java/org/apache/synapse/transport/passthru/PassThroughConstants.java
URL: http://svn.apache.org/viewvc/synapse/trunk/java/modules/transports/core/nhttp/src/main/java/org/apache/synapse/transport/passthru/PassThroughConstants.java?rev=1502386&view=auto
==============================================================================
--- synapse/trunk/java/modules/transports/core/nhttp/src/main/java/org/apache/synapse/transport/passthru/PassThroughConstants.java (added)
+++ synapse/trunk/java/modules/transports/core/nhttp/src/main/java/org/apache/synapse/transport/passthru/PassThroughConstants.java Thu Jul 11 22:18:46 2013
@@ -0,0 +1,92 @@
+/*
+ *  Copyright 2013 Apache Software Foundation
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+
+package org.apache.synapse.transport.passthru;
+
+public class PassThroughConstants {
+
+    public static final int DEFAULT_IO_THREAD_COUNT = Runtime.getRuntime().availableProcessors();
+    public static final int DEFAULT_MAX_CONN_PER_HOST_PORT = Integer.MAX_VALUE;
+    
+    public static final String REQUEST_MESSAGE_CONTEXT = "REQUEST_MESSAGE_CONTEXT";
+    public static final String CONNECTION_POOL = "CONNECTION_POOL";
+
+    public static final String TRUE = "TRUE";
+
+    public static final String FAULT_MESSAGE = "FAULT_MESSAGE"; // corresponds with BaseConstants
+    public static final String FAULTS_AS_HTTP_200 = "FAULTS_AS_HTTP_200";
+    public static final String SC_ACCEPTED = "SC_ACCEPTED";
+    public static final String HTTP_SC = "HTTP_SC";
+    public static final String FORCE_HTTP_1_0 = "FORCE_HTTP_1.0";
+    public static final String DISABLE_CHUNKING = "DISABLE_CHUNKING";
+    public static final String FULL_URI = "FULL_URI";
+    public static final String NO_KEEPALIVE = "NO_KEEPALIVE";
+    public static final String DISABLE_KEEPALIVE = "http.connection.disable.keepalive";
+    public static final String IGNORE_SC_ACCEPTED = "IGNORE_SC_ACCEPTED";
+    public static final String FORCE_SC_ACCEPTED = "FORCE_SC_ACCEPTED";
+    public static final String DISCARD_ON_COMPLETE = "DISCARD_ON_COMPLETE";
+
+    public static final String SERVICE_URI_LOCATION = "ServiceURI";
+
+    public static final String WSDL_EPR_PREFIX = "WSDLEPRPrefix";
+
+    public static final String EPR_TO_SERVICE_NAME_MAP = "service.epr.map";
+    public static final String NON_BLOCKING_TRANSPORT = "NonBlockingTransport";
+    public static final String SERIALIZED_BYTES = "SerializedBytes";
+
+    public static final String CONTENT_TYPE = "CONTENT_TYPE";
+
+    public static final String DEFAULT_CONTENT_TYPE = "application/octet-stream";
+
+    public static final String HIDDEN_SERVICE_PARAM_NAME = "hiddenService";
+
+    /** An Axis2 message context property indicating a transport send failure */
+    public static final String SENDING_FAULT = "SENDING_FAULT";
+    /** The message context property name which holds the error code for the last encountered exception */
+    public static final String ERROR_CODE = "ERROR_CODE";
+    /** The MC property name which holds the error message for the last encountered exception */
+    public static final String ERROR_MESSAGE = "ERROR_MESSAGE";
+    /** The message context property name which holds the error detail (stack trace) for the last encountered exception */
+    public static final String ERROR_DETAIL = "ERROR_DETAIL";
+    /** The message context property name which holds the exception (if any) for the last encountered exception */
+    public static final String ERROR_EXCEPTION = "ERROR_EXCEPTION";
+
+    // ********** DO NOT CHANGE THESE UNLESS CORRESPONDING SYNAPSE CONSTANT ARE CHANGED ************
+
+    public static final String REST_URL_POSTFIX = "REST_URL_POSTFIX";
+    public static final String SERVICE_PREFIX = "SERVICE_PREFIX";
+    public static final String NO_ENTITY_BODY = "NO_ENTITY_BODY";
+
+    protected static final String PASS_THROUGH_TRANSPORT_WORKER_POOL =
+            "PASS_THROUGH_TRANSPORT_WORKER_POOL";
+    protected static final String PASS_THROUGH_SOURCE_CONFIGURATION =
+            "PASS_THROUGH_SOURCE_CONFIGURATION";
+    protected static final String PASS_THROUGH_SOURCE_CONNECTION = "pass-through.Source-Connection";
+    protected static final String PASS_THROUGH_SOURCE_REQUEST = "pass-through.Source-Request";
+
+    protected static final String PASS_THROUGH_TARGET_CONNECTION = "pass-through.Target-Connection";
+    protected static final String PASS_THROUGH_TARGET_RESPONSE = "pass-through.Target-Response";
+
+    public static final String PASS_THROUGH_PIPE = "pass-through.pipe";
+
+    // used to define the default content type as a parameter in the axis2.xml
+    public static final String REQUEST_CONTENT_TYPE = "DEFAULT_REQUEST_CONTENT_TYPE";
+
+    // This is a workaround  for  axis2 RestUtils behaviour
+    public static final String REST_REQUEST_CONTENT_TYPE = "synapse.internal.rest.contentType";
+
+    public static final String MESSAGE_BUILDER_INVOKED = "message.builder.invoked";
+}

Added: synapse/trunk/java/modules/transports/core/nhttp/src/main/java/org/apache/synapse/transport/passthru/PassThroughHttpListener.java
URL: http://svn.apache.org/viewvc/synapse/trunk/java/modules/transports/core/nhttp/src/main/java/org/apache/synapse/transport/passthru/PassThroughHttpListener.java?rev=1502386&view=auto
==============================================================================
--- synapse/trunk/java/modules/transports/core/nhttp/src/main/java/org/apache/synapse/transport/passthru/PassThroughHttpListener.java (added)
+++ synapse/trunk/java/modules/transports/core/nhttp/src/main/java/org/apache/synapse/transport/passthru/PassThroughHttpListener.java Thu Jul 11 22:18:46 2013
@@ -0,0 +1,416 @@
+/*
+ *  Copyright 2013 Apache Software Foundation
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+
+package org.apache.synapse.transport.passthru;
+
+import org.apache.axiom.om.OMElement;
+import org.apache.axis2.AxisFault;
+import org.apache.axis2.addressing.EndpointReference;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.axis2.context.MessageContext;
+import org.apache.axis2.context.SessionContext;
+import org.apache.axis2.description.*;
+import org.apache.axis2.engine.AxisConfiguration;
+import org.apache.axis2.engine.AxisEvent;
+import org.apache.axis2.engine.AxisObserver;
+import org.apache.axis2.transport.TransportListener;
+import org.apache.axis2.transport.base.BaseConstants;
+import org.apache.axis2.transport.base.BaseUtils;
+import org.apache.axis2.transport.base.threads.NativeThreadFactory;
+import org.apache.axis2.transport.base.threads.WorkerPool;
+import org.apache.axis2.util.JavaUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.http.impl.nio.reactor.DefaultListeningIOReactor;
+import org.apache.http.impl.nio.reactor.SSLIOSessionHandler;
+import org.apache.http.nio.NHttpServiceHandler;
+import org.apache.http.nio.reactor.IOEventDispatch;
+import org.apache.http.nio.reactor.IOReactorException;
+import org.apache.http.nio.reactor.IOReactorExceptionHandler;
+import org.apache.http.nio.reactor.ListenerEndpoint;
+import org.apache.http.params.HttpParams;
+import org.apache.synapse.transport.passthru.config.SourceConfiguration;
+import org.apache.synapse.transport.passthru.jmx.MBeanRegistrar;
+import org.apache.synapse.transport.passthru.jmx.PassThroughTransportMetricsCollector;
+import org.apache.synapse.transport.passthru.jmx.TransportView;
+
+import javax.net.ssl.SSLContext;
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * This is the TransportListener listening for incoming connections. This class start the IOReactor
+ * and registers the InRequest Handlers on it.
+ */
+public class PassThroughHttpListener implements TransportListener {
+
+    protected Log log = LogFactory.getLog(this.getClass());
+
+    /** The reactor being used */
+    private DefaultListeningIOReactor ioReactor;
+
+    /** The configuration of the listener */
+    private SourceConfiguration sourceConfiguration = null;
+
+    /** SSLContext if this listener is a SSL listener */
+    private SSLContext sslContext = null;
+    
+    /** The SSL session handler that manages client authentication etc */
+    private SSLIOSessionHandler sslIOSessionHandler = null;
+
+    /** The custom URI map for the services if there are any */
+    private Map<String, String> serviceNameToEPRMap = new HashMap<String, String>();
+    /** The service name map for the custom URI if there are any */
+    private Map<String, String> eprToServiceNameMap = new HashMap<String, String>();
+    /** the axis observer that gets notified of service life cycle events*/
+    private final AxisObserver axisObserver = new GenericAxisObserver();
+
+    private volatile int state = BaseConstants.STOPPED;
+
+    private String namePrefix;
+
+    public void init(ConfigurationContext cfgCtx, TransportInDescription transportInDescription)
+            throws AxisFault {
+
+        log.info("Initializing Pass-through HTTP/S Listener...");
+
+        Object obj = cfgCtx.getProperty(PassThroughConstants.PASS_THROUGH_TRANSPORT_WORKER_POOL);
+        WorkerPool workerPool = null;
+        if (obj != null) {
+            workerPool = (WorkerPool) obj;
+        }
+
+        // is this a SSL listener?
+        sslContext = getSSLContext(transportInDescription);
+        sslIOSessionHandler = getSSLIOSessionHandler(transportInDescription);
+
+        namePrefix = (sslContext == null) ? "HTTP" : "HTTPS";
+
+        sourceConfiguration = new SourceConfiguration(cfgCtx, transportInDescription, workerPool);
+        sourceConfiguration.build();
+
+        // register to receive updates on services for lifetime management
+        cfgCtx.getAxisConfiguration().addObservers(axisObserver);
+        cfgCtx.setProperty(PassThroughConstants.EPR_TO_SERVICE_NAME_MAP, eprToServiceNameMap);
+
+        cfgCtx.setProperty(PassThroughConstants.PASS_THROUGH_TRANSPORT_WORKER_POOL,
+                sourceConfiguration.getWorkerPool());
+
+        PassThroughTransportMetricsCollector metrics = new PassThroughTransportMetricsCollector(
+                                                            true, sslContext != null);
+
+        MBeanRegistrar.getInstance().registerMBean(
+                new TransportView(this, null, metrics, null), "Transport",
+                "passthru-" + namePrefix.toLowerCase() + "-receiver");
+        sourceConfiguration.setMetrics(metrics);
+    }
+
+    public void start() throws AxisFault {
+
+        log.info("Starting Pass-through " + namePrefix + " Listener...");
+
+        try {
+            String prefix = namePrefix + "-Listener I/O dispatcher";
+
+            ioReactor = new DefaultListeningIOReactor(
+                            sourceConfiguration.getIOThreadsPerReactor(),
+                            new NativeThreadFactory(new ThreadGroup(prefix + " thread group"), prefix),
+                            sourceConfiguration.getHttpParameters());
+            
+            ioReactor.setExceptionHandler(new IOReactorExceptionHandler() {
+
+                public boolean handle(IOException ioException) {
+                    log.warn("System may be unstable: " + namePrefix +
+                            " ListeningIOReactor encountered a checked exception : " +
+                            ioException.getMessage(), ioException);
+                    return true;
+                }
+
+                public boolean handle(RuntimeException runtimeException) {
+                    log.warn("System may be unstable: " + namePrefix +
+                            " ListeningIOReactor encountered a runtime exception : "
+                            + runtimeException.getMessage(), runtimeException);
+                    return true;
+                }
+            });
+
+        } catch (IOReactorException e) {
+            handleException("Error starting " + namePrefix + " ListeningIOReactor", e);
+        }
+
+        SourceHandler handler = new SourceHandler(sourceConfiguration);
+
+        final IOEventDispatch ioEventDispatch = getEventDispatch(handler, sslContext,
+                                      sslIOSessionHandler, sourceConfiguration.getHttpParameters());
+
+        ListenerEndpoint endpoint = ioReactor.listen(
+                                      new InetSocketAddress(sourceConfiguration.getPort()));
+
+        Thread t = new Thread(new Runnable() {
+            public void run() {
+                try {
+                    ioReactor.execute(ioEventDispatch);
+                } catch (Exception e) {
+                    log.fatal("Exception encountered in the " + namePrefix + " Listener. " +
+                            "No more connections will be accepted by this transport", e);
+                }
+                log.info(namePrefix + " Listener shutdown.");
+            }
+        }, "PassThrough" + namePrefix + "Listener");
+        t.start();
+
+        try {
+            endpoint.waitFor();
+        } catch (InterruptedException e) {
+            log.warn("PassThroughHttpListener start event was interrupted", e);
+        }
+
+        state = BaseConstants.STARTED;
+
+        log.info("Pass-through " + namePrefix + " Listener " + "started on port : " +
+                sourceConfiguration.getPort());
+    }
+
+    private void handleException(String s, Exception e) throws AxisFault {
+        log.error(s, e);
+        throw new AxisFault(s, e);
+    }
+
+    public EndpointReference getEPRForService(String serviceName, String ip) throws AxisFault {
+        String trailer = "";
+        //Strip out the operation name
+        if (serviceName.indexOf('/') != -1) {
+            trailer += serviceName.substring(serviceName.indexOf("/"));
+            serviceName = serviceName.substring(0, serviceName.indexOf('/'));
+        }
+        // strip out the endpoint name if present
+        if (serviceName.indexOf('.') != -1) {
+            trailer += serviceName.substring(serviceName.indexOf("."));
+            serviceName = serviceName.substring(0, serviceName.indexOf('.'));
+        }
+
+        if (serviceNameToEPRMap.containsKey(serviceName)) {
+            return new EndpointReference(
+                    sourceConfiguration.getCustomEPRPrefix() +
+                            serviceNameToEPRMap.get(serviceName) + trailer);
+        } else {
+            return new EndpointReference(sourceConfiguration.getServiceEPRPrefix() +
+                    serviceName + trailer);
+        }
+    }
+
+    /**
+     * Return the EPRs for the given service over this transport
+     * @param serviceName name of the service
+     * @param ip IP address
+     * @return the EndpointReferences for this service over the transport
+     * @throws AxisFault on error
+     */
+    public EndpointReference[] getEPRsForService(String serviceName, String ip) throws AxisFault {
+        String trailer = "";
+        //Strip out the operation name
+        if (serviceName.indexOf('/') != -1) {
+            trailer += serviceName.substring(serviceName.indexOf("/"));
+            serviceName = serviceName.substring(0, serviceName.indexOf('/'));
+        }
+        // strip out the endpoint name if present
+        if (serviceName.indexOf('.') != -1) {
+            trailer += serviceName.substring(serviceName.indexOf("."));
+            serviceName = serviceName.substring(0, serviceName.indexOf('.'));
+        }
+
+        EndpointReference[] endpointReferences = new EndpointReference[1];
+        if (serviceNameToEPRMap.containsKey(serviceName)) {
+            endpointReferences[0] = new EndpointReference(
+                    sourceConfiguration.getCustomEPRPrefix() +
+                            serviceNameToEPRMap.get(serviceName) + trailer);
+        } else {
+            endpointReferences[0]
+                    = new EndpointReference(sourceConfiguration.getServiceEPRPrefix() +
+                    serviceName + trailer);
+        }
+        return endpointReferences;
+    }
+
+    public SessionContext getSessionContext(MessageContext messageContext) {
+        return null;
+    }
+
+
+    public void stop() throws AxisFault {
+        log.info("Stopping Pass-through " + namePrefix + " Listener..");
+        try {
+            ioReactor.shutdown();
+        } catch (IOException e) {
+            handleException("Error shutting down " + namePrefix + " listening IO reactor", e);
+        }
+    }
+
+    public void destroy() {
+        log.info("Destroying PassThroughHttpListener");
+        sourceConfiguration.getConfigurationContext().
+                getAxisConfiguration().getObserversList().remove(axisObserver);
+
+        sourceConfiguration.getMetrics().destroy();
+    }
+
+    /**
+     * Pause the listener - Stops accepting new connections, but continues processing existing
+     * connections until they complete. This helps bring an instance into a maintenance mode
+     *
+     * @throws AxisFault if pausing fails
+     */
+    public void pause() throws AxisFault {
+        if (state != BaseConstants.STARTED) return;
+        try {
+            ioReactor.pause();
+
+            state = BaseConstants.PAUSED;
+            log.info(namePrefix + " Listener Paused");
+        } catch (IOException e) {
+            handleException("Error pausing IOReactor", e);
+        }
+    }
+
+    /**
+     * Resume the lister - Brings the lister into active mode back from a paused state
+     *
+     * @throws AxisFault if the resume fails
+     */
+    public void resume() throws AxisFault {
+        if (state != BaseConstants.PAUSED) return;
+        try {
+            ioReactor.resume();
+            state = BaseConstants.STARTED;
+            log.info((sslContext == null ? "HTTP" : "HTTPS") + "Listener Resumed");
+        } catch (IOException e) {
+            handleException("Error resuming IOReactor", e);
+        }
+    }
+
+    /**
+     * Stop accepting new connections, and wait the maximum specified time for in-flight
+     * requests to complete before a controlled shutdown for maintenance
+     *
+     * @param milliSecs number of milliseconds to wait until pending requests complete
+     * @throws AxisFault if the shutdown fails
+     */
+    public void maintenanceShutdown(long milliSecs) throws AxisFault {
+        if (state != BaseConstants.STARTED) return;
+        try {
+            long start = System.currentTimeMillis();
+            ioReactor.pause();
+            ioReactor.shutdown(milliSecs);
+            state = BaseConstants.STOPPED;
+            log.info("Listener shutdown in : " + (System.currentTimeMillis() - start) / 1000 + "s");
+        } catch (IOException e) {
+            handleException("Error shutting down the IOReactor for maintenance", e);
+        }
+    }
+
+    /**
+     * An AxisObserver which will start listening for newly deployed or started services,
+     * and stop listening when services are un-deployed or stopped.
+     */
+    private class GenericAxisObserver implements AxisObserver {
+        public void init(AxisConfiguration axisConfig) {}
+
+        public void serviceUpdate(AxisEvent event, AxisService service) {
+            if (!ignoreService(service)
+                    && BaseUtils.isUsingTransport(service,
+                    sourceConfiguration.getInDescription().getName())) {
+                switch (event.getEventType()) {
+                    case AxisEvent.SERVICE_DEPLOY :
+                        addToServiceURIMap(service);
+                        break;
+                    case AxisEvent.SERVICE_REMOVE :
+                        removeServiceFfromURIMap(service);
+                        break;
+                    case AxisEvent.SERVICE_START  :
+                        addToServiceURIMap(service);
+                        break;
+                    case AxisEvent.SERVICE_STOP   :
+                        removeServiceFfromURIMap(service);
+                        break;
+                }
+            }
+        }
+
+        public void moduleUpdate(AxisEvent event, AxisModule module) {}
+        public void addParameter(Parameter parameter) throws AxisFault {}
+        public void removeParameter(Parameter parameter) throws AxisFault {}
+        public void deserializeParameters(OMElement parameterElement) throws AxisFault {}
+        public Parameter getParameter(String name) { return null; }
+        public ArrayList<Parameter> getParameters() { return null; }
+        public boolean isParameterLocked(String parameterName) { return false; }
+        public void serviceGroupUpdate(AxisEvent event, AxisServiceGroup serviceGroup) {}
+    }
+
+    private boolean ignoreService(AxisService service) {
+        // these are "private" services
+        return service.getName().startsWith("__") || JavaUtils.isTrueExplicitly(
+                service.getParameter(PassThroughConstants.HIDDEN_SERVICE_PARAM_NAME));
+    }
+
+    private void addToServiceURIMap(AxisService service) {
+        Parameter param = service.getParameter(PassThroughConstants.SERVICE_URI_LOCATION);
+        if (param != null) {
+            String uriLocation = param.getValue().toString();
+            if (uriLocation.startsWith("/")) {
+                uriLocation = uriLocation.substring(1);
+            }
+            serviceNameToEPRMap.put(service.getName(), uriLocation);
+            eprToServiceNameMap.put(uriLocation, service.getName());
+        }
+    }
+
+    private void removeServiceFfromURIMap(AxisService service) {
+        eprToServiceNameMap.remove(serviceNameToEPRMap.get(service.getName()));
+        serviceNameToEPRMap.remove(service.getName());
+    }
+
+    protected IOEventDispatch getEventDispatch(
+            NHttpServiceHandler handler, SSLContext sslContext,
+            SSLIOSessionHandler sslioSessionHandler, HttpParams params) {
+        return new SourceIOEventDispatch(handler, params);
+    }
+
+    /**
+     * Create the SSLContext to be used by this listener
+     * @param transportIn transport in description
+     * @return always null
+     * @throws AxisFault never thrown
+     */
+    protected SSLContext getSSLContext(
+            TransportInDescription transportIn) throws AxisFault {
+        return null;
+    }
+
+    /**
+     * Create the SSL IO Session handler to be used by this listener
+     * @param transportIn transport in descritption
+     * @return always null
+     * @throws AxisFault never thrown
+     */
+    protected SSLIOSessionHandler getSSLIOSessionHandler(
+            TransportInDescription transportIn) throws AxisFault {
+        return null;
+    }
+
+}

Added: synapse/trunk/java/modules/transports/core/nhttp/src/main/java/org/apache/synapse/transport/passthru/PassThroughHttpSSLListener.java
URL: http://svn.apache.org/viewvc/synapse/trunk/java/modules/transports/core/nhttp/src/main/java/org/apache/synapse/transport/passthru/PassThroughHttpSSLListener.java?rev=1502386&view=auto
==============================================================================
--- synapse/trunk/java/modules/transports/core/nhttp/src/main/java/org/apache/synapse/transport/passthru/PassThroughHttpSSLListener.java (added)
+++ synapse/trunk/java/modules/transports/core/nhttp/src/main/java/org/apache/synapse/transport/passthru/PassThroughHttpSSLListener.java Thu Jul 11 22:18:46 2013
@@ -0,0 +1,155 @@
+package org.apache.synapse.transport.passthru;
+
+import org.apache.axiom.om.OMElement;
+import org.apache.axis2.AxisFault;
+import org.apache.axis2.description.Parameter;
+import org.apache.axis2.description.TransportInDescription;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.http.impl.nio.SSLServerIOEventDispatch;
+import org.apache.http.impl.nio.reactor.SSLIOSessionHandler;
+import org.apache.http.nio.NHttpServiceHandler;
+import org.apache.http.nio.reactor.IOEventDispatch;
+import org.apache.http.params.HttpParams;
+
+import javax.net.ssl.*;
+import javax.xml.namespace.QName;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.net.SocketAddress;
+import java.security.GeneralSecurityException;
+import java.security.KeyStore;
+
+public class PassThroughHttpSSLListener extends PassThroughHttpListener {
+    
+    private Log log = LogFactory.getLog(PassThroughHttpSSLListener.class);
+
+    protected IOEventDispatch getEventDispatch(
+        NHttpServiceHandler handler, SSLContext sslContext,
+        SSLIOSessionHandler sslIOSessionHandler, HttpParams params) {
+        return new SSLServerIOEventDispatch(handler, sslContext, sslIOSessionHandler, params);
+    }
+
+    /**
+     * Create the SSLContext to be used by this listener
+     * @param transportIn the Axis2 transport description
+     * @return the SSLContext to be used
+     * @throws org.apache.axis2.AxisFault if an error occurs
+     */
+    protected SSLContext getSSLContext(TransportInDescription transportIn) throws AxisFault {
+
+        KeyManager[] keymanagers  = null;
+        TrustManager[] trustManagers = null;
+
+        Parameter keyParam    = transportIn.getParameter("keystore");
+        Parameter trustParam  = transportIn.getParameter("truststore");
+
+        if (keyParam != null) {
+            OMElement ksEle      = keyParam.getParameterElement().getFirstElement();
+            String location      = ksEle.getFirstChildWithName(new QName("Location")).getText();
+            String type          = ksEle.getFirstChildWithName(new QName("Type")).getText();
+            String storePassword = ksEle.getFirstChildWithName(new QName("Password")).getText();
+            String keyPassword   = ksEle.getFirstChildWithName(new QName("KeyPassword")).getText();
+
+            FileInputStream fis = null;
+            try {
+                KeyStore keyStore = KeyStore.getInstance(type);
+                fis = new FileInputStream(location);
+                log.info("Loading Identity Keystore from : " + location);
+
+                keyStore.load(fis, storePassword.toCharArray());
+                KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(
+                    KeyManagerFactory.getDefaultAlgorithm());
+                kmfactory.init(keyStore, keyPassword.toCharArray());
+                keymanagers = kmfactory.getKeyManagers();
+
+            } catch (GeneralSecurityException gse) {
+                log.error("Error loading Key store : " + location, gse);
+                throw new AxisFault("Error loading Key store : " + location, gse);
+            } catch (IOException ioe) {
+                log.error("Error opening Key store : " + location, ioe);
+                throw new AxisFault("Error opening Key store : " + location, ioe);
+            } finally {
+                if (fis != null) {
+                    try {
+                        fis.close();
+                    } catch (IOException ignore) {}
+                }
+            }
+        }
+
+        if (trustParam != null) {
+            OMElement tsEle      = trustParam.getParameterElement().getFirstElement();
+            String location      = tsEle.getFirstChildWithName(new QName("Location")).getText();
+            String type          = tsEle.getFirstChildWithName(new QName("Type")).getText();
+            String storePassword = tsEle.getFirstChildWithName(new QName("Password")).getText();
+
+            FileInputStream fis = null;
+            try {
+                KeyStore trustStore = KeyStore.getInstance(type);
+                fis = new FileInputStream(location);
+                log.info("Loading Trust Keystore from : " + location);
+
+                trustStore.load(fis, storePassword.toCharArray());
+                TrustManagerFactory trustManagerfactory = TrustManagerFactory.getInstance(
+                    TrustManagerFactory.getDefaultAlgorithm());
+                trustManagerfactory.init(trustStore);
+                trustManagers = trustManagerfactory.getTrustManagers();
+
+            } catch (GeneralSecurityException gse) {
+                log.error("Error loading Key store : " + location, gse);
+                throw new AxisFault("Error loading Key store : " + location, gse);
+            } catch (IOException ioe) {
+                log.error("Error opening Key store : " + location, ioe);
+                throw new AxisFault("Error opening Key store : " + location, ioe);
+            } finally {
+                if (fis != null) {
+                    try {
+                        fis.close();
+                    } catch (IOException ignore) {}
+                }
+            }
+        }
+
+        try {
+            SSLContext sslcontext = SSLContext.getInstance("TLS");
+            sslcontext.init(keymanagers, trustManagers, null);
+            return sslcontext;
+
+        } catch (GeneralSecurityException gse) {
+            log.error("Unable to create SSL context with the given configuration", gse);
+            throw new AxisFault("Unable to create SSL context with the given configuration", gse);
+        }
+    }
+
+    /**
+     * Create the SSLIOSessionHandler to initialize the SSL session / engine, and request for
+     * client authentication at the following levels, through an Axis2 transport configuration
+     * parameter as follows:
+     * SSLVerifyClient - none, optional, require
+     *
+     * @param transportIn the Axis2 transport configuration
+     * @return the SSLIOSessionHandler to be used
+     * @throws AxisFault if a configuration error occurs
+     */
+    protected SSLIOSessionHandler getSSLIOSessionHandler(TransportInDescription transportIn) throws AxisFault {
+
+        final Parameter clientAuth = transportIn.getParameter("SSLVerifyClient");
+
+        return new SSLIOSessionHandler() {
+
+            public void initalize(SSLEngine sslengine, HttpParams params) {
+                if (clientAuth != null) {
+                    if ("optional".equals(clientAuth.getValue())) {
+                        sslengine.setWantClientAuth(true);
+                    } else if ("require".equals(clientAuth.getValue())) {
+                        sslengine.setNeedClientAuth(true);
+                    }
+                }
+            }
+
+            public void verify(SocketAddress removeAddress, SSLSession session)
+                throws SSLException {}
+        };
+    }
+}

Added: synapse/trunk/java/modules/transports/core/nhttp/src/main/java/org/apache/synapse/transport/passthru/PassThroughHttpSSLSender.java
URL: http://svn.apache.org/viewvc/synapse/trunk/java/modules/transports/core/nhttp/src/main/java/org/apache/synapse/transport/passthru/PassThroughHttpSSLSender.java?rev=1502386&view=auto
==============================================================================
--- synapse/trunk/java/modules/transports/core/nhttp/src/main/java/org/apache/synapse/transport/passthru/PassThroughHttpSSLSender.java (added)
+++ synapse/trunk/java/modules/transports/core/nhttp/src/main/java/org/apache/synapse/transport/passthru/PassThroughHttpSSLSender.java Thu Jul 11 22:18:46 2013
@@ -0,0 +1,338 @@
+/*
+ *  Copyright 2013 Apache Software Foundation
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+
+package org.apache.synapse.transport.passthru;
+
+import org.apache.axiom.om.OMElement;
+import org.apache.axis2.AxisFault;
+import org.apache.axis2.description.Parameter;
+import org.apache.axis2.description.TransportOutDescription;
+import org.apache.axis2.transport.base.ParamUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.http.impl.nio.reactor.SSLSetupHandler;
+import org.apache.http.nio.NHttpClientHandler;
+import org.apache.http.nio.reactor.IOEventDispatch;
+import org.apache.http.nio.reactor.IOSession;
+import org.apache.http.params.HttpParams;
+
+import javax.net.ssl.*;
+import javax.xml.namespace.QName;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.net.SocketAddress;
+import java.security.GeneralSecurityException;
+import java.security.KeyStore;
+import java.security.cert.CertificateException;
+import java.security.cert.X509Certificate;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+
+
+public class PassThroughHttpSSLSender extends PassThroughHttpSender {
+    private Log log = LogFactory.getLog(PassThroughHttpSSLSender.class);
+
+    protected IOEventDispatch getEventDispatch(NHttpClientHandler handler,
+                                               SSLContext sslContext,
+                                               SSLSetupHandler sslIOSessionHandler,
+                                               HttpParams params,
+                                               TransportOutDescription transportOut)
+            throws AxisFault {
+
+        SSLTargetIOEventDispatch dispatch = new SSLTargetIOEventDispatch(handler, sslContext,
+                sslIOSessionHandler, params);
+        dispatch.setContextMap(getCustomSSLContexts(transportOut));
+        return dispatch;
+    }
+
+    /**
+     * Create the SSLContext to be used by this sender
+     *
+     * @param transportOut the Axis2 transport configuration
+     * @return the SSLContext to be used
+     * @throws org.apache.axis2.AxisFault if an error occurs
+     */
+    protected SSLContext getSSLContext(TransportOutDescription transportOut) throws AxisFault {
+
+        Parameter keyParam    = transportOut.getParameter("keystore");
+        Parameter trustParam  = transportOut.getParameter("truststore");
+
+        OMElement ksEle = null;
+        OMElement tsEle = null;
+
+        if (keyParam != null) {
+            ksEle = keyParam.getParameterElement().getFirstElement();
+        }
+
+        boolean noValidateCert = ParamUtils.getOptionalParamBoolean(transportOut,
+                "novalidatecert", false);
+
+        if (trustParam != null) {
+            if (noValidateCert) {
+                log.warn("Ignoring novalidatecert parameter since a truststore has been specified");
+            }
+            tsEle = trustParam.getParameterElement().getFirstElement();
+        }
+
+        return createSSLContext(ksEle, tsEle, noValidateCert);
+    }
+
+    /**
+     * Create the SSLIOSessionHandler to initialize the host name verification at the following
+     * levels, through an Axis2 transport configuration parameter as follows:
+     * HostnameVerifier - Default, DefaultAndLocalhost, Strict, AllowAll
+     *
+     * @param transportOut the Axis2 transport configuration
+     * @return the SSLIOSessionHandler to be used
+     * @throws AxisFault if a configuration error occurs
+     */
+    protected SSLSetupHandler getSSLSetupHandler(TransportOutDescription transportOut)
+            throws AxisFault {
+
+        final Parameter hostnameVerifier = transportOut.getParameter("HostnameVerifier");
+        if (hostnameVerifier != null) {
+            return createSSLIOSessionHandler(hostnameVerifier.getValue().toString());
+        } else {
+            return createSSLIOSessionHandler(null);
+        }
+    }
+
+    /**
+     * Looks for a transport parameter named customSSLProfiles and initializes zero or more
+     * custom SSLContext instances. The syntax for defining custom SSL profiles is as follows.
+     *
+     * <parameter name="customSSLProfiles>
+     *      <profile>
+     *          <servers>www.test.org:80, www.test2.com:9763</servers>
+     *          <KeyStore>
+     *              <Location>/path/to/identity/store</Location>
+     *              <Type>JKS</Type>
+     *              <Password>password</Password>
+     *              <KeyPassword>password</KeyPassword>
+     *          </KeyStore>
+     *          <TrustStore>
+     *              <Location>path/tp/trust/store</Location>
+     *              <Type>JKS</Type>
+     *              <Password>password</Password>
+     *          </TrustStore>
+     *      </profile>
+     * </parameter>
+     *
+     * Any number of profiles can be defined under the customSSLProfiles parameter.
+     *
+     * @param transportOut transport out description
+     * @return a map of server addresses and SSL contexts
+     * @throws AxisFault if at least on SSL profile is not properly configured
+     */
+    private Map<String, SSLContext> getCustomSSLContexts(TransportOutDescription transportOut)
+            throws AxisFault {
+
+        if (log.isDebugEnabled()) {
+            log.info("Loading custom SSL profiles for the HTTPS sender");
+        }
+
+        Parameter customProfilesParam = transportOut.getParameter("customSSLProfiles");
+        if (customProfilesParam == null) {
+            return null;
+        }
+
+        OMElement customProfilesElt = customProfilesParam.getParameterElement();
+        Iterator profiles = customProfilesElt.getChildrenWithName(new QName("profile"));
+        Map<String, SSLContext> contextMap = new HashMap<String, SSLContext>();
+        while (profiles.hasNext()) {
+            OMElement profile = (OMElement) profiles.next();
+            OMElement serversElt = profile.getFirstChildWithName(new QName("servers"));
+            if (serversElt == null || serversElt.getText() == null) {
+                String msg = "Each custom SSL profile must define at least one host:port " +
+                        "pair under the servers element";
+                log.error(msg);
+                throw new AxisFault(msg);
+            }
+
+            String[] servers = serversElt.getText().split(",");
+            OMElement ksElt = profile.getFirstChildWithName(new QName("KeyStore"));
+            OMElement trElt = profile.getFirstChildWithName(new QName("TrustStore"));
+            String noValCert = profile.getAttributeValue(new QName("novalidatecert"));
+            boolean novalidatecert = "true".equals(noValCert);
+            SSLContext sslContext = createSSLContext(ksElt, trElt, novalidatecert);
+
+            for (String server : servers) {
+                server = server.trim();
+                if (!contextMap.containsKey(server)) {
+                    contextMap.put(server, sslContext);
+                } else {
+                    log.warn("Multiple SSL profiles were found for the server : " + server + ". " +
+                            "Ignoring the excessive profiles.");
+                }
+            }
+        }
+
+        if (contextMap.size() > 0) {
+            log.info("Custom SSL profiles initialized for " + contextMap.size() + " servers");
+            return contextMap;
+        }
+        return null;
+    }
+
+    private SSLContext createSSLContext(OMElement keyStoreElt, OMElement trustStoreElt,
+                                        boolean novalidatecert) throws AxisFault {
+
+        KeyManager[] keymanagers  = null;
+        TrustManager[] trustManagers = null;
+
+
+        if (keyStoreElt != null) {
+            String location      = keyStoreElt.getFirstChildWithName(new QName("Location")).getText();
+            String type          = keyStoreElt.getFirstChildWithName(new QName("Type")).getText();
+            String storePassword = keyStoreElt.getFirstChildWithName(new QName("Password")).getText();
+            String keyPassword   = keyStoreElt.getFirstChildWithName(new QName("KeyPassword")).getText();
+
+            FileInputStream fis = null;
+            try {
+                KeyStore keyStore = KeyStore.getInstance(type);
+                fis = new FileInputStream(location);
+                log.info("Loading Identity Keystore from : " + location);
+
+                keyStore.load(fis, storePassword.toCharArray());
+                KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(
+                    KeyManagerFactory.getDefaultAlgorithm());
+                kmfactory.init(keyStore, keyPassword.toCharArray());
+                keymanagers = kmfactory.getKeyManagers();
+
+            } catch (GeneralSecurityException gse) {
+                log.error("Error loading Keystore : " + location, gse);
+                throw new AxisFault("Error loading Keystore : " + location, gse);
+            } catch (IOException ioe) {
+                log.error("Error opening Keystore : " + location, ioe);
+                throw new AxisFault("Error opening Keystore : " + location, ioe);
+            } finally {
+                if (fis != null) {
+                    try {
+                        fis.close();
+                    } catch (IOException ignore) {}
+                }
+            }
+        }
+
+        if (trustStoreElt != null) {
+            if (novalidatecert) {
+                log.warn("Ignoring novalidatecert parameter since a truststore has been specified");
+            }
+
+            String location      = trustStoreElt.getFirstChildWithName(new QName("Location")).getText();
+            String type          = trustStoreElt.getFirstChildWithName(new QName("Type")).getText();
+            String storePassword = trustStoreElt.getFirstChildWithName(new QName("Password")).getText();
+
+            FileInputStream fis = null;
+            try {
+                KeyStore trustStore = KeyStore.getInstance(type);
+                fis = new FileInputStream(location);
+                log.info("Loading Trust Keystore from : " + location);
+
+                trustStore.load(fis, storePassword.toCharArray());
+                TrustManagerFactory trustManagerfactory = TrustManagerFactory.getInstance(
+                    TrustManagerFactory.getDefaultAlgorithm());
+                trustManagerfactory.init(trustStore);
+                trustManagers = trustManagerfactory.getTrustManagers();
+
+            } catch (GeneralSecurityException gse) {
+                log.error("Error loading Key store : " + location, gse);
+                throw new AxisFault("Error loading Key store : " + location, gse);
+            } catch (IOException ioe) {
+                log.error("Error opening Key store : " + location, ioe);
+                throw new AxisFault("Error opening Key store : " + location, ioe);
+            } finally {
+                if (fis != null) {
+                    try {
+                        fis.close();
+                    } catch (IOException ignore) {}
+                }
+            }
+        } else if (novalidatecert) {
+            log.warn("Server certificate validation (trust) has been disabled. " +
+                    "DO NOT USE IN PRODUCTION!");
+            trustManagers = new TrustManager[] { new NoValidateCertTrustManager() };
+        }
+
+        try {
+            SSLContext sslcontext = SSLContext.getInstance("TLS");
+            sslcontext.init(keymanagers, trustManagers, null);
+            return sslcontext;
+
+        } catch (GeneralSecurityException gse) {
+            log.error("Unable to create SSL context with the given configuration", gse);
+            throw new AxisFault("Unable to create SSL context with the given configuration", gse);
+        }
+    }
+
+    private SSLSetupHandler createSSLIOSessionHandler(final String hostnameVerifier)
+            throws AxisFault {
+
+        return new SSLSetupHandler() {
+
+            public void initalize(SSLEngine sslengine, HttpParams params) {
+            }
+
+            public void verify(IOSession ioSession, SSLSession session) throws SSLException {
+                SocketAddress remoteAddress = ioSession.getRemoteAddress();
+                String address;
+                if (remoteAddress instanceof InetSocketAddress) {
+                    address = ((InetSocketAddress) remoteAddress).getHostName();
+                } else {
+                    address = remoteAddress.toString();
+                }
+
+                boolean valid = false;
+                if (hostnameVerifier != null) {
+                    if ("Strict".equals(hostnameVerifier)) {
+                        valid = HostnameVerifier.STRICT.verify(address, session);
+                    } else if ("AllowAll".equals(hostnameVerifier)) {
+                        valid = HostnameVerifier.ALLOW_ALL.verify(address, session);
+                    } else if ("DefaultAndLocalhost".equals(hostnameVerifier)) {
+                        valid = HostnameVerifier.DEFAULT_AND_LOCALHOST.verify(address, session);
+                    }
+                } else {
+                    valid = HostnameVerifier.DEFAULT.verify(address, session);
+                }
+
+                if (!valid) {
+                    throw new SSLException("Host name verification failed for host : " + address);
+                }
+            }
+        };
+    }
+
+    /**
+     * Trust manager accepting any certificate.
+     */
+    public static class NoValidateCertTrustManager implements X509TrustManager {
+        public void checkClientTrusted(X509Certificate[] chain, String authType)
+                throws CertificateException {
+            // Do nothing: we accept any certificate
+        }
+
+        public void checkServerTrusted(X509Certificate[] chain, String authType)
+                throws CertificateException {
+            // Do nothing: we accept any certificate
+        }
+
+        public X509Certificate[] getAcceptedIssuers() {
+            return new X509Certificate[0];
+        }
+    }
+}