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