View Javadoc
1   /*
2    * Copyright 2012 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.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.ChannelHandlerContext;
23  import io.netty.channel.ChannelInboundHandler;
24  import io.netty.channel.ChannelInboundHandlerAdapter;
25  import io.netty.channel.ChannelOption;
26  import io.netty.channel.DefaultFileRegion;
27  import io.netty.channel.FileRegion;
28  import io.netty.channel.SimpleChannelInboundHandler;
29  import io.netty.util.CharsetUtil;
30  import io.netty.util.concurrent.ImmediateEventExecutor;
31  import io.netty.util.concurrent.Promise;
32  import io.netty.util.internal.PlatformDependent;
33  import io.netty.util.internal.SuppressJava6Requirement;
34  import org.junit.jupiter.api.Test;
35  import org.junit.jupiter.api.TestInfo;
36  import org.junit.jupiter.api.Timeout;
37  import org.junit.jupiter.api.io.TempDir;
38  
39  import java.io.File;
40  import java.io.FileOutputStream;
41  import java.io.IOException;
42  import java.io.RandomAccessFile;
43  import java.net.URI;
44  import java.nio.channels.FileChannel;
45  import java.nio.channels.WritableByteChannel;
46  import java.nio.file.FileSystem;
47  import java.nio.file.FileSystems;
48  import java.nio.file.Files;
49  import java.nio.file.Path;
50  import java.nio.file.StandardOpenOption;
51  import java.util.Arrays;
52  import java.util.Collections;
53  import java.util.Random;
54  import java.util.concurrent.BlockingQueue;
55  import java.util.concurrent.LinkedBlockingQueue;
56  import java.util.concurrent.TimeUnit;
57  import java.util.concurrent.atomic.AtomicReference;
58  
59  import static io.netty.testsuite.transport.TestsuitePermutation.randomBufferType;
60  import static org.assertj.core.api.Assertions.assertThat;
61  import static org.junit.jupiter.api.Assertions.assertEquals;
62  import static org.junit.jupiter.api.Assertions.assertInstanceOf;
63  import static org.junit.jupiter.api.Assertions.assertNotEquals;
64  import static org.junit.jupiter.api.Assumptions.assumeFalse;
65  import static org.junit.jupiter.api.Assumptions.assumeTrue;
66  
67  public class SocketFileRegionTest extends AbstractSocketTest {
68  
69      static final byte[] data = new byte[1048576 * 10];
70  
71      static {
72          PlatformDependent.threadLocalRandom().nextBytes(data);
73      }
74  
75      @Test
76      public void testFileRegion(TestInfo testInfo) throws Throwable {
77          run(testInfo, new Runner<ServerBootstrap, Bootstrap>() {
78              @Override
79              public void run(ServerBootstrap serverBootstrap, Bootstrap bootstrap) throws Throwable {
80                  testFileRegion(serverBootstrap, bootstrap);
81              }
82          });
83      }
84  
85      @Test
86      public void testCustomFileRegion(TestInfo testInfo) throws Throwable {
87          run(testInfo, new Runner<ServerBootstrap, Bootstrap>() {
88              @Override
89              public void run(ServerBootstrap serverBootstrap, Bootstrap bootstrap) throws Throwable {
90                  testCustomFileRegion(serverBootstrap, bootstrap);
91              }
92          });
93      }
94  
95      @Test
96      public void testFileRegionNotAutoRead(TestInfo testInfo) throws Throwable {
97          run(testInfo, new Runner<ServerBootstrap, Bootstrap>() {
98              @Override
99              public void run(ServerBootstrap serverBootstrap, Bootstrap bootstrap) throws Throwable {
100                 testFileRegionNotAutoRead(serverBootstrap, bootstrap);
101             }
102         });
103     }
104 
105     @Test
106     public void testFileRegionVoidPromise(TestInfo testInfo) throws Throwable {
107         run(testInfo, new Runner<ServerBootstrap, Bootstrap>() {
108             @Override
109             public void run(ServerBootstrap serverBootstrap, Bootstrap bootstrap) throws Throwable {
110                 testFileRegionVoidPromise(serverBootstrap, bootstrap);
111             }
112         });
113     }
114 
115     @Test
116     public void testFileRegionVoidPromiseNotAutoRead(TestInfo testInfo) throws Throwable {
117         run(testInfo, new Runner<ServerBootstrap, Bootstrap>() {
118             @Override
119             public void run(ServerBootstrap serverBootstrap, Bootstrap bootstrap) throws Throwable {
120                 testFileRegionVoidPromiseNotAutoRead(serverBootstrap, bootstrap);
121             }
122         });
123     }
124 
125     @Test
126     public void testFileRegionCountLargerThenFile(TestInfo testInfo) throws Throwable {
127         run(testInfo, new Runner<ServerBootstrap, Bootstrap>() {
128             @Override
129             public void run(ServerBootstrap serverBootstrap, Bootstrap bootstrap) throws Throwable {
130                 testFileRegionCountLargerThenFile(serverBootstrap, bootstrap);
131             }
132         });
133     }
134 
135     @Test
136     @Timeout(value = 30, unit = TimeUnit.SECONDS)
137     public void testFileRegionBeyond2GiB(TestInfo testInfo) throws Throwable {
138         run(testInfo, new Runner<ServerBootstrap, Bootstrap>() {
139             @Override
140             public void run(ServerBootstrap serverBootstrap, Bootstrap bootstrap) throws Throwable {
141                 testFileRegionBeyond2GiB(serverBootstrap, bootstrap);
142             }
143         });
144     }
145 
146     @Test
147     @Timeout(value = 30, unit = TimeUnit.SECONDS)
148     public void testZipFileRegion(TestInfo testInfo, @TempDir final File archive) throws Throwable {
149         assumeTrue(PlatformDependent.javaVersion() >= 7);
150         run(testInfo, new Runner<ServerBootstrap, Bootstrap>() {
151             @Override
152             @SuppressJava6Requirement(reason = "Guarded by version check")
153             public void run(ServerBootstrap sb, Bootstrap cb) throws Throwable {
154                 final byte[] data = new byte[256 * 1024 + 73];
155                 new Random(0).nextBytes(data);
156                 final byte[] expected = Arrays.copyOfRange(data, 37, data.length - 19);
157                 URI uri = URI.create("jar:" + new File(archive, "file.zip").toURI());
158                 Channel server = null;
159                 Channel client = null;
160                 final Promise<byte[]> received = ImmediateEventExecutor.INSTANCE.newPromise();
161                 final AtomicReference<Channel> child =
162                         new AtomicReference<Channel>();
163                 FileSystem zip = null;
164                 try {
165                     zip = FileSystems.newFileSystem(uri, Collections.singletonMap("create", "true"));
166                     Path path = zip.getPath("/file");
167                     Files.write(path, data);
168                     sb.childHandler(new SimpleChannelInboundHandler<ByteBuf>() {
169                         private final byte[] bytes = new byte[expected.length];
170                         private int offset;
171 
172                         @Override
173                         public void channelActive(ChannelHandlerContext ctx) {
174                             child.set(ctx.channel());
175                         }
176 
177                         @Override
178                         protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) {
179                             int length = msg.readableBytes();
180                             msg.readBytes(bytes, offset, length);
181                             offset += length;
182                             if (offset == bytes.length) {
183                                 received.trySuccess(bytes);
184                             }
185                         }
186 
187                         @Override
188                         public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
189                             received.tryFailure(cause);
190                             ctx.close();
191                         }
192                     });
193                     cb.handler(new ChannelInboundHandlerAdapter());
194                     server = sb.bind().sync().channel();
195                     client = cb.connect(server.localAddress()).sync().channel();
196                     DefaultFileRegion region = new DefaultFileRegion(
197                             FileChannel.open(path, StandardOpenOption.READ), 37, expected.length);
198                     client.writeAndFlush(region).sync();
199                     assertThat(received.get(10, TimeUnit.SECONDS))
200                             .containsExactly(expected);
201                     assertThat(region.refCnt()).isZero();
202                 } finally {
203                     if (client != null) {
204                         client.close().syncUninterruptibly();
205                     }
206                     if (child.get() != null) {
207                         child.get().close().syncUninterruptibly();
208                     }
209                     if (server != null) {
210                         server.close().syncUninterruptibly();
211                     }
212                     if (zip != null) {
213                         zip.close();
214                     }
215                 }
216             }
217         });
218     }
219 
220     public void testFileRegion(ServerBootstrap sb, Bootstrap cb) throws Throwable {
221         testFileRegion0(sb, cb, false, true, true);
222     }
223 
224     public void testCustomFileRegion(ServerBootstrap sb, Bootstrap cb) throws Throwable {
225         testFileRegion0(sb, cb, false, true, false);
226     }
227 
228     public void testFileRegionVoidPromise(ServerBootstrap sb, Bootstrap cb) throws Throwable {
229         testFileRegion0(sb, cb, true, true, true);
230     }
231 
232     public void testFileRegionNotAutoRead(ServerBootstrap sb, Bootstrap cb) throws Throwable {
233         testFileRegion0(sb, cb, false, false, true);
234     }
235 
236     public void testFileRegionVoidPromiseNotAutoRead(ServerBootstrap sb, Bootstrap cb) throws Throwable {
237         testFileRegion0(sb, cb, true, false, true);
238     }
239 
240     /**
241      * Sends {@link DefaultFileRegion}s which start beyond 2 GiB and beyond 4 GiB of a file, so that a transport
242      * which truncates the file offset to an {@code int} either fails or sends the bytes from the wrong offset.
243      */
244     public void testFileRegionBeyond2GiB(ServerBootstrap sb, Bootstrap cb) throws Throwable {
245         final String wrong = "wrong file offset";
246         final String beyond2GiB = "beyond 2 GiB !!!!";
247         final String beyond4GiB = "beyond 4 GiB !!!!";
248         final int length = wrong.length();
249         final long position2GiB = (1L << 31) + 100;
250         final long position4GiB = (1L << 32) + 100;
251 
252         // Other file systems (for example NTFS) zero-fill the gap when writing beyond the end of the file, which
253         // would mean writing 4 GiB to the disk.
254         assumeFalse(PlatformDependent.isWindows());
255 
256         File file = PlatformDependent.createTempFile("netty-", ".tmp", null);
257         file.deleteOnExit();
258         // Writing beyond the end of the file creates a sparse file on most file systems, so only a few KiB are used.
259         RandomAccessFile raf = new RandomAccessFile(file, "rw");
260         try {
261             // Where the offset ends up if it is truncated to an int.
262             write(raf, wrong, position4GiB & 0xFFFFFFFFL);
263             write(raf, beyond2GiB, position2GiB);
264             write(raf, beyond4GiB, position4GiB);
265         } finally {
266             raf.close();
267         }
268 
269         final BlockingQueue<String> received = new LinkedBlockingQueue<String>();
270         sb.childHandler(new ChannelInboundHandlerAdapter() {
271             private final StringBuilder builder = new StringBuilder();
272 
273             @Override
274             public void channelRead(ChannelHandlerContext ctx, Object msg) {
275                 ByteBuf buf = (ByteBuf) msg;
276                 try {
277                     builder.append(buf.toString(CharsetUtil.US_ASCII));
278                 } finally {
279                     buf.release();
280                 }
281                 while (builder.length() >= length) {
282                     received.add(builder.substring(0, length));
283                     builder.delete(0, length);
284                 }
285             }
286         });
287         cb.handler(new ChannelInboundHandlerAdapter());
288 
289         Channel sc = sb.bind().sync().channel();
290         Channel cc = cb.connect(sc.localAddress()).sync().channel();
291         try {
292             cc.writeAndFlush(new DefaultFileRegion(file, position4GiB, length)).sync();
293             assertEquals(beyond4GiB, received.poll(10, TimeUnit.SECONDS));
294             cc.writeAndFlush(new DefaultFileRegion(file, position2GiB, length)).sync();
295             assertEquals(beyond2GiB, received.poll(10, TimeUnit.SECONDS));
296         } finally {
297             cc.close().sync();
298             sc.close().sync();
299             file.delete();
300         }
301     }
302 
303     private static void write(RandomAccessFile raf, String value, long position) throws IOException {
304         raf.seek(position);
305         raf.write(value.getBytes(CharsetUtil.US_ASCII));
306     }
307 
308     public void testFileRegionCountLargerThenFile(ServerBootstrap sb, Bootstrap cb) throws Throwable {
309         File file = PlatformDependent.createTempFile("netty-", ".tmp", null);
310         file.deleteOnExit();
311 
312         final FileOutputStream out = new FileOutputStream(file);
313         out.write(data);
314         out.close();
315 
316         sb.childHandler(new SimpleChannelInboundHandler<ByteBuf>() {
317             @Override
318             protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) {
319                 // Just drop the message.
320             }
321         });
322         cb.handler(new ChannelInboundHandlerAdapter());
323 
324         Channel sc = sb.bind().sync().channel();
325         Channel cc = cb.connect(sc.localAddress()).sync().channel();
326 
327         // Request file region which is bigger then the underlying file.
328         FileRegion region = new DefaultFileRegion(
329                 new RandomAccessFile(file, "r").getChannel(), 0, data.length + 1024);
330 
331         assertInstanceOf(IOException.class, cc.writeAndFlush(region).await().cause());
332         cc.close().sync();
333         sc.close().sync();
334     }
335 
336     private static void testFileRegion0(
337             ServerBootstrap sb, Bootstrap cb, boolean voidPromise, final boolean autoRead, boolean defaultFileRegion)
338             throws Throwable {
339         sb.childOption(ChannelOption.AUTO_READ, autoRead);
340         cb.option(ChannelOption.AUTO_READ, autoRead);
341 
342         final int bufferSize = 1024;
343         final File file = PlatformDependent.createTempFile("netty-", ".tmp", null);
344         file.deleteOnExit();
345 
346         final FileOutputStream out = new FileOutputStream(file);
347         final Random random = PlatformDependent.threadLocalRandom();
348 
349         // Prepend random data which will not be transferred, so that we can test non-zero start offset
350         final int startOffset = random.nextInt(8192);
351         for (int i = 0; i < startOffset; i ++) {
352             out.write(random.nextInt());
353         }
354 
355         // .. and here comes the real data to transfer.
356         out.write(data, bufferSize, data.length - bufferSize);
357 
358         // .. and then some extra data which is not supposed to be transferred.
359         for (int i = random.nextInt(8192); i > 0; i --) {
360             out.write(random.nextInt());
361         }
362 
363         out.close();
364 
365         ChannelInboundHandler ch = new SimpleChannelInboundHandler<Object>() {
366             @Override
367             public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
368             }
369 
370             @Override
371             public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
372                 if (!autoRead) {
373                     ctx.read();
374                 }
375             }
376 
377             @Override
378             public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
379                 ctx.close();
380             }
381         };
382         TestHandler sh = new TestHandler(autoRead);
383 
384         sb.childHandler(sh);
385         cb.handler(ch);
386 
387         Channel sc = sb.bind().sync().channel();
388 
389         Channel cc = cb.connect(sc.localAddress()).sync().channel();
390         FileRegion region = new DefaultFileRegion(
391                 new RandomAccessFile(file, "r").getChannel(), startOffset, data.length - bufferSize);
392         FileRegion emptyRegion = new DefaultFileRegion(new RandomAccessFile(file, "r").getChannel(), 0, 0);
393 
394         if (!defaultFileRegion) {
395             region = new FileRegionWrapper(region);
396             emptyRegion = new FileRegionWrapper(emptyRegion);
397         }
398         // Do write ByteBuf and then FileRegion to ensure that mixed writes work
399         // Also, write an empty FileRegion to test if writing an empty FileRegion does not cause any issues.
400         //
401         // See https://github.com/netty/netty/issues/2769
402         //     https://github.com/netty/netty/issues/2964
403         if (voidPromise) {
404             assertEquals(cc.voidPromise(), cc.write(
405                     randomBufferType(cc.alloc(), data, 0, bufferSize), cc.voidPromise()));
406             assertEquals(cc.voidPromise(), cc.write(emptyRegion, cc.voidPromise()));
407             assertEquals(cc.voidPromise(), cc.writeAndFlush(region, cc.voidPromise()));
408         } else {
409             assertNotEquals(cc.voidPromise(), cc.write(
410                     randomBufferType(cc.alloc(), data, 0, bufferSize)));
411             assertNotEquals(cc.voidPromise(), cc.write(emptyRegion));
412             assertNotEquals(cc.voidPromise(), cc.writeAndFlush(region));
413         }
414 
415         while (sh.counter < data.length) {
416             if (sh.exception.get() != null) {
417                 break;
418             }
419 
420             Thread.sleep(50);
421         }
422 
423         sh.channel.close().sync();
424         cc.close().sync();
425         sc.close().sync();
426 
427         if (sh.exception.get() != null && !(sh.exception.get() instanceof IOException)) {
428             throw sh.exception.get();
429         }
430 
431         if (sh.exception.get() != null) {
432             throw sh.exception.get();
433         }
434 
435         // Make sure we did not receive more than we expected.
436         assertEquals(data.length, sh.counter);
437     }
438 
439     private static class TestHandler extends SimpleChannelInboundHandler<ByteBuf> {
440         private final boolean autoRead;
441         volatile Channel channel;
442         final AtomicReference<Throwable> exception = new AtomicReference<Throwable>();
443         volatile int counter;
444 
445         TestHandler(boolean autoRead) {
446             this.autoRead = autoRead;
447         }
448 
449         @Override
450         public void channelActive(ChannelHandlerContext ctx)
451                 throws Exception {
452             channel = ctx.channel();
453             if (!autoRead) {
454                 ctx.read();
455             }
456         }
457 
458         @Override
459         public void channelRead0(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
460             byte[] actual = new byte[in.readableBytes()];
461             in.readBytes(actual);
462 
463             int lastIdx = counter;
464             for (int i = 0; i < actual.length; i ++) {
465                 assertEquals(data[i + lastIdx], actual[i]);
466             }
467             counter += actual.length;
468         }
469 
470         @Override
471         public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
472             if (!autoRead) {
473                 ctx.read();
474             }
475         }
476 
477         @Override
478         public void exceptionCaught(ChannelHandlerContext ctx,
479                 Throwable cause) throws Exception {
480             if (exception.compareAndSet(null, cause)) {
481                 ctx.close();
482             }
483         }
484     }
485 
486     private static final class FileRegionWrapper implements FileRegion {
487         private final FileRegion region;
488 
489         FileRegionWrapper(FileRegion region) {
490             this.region = region;
491         }
492 
493         @Override
494         public int refCnt() {
495             return region.refCnt();
496         }
497 
498         @Override
499         public long position() {
500             return region.position();
501         }
502 
503         @Override
504         @Deprecated
505         public long transfered() {
506             return region.transferred();
507         }
508 
509         @Override
510         public boolean release() {
511             return region.release();
512         }
513 
514         @Override
515         public long transferred() {
516             return region.transferred();
517         }
518 
519         @Override
520         public long count() {
521             return region.count();
522         }
523 
524         @Override
525         public boolean release(int decrement) {
526             return region.release(decrement);
527         }
528 
529         @Override
530         public long transferTo(WritableByteChannel target, long position) throws IOException {
531             return region.transferTo(target, position);
532         }
533 
534         @Override
535         public FileRegion retain() {
536             region.retain();
537             return this;
538         }
539 
540         @Override
541         public FileRegion retain(int increment) {
542             region.retain(increment);
543             return this;
544         }
545 
546         @Override
547         public FileRegion touch() {
548             region.touch();
549             return this;
550         }
551 
552         @Override
553         public FileRegion touch(Object hint) {
554             region.touch(hint);
555             return this;
556         }
557     }
558 }