View Javadoc
1   /*
2    * Copyright 2017 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;
17  
18  import io.netty.buffer.ByteBuf;
19  
20  import java.io.IOException;
21  import java.net.InetAddress;
22  import java.net.InetSocketAddress;
23  import java.net.UnknownHostException;
24  import java.nio.channels.FileChannel;
25  import java.nio.file.Files;
26  import java.nio.file.InvalidPathException;
27  import java.nio.file.LinkOption;
28  import java.nio.file.Path;
29  import java.nio.file.Paths;
30  import java.nio.file.attribute.BasicFileAttributes;
31  
32  import static io.netty.channel.unix.Limits.IOV_MAX;
33  
34  public final class UnixChannelUtil {
35  
36      // File type bits of st_mode, see sys/stat.h. These values are the same on Linux and the BSDs (including macOS).
37      private static final int S_IFMT = 0170000;
38      private static final int S_IFSOCK = 0140000;
39  
40      private static final Class<?> FILE_CHANNEL_IMPL_CLASS;
41  
42      static {
43          Class<?> fileChannelImplClass;
44          try {
45              fileChannelImplClass = Class.forName("sun.nio.ch.FileChannelImpl", false, null);
46          } catch (Throwable ignore) {
47              fileChannelImplClass = null;
48          }
49          FILE_CHANNEL_IMPL_CLASS = fileChannelImplClass;
50      }
51  
52      private UnixChannelUtil() {
53      }
54  
55      /**
56       * Returns whether the given channel is an instance of {@code sun.nio.ch.FileChannelImpl}.
57       */
58      public static boolean isFileChannelImpl(FileChannel channel) {
59          return FILE_CHANNEL_IMPL_CLASS != null && FILE_CHANNEL_IMPL_CLASS.isInstance(channel);
60      }
61  
62      /**
63       * Checks if the specified buffer has memory address or is composed of n(n <= IOV_MAX) NIO direct buffers.
64       * (We check this because otherwise we need to make it a new direct buffer.)
65       */
66      public static boolean isBufferCopyNeededForWrite(ByteBuf byteBuf) {
67          return isBufferCopyNeededForWrite(byteBuf, IOV_MAX);
68      }
69  
70      static boolean isBufferCopyNeededForWrite(ByteBuf byteBuf, int iovMax) {
71          return !byteBuf.hasMemoryAddress() && (!byteBuf.isDirect() || byteBuf.nioBufferCount() > iovMax);
72      }
73  
74      /**
75       * Delete the file at {@code path} but only if it is a socket inode (as left behind by a bound domain socket).
76       * Any other kind of file (regular file, directory, symbolic link, FIFO, device, ...) is left alone. Symbolic links
77       * are never followed.
78       *
79       * @return {@code true} if the file was deleted.
80       */
81      public static boolean deleteDomainSocketFile(String path) {
82          try {
83              Path file = Paths.get(path);
84              if (!isSocket(file)) {
85                  return false;
86              }
87              Files.delete(file);
88              return true;
89          } catch (IOException ignore) {
90              return false;
91          } catch (InvalidPathException ignore) {
92              // For example abstract namespace addresses, which have no file system presence.
93              return false;
94          }
95      }
96  
97      private static boolean isSocket(Path file) throws IOException {
98          try {
99              Object mode = Files.getAttribute(file, "unix:mode", LinkOption.NOFOLLOW_LINKS);
100             if (mode instanceof Integer) {
101                 return ((Integer) mode & S_IFMT) == S_IFSOCK;
102             }
103         } catch (UnsupportedOperationException ignore) {
104             // The "unix" attribute view is not supported, fall back to the less precise check below.
105         } catch (IllegalArgumentException ignore) {
106             // The "mode" attribute is not supported, fall back to the less precise check below.
107         }
108         return Files.readAttributes(file, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS).isOther();
109     }
110 
111     public static InetSocketAddress computeRemoteAddr(InetSocketAddress remoteAddr, InetSocketAddress osRemoteAddr) {
112         if (osRemoteAddr != null) {
113             try {
114                 // Only try to construct a new InetSocketAddress if we using java >= 7 as getHostString() does not
115                 // exists in earlier releases and so the retrieval of the hostname could block the EventLoop if a
116                 // reverse lookup would be needed.
117                 return new InetSocketAddress(InetAddress.getByAddress(remoteAddr.getHostString(),
118                         osRemoteAddr.getAddress().getAddress()),
119                         osRemoteAddr.getPort());
120             } catch (UnknownHostException ignore) {
121                 // Should never happen but fallback to osRemoteAddr anyway.
122             }
123             return osRemoteAddr;
124         }
125         return remoteAddr;
126     }
127 }