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.future.IoFuture;
32  import org.apache.mina.core.service.AbstractIoConnector;
33  import org.apache.mina.core.service.DefaultTransportMetadata;
34  import org.apache.mina.core.service.IoHandler;
35  import org.apache.mina.core.service.TransportMetadata;
36  import org.apache.mina.core.session.IoSession;
37  import org.apache.mina.core.session.IoSessionConfig;
38  import org.apache.mina.core.session.IoSessionInitializer;
39  import org.apache.mina.proxy.filter.ProxyFilter;
40  import org.apache.mina.proxy.handlers.socks.SocksProxyRequest;
41  import org.apache.mina.proxy.session.ProxyIoSession;
42  import org.apache.mina.proxy.session.ProxyIoSessionInitializer;
43  import org.apache.mina.transport.socket.DefaultSocketSessionConfig;
44  import org.apache.mina.transport.socket.SocketConnector;
45  import org.apache.mina.transport.socket.SocketSessionConfig;
46  
47  /**
48   * ProxyConnector.java - Decorator for {@link SocketConnector} to provide proxy support, as suggested by MINA list discussions.
49   * <p>
50   * Operates by intercepting connect requests and replacing the endpoint address with the proxy address,
51   * then adding a {@link ProxyFilter} as the first {@link IoFilter} which performs any necessary
52   * handshaking with the proxy before allowing data to flow normally. During the handshake, any outgoing
53   * 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 The Apache MINA Project (dev@mina.apache.org)
59   * @version $Rev: 685703 $, $Date: 2008-08-14 00:14:47 +0200 (Thu, 14 Aug 2008) $
60   * @since MINA 2.0.0-M3
61   */
62  public class ProxyConnector extends AbstractIoConnector {
63      static final TransportMetadata METADATA = new DefaultTransportMetadata(
64              "proxy", "proxyconnector", false, true, InetSocketAddress.class,
65              SocketSessionConfig.class, IoBuffer.class, FileRegion.class);
66  
67      /**
68       * Wrapped connector to use for outgoing TCP connections.
69       */
70      private SocketConnector connector = null;
71  
72      /**
73       * Proxy filter instance.
74       */
75      private final ProxyFilter proxyFilter = new ProxyFilter();
76  
77      /**
78       * The {@link ProxyIoSession} in use.
79       */
80      private ProxyIoSession proxyIoSession;
81  
82      /**
83       * This future will notify it's listeners when really connected to the target
84       */
85      private DefaultConnectFuture future;
86  
87      /**
88       * Creates a new proxy connector.
89       */
90      public ProxyConnector() {
91          super(new DefaultSocketSessionConfig(), null);
92      }
93  
94      /**
95       * Creates a new proxy connector.
96       * 
97       * @param connector         Connector used to establish proxy connections.
98       */
99      public ProxyConnector(final SocketConnector connector) {        
100         this(connector, new DefaultSocketSessionConfig(), null);
101     }
102 
103     /**
104      * Creates a new proxy connector. 
105      * @see AbstractIoConnector(IoSessionConfig, Executor).
106      */
107     public ProxyConnector(final SocketConnector connector, IoSessionConfig config, Executor executor) {
108         super(config, executor);
109         setConnector(connector);
110     }    
111         
112     @Override
113     public IoSessionConfig getSessionConfig() {
114         return connector.getSessionConfig();
115     }
116 
117     public ProxyIoSession getProxyIoSession() {
118         return proxyIoSession;
119     }
120 
121     public void setProxyIoSession(ProxyIoSession proxyIoSession) {
122         if (proxyIoSession == null) {
123             throw new NullPointerException("proxySession cannot be null");
124         }
125 
126         if (proxyIoSession.getProxyAddress() == null) {
127             throw new NullPointerException(
128                     "proxySession.proxyAddress cannot be null");
129         }
130 
131         proxyIoSession.setConnector(this);
132         setDefaultRemoteAddress(proxyIoSession.getProxyAddress());
133         this.proxyIoSession = proxyIoSession;
134     }
135 
136     /**
137      * Connects to the specified <code>address</code>.  If communication starts
138      * successfully, events are fired to the specified
139      * <code>handler</code>.
140      * 
141      * @return {@link ConnectFuture} that will tell the result of the connection attempt
142      */
143     @SuppressWarnings("unchecked")
144     @Override
145     protected ConnectFuture connect0(
146             final SocketAddress remoteAddress,
147             final SocketAddress localAddress,
148             final IoSessionInitializer<? extends ConnectFuture> sessionInitializer) {
149         if (!proxyIoSession.isReconnectionNeeded()) {
150             // First connection
151             IoHandler handler = getHandler();
152             if (!(handler instanceof AbstractProxyIoHandler)) {
153                 throw new IllegalArgumentException(
154                         "IoHandler must be an instance of AbstractProxyIoHandler");
155             }
156 
157             connector.setHandler(handler);
158             future = new DefaultConnectFuture();
159         }
160 
161         ConnectFuture conFuture = connector.connect(proxyIoSession
162                 .getProxyAddress(), new ProxyIoSessionInitializer(
163                 sessionInitializer, proxyIoSession));
164 
165         if (proxyIoSession.getRequest() instanceof SocksProxyRequest
166                 || proxyIoSession.isReconnectionNeeded()) {
167             return conFuture;
168         } else {
169             return future;
170         }
171     }
172 
173     public void cancelConnectFuture() {
174         future.cancel();
175     }
176 
177     protected ConnectFuture fireConnected(final IoSession session) {
178         future.setSession(session);
179         return future;
180     }
181 
182     /**
183      * Get the {@link SocketConnector} to be used for connections
184      * to the proxy server.
185      */
186     public final SocketConnector getConnector() {
187         return connector;
188     }
189 
190     /**
191      * Set the {@link SocketConnector} to be used for connections
192      * to the proxy server.
193      */
194     public final void setConnector(final SocketConnector newConnector) {
195         if (newConnector == null) {
196             throw new NullPointerException("connector cannot be null");
197         }
198 
199         SocketConnector oldConnector = this.connector;
200 
201         // Remove the ProxyFilter from the old filter chain builder
202         if (oldConnector != null) {
203             oldConnector.getFilterChain().remove(ProxyFilter.class.getName());
204         }
205 
206         this.connector = newConnector;
207 
208         // Insert the ProxyFilter as the first filter in the filter chain builder
209         if (newConnector.getFilterChain().contains(ProxyFilter.class.getName())) {
210             newConnector.getFilterChain().remove(ProxyFilter.class.getName());
211         }
212 
213         newConnector.getFilterChain().addFirst(ProxyFilter.class.getName(),
214                 proxyFilter);
215     }
216 
217     /* (non-Javadoc)
218      * @see org.apache.mina.common.AbstractIoService#dispose0()
219      */
220     @Override
221     protected IoFuture dispose0() throws Exception {
222         if (connector != null) {
223             connector.dispose();
224         }
225         return null;
226     }
227 
228     /* (non-Javadoc)
229      * @see org.apache.mina.common.IoService#getTransportMetadata()
230      */
231     public TransportMetadata getTransportMetadata() {
232         return METADATA;
233     }
234 }