View Javadoc
1   /*
2    * Copyright 2016 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.epoll;
17  
18  import io.netty.channel.ChannelException;
19  import io.netty.channel.DefaultFileRegion;
20  import io.netty.channel.unix.Errors;
21  import io.netty.channel.unix.NativeInetAddress;
22  import io.netty.channel.unix.PeerCredentials;
23  import io.netty.channel.unix.Socket;
24  import io.netty.channel.socket.InternetProtocolFamily;
25  import io.netty.util.internal.PlatformDependent;
26  import io.netty.util.internal.SocketUtils;
27  import io.netty.util.internal.UnstableApi;
28  
29  import java.io.IOException;
30  import java.net.InetAddress;
31  import java.net.Inet6Address;
32  import java.net.NetworkInterface;
33  import java.net.UnknownHostException;
34  import java.util.Enumeration;
35  
36  import static io.netty.channel.unix.Errors.ioResult;
37  import static io.netty.channel.unix.Errors.newIOException;
38  
39  /**
40   * A socket which provides access Linux native methods.
41   */
42  @UnstableApi
43  public final class LinuxSocket extends Socket {
44      private static final long MAX_UINT32_T = 0xFFFFFFFFL;
45  
46      LinuxSocket(int fd) {
47          super(fd);
48      }
49  
50      InternetProtocolFamily family() {
51          return ipv6 ? InternetProtocolFamily.IPv6 : InternetProtocolFamily.IPv4;
52      }
53  
54      int sendmmsg(NativeDatagramPacketArray.NativeDatagramPacket[] msgs,
55                                 int offset, int len) throws IOException {
56          return Native.sendmmsg(intValue(), ipv6, msgs, offset, len);
57      }
58  
59      int recvmmsg(NativeDatagramPacketArray.NativeDatagramPacket[] msgs,
60                   int offset, int len) throws IOException {
61          return Native.recvmmsg(intValue(), ipv6, msgs, offset, len);
62      }
63  
64      int recvmsg(NativeDatagramPacketArray.NativeDatagramPacket msg) throws IOException {
65          return Native.recvmsg(intValue(), ipv6, msg);
66      }
67  
68      void setTimeToLive(int ttl) throws IOException {
69          setTimeToLive(intValue(), ttl);
70      }
71  
72      void setInterface(InetAddress address) throws IOException {
73          final NativeInetAddress a = NativeInetAddress.newInstance(address);
74          setInterface(intValue(), ipv6, a.address(), a.scopeId(), interfaceIndex(address));
75      }
76  
77      void setNetworkInterface(NetworkInterface netInterface) throws IOException {
78          InetAddress address = deriveInetAddress(netInterface, family() == InternetProtocolFamily.IPv6);
79          if (address.equals(family() == InternetProtocolFamily.IPv4 ? Native.INET_ANY : Native.INET6_ANY)) {
80              throw new IOException("NetworkInterface does not support " + family());
81          }
82          final NativeInetAddress nativeAddress = NativeInetAddress.newInstance(address);
83          setInterface(intValue(), ipv6, nativeAddress.address(), nativeAddress.scopeId(), interfaceIndex(netInterface));
84      }
85  
86      InetAddress getInterface() throws IOException {
87          NetworkInterface inf = getNetworkInterface();
88          if (inf != null) {
89              Enumeration<InetAddress> addresses = SocketUtils.addressesFromNetworkInterface(inf);
90              if (addresses.hasMoreElements()) {
91                  return addresses.nextElement();
92              }
93          }
94          return null;
95      }
96  
97      NetworkInterface getNetworkInterface() throws IOException {
98          int ret = getInterface(intValue(), ipv6);
99          if (ipv6) {
100             return PlatformDependent.javaVersion() >= 7 ? NetworkInterface.getByIndex(ret) : null;
101         }
102         InetAddress address = inetAddress(ret);
103         return address != null ? NetworkInterface.getByInetAddress(address) : null;
104     }
105 
106     private static InetAddress inetAddress(int value) {
107         byte[] var1 = {
108                 (byte) (value >>> 24 & 255),
109                 (byte) (value >>> 16 & 255),
110                 (byte) (value >>> 8 & 255),
111                 (byte) (value & 255)
112         };
113 
114         try {
115             return InetAddress.getByAddress(var1);
116         } catch (UnknownHostException ignore) {
117             return null;
118         }
119     }
120 
121     void joinGroup(InetAddress group, NetworkInterface netInterface, InetAddress source) throws IOException {
122         final NativeInetAddress g = NativeInetAddress.newInstance(group);
123         final boolean isIpv6 = group instanceof Inet6Address;
124         final NativeInetAddress i = NativeInetAddress.newInstance(deriveInetAddress(netInterface, isIpv6));
125         if (source != null) {
126             if (source.getClass() != group.getClass()) {
127                 throw new IllegalArgumentException("Source address is different type to group");
128             }
129             final NativeInetAddress s = NativeInetAddress.newInstance(source);
130             joinSsmGroup(intValue(), ipv6 && isIpv6, g.address(), i.address(),
131                     g.scopeId(), interfaceIndex(netInterface), s.address());
132         } else {
133             joinGroup(intValue(), ipv6 && isIpv6, g.address(), i.address(), g.scopeId(), interfaceIndex(netInterface));
134         }
135     }
136 
137     void leaveGroup(InetAddress group, NetworkInterface netInterface, InetAddress source) throws IOException {
138         final NativeInetAddress g = NativeInetAddress.newInstance(group);
139         final boolean isIpv6 = group instanceof Inet6Address;
140         final NativeInetAddress i = NativeInetAddress.newInstance(deriveInetAddress(netInterface, isIpv6));
141         if (source != null) {
142             if (source.getClass() != group.getClass()) {
143                 throw new IllegalArgumentException("Source address is different type to group");
144             }
145             final NativeInetAddress s = NativeInetAddress.newInstance(source);
146             leaveSsmGroup(intValue(), ipv6 && isIpv6, g.address(), i.address(),
147                     g.scopeId(), interfaceIndex(netInterface), s.address());
148         } else {
149             leaveGroup(intValue(), ipv6 && isIpv6, g.address(), i.address(), g.scopeId(), interfaceIndex(netInterface));
150         }
151     }
152 
153     private static int interfaceIndex(NetworkInterface networkInterface) {
154         return PlatformDependent.javaVersion() >= 7 ? networkInterface.getIndex() : -1;
155     }
156 
157     private static int interfaceIndex(InetAddress address) throws IOException {
158         if (PlatformDependent.javaVersion() >= 7) {
159             NetworkInterface iface = NetworkInterface.getByInetAddress(address);
160             if (iface != null) {
161                 return iface.getIndex();
162             }
163         }
164         return -1;
165     }
166 
167     void setTcpDeferAccept(int deferAccept) throws IOException {
168         setTcpDeferAccept(intValue(), deferAccept);
169     }
170 
171     void setTcpQuickAck(boolean quickAck) throws IOException {
172         setTcpQuickAck(intValue(), quickAck ? 1 : 0);
173     }
174 
175     void setTcpCork(boolean tcpCork) throws IOException {
176         setTcpCork(intValue(), tcpCork ? 1 : 0);
177     }
178 
179     void setSoBusyPoll(int loopMicros) throws IOException {
180         setSoBusyPoll(intValue(), loopMicros);
181     }
182 
183     void setTcpNotSentLowAt(long tcpNotSentLowAt) throws IOException {
184         if (tcpNotSentLowAt < 0 || tcpNotSentLowAt > MAX_UINT32_T) {
185             throw new IllegalArgumentException("tcpNotSentLowAt must be a uint32_t");
186         }
187         setTcpNotSentLowAt(intValue(), (int) tcpNotSentLowAt);
188     }
189 
190     void setTcpFastOpen(int tcpFastopenBacklog) throws IOException {
191         setTcpFastOpen(intValue(), tcpFastopenBacklog);
192     }
193 
194     void setTcpKeepIdle(int seconds) throws IOException {
195         setTcpKeepIdle(intValue(), seconds);
196     }
197 
198     void setTcpKeepIntvl(int seconds) throws IOException {
199         setTcpKeepIntvl(intValue(), seconds);
200     }
201 
202     void setTcpKeepCnt(int probes) throws IOException {
203         setTcpKeepCnt(intValue(), probes);
204     }
205 
206     void setTcpUserTimeout(int milliseconds) throws IOException {
207         setTcpUserTimeout(intValue(), milliseconds);
208     }
209 
210     void setIpBindAddressNoPort(boolean enabled) throws IOException {
211         setIpBindAddressNoPort(intValue(), enabled ? 1 : 0);
212     }
213 
214     void setIpFreeBind(boolean enabled) throws IOException {
215         setIpFreeBind(intValue(), enabled ? 1 : 0);
216     }
217 
218     void setIpTransparent(boolean enabled) throws IOException {
219         setIpTransparent(intValue(), enabled ? 1 : 0);
220     }
221 
222     void setIpRecvOrigDestAddr(boolean enabled) throws IOException {
223         setIpRecvOrigDestAddr(intValue(), enabled ? 1 : 0);
224     }
225 
226     int getTimeToLive() throws IOException {
227         return getTimeToLive(intValue());
228     }
229 
230     void getTcpInfo(EpollTcpInfo info) throws IOException {
231         getTcpInfo(intValue(), info.info);
232     }
233 
234     void setTcpMd5Sig(InetAddress address, byte[] key) throws IOException {
235         final NativeInetAddress a = NativeInetAddress.newInstance(address);
236         setTcpMd5Sig(intValue(), ipv6, a.address(), a.scopeId(), key);
237     }
238 
239     boolean isTcpCork() throws IOException  {
240         return isTcpCork(intValue()) != 0;
241     }
242 
243     int getSoBusyPoll() throws IOException  {
244         return getSoBusyPoll(intValue());
245     }
246 
247     int getTcpDeferAccept() throws IOException {
248         return getTcpDeferAccept(intValue());
249     }
250 
251     boolean isTcpQuickAck() throws IOException {
252         return isTcpQuickAck(intValue()) != 0;
253     }
254 
255     long getTcpNotSentLowAt() throws IOException {
256         return getTcpNotSentLowAt(intValue()) & MAX_UINT32_T;
257     }
258 
259     int getTcpKeepIdle() throws IOException {
260         return getTcpKeepIdle(intValue());
261     }
262 
263     int getTcpKeepIntvl() throws IOException {
264         return getTcpKeepIntvl(intValue());
265     }
266 
267     int getTcpKeepCnt() throws IOException {
268         return getTcpKeepCnt(intValue());
269     }
270 
271     int getTcpUserTimeout() throws IOException {
272         return getTcpUserTimeout(intValue());
273     }
274 
275     boolean isIpBindAddressNoPort() throws IOException {
276         return isIpBindAddressNoPort(intValue()) != 0;
277     }
278 
279     boolean isIpFreeBind() throws IOException {
280         return isIpFreeBind(intValue()) != 0;
281     }
282 
283     boolean isIpTransparent() throws IOException {
284         return isIpTransparent(intValue()) != 0;
285     }
286 
287     boolean isIpRecvOrigDestAddr() throws IOException {
288         return isIpRecvOrigDestAddr(intValue()) != 0;
289     }
290 
291     PeerCredentials getPeerCredentials() throws IOException {
292         return getPeerCredentials(intValue());
293     }
294 
295     boolean isLoopbackModeDisabled() throws IOException {
296         return getIpMulticastLoop(intValue(), ipv6) == 0;
297     }
298 
299     void setLoopbackModeDisabled(boolean loopbackModeDisabled) throws IOException {
300         setIpMulticastLoop(intValue(), ipv6, loopbackModeDisabled ? 0 : 1);
301     }
302 
303     boolean isUdpGro() throws IOException {
304         return isUdpGro(intValue()) != 0;
305     }
306 
307     void setUdpGro(boolean gro) throws IOException {
308         setUdpGro(intValue(), gro ? 1 : 0);
309     }
310 
311     long sendFile(DefaultFileRegion src, long baseOffset, long offset, long length) throws IOException {
312         // Open the file-region as it may be created via the lazy constructor. This is needed as we directly access
313         // the FileChannel field via JNI.
314         src.open();
315 
316         long res = sendFile(intValue(), src, baseOffset, offset, length);
317         if (res >= 0) {
318             return res;
319         }
320         return ioResult("sendfile", (int) res);
321     }
322 
323     public void bindVSock(VSockAddress address) throws IOException {
324         int res = bindVSock(/*fd*/intValue(), address.getCid(), address.getPort());
325         if (res < 0) {
326             throw newIOException("bindVSock", res);
327         }
328     }
329 
330     public boolean connectVSock(VSockAddress address) throws IOException {
331         int res = connectVSock(/*fd*/intValue(), address.getCid(), address.getPort());
332         if (res < 0) {
333             return Errors.handleConnectErrno("connectVSock", res);
334         }
335         return true;
336     }
337 
338     public VSockAddress remoteVSockAddress() {
339         byte[] addr = remoteVSockAddress(/*fd*/intValue());
340         if (addr == null) {
341             return null;
342         }
343         int cid = getIntAt(addr, 0);
344         int port = getIntAt(addr, 4);
345         return new VSockAddress(cid, port);
346     }
347 
348     public VSockAddress localVSockAddress() {
349         byte[] addr = localVSockAddress(/*fd*/intValue());
350         if (addr == null) {
351             return null;
352         }
353         int cid = getIntAt(addr, 0);
354         int port = getIntAt(addr, 4);
355         return new VSockAddress(cid, port);
356     }
357 
358     private static int getIntAt(byte[] array, int startIndex) {
359         return array[startIndex] << 24 | (array[startIndex + 1] & 0xFF) << 16
360                 | (array[startIndex + 2] & 0xFF) << 8 | (array[startIndex + 3] & 0xFF);
361     }
362 
363     private static InetAddress deriveInetAddress(NetworkInterface netInterface, boolean ipv6) {
364         final InetAddress ipAny = ipv6 ? Native.INET6_ANY : Native.INET_ANY;
365         if (netInterface != null) {
366             final Enumeration<InetAddress> ias = netInterface.getInetAddresses();
367             while (ias.hasMoreElements()) {
368                 final InetAddress ia = ias.nextElement();
369                 final boolean isV6 = ia instanceof Inet6Address;
370                 if (isV6 == ipv6) {
371                     return ia;
372                 }
373             }
374         }
375         return ipAny;
376     }
377 
378     public static LinuxSocket newSocket(int fd) {
379         return new LinuxSocket(fd);
380     }
381 
382     public static LinuxSocket newVSockStream() {
383         return new LinuxSocket(newVSockStream0());
384     }
385 
386     static int newVSockStream0() {
387         int res = newVSockStreamFd();
388         if (res < 0) {
389             throw new ChannelException(newIOException("newVSockStream", res));
390         }
391         return res;
392     }
393 
394     public static LinuxSocket newSocketStream(boolean ipv6) {
395         return new LinuxSocket(newSocketStream0(ipv6));
396     }
397 
398     public static LinuxSocket newSocketStream(InternetProtocolFamily protocol) {
399         return new LinuxSocket(newSocketStream0(protocol));
400     }
401 
402     public static LinuxSocket newSocketStream() {
403         return newSocketStream(isIPv6Preferred());
404     }
405 
406     public static LinuxSocket newSocketDgram(boolean ipv6) {
407         return new LinuxSocket(newSocketDgram0(ipv6));
408     }
409 
410     public static LinuxSocket newSocketDgram(InternetProtocolFamily family) {
411         return new LinuxSocket(newSocketDgram0(family));
412     }
413 
414     public static LinuxSocket newSocketDgram() {
415         return newSocketDgram(isIPv6Preferred());
416     }
417 
418     public static LinuxSocket newSocketDomain() {
419         return new LinuxSocket(newSocketDomain0());
420     }
421 
422     public static LinuxSocket newSocketDomainDgram() {
423         return new LinuxSocket(newSocketDomainDgram0());
424     }
425 
426     private static native int newVSockStreamFd();
427     private static native int bindVSock(int fd, int cid, int port);
428     private static native int connectVSock(int fd, int cid, int port);
429     private static native byte[] remoteVSockAddress(int fd);
430     private static native byte[] localVSockAddress(int fd);
431 
432     private static native void joinGroup(int fd, boolean ipv6, byte[] group, byte[] interfaceAddress,
433                                          int scopeId, int interfaceIndex) throws IOException;
434     private static native void joinSsmGroup(int fd, boolean ipv6, byte[] group, byte[] interfaceAddress,
435                                             int scopeId, int interfaceIndex, byte[] source) throws IOException;
436     private static native void leaveGroup(int fd, boolean ipv6, byte[] group, byte[] interfaceAddress,
437                                           int scopeId, int interfaceIndex) throws IOException;
438     private static native void leaveSsmGroup(int fd, boolean ipv6, byte[] group, byte[] interfaceAddress,
439                                              int scopeId, int interfaceIndex, byte[] source) throws IOException;
440     private static native long sendFile(int socketFd, DefaultFileRegion src, long baseOffset,
441                                         long offset, long length) throws IOException;
442 
443     private static native int getTcpDeferAccept(int fd) throws IOException;
444     private static native int isTcpQuickAck(int fd) throws IOException;
445     private static native int isTcpCork(int fd) throws IOException;
446     private static native int getSoBusyPoll(int fd) throws IOException;
447     private static native int getTcpNotSentLowAt(int fd) throws IOException;
448     private static native int getTcpKeepIdle(int fd) throws IOException;
449     private static native int getTcpKeepIntvl(int fd) throws IOException;
450     private static native int getTcpKeepCnt(int fd) throws IOException;
451     private static native int getTcpUserTimeout(int fd) throws IOException;
452     private static native int getTimeToLive(int fd) throws IOException;
453     private static native int isIpBindAddressNoPort(int fd) throws IOException;
454     private static native int isIpFreeBind(int fd) throws IOException;
455     private static native int isIpTransparent(int fd) throws IOException;
456     private static native int isIpRecvOrigDestAddr(int fd) throws IOException;
457     private static native void getTcpInfo(int fd, long[] array) throws IOException;
458     private static native PeerCredentials getPeerCredentials(int fd) throws IOException;
459 
460     private static native void setTcpDeferAccept(int fd, int deferAccept) throws IOException;
461     private static native void setTcpQuickAck(int fd, int quickAck) throws IOException;
462     private static native void setTcpCork(int fd, int tcpCork) throws IOException;
463     private static native void setSoBusyPoll(int fd, int loopMicros) throws IOException;
464     private static native void setTcpNotSentLowAt(int fd, int tcpNotSentLowAt) throws IOException;
465     private static native void setTcpFastOpen(int fd, int tcpFastopenBacklog) throws IOException;
466     private static native void setTcpKeepIdle(int fd, int seconds) throws IOException;
467     private static native void setTcpKeepIntvl(int fd, int seconds) throws IOException;
468     private static native void setTcpKeepCnt(int fd, int probes) throws IOException;
469     private static native void setTcpUserTimeout(int fd, int milliseconds)throws IOException;
470     private static native void setIpBindAddressNoPort(int fd, int ipBindAddressNoPort) throws IOException;
471     private static native void setIpFreeBind(int fd, int freeBind) throws IOException;
472     private static native void setIpTransparent(int fd, int transparent) throws IOException;
473     private static native void setIpRecvOrigDestAddr(int fd, int transparent) throws IOException;
474     private static native void setTcpMd5Sig(
475             int fd, boolean ipv6, byte[] address, int scopeId, byte[] key) throws IOException;
476     private static native void setInterface(
477             int fd, boolean ipv6, byte[] interfaceAddress, int scopeId, int networkInterfaceIndex) throws IOException;
478     private static native int getInterface(int fd, boolean ipv6);
479     private static native int getIpMulticastLoop(int fd, boolean ipv6) throws IOException;
480     private static native void setIpMulticastLoop(int fd, boolean ipv6, int enabled) throws IOException;
481     private static native void setTimeToLive(int fd, int ttl) throws IOException;
482     private static native int isUdpGro(int fd) throws IOException;
483     private static native void setUdpGro(int fd, int gro) throws IOException;
484 }