View Javadoc

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.proxy;
21  
22  import java.net.InetSocketAddress;
23  import java.net.SocketAddress;
24  import java.util.concurrent.Executor;
25  
26  import org.apache.mina.core.buffer.IoBuffer;
27  import org.apache.mina.core.file.FileRegion;
28  import org.apache.mina.core.filterchain.IoFilter;
29  import org.apache.mina.core.future.ConnectFuture;
30  import org.apache.mina.core.future.DefaultConnectFuture;
31  import org.apache.mina.core.service.AbstractIoConnector;
32  import org.apache.mina.core.service.DefaultTransportMetadata;
33  import org.apache.mina.core.service.IoHandler;
34  import org.apache.mina.core.service.TransportMetadata;
35  import org.apache.mina.core.session.IoSession;
36  import org.apache.mina.core.session.IoSessionConfig;
37  import org.apache.mina.core.session.IoSessionInitializer;
38  import org.apache.mina.proxy.filter.ProxyFilter;
39  import org.apache.mina.proxy.handlers.socks.SocksProxyRequest;
40  import org.apache.mina.proxy.session.ProxyIoSession;
41  import org.apache.mina.proxy.session.ProxyIoSessionInitializer;
42  import org.apache.mina.transport.socket.DefaultSocketSessionConfig;
43  import org.apache.mina.transport.socket.SocketConnector;
44  import org.apache.mina.transport.socket.SocketSessionConfig;
45  
46  /**
47   * ProxyConnector.java - Decorator for {@link SocketConnector} to provide proxy support, 
48   * as suggested by MINA list discussions.
49   * <p>
50   * Operates by intercepting connect requests and replacing the endpoint address with the 
51   * proxy address, then adding a {@link ProxyFilter} as the first {@link IoFilter} which 
52   * performs any necessary handshaking with the proxy before allowing data to flow 
53   * normally. During the handshake, any outgoing write requests are buffered.
54   * 
55   * @see        http://www.nabble.com/Meta-Transport%3A-an-idea-on-implementing-reconnection-and-proxy-td12969001.html
56   * @see        http://issues.apache.org/jira/browse/DIRMINA-415
57   * 
58   * @author <a href="http://mina.apache.org">Apache MINA Project</a>
59   * @since MINA 2.0.0-M3
60   */
61  public class ProxyConnector extends AbstractIoConnector {
62      private static final TransportMetadata METADATA = new DefaultTransportMetadata("proxy", "proxyconnector", false,
63              true, InetSocketAddress.class, SocketSessionConfig.class, IoBuffer.class, FileRegion.class);
64  
65      /**
66       * Wrapped connector to use for outgoing TCP connections.
67       */
68      private SocketConnector connector = null;
69  
70      /**
71       * Proxy filter instance.
72       */
73      private final ProxyFilter proxyFilter = new ProxyFilter();
74  
75      /**
76       * The {@link ProxyIoSession} in use.
77       */
78      private ProxyIoSession proxyIoSession;
79  
80      /**
81       * This future will notify it's listeners when really connected to the target
82       */
83      private DefaultConnectFuture future;
84  
85      /**
86       * Creates a new proxy connector.
87       */
88      public ProxyConnector() {
89          super(new DefaultSocketSessionConfig(), null);
90      }
91  
92      /**
93       * Creates a new proxy connector.
94       * 
95       * @param connector Connector used to establish proxy connections.
96       */
97      public ProxyConnector(final SocketConnector connector) {
98          this(connector, new DefaultSocketSessionConfig(), null);
99      }
100 
101     /**
102      * Creates a new proxy connector. 
103      * @see AbstractIoConnector(IoSessionConfig, Executor).
104      */
105     public ProxyConnector(final SocketConnector connector, IoSessionConfig config, Executor executor) {
106         super(config, executor);
107         setConnector(connector);
108     }
109 
110     /**
111      * {@inheritDoc}
112      */
113     public IoSessionConfig getSessionConfig() {
114         return connector.getSessionConfig();
115     }
116 
117     /**
118      * Returns the {@link ProxyIoSession} linked with this connector.
119      */
120     public ProxyIoSession getProxyIoSession() {
121         return proxyIoSession;
122     }
123 
124     /**
125      * Sets the proxy session object of this connector.
126      * @param proxyIoSession the configuration of this connector.
127      */
128     public void setProxyIoSession(ProxyIoSession proxyIoSession) {
129         if (proxyIoSession == null) {
130             throw new IllegalArgumentException("proxySession object cannot be null");
131         }
132 
133         if (proxyIoSession.getProxyAddress() == null) {
134             throw new IllegalArgumentException("proxySession.proxyAddress cannot be null");
135         }
136 
137         proxyIoSession.setConnector(this);
138         setDefaultRemoteAddress(proxyIoSession.getProxyAddress());
139         this.proxyIoSession = proxyIoSession;
140     }
141 
142     /**
143      * Connects to the specified <code>address</code>.  If communication starts
144      * successfully, events are fired to the connector's <code>handler</code>.
145      * 
146      * @param remoteAddress the remote address to connect to
147      * @param localAddress the local address
148      * @param sessionInitializer the session initializer
149      * @return {@link ConnectFuture} that will tell the result of the connection attempt
150      */
151     @SuppressWarnings("unchecked")
152     @Override
153     protected ConnectFuture connect0(final SocketAddress remoteAddress, final SocketAddress localAddress,
154             final IoSessionInitializer<? extends ConnectFuture> sessionInitializer) {
155         if (!proxyIoSession.isReconnectionNeeded()) {
156             // First connection
157             IoHandler handler = getHandler();
158             if (!(handler instanceof AbstractProxyIoHandler)) {
159                 throw new IllegalArgumentException("IoHandler must be an instance of AbstractProxyIoHandler");
160             }
161 
162             connector.setHandler(handler);
163             future = new DefaultConnectFuture();
164         }
165 
166         ConnectFuture conFuture = connector.connect(proxyIoSession.getProxyAddress(), new ProxyIoSessionInitializer(
167                 sessionInitializer, proxyIoSession));
168 
169         // If proxy does not use reconnection like socks the connector's 
170         // future is returned. If we're in the middle of a reconnection
171         // then we send back the connector's future which is only used
172         // internally while <code>future</code> will be used to notify
173         // the user of the connection state.
174         if (proxyIoSession.getRequest() instanceof SocksProxyRequest || proxyIoSession.isReconnectionNeeded()) {
175             return conFuture;
176         }
177 
178         return future;
179     }
180 
181     /**
182      * Cancels the real connection when reconnection is in use.
183      */
184     public void cancelConnectFuture() {
185         future.cancel();
186     }
187 
188     /**
189      * Fires the connection event on the real future to notify the client.
190      * 
191      * @param session the current session
192      * @return the future holding the connected session
193      */
194     protected ConnectFuture fireConnected(final IoSession session) {
195         future.setSession(session);
196         return future;
197     }
198 
199     /**
200      * Get the {@link SocketConnector} to be used for connections
201      * to the proxy server.
202      */
203     public final SocketConnector getConnector() {
204         return connector;
205     }
206 
207     /**
208      * Sets the {@link SocketConnector} to be used for connections
209      * to the proxy server.
210      * 
211      * @param connector the connector to use
212      */
213     private final void setConnector(final SocketConnector connector) {
214         if (connector == null) {
215             throw new IllegalArgumentException("connector cannot be null");
216         }
217 
218         this.connector = connector;
219         String className = ProxyFilter.class.getName();
220 
221         // Removes an old ProxyFilter instance from the chain
222         if (connector.getFilterChain().contains(className)) {
223             connector.getFilterChain().remove(className);
224         }
225 
226         // Insert the ProxyFilter as the first filter in the filter chain builder        
227         connector.getFilterChain().addFirst(className, proxyFilter);
228     }
229 
230     /**
231      * {@inheritDoc}
232      */
233     @Override
234     protected void dispose0() throws Exception {
235         if (connector != null) {
236             connector.dispose();
237         }
238     }
239 
240     /**
241      * {@inheritDoc}
242      */
243     public TransportMetadata getTransportMetadata() {
244         return METADATA;
245     }
246 }