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