View Javadoc
1   /*
2    * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.com
3    * The software in this package is published under the terms of the CPAL v1.0
4    * license, a copy of which has been included with this distribution in the
5    * LICENSE.txt file.
6    */
7   package org.mule.test.firewall;
8   
9   import org.mule.config.factories.HostNameFactory;
10  import org.mule.tck.junit4.AbstractMuleTestCase;
11  
12  import java.io.IOException;
13  import java.net.DatagramPacket;
14  import java.net.DatagramSocket;
15  import java.net.InetAddress;
16  import java.net.ServerSocket;
17  import java.net.Socket;
18  import java.net.UnknownHostException;
19  import java.security.SecureRandom;
20  
21  import org.apache.commons.logging.Log;
22  import org.apache.commons.logging.LogFactory;
23  import org.junit.Test;
24  
25  import static org.junit.Assert.assertEquals;
26  import static org.junit.Assert.assertNotSame;
27  
28  public class FirewallTestCase extends AbstractMuleTestCase
29  {
30      public static final String LOCALHOST = "localhost";
31      public static final String LOCALADDR = "127.0.0.1";
32      public static final int TEST_COUNT = 1;
33  
34      protected final Log logger = LogFactory.getLog(this.getClass());
35  
36      private SecureRandom random = new SecureRandom();
37  
38      @Test
39      public void testLoopback() throws Exception
40      {
41          // this gives localhost.localdomain on sourceforge
42  //        consistentAddress(LOCALHOST, true);
43          consistentAddress(LOCALHOST, false);
44  //        assertEquals("Strange name for loopback", LOCALHOST, InetAddress.getByName(LOCALADDR).getCanonicalHostName());
45      }
46  
47      @Test
48      public void testLocalHost() throws Exception
49      {
50          InetAddress aLocalAddress = InetAddress.getLocalHost();
51          logger.info("Java returns " + addressToString(aLocalAddress) + " as the 'local' address");
52          assertNotSame("No external address", LOCALADDR, aLocalAddress.getHostAddress());
53          consistentAddress(aLocalAddress.getHostName(), false);
54          assertEquals("Inconsistent hostname", aLocalAddress.getHostName(), new HostNameFactory().create(null));
55      }
56  
57      @Test
58      public void testCanonicalHost() throws Exception
59      {
60          InetAddress aLocalAddress = InetAddress.getLocalHost();
61          assertNotSame("No extrernal name", LOCALHOST, aLocalAddress.getCanonicalHostName());
62          consistentAddress(aLocalAddress.getCanonicalHostName(), true);
63      }
64  
65      protected void consistentAddress(String name, boolean canonical) throws UnknownHostException
66      {
67          String address = InetAddress.getByName(name).getHostAddress();
68          logger.debug("Testing relationship between " + name + " and " + address);
69          assertEquals("Name " + name + " is inconsistent", name,
70                  name(InetAddress.getByName(name), canonical));
71          assertEquals("Address " + address + " is inconsistent", address,
72                  InetAddress.getByName(address).getHostAddress());
73          // we cannot expect to go from address to name consistently, but we can expect
74          // names always to resolve to the same address, and for addresses not to change
75          // when going via a name (in other words, any aliases are consistent).
76          assertEquals(name + " -> " + address + " is inconsistent", address,
77                  InetAddress.getByName(name).getHostAddress());
78          assertEquals(name + " -> " + address + " -> " + name + " -> " + address + " is inconsistent", address,
79                  InetAddress.getByName(
80                          name(
81                                  InetAddress.getByName(
82                                          InetAddress.getByName(name).getHostAddress()), canonical)).getHostAddress());
83      }
84  
85      protected String name(InetAddress address, boolean canonical)
86      {
87          if (canonical)
88          {
89              return address.getCanonicalHostName();
90          }
91          else
92          {
93              return address.getHostName();
94          }
95      }
96  
97      @Test
98      public void testLocalhostTcp() throws Exception
99      {
100         for (int i = 0; i < TEST_COUNT; ++i)
101         {
102             doTestTcp(InetAddress.getByName(LOCALHOST), randomPrivatePort());
103         }
104     }
105 
106     @Test
107     public void testHostnameTcp() throws Exception
108     {
109         for (int i = 0; i < TEST_COUNT; ++i)
110         {
111             doTestTcp(InetAddress.getLocalHost(), randomPrivatePort());
112         }
113     }
114 
115     @Test
116     public void testLocalhostUdp() throws Exception
117     {
118         for (int i = 0; i < TEST_COUNT; ++i)
119         {
120             doTestUdp(InetAddress.getByName(LOCALHOST), randomPrivatePort());
121         }
122     }
123 
124     @Test
125     public void testHostnameUdp() throws Exception
126     {
127         for (int i = 0; i < TEST_COUNT; ++i)
128         {
129             doTestUdp(InetAddress.getLocalHost(), randomPrivatePort());
130         }
131     }
132 
133     protected void doTestTcp(InetAddress address, int port) throws Exception
134     {
135         try
136         {
137             logger.debug("Testing TCP on " + addressToString(address, port));
138             ServerSocket server = openTcpServer(address, port);
139             Socket client = openTcpClient(address, port);
140             Socket receiver = server.accept();
141             client.getOutputStream().write(1);
142             assertEquals("Failed to send byte via " + addressToString(address, port),
143                     1, receiver.getInputStream().read());
144             client.close();
145             server.close();
146         }
147         catch (Exception e)
148         {
149             logger.error("Error while attempting TCP message on " + addressToString(address, port));
150             throw e;
151         }
152     }
153 
154     protected void doTestUdp(InetAddress address, int port) throws Exception
155     {
156         try
157         {
158             logger.debug("Testing UDP on " + addressToString(address, port));
159             DatagramSocket server = openUdpServer(address, port);
160             DatagramSocket client = openUdpClient();
161             client.send(new DatagramPacket(new byte[]{1}, 1, address, port));
162             DatagramPacket packet = new DatagramPacket(new byte[1], 1);
163             server.receive(packet);
164             assertEquals("Failed to send packet via " + addressToString(address, port),
165                     1, packet.getData()[0]);
166             client.close();
167             server.close();
168         }
169         catch (Exception e)
170         {
171             logger.error("Error while attempting UDP message on " + addressToString(address, port));
172             throw e;
173         }
174     }
175 
176     protected Socket openTcpClient(InetAddress address, int port) throws IOException
177     {
178         try
179         {
180             return new Socket(address, port);
181         }
182         catch (IOException e)
183         {
184             logger.error("Could not open TCP client to " + addressToString(address, port));
185             throw e;
186         }
187     }
188 
189     protected ServerSocket openTcpServer(InetAddress address, int port) throws IOException
190     {
191         try
192         {
193             return new ServerSocket(port, 1, address);
194         }
195         catch (IOException e)
196         {
197             logger.error("Could not open TCP server on " + addressToString(address, port));
198             throw e;
199         }
200     }
201 
202     protected DatagramSocket openUdpServer(InetAddress address, int port) throws IOException
203     {
204         try
205         {
206             return new DatagramSocket(port, address);
207         }
208         catch (IOException e)
209         {
210             logger.error("Could not open UDP server on " + addressToString(address, port));
211             throw e;
212         }
213     }
214 
215     protected DatagramSocket openUdpClient() throws IOException
216     {
217         try
218         {
219             return new DatagramSocket();
220         }
221         catch (IOException e)
222         {
223             logger.error("Could not open UDP client");
224             throw e;
225         }
226     }
227 
228     protected String addressToString(InetAddress address, int port)
229     {
230         return addressToString(address) + ":" + port;
231     }
232 
233     protected String addressToString(InetAddress address)
234     {
235         return address.getHostName() + "/" + address.getCanonicalHostName() + "/" + address.getHostAddress();
236     }
237 
238     protected int randomPrivatePort()
239     {
240         return randomPort(49152, 65535);
241     }
242 
243     /**
244      * @param lo
245      * @param hi
246      * @return A number between lo and hi (inclusive)
247      */
248     protected int randomPort(int lo, int hi)
249     {
250         return lo + random.nextInt(hi - lo + 1);
251     }
252 
253 }