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 org.apache.mina.core.service.IoHandlerAdapter;
35  import org.apache.mina.core.session.IoSession;
36  import org.apache.mina.filter.codec.ProtocolCodecFilter;
37  import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
38  import org.apache.mina.filter.ssl.SslFilter;
39  import org.apache.mina.transport.socket.SocketAcceptor;
40  import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
41  import org.junit.After;
42  import org.junit.Before;
43  import org.junit.Test;
44  import static org.junit.Assert.assertEquals;
45  import static org.junit.Assert.assertTrue;
46  
47  /**
48   * TODO Add documentation
49   * 
50   * @author The Apache MINA Project (dev@mina.apache.org)
51   * @version $Rev: 751473 $, $Date: 2009-03-08 18:22:14 +0100 (Sun, 08 Mar 2009) $
52   */
53  public class SslFilterTest {
54  
55      private int port;
56      private SocketAcceptor acceptor;
57  
58      @Before
59      public void setUp() throws Exception {
60          acceptor = new NioSocketAcceptor();
61      }
62  
63      @After
64      public void tearDown() throws Exception {
65          acceptor.setCloseOnDeactivation(true);
66          acceptor.dispose();
67      }
68  
69      @Test
70      public void testMessageSentIsCalled() throws Exception {
71          testMessageSentIsCalled(false);
72      }
73  
74      @Test
75      public void testMessageSentIsCalled_With_SSL() throws Exception {
76          testMessageSentIsCalled(true);
77      }
78  
79      private void testMessageSentIsCalled(boolean useSSL) throws Exception {
80          SslFilter sslFilter = null;
81          if (useSSL) {
82              sslFilter = new SslFilter(BogusSslContextFactory.getInstance(true));
83              acceptor.getFilterChain().addLast("sslFilter", sslFilter);
84          }
85          acceptor.getFilterChain().addLast(
86                  "codec",
87                  new ProtocolCodecFilter(new TextLineCodecFactory(Charset
88                          .forName("UTF-8"))));
89  
90          EchoHandler handler = new EchoHandler();
91          acceptor.setHandler(handler);
92          acceptor.bind(new InetSocketAddress(0));
93          port = acceptor.getLocalAddress().getPort();
94          //System.out.println("MINA server started.");
95  
96          Socket socket = getClientSocket(useSSL);
97          int bytesSent = 0;
98          bytesSent += writeMessage(socket, "test-1\n");
99  
100         if (useSSL) {
101             // Test renegotiation
102             SSLSocket ss = (SSLSocket) socket;
103             //ss.getSession().invalidate();
104             ss.startHandshake();
105         }
106 
107         bytesSent += writeMessage(socket, "test-2\n");
108 
109         int[] response = new int[bytesSent];
110         for (int i = 0; i < response.length; i++) {
111             response[i] = socket.getInputStream().read();
112         }
113 
114         if (useSSL) {
115             // Read SSL close notify.
116             while (socket.getInputStream().read() >= 0) {
117                 continue;
118             }
119         }
120 
121         socket.close();
122         while (acceptor.getManagedSessions().size() != 0) {
123             Thread.sleep(100);
124         }
125 
126         //System.out.println("handler: " + handler.sentMessages);
127         assertEquals("handler should have sent 2 messages:", 2,
128                 handler.sentMessages.size());
129         assertTrue(handler.sentMessages.contains("test-1"));
130         assertTrue(handler.sentMessages.contains("test-2"));
131     }
132 
133     private int writeMessage(Socket socket, String message) throws Exception {
134         byte request[] = message.getBytes("UTF-8");
135         socket.getOutputStream().write(request);
136         return request.length;
137     }
138 
139     private Socket getClientSocket(boolean ssl) throws Exception {
140         if (ssl) {
141             SSLContext ctx = SSLContext.getInstance("TLS");
142             ctx.init(null, trustManagers, null);
143             return ctx.getSocketFactory().createSocket("localhost", port);
144         }
145         return new Socket("localhost", port);
146     }
147 
148     private static class EchoHandler extends IoHandlerAdapter {
149 
150         List<String> sentMessages = new ArrayList<String>();
151 
152         @Override
153         public void exceptionCaught(IoSession session, Throwable cause)
154                 throws Exception {
155             //cause.printStackTrace();
156         }
157 
158         @Override
159         public void messageReceived(IoSession session, Object message)
160                 throws Exception {
161             session.write(message);
162         }
163 
164         @Override
165         public void messageSent(IoSession session, Object message)
166                 throws Exception {
167             sentMessages.add(message.toString());
168             //System.out.println(message);
169             if (sentMessages.size() >= 2) {
170                 session.close(true);
171             }
172         }
173     }
174 
175     TrustManager[] trustManagers = new TrustManager[] { new TrustAnyone() };
176 
177     private static class TrustAnyone implements X509TrustManager {
178         public void checkClientTrusted(
179                 java.security.cert.X509Certificate[] x509Certificates, String s)
180                 throws CertificateException {
181         }
182 
183         public void checkServerTrusted(
184                 java.security.cert.X509Certificate[] x509Certificates, String s)
185                 throws CertificateException {
186         }
187 
188         public java.security.cert.X509Certificate[] getAcceptedIssuers() {
189             return new java.security.cert.X509Certificate[0];
190         }
191     }
192 
193 }