1   /*
2    *  Licensed to the Apache Software Foundation (ASF) under one
3    *  or more contributor license agreements.  See the NOTICE file
4    *  distributed with this work for additional information
5    *  regarding copyright ownership.  The ASF licenses this file
6    *  to you under the Apache License, Version 2.0 (the
7    *  "License"); you may not use this file except in compliance
8    *  with the License.  You may obtain a copy of the License at
9    *
10   *    http://www.apache.org/licenses/LICENSE-2.0
11   *
12   *  Unless required by applicable law or agreed to in writing,
13   *  software distributed under the License is distributed on an
14   *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   *  KIND, either express or implied.  See the License for the
16   *  specific language governing permissions and limitations
17   *  under the License.
18   *
19   */
20  package org.apache.mina.example.echoserver.ssl;
21  
22  import java.net.InetSocketAddress;
23  import java.net.Socket;
24  import java.nio.charset.Charset;
25  import java.security.cert.CertificateException;
26  import java.util.ArrayList;
27  import java.util.List;
28  
29  import javax.net.ssl.SSLContext;
30  import javax.net.ssl.SSLSocket;
31  import javax.net.ssl.TrustManager;
32  import javax.net.ssl.X509TrustManager;
33  
34  import junit.framework.TestCase;
35  
36  import org.apache.mina.core.service.IoHandlerAdapter;
37  import org.apache.mina.core.session.IoSession;
38  import org.apache.mina.filter.codec.ProtocolCodecFilter;
39  import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
40  import org.apache.mina.filter.ssl.SslFilter;
41  import org.apache.mina.transport.socket.SocketAcceptor;
42  import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
43  
44  /**
45   * TODO Add documentation
46   * 
47   * @author The Apache MINA Project (dev@mina.apache.org)
48   * @version $Rev: 671827 $, $Date: 2008-06-26 10:49:48 +0200 (jeu, 26 jun 2008) $
49   */
50  public class SslFilterTest extends TestCase {
51  
52      private int port;
53      private SocketAcceptor acceptor;
54  
55      @Override
56      protected void setUp() throws Exception {
57          super.setUp();
58          acceptor = new NioSocketAcceptor();
59      }
60  
61      @Override
62      protected void tearDown() throws Exception {
63          acceptor.setCloseOnDeactivation(true);
64          acceptor.dispose();
65          super.tearDown();
66      }
67  
68      public void testMessageSentIsCalled() throws Exception {
69          testMessageSentIsCalled(false);
70      }
71  
72      public void testMessageSentIsCalled_With_SSL() throws Exception {
73          testMessageSentIsCalled(true);
74      }
75  
76      private void testMessageSentIsCalled(boolean useSSL) throws Exception {
77          SslFilter sslFilter = null;
78          if (useSSL) {
79              sslFilter = new SslFilter(BogusSslContextFactory.getInstance(true));
80              acceptor.getFilterChain().addLast("sslFilter", sslFilter);
81          }
82          acceptor.getFilterChain().addLast(
83                  "codec",
84                  new ProtocolCodecFilter(new TextLineCodecFactory(Charset
85                          .forName("UTF-8"))));
86  
87          EchoHandler handler = new EchoHandler();
88          acceptor.setHandler(handler);
89          acceptor.bind(new InetSocketAddress(0));
90          port = acceptor.getLocalAddress().getPort();
91          System.out.println("MINA server started.");
92  
93          Socket socket = getClientSocket(useSSL);
94          int bytesSent = 0;
95          bytesSent += writeMessage(socket, "test-1\n");
96  
97          if (useSSL) {
98              // Test renegotiation
99              SSLSocket ss = (SSLSocket) socket;
100             //ss.getSession().invalidate();
101             ss.startHandshake();
102         }
103 
104         bytesSent += writeMessage(socket, "test-2\n");
105 
106         int[] response = new int[bytesSent];
107         for (int i = 0; i < response.length; i++) {
108             response[i] = socket.getInputStream().read();
109         }
110 
111         if (useSSL) {
112             // Read SSL close notify.
113             while (socket.getInputStream().read() >= 0) {
114                 continue;
115             }
116         }
117 
118         socket.close();
119         while (acceptor.getManagedSessions().size() != 0) {
120             Thread.sleep(100);
121         }
122 
123         System.out.println("handler: " + handler.sentMessages);
124         assertEquals("handler should have sent 2 messages:", 2,
125                 handler.sentMessages.size());
126         assertTrue(handler.sentMessages.contains("test-1"));
127         assertTrue(handler.sentMessages.contains("test-2"));
128     }
129 
130     private int writeMessage(Socket socket, String message) throws Exception {
131         byte request[] = message.getBytes("UTF-8");
132         socket.getOutputStream().write(request);
133         return request.length;
134     }
135 
136     private Socket getClientSocket(boolean ssl) throws Exception {
137         if (ssl) {
138             SSLContext ctx = SSLContext.getInstance("TLS");
139             ctx.init(null, trustManagers, null);
140             return ctx.getSocketFactory().createSocket("localhost", port);
141         }
142         return new Socket("localhost", port);
143     }
144 
145     private static class EchoHandler extends IoHandlerAdapter {
146 
147         List<String> sentMessages = new ArrayList<String>();
148 
149         @Override
150         public void exceptionCaught(IoSession session, Throwable cause)
151                 throws Exception {
152             cause.printStackTrace();
153         }
154 
155         @Override
156         public void messageReceived(IoSession session, Object message)
157                 throws Exception {
158             session.write(message);
159         }
160 
161         @Override
162         public void messageSent(IoSession session, Object message)
163                 throws Exception {
164             sentMessages.add(message.toString());
165             System.out.println(message);
166             if (sentMessages.size() >= 2) {
167                 session.close();
168             }
169         }
170     }
171 
172     TrustManager[] trustManagers = new TrustManager[] { new TrustAnyone() };
173 
174     private static class TrustAnyone implements X509TrustManager {
175         public void checkClientTrusted(
176                 java.security.cert.X509Certificate[] x509Certificates, String s)
177                 throws CertificateException {
178         }
179 
180         public void checkServerTrusted(
181                 java.security.cert.X509Certificate[] x509Certificates, String s)
182                 throws CertificateException {
183         }
184 
185         public java.security.cert.X509Certificate[] getAcceptedIssuers() {
186             return new java.security.cert.X509Certificate[0];
187         }
188     }
189 
190 }