1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty.testsuite.transport.socket;
17
18 import io.netty.bootstrap.Bootstrap;
19 import io.netty.bootstrap.ServerBootstrap;
20 import io.netty.buffer.ByteBuf;
21 import io.netty.channel.Channel;
22 import io.netty.channel.ChannelFuture;
23 import io.netty.channel.ChannelFutureListener;
24 import io.netty.channel.ChannelHandlerContext;
25 import io.netty.channel.ChannelInboundHandlerAdapter;
26 import io.netty.channel.ChannelInitializer;
27 import io.netty.channel.ChannelOption;
28 import io.netty.channel.ChannelPromise;
29 import io.netty.channel.socket.DuplexChannel;
30 import io.netty.channel.socket.SocketChannel;
31 import io.netty.util.concurrent.ImmediateEventExecutor;
32 import io.netty.util.concurrent.Promise;
33 import org.junit.jupiter.api.Test;
34 import org.junit.jupiter.api.TestInfo;
35 import org.junit.jupiter.api.Timeout;
36
37 import java.io.ByteArrayOutputStream;
38 import java.net.InetSocketAddress;
39 import java.net.SocketAddress;
40 import java.util.concurrent.BlockingQueue;
41 import java.util.concurrent.LinkedBlockingQueue;
42 import java.util.concurrent.Semaphore;
43 import java.util.concurrent.TimeUnit;
44 import java.util.concurrent.atomic.AtomicBoolean;
45
46 import static io.netty.buffer.ByteBufUtil.writeAscii;
47 import static io.netty.buffer.UnpooledByteBufAllocator.DEFAULT;
48 import static io.netty.util.CharsetUtil.US_ASCII;
49 import static org.junit.jupiter.api.Assertions.assertEquals;
50 import static org.junit.jupiter.api.Assertions.assertFalse;
51 import static org.junit.jupiter.api.Assertions.assertNotNull;
52 import static org.junit.jupiter.api.Assertions.assertNull;
53 import static org.junit.jupiter.api.Assertions.assertTrue;
54
55 public class SocketConnectTest extends AbstractSocketTest {
56
57 @Test
58 @Timeout(value = 30000, unit = TimeUnit.MILLISECONDS)
59 public void testLocalAddressAfterConnect(TestInfo testInfo) throws Throwable {
60 run(testInfo, new Runner<ServerBootstrap, Bootstrap>() {
61 @Override
62 public void run(ServerBootstrap serverBootstrap, Bootstrap bootstrap) throws Throwable {
63 testLocalAddressAfterConnect(serverBootstrap, bootstrap);
64 }
65 });
66 }
67
68 public void testLocalAddressAfterConnect(ServerBootstrap sb, Bootstrap cb) throws Throwable {
69 Channel serverChannel = null;
70 Channel clientChannel = null;
71 try {
72 final Promise<InetSocketAddress> localAddressPromise = ImmediateEventExecutor.INSTANCE.newPromise();
73 serverChannel = sb.childHandler(new ChannelInboundHandlerAdapter() {
74 @Override
75 public void channelActive(ChannelHandlerContext ctx) throws Exception {
76 localAddressPromise.setSuccess((InetSocketAddress) ctx.channel().localAddress());
77 }
78 }).bind().syncUninterruptibly().channel();
79
80 clientChannel = cb.handler(new ChannelInboundHandlerAdapter()).register().syncUninterruptibly().channel();
81
82 assertNull(clientChannel.localAddress());
83 assertNull(clientChannel.remoteAddress());
84
85 clientChannel.connect(serverChannel.localAddress()).syncUninterruptibly().channel();
86 assertLocalAddress((InetSocketAddress) clientChannel.localAddress());
87 assertNotNull(clientChannel.remoteAddress());
88
89 assertLocalAddress(localAddressPromise.get());
90 } finally {
91 if (clientChannel != null) {
92 clientChannel.close().syncUninterruptibly();
93 }
94 if (serverChannel != null) {
95 serverChannel.close().syncUninterruptibly();
96 }
97 }
98 }
99
100 @Test
101 @Timeout(value = 3000, unit = TimeUnit.MILLISECONDS)
102 public void testChannelEventsFiredWhenClosedDirectly(TestInfo testInfo) throws Throwable {
103 run(testInfo, new Runner<ServerBootstrap, Bootstrap>() {
104 @Override
105 public void run(ServerBootstrap serverBootstrap, Bootstrap bootstrap) throws Throwable {
106 testChannelEventsFiredWhenClosedDirectly(serverBootstrap, bootstrap);
107 }
108 });
109 }
110
111 public void testChannelEventsFiredWhenClosedDirectly(ServerBootstrap sb, Bootstrap cb) throws Throwable {
112 final BlockingQueue<Integer> events = new LinkedBlockingQueue<Integer>();
113
114 Channel sc = null;
115 Channel cc = null;
116 try {
117 sb.childHandler(new ChannelInboundHandlerAdapter());
118 sc = sb.bind().syncUninterruptibly().channel();
119
120 cb.handler(new ChannelInboundHandlerAdapter() {
121 @Override
122 public void channelActive(ChannelHandlerContext ctx) throws Exception {
123 events.add(0);
124 }
125
126 @Override
127 public void channelInactive(ChannelHandlerContext ctx) throws Exception {
128 events.add(1);
129 }
130 });
131
132 cc = cb.connect(sc.localAddress()).addListener(ChannelFutureListener.CLOSE).
133 syncUninterruptibly().channel();
134 assertEquals(0, events.take().intValue());
135 assertEquals(1, events.take().intValue());
136 } finally {
137 if (cc != null) {
138 cc.close();
139 }
140 if (sc != null) {
141 sc.close();
142 }
143 }
144 }
145
146 @Test
147 @Timeout(value = 3000, unit = TimeUnit.MILLISECONDS)
148 public void testWriteWithFastOpenBeforeConnect(TestInfo testInfo) throws Throwable {
149 run(testInfo, new Runner<ServerBootstrap, Bootstrap>() {
150 @Override
151 public void run(ServerBootstrap serverBootstrap, Bootstrap bootstrap) throws Throwable {
152 testWriteWithFastOpenBeforeConnect(serverBootstrap, bootstrap);
153 }
154 });
155 }
156
157 public void testWriteWithFastOpenBeforeConnect(ServerBootstrap sb, Bootstrap cb) throws Throwable {
158 enableTcpFastOpen(sb, cb);
159 sb.childOption(ChannelOption.AUTO_READ, true);
160 cb.option(ChannelOption.AUTO_READ, true);
161
162 sb.childHandler(new ChannelInitializer<SocketChannel>() {
163 @Override
164 protected void initChannel(SocketChannel ch) throws Exception {
165 ch.pipeline().addLast(new EchoServerHandler());
166 }
167 });
168
169 Channel sc = sb.bind().sync().channel();
170 connectAndVerifyDataTransfer(cb, sc);
171 connectAndVerifyDataTransfer(cb, sc);
172 }
173
174 private static void connectAndVerifyDataTransfer(Bootstrap cb, Channel sc)
175 throws InterruptedException {
176 BufferingClientHandler handler = new BufferingClientHandler();
177 cb.handler(handler);
178 ChannelFuture register = cb.register();
179 Channel channel = register.sync().channel();
180 ChannelFuture write = channel.write(writeAscii(DEFAULT, "[fastopen]"));
181 SocketAddress remoteAddress = sc.localAddress();
182 ChannelFuture connectFuture = channel.connect(remoteAddress);
183 Channel cc = connectFuture.sync().channel();
184 cc.writeAndFlush(writeAscii(DEFAULT, "[normal data]")).sync();
185 write.sync();
186 String expectedString = "[fastopen][normal data]";
187 String result = handler.collectBuffer(expectedString.getBytes(US_ASCII).length);
188 cc.disconnect().sync();
189 assertEquals(expectedString, result);
190 }
191
192 @Test
193 @Timeout(value = 3000, unit = TimeUnit.MILLISECONDS)
194 public void testWriteFromFastOpenInitialDataListener(TestInfo testInfo) throws Throwable {
195 run(testInfo, new Runner<ServerBootstrap, Bootstrap>() {
196 @Override
197 public void run(ServerBootstrap serverBootstrap, Bootstrap bootstrap) throws Throwable {
198 testWriteFromFastOpenInitialDataListener(serverBootstrap, bootstrap);
199 }
200 });
201 }
202
203 public void testWriteFromFastOpenInitialDataListener(ServerBootstrap sb, Bootstrap cb) throws Throwable {
204 enableTcpFastOpen(sb, cb);
205 sb.childOption(ChannelOption.AUTO_READ, true);
206 cb.option(ChannelOption.AUTO_READ, true);
207
208 sb.childHandler(new ChannelInitializer<SocketChannel>() {
209 @Override
210 protected void initChannel(SocketChannel ch) throws Exception {
211 ch.pipeline().addLast(new EchoServerHandler());
212 }
213 });
214
215 Channel sc = sb.bind().sync().channel();
216
217
218 connectAndWriteFromInitialDataListener(cb, sc);
219 connectAndWriteFromInitialDataListener(cb, sc);
220 }
221
222 private static void connectAndWriteFromInitialDataListener(Bootstrap cb, Channel sc) throws Exception {
223 BufferingClientHandler handler = new BufferingClientHandler();
224 cb.handler(handler);
225 final Channel channel = cb.register().sync().channel();
226 final AtomicBoolean activeInListener = new AtomicBoolean();
227 final BlockingQueue<ChannelFuture> followUpFutures = new LinkedBlockingQueue<ChannelFuture>();
228 ChannelFuture initialFuture = channel.write(writeAscii(DEFAULT, "[fastopen]")).addListener(
229 new ChannelFutureListener() {
230 @Override
231 public void operationComplete(ChannelFuture f) {
232 activeInListener.set(channel.isActive());
233 followUpFutures.add(channel.writeAndFlush(writeAscii(DEFAULT, "[follow-up]")));
234 }
235 });
236 Channel cc = channel.connect(sc.localAddress()).sync().channel();
237
238 cc.flush();
239
240 initialFuture.sync();
241
242 ChannelFuture followUpFuture = followUpFutures.poll(2, TimeUnit.SECONDS);
243 assertNotNull(followUpFuture, "listener of the initial write was not notified");
244 assertTrue(activeInListener.get(), "channel was not active when the initial write was notified");
245 followUpFuture.sync();
246 String expectedString = "[fastopen][follow-up]";
247 String result = handler.collectBuffer(expectedString.getBytes(US_ASCII).length);
248 cc.close().sync();
249 assertEquals(expectedString, result);
250 }
251
252 @Test
253 @Timeout(value = 3000, unit = TimeUnit.MILLISECONDS)
254 public void testShutdownOutputFromFastOpenConnectListener(TestInfo testInfo) throws Throwable {
255 run(testInfo, new Runner<ServerBootstrap, Bootstrap>() {
256 @Override
257 public void run(ServerBootstrap serverBootstrap, Bootstrap bootstrap) throws Throwable {
258 testShutdownOutputFromFastOpenConnectListener(serverBootstrap, bootstrap);
259 }
260 });
261 }
262
263 public void testShutdownOutputFromFastOpenConnectListener(ServerBootstrap sb, Bootstrap cb) throws Throwable {
264 enableTcpFastOpen(sb, cb);
265 sb.childOption(ChannelOption.AUTO_READ, true);
266 final BlockingQueue<String> received = new LinkedBlockingQueue<String>();
267 sb.childHandler(new ChannelInitializer<SocketChannel>() {
268 @Override
269 protected void initChannel(SocketChannel ch) {
270 ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
271 private final StringBuilder data = new StringBuilder();
272
273 @Override
274 public void channelRead(ChannelHandlerContext ctx, Object msg) {
275 ByteBuf buf = (ByteBuf) msg;
276 data.append(buf.toString(US_ASCII));
277 buf.release();
278 }
279
280 @Override
281 public void channelInactive(ChannelHandlerContext ctx) {
282 received.add(data.toString());
283 }
284 });
285 }
286 });
287
288 Channel sc = sb.bind().sync().channel();
289
290
291 shutdownOutputFromConnectListener(cb, sc, received);
292 shutdownOutputFromConnectListener(cb, sc, received);
293 }
294
295 private static void shutdownOutputFromConnectListener(Bootstrap cb, Channel sc, BlockingQueue<String> received)
296 throws Exception {
297 cb.handler(new ChannelInboundHandlerAdapter());
298 final Channel channel = cb.register().sync().channel();
299 ChannelFuture initialFuture = channel.write(writeAscii(DEFAULT, "[fastopen]"));
300
301 ChannelPromise connectPromise = channel.newPromise();
302 connectPromise.addListener(new ChannelFutureListener() {
303 @Override
304 public void operationComplete(ChannelFuture f) {
305 ((DuplexChannel) channel).shutdownOutput();
306 }
307 });
308 try {
309 channel.connect(sc.localAddress(), connectPromise).sync();
310 String data = received.poll(2, TimeUnit.SECONDS);
311 assertNotNull(data, "connection was not closed by the server");
312 initialFuture.await();
313
314 if (initialFuture.isSuccess()) {
315 assertEquals("[fastopen]", data);
316 } else {
317 assertEquals("", data, "initial data was sent but the write failed");
318 }
319 } finally {
320 channel.close().sync();
321 }
322 }
323
324 protected void enableTcpFastOpen(ServerBootstrap sb, Bootstrap cb) {
325
326 sb.option(ChannelOption.TCP_FASTOPEN, 5);
327 cb.option(ChannelOption.TCP_FASTOPEN_CONNECT, true);
328 }
329
330 private static void assertLocalAddress(InetSocketAddress address) {
331 assertTrue(address.getPort() > 0);
332 assertFalse(address.getAddress().isAnyLocalAddress());
333 }
334
335 private static class BufferingClientHandler extends ChannelInboundHandlerAdapter {
336 private final Semaphore semaphore = new Semaphore(0);
337 private final ByteArrayOutputStream streamBuffer = new ByteArrayOutputStream();
338
339 @Override
340 public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
341 if (msg instanceof ByteBuf) {
342 ByteBuf buf = (ByteBuf) msg;
343 int readableBytes = buf.readableBytes();
344 buf.readBytes(streamBuffer, readableBytes);
345 semaphore.release(readableBytes);
346 buf.release();
347 } else {
348 throw new IllegalArgumentException("Unexpected message type: " + msg);
349 }
350 }
351
352 String collectBuffer(int expectedBytes) throws InterruptedException {
353 semaphore.acquire(expectedBytes);
354 byte[] bytes = streamBuffer.toByteArray();
355 streamBuffer.reset();
356 return new String(bytes, US_ASCII);
357 }
358 }
359
360 private static final class EchoServerHandler extends ChannelInboundHandlerAdapter {
361 @Override
362 public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
363 if (msg instanceof ByteBuf) {
364 ByteBuf buffer = ctx.alloc().buffer();
365 ByteBuf buf = (ByteBuf) msg;
366 buffer.writeBytes(buf);
367 buf.release();
368 ctx.channel().writeAndFlush(buffer);
369 } else {
370 throw new IllegalArgumentException("Unexpected message type: " + msg);
371 }
372 }
373 }
374 }