1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
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
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
64
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
76
77
78
79
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
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
105 } catch (IllegalArgumentException ignore) {
106
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
115
116
117 return new InetSocketAddress(InetAddress.getByAddress(remoteAddr.getHostString(),
118 osRemoteAddr.getAddress().getAddress()),
119 osRemoteAddr.getPort());
120 } catch (UnknownHostException ignore) {
121
122 }
123 return osRemoteAddr;
124 }
125 return remoteAddr;
126 }
127 }