1 /*
2 * Copyright 2019 The Netty Project
3 *
4 * The Netty Project licenses this file to you under the Apache License,
5 * version 2.0 (the "License"); you may not use this file except in compliance
6 * with the License. You may obtain a copy of the License at:
7 *
8 * https://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 * License for the specific language governing permissions and limitations
14 * under the License.
15 */
16 package io.netty5.handler.address;
17
18 import io.netty5.channel.ChannelHandler;
19 import io.netty5.channel.ChannelHandlerContext;
20 import io.netty5.util.concurrent.Future;
21
22 import java.net.NetworkInterface;
23 import java.net.SocketAddress;
24
25 /**
26 * {@link ChannelHandler} implementation which allows to dynamically replace the used
27 * {@code remoteAddress} and / or {@code localAddress} when making a connection attempt.
28 * <p>
29 * This can be useful to for example bind to a specific {@link NetworkInterface} based on
30 * the {@code remoteAddress}.
31 */
32 public abstract class DynamicAddressConnectHandler implements ChannelHandler {
33
34 @Override
35 public final Future<Void> connect(ChannelHandlerContext ctx, SocketAddress remoteAddress,
36 SocketAddress localAddress) {
37 final SocketAddress remote;
38 final SocketAddress local;
39 try {
40 remote = remoteAddress(remoteAddress, localAddress);
41 local = localAddress(remoteAddress, localAddress);
42 } catch (Exception e) {
43 return ctx.newFailedFuture(e);
44 }
45 return ctx.connect(remote, local).addListener(future -> {
46 if (future.isSuccess()) {
47 // We only remove this handler from the pipeline once the connect was successful as otherwise
48 // the user may try to connect again.
49 ctx.pipeline().remove(this);
50 }
51 });
52 }
53
54 /**
55 * Returns the local {@link SocketAddress} to use for
56 * {@link ChannelHandlerContext#connect(SocketAddress, SocketAddress)} based on the original {@code remoteAddress}
57 * and {@code localAddress}.
58 * By default, this method returns the given {@code localAddress}.
59 */
60 protected SocketAddress localAddress(
61 @SuppressWarnings("unused") SocketAddress remoteAddress, SocketAddress localAddress) throws Exception {
62 return localAddress;
63 }
64
65 /**
66 * Returns the remote {@link SocketAddress} to use for
67 * {@link ChannelHandlerContext#connect(SocketAddress, SocketAddress)} based on the original {@code remoteAddress}
68 * and {@code localAddress}.
69 * By default, this method returns the given {@code remoteAddress}.
70 */
71 protected SocketAddress remoteAddress(
72 SocketAddress remoteAddress, @SuppressWarnings("unused") SocketAddress localAddress) throws Exception {
73 return remoteAddress;
74 }
75 }