View Javadoc
1   /*
2    * Copyright 2015 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.channel.unix.tests;
17  
18  import io.netty.channel.unix.Buffer;
19  import io.netty.channel.unix.DomainSocketAddress;
20  import io.netty.channel.unix.Errors;
21  import io.netty.channel.unix.Errors.NativeIoException;
22  import io.netty.channel.unix.Limits;
23  import io.netty.channel.unix.Socket;
24  import io.netty.channel.unix.UnixChannelUtil;
25  import io.netty.util.CharsetUtil;
26  import io.netty.util.internal.PlatformDependent;
27  import org.junit.jupiter.api.AfterEach;
28  import org.junit.jupiter.api.BeforeEach;
29  import org.junit.jupiter.api.Test;
30  import org.opentest4j.TestAbortedException;
31  
32  import java.io.DataInputStream;
33  import java.io.File;
34  import java.io.FileInputStream;
35  import java.io.FileOutputStream;
36  import java.io.IOException;
37  import java.nio.ByteBuffer;
38  import java.util.Arrays;
39  
40  import static org.junit.jupiter.api.Assertions.assertArrayEquals;
41  import static org.junit.jupiter.api.Assertions.assertEquals;
42  import static org.junit.jupiter.api.Assertions.assertFalse;
43  import static org.junit.jupiter.api.Assertions.assertNotEquals;
44  import static org.junit.jupiter.api.Assertions.assertTrue;
45  import static org.junit.jupiter.api.Assertions.fail;
46  import static org.junit.jupiter.api.Assumptions.assumeTrue;
47  
48  public abstract class SocketTest<T extends Socket> {
49      protected T socket;
50  
51      protected abstract T newSocket();
52  
53      @BeforeEach
54      public void setup() {
55          socket = newSocket();
56      }
57  
58      @AfterEach
59      public void tearDown() throws IOException {
60          socket.close();
61      }
62  
63      @Test
64      public void testKeepAlive() throws Exception {
65          assertFalse(socket.isKeepAlive());
66          socket.setKeepAlive(true);
67          assertTrue(socket.isKeepAlive());
68      }
69  
70      @Test
71      public void testTcpNoDelay() throws Exception {
72          assertFalse(socket.isTcpNoDelay());
73          socket.setTcpNoDelay(true);
74          assertTrue(socket.isTcpNoDelay());
75      }
76  
77      @Test
78      public void testReceivedBufferSize() throws Exception {
79          int size = socket.getReceiveBufferSize();
80          int newSize = 65535;
81          assertTrue(size > 0);
82          socket.setReceiveBufferSize(newSize);
83          // Linux usually set it to double what is specified
84          assertTrue(newSize <= socket.getReceiveBufferSize());
85      }
86  
87      @Test
88      public void testSendBufferSize() throws Exception {
89          int size = socket.getSendBufferSize();
90          int newSize = 65535;
91          assertTrue(size > 0);
92          socket.setSendBufferSize(newSize);
93          // Linux usually set it to double what is specified
94          assertTrue(newSize <= socket.getSendBufferSize());
95      }
96  
97      @Test
98      public void testSoLinger() throws Exception {
99          assertEquals(-1, socket.getSoLinger());
100         socket.setSoLinger(10);
101         assertEquals(10, socket.getSoLinger());
102     }
103 
104     @Test
105     public void testDoubleCloseDoesNotThrow() throws IOException {
106         Socket socket = Socket.newSocketStream();
107         socket.close();
108         socket.close();
109     }
110 
111     @Test
112     public void testTrafficClass() throws IOException {
113         // IPTOS_THROUGHPUT
114         final int value = 0x08;
115         socket.setTrafficClass(value);
116         assertEquals(value, socket.getTrafficClass());
117     }
118 
119     @Test
120     public void testIntOpt() throws IOException {
121         socket.setReuseAddress(false);
122         socket.setIntOpt(level(), optname(), 1);
123         // Anything which is != 0 is considered enabled
124         assertNotEquals(0, socket.getIntOpt(level(), optname()));
125         socket.setIntOpt(level(), optname(), 0);
126         // This should be disabled again
127         assertEquals(0, socket.getIntOpt(level(), optname()));
128     }
129 
130     @Test
131     public void testRawOpt() throws IOException {
132         ByteBuffer buffer = Buffer.allocateDirectWithNativeOrder(4);
133         buffer.putInt(1).flip();
134         socket.setRawOpt(level(), optname(), buffer);
135 
136         ByteBuffer out = ByteBuffer.allocate(4);
137         socket.getRawOpt(level(), optname(), out);
138         assertFalse(out.hasRemaining());
139 
140         out.flip();
141         assertNotEquals(ByteBuffer.allocate(0), out);
142     }
143 
144     @Test
145     public void testSendToDomainSocketWithTooLongPath() throws IOException {
146         byte[] path = new byte[4096];
147         Arrays.fill(path, (byte) 'a');
148         path[0] = '/';
149 
150         ByteBuffer buffer = Buffer.allocateDirectWithNativeOrder(1);
151         Socket domainSocket = Socket.newSocketDomainDgram();
152         try {
153             // The path must be rejected instead of silently being truncated and sent to a different address.
154             try {
155                 domainSocket.sendToDomainSocket(buffer, 0, 1, path);
156                 fail("sendToDomainSocket should fail as the path is too long");
157             } catch (NativeIoException e) {
158                 assertEquals(Errors.ERRNO_ENAMETOOLONG_NEGATIVE, e.expectedErr());
159             }
160         } finally {
161             domainSocket.close();
162             Buffer.free(buffer);
163         }
164     }
165 
166     protected int level() {
167         throw new TestAbortedException("Not supported");
168     }
169 
170     protected int optname() {
171         throw new TestAbortedException("Not supported");
172     }
173 
174     @Test
175     public void testBindDomainSocketDoesNotRemoveRegularFile() throws Exception {
176         File file = PlatformDependent.createTempFile("NETTY", "UDS", null);
177         try {
178             byte[] content = "do not delete".getBytes(CharsetUtil.US_ASCII);
179             FileOutputStream out = new FileOutputStream(file);
180             try {
181                 out.write(content);
182             } finally {
183                 out.close();
184             }
185 
186             Socket domainSocket = Socket.newSocketDomain();
187             try {
188                 try {
189                     domainSocket.bind(new DomainSocketAddress(file));
190                     fail("bind should fail as the file already exists");
191                 } catch (IOException expected) {
192                     // expected
193                 }
194             } finally {
195                 domainSocket.close();
196             }
197             assertTrue(file.isFile());
198             byte[] read = new byte[content.length];
199             DataInputStream in = new DataInputStream(new FileInputStream(file));
200             try {
201                 in.readFully(read);
202                 assertEquals(-1, in.read());
203             } finally {
204                 in.close();
205             }
206             assertArrayEquals(content, read);
207         } finally {
208             file.delete();
209         }
210     }
211 
212     @Test
213     public void testBindDomainSocketReplacesStaleSocket() throws Exception {
214         DomainSocketAddress address = UnixTestUtils.newDomainSocketAddress();
215         File file = new File(address.path());
216         try {
217             Socket first = Socket.newSocketDomain();
218             try {
219                 first.bind(address);
220             } finally {
221                 first.close();
222             }
223             // The socket inode is left behind after close.
224             assertTrue(file.exists());
225 
226             Socket second = Socket.newSocketDomain();
227             try {
228                 second.bind(address);
229             } finally {
230                 second.close();
231             }
232         } finally {
233             file.delete();
234         }
235     }
236 
237     @Test
238     public void testDeleteDomainSocketFileOnlyDeletesSockets() throws Exception {
239         File regular = PlatformDependent.createTempFile("NETTY", "UDS", null);
240         DomainSocketAddress address = UnixTestUtils.newDomainSocketAddress();
241         File socketFile = new File(address.path());
242         try {
243             assertFalse(UnixChannelUtil.deleteDomainSocketFile(regular.getPath()));
244             assertTrue(regular.exists());
245 
246             Socket domainSocket = Socket.newSocketDomain();
247             try {
248                 domainSocket.bind(address);
249             } finally {
250                 domainSocket.close();
251             }
252             assertTrue(UnixChannelUtil.deleteDomainSocketFile(address.path()));
253             assertFalse(socketFile.exists());
254             // Does not exist anymore.
255             assertFalse(UnixChannelUtil.deleteDomainSocketFile(address.path()));
256         } finally {
257             regular.delete();
258             socketFile.delete();
259         }
260     }
261 
262     @Test
263     public void testBindDomainSocketWithTrailingSlashDoesNotRemoveSocket() throws Exception {
264         DomainSocketAddress address = UnixTestUtils.newDomainSocketAddress();
265         File file = new File(address.path());
266         try {
267             Socket first = Socket.newSocketDomain();
268             try {
269                 first.bind(address);
270             } finally {
271                 first.close();
272             }
273             assertTrue(file.exists());
274 
275             // "<socket>/" does not refer to the socket file (lstat fails with ENOTDIR), so it must not be removed.
276             Socket second = Socket.newSocketDomain();
277             try {
278                 try {
279                     second.bind(new DomainSocketAddress(address.path() + '/'));
280                     fail("bind should have failed");
281                 } catch (IOException expected) {
282                     // expected
283                 }
284             } finally {
285                 second.close();
286             }
287             assertTrue(file.exists());
288         } finally {
289             file.delete();
290         }
291     }
292 
293     @Test
294     public void testBindDomainSocketDoesNotRemoveFifo() throws Exception {
295         DomainSocketAddress address = UnixTestUtils.newDomainSocketAddress();
296         File fifo = new File(address.path());
297         try {
298             mkfifo(fifo);
299 
300             Socket domainSocket = Socket.newSocketDomain();
301             try {
302                 try {
303                     domainSocket.bind(address);
304                     fail("bind should have failed");
305                 } catch (IOException expected) {
306                     // expected
307                 }
308             } finally {
309                 domainSocket.close();
310             }
311             assertTrue(fifo.exists());
312         } finally {
313             fifo.delete();
314         }
315     }
316 
317     @Test
318     public void testDeleteDomainSocketFileDoesNotDeleteFifo() throws Exception {
319         DomainSocketAddress address = UnixTestUtils.newDomainSocketAddress();
320         File fifo = new File(address.path());
321         try {
322             mkfifo(fifo);
323 
324             assertFalse(UnixChannelUtil.deleteDomainSocketFile(fifo.getPath()));
325             assertTrue(fifo.exists());
326         } finally {
327             fifo.delete();
328         }
329     }
330 
331     @Test
332     public void testBindAbstractDomainSocket() throws Exception {
333         // Abstract namespace addresses are only supported on Linux.
334         assumeTrue("linux".equals(PlatformDependent.normalizedOs()));
335         // Abstract namespace addresses have no file system presence, so there is no stale file to remove.
336         DomainSocketAddress address = new DomainSocketAddress("\0" + UnixTestUtils.newDomainSocketAddress().path());
337         Socket domainSocket = Socket.newSocketDomain();
338         try {
339             domainSocket.bind(address);
340         } finally {
341             domainSocket.close();
342         }
343     }
344 
345     private static void mkfifo(File file) throws Exception {
346         int exitCode;
347         try {
348             exitCode = new ProcessBuilder("mkfifo", file.getPath()).redirectErrorStream(true).start().waitFor();
349         } catch (IOException e) {
350             throw new TestAbortedException("mkfifo not available", e);
351         }
352         if (exitCode != 0) {
353             throw new TestAbortedException("mkfifo failed with exit code " + exitCode);
354         }
355     }
356 
357     @Test
358     public void testConnectDomainSocketWithMaxLengthPath() throws Exception {
359         int max = Limits.UDS_SUN_PATH_SIZE;
360         assertTrue(max >= 100);
361         // A path that fills sun_path completely does not need a NUL terminator and must be handled deterministically.
362         for (int i = 0; i < 100; i++) {
363             assertFalse(isConnectPathTooLong(max));
364         }
365         assertTrue(isConnectPathTooLong(max + 1));
366     }
367 
368     private static boolean isConnectPathTooLong(int length) throws IOException {
369         StringBuilder path = new StringBuilder("/");
370         while (path.length() < length) {
371             path.append('a');
372         }
373         Socket domainSocket = Socket.newSocketDomain();
374         try {
375             domainSocket.connect(new DomainSocketAddress(path.toString()));
376             return false;
377         } catch (IOException e) {
378             return e.getMessage() != null && e.getMessage().contains("too long");
379         } finally {
380             domainSocket.close();
381         }
382     }
383 }