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.socket.InternetProtocolFamily;
21  import io.netty.channel.socket.SocketProtocolFamily;
22  import io.netty.channel.unix.Errors;
23  import io.netty.channel.unix.NativeInetAddress;
24  import io.netty.channel.unix.PeerCredentials;
25  import io.netty.channel.unix.Socket;
26  import io.netty.util.internal.SocketUtils;
27  import io.netty.util.internal.UnstableApi;
28  
29  import java.io.IOException;
30  import java.net.Inet6Address;
31  import java.net.InetAddress;
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      SocketProtocolFamily family() {
51          return ipv6 ? SocketProtocolFamily.INET6 : SocketProtocolFamily.INET;
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() == SocketProtocolFamily.INET6);
79          if (address.equals(family() == SocketProtocolFamily.INET ? 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 NetworkInterface.getByIndex(ret);
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 networkInterface.getIndex();
155     }
156 
157     private static int interfaceIndex(InetAddress address) throws IOException {
158         NetworkInterface iface = NetworkInterface.getByInetAddress(address);
159         if (iface != null) {
160             return iface.getIndex();
161         }
162         return -1;
163     }
164 
165     void setTcpDeferAccept(int deferAccept) throws IOException {
166         setTcpDeferAccept(intValue(), deferAccept);
167     }
168 
169     void setTcpQuickAck(boolean quickAck) throws IOException {
170         setTcpQuickAck(intValue(), quickAck ? 1 : 0);
171     }
172 
173     void setTcpCork(boolean tcpCork) throws IOException {
174         setTcpCork(intValue(), tcpCork ? 1 : 0);
175     }
176 
177     void setSoBusyPoll(int loopMicros) throws IOException {
178         setSoBusyPoll(intValue(), loopMicros);
179     }
180 
181     void setTcpNotSentLowAt(long tcpNotSentLowAt) throws IOException {
182         if (tcpNotSentLowAt < 0 || tcpNotSentLowAt > MAX_UINT32_T) {
183             throw new IllegalArgumentException("tcpNotSentLowAt must be a uint32_t");
184         }
185         setTcpNotSentLowAt(intValue(), (int) tcpNotSentLowAt);
186     }
187 
188     void setTcpFastOpen(int tcpFastopenBacklog) throws IOException {
189         setTcpFastOpen(intValue(), tcpFastopenBacklog);
190     }
191 
192     void setTcpKeepIdle(int seconds) throws IOException {
193         setTcpKeepIdle(intValue(), seconds);
194     }
195 
196     void setTcpKeepIntvl(int seconds) throws IOException {
197         setTcpKeepIntvl(intValue(), seconds);
198     }
199 
200     void setTcpKeepCnt(int probes) throws IOException {
201         setTcpKeepCnt(intValue(), probes);
202     }
203 
204     void setTcpUserTimeout(int milliseconds) throws IOException {
205         setTcpUserTimeout(intValue(), milliseconds);
206     }
207 
208     void setIpFreeBind(boolean enabled) throws IOException {
209         setIpFreeBind(intValue(), enabled ? 1 : 0);
210     }
211 
212     void setIpTransparent(boolean enabled) throws IOException {
213         setIpTransparent(intValue(), enabled ? 1 : 0);
214     }
215 
216     void setIpRecvOrigDestAddr(boolean enabled) throws IOException {
217         setIpRecvOrigDestAddr(intValue(), enabled ? 1 : 0);
218     }
219 
220     int getTimeToLive() throws IOException {
221         return getTimeToLive(intValue());
222     }
223 
224     void getTcpInfo(EpollTcpInfo info) throws IOException {
225         getTcpInfo(intValue(), info.info);
226     }
227 
228     void setTcpMd5Sig(InetAddress address, byte[] key) throws IOException {
229         final NativeInetAddress a = NativeInetAddress.newInstance(address);
230         setTcpMd5Sig(intValue(), ipv6, a.address(), a.scopeId(), key);
231     }
232 
233     boolean isTcpCork() throws IOException  {
234         return isTcpCork(intValue()) != 0;
235     }
236 
237     int getSoBusyPoll() throws IOException  {
238         return getSoBusyPoll(intValue());
239     }
240 
241     int getTcpDeferAccept() throws IOException {
242         return getTcpDeferAccept(intValue());
243     }
244 
245     boolean isTcpQuickAck() throws IOException {
246         return isTcpQuickAck(intValue()) != 0;
247     }
248 
249     long getTcpNotSentLowAt() throws IOException {
250         return getTcpNotSentLowAt(intValue()) & MAX_UINT32_T;
251     }
252 
253     int getTcpKeepIdle() throws IOException {
254         return getTcpKeepIdle(intValue());
255     }
256 
257     int getTcpKeepIntvl() throws IOException {
258         return getTcpKeepIntvl(intValue());
259     }
260 
261     int getTcpKeepCnt() throws IOException {
262         return getTcpKeepCnt(intValue());
263     }
264 
265     int getTcpUserTimeout() throws IOException {
266         return getTcpUserTimeout(intValue());
267     }
268 
269     boolean isIpFreeBind() throws IOException {
270         return isIpFreeBind(intValue()) != 0;
271     }
272 
273     boolean isIpTransparent() throws IOException {
274         return isIpTransparent(intValue()) != 0;
275     }
276 
277     boolean isIpRecvOrigDestAddr() throws IOException {
278         return isIpRecvOrigDestAddr(intValue()) != 0;
279     }
280 
281     PeerCredentials getPeerCredentials() throws IOException {
282         return getPeerCredentials(intValue());
283     }
284 
285     boolean isLoopbackModeDisabled() throws IOException {
286         return getIpMulticastLoop(intValue(), ipv6) == 0;
287     }
288 
289     void setLoopbackModeDisabled(boolean loopbackModeDisabled) throws IOException {
290         setIpMulticastLoop(intValue(), ipv6, loopbackModeDisabled ? 0 : 1);
291     }
292 
293     boolean isUdpGro() throws IOException {
294         return isUdpGro(intValue()) != 0;
295     }
296 
297     void setUdpGro(boolean gro) throws IOException {
298         setUdpGro(intValue(), gro ? 1 : 0);
299     }
300 
301     long sendFile(DefaultFileRegion src, long baseOffset, long offset, long length) throws IOException {
302         // Open the file-region as it may be created via the lazy constructor. This is needed as we directly access
303         // the FileChannel field via JNI.
304         src.open();
305 
306         long res = sendFile(intValue(), src, baseOffset, offset, length);
307         if (res >= 0) {
308             return res;
309         }
310         return ioResult("sendfile", (int) res);
311     }
312 
313     public void bindVSock(VSockAddress address) throws IOException {
314         int res = bindVSock(/*fd*/intValue(), address.getCid(), address.getPort());
315         if (res < 0) {
316             throw newIOException("bindVSock", res);
317         }
318     }
319 
320     public boolean connectVSock(VSockAddress address) throws IOException {
321         int res = connectVSock(/*fd*/intValue(), address.getCid(), address.getPort());
322         if (res < 0) {
323             return Errors.handleConnectErrno("connectVSock", res);
324         }
325         return true;
326     }
327 
328     public VSockAddress remoteVSockAddress() {
329         byte[] addr = remoteVSockAddress(/*fd*/intValue());
330         if (addr == null) {
331             return null;
332         }
333         int cid = getIntAt(addr, 0);
334         int port = getIntAt(addr, 4);
335         return new VSockAddress(cid, port);
336     }
337 
338     public VSockAddress localVSockAddress() {
339         byte[] addr = localVSockAddress(/*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     private static int getIntAt(byte[] array, int startIndex) {
349         return array[startIndex] << 24 | (array[startIndex + 1] & 0xFF) << 16
350                 | (array[startIndex + 2] & 0xFF) << 8 | (array[startIndex + 3] & 0xFF);
351     }
352 
353     private static InetAddress deriveInetAddress(NetworkInterface netInterface, boolean ipv6) {
354         final InetAddress ipAny = ipv6 ? Native.INET6_ANY : Native.INET_ANY;
355         if (netInterface != null) {
356             final Enumeration<InetAddress> ias = netInterface.getInetAddresses();
357             while (ias.hasMoreElements()) {
358                 final InetAddress ia = ias.nextElement();
359                 final boolean isV6 = ia instanceof Inet6Address;
360                 if (isV6 == ipv6) {
361                     return ia;
362                 }
363             }
364         }
365         return ipAny;
366     }
367 
368     public static LinuxSocket newSocket(int fd) {
369         return new LinuxSocket(fd);
370     }
371 
372     public static LinuxSocket newVSockStream() {
373         return new LinuxSocket(newVSockStream0());
374     }
375 
376     static int newVSockStream0() {
377         int res = newVSockStreamFd();
378         if (res < 0) {
379             throw new ChannelException(newIOException("newVSockStream", res));
380         }
381         return res;
382     }
383 
384     public static LinuxSocket newSocketStream(boolean ipv6) {
385         return new LinuxSocket(newSocketStream0(ipv6));
386     }
387 
388     /**
389      * @deprecated use {@link #newSocketStream(SocketProtocolFamily)}
390      */
391     @Deprecated
392     public static LinuxSocket newSocketStream(InternetProtocolFamily protocol) {
393         return new LinuxSocket(newSocketStream0(protocol));
394     }
395 
396     public static LinuxSocket newSocketStream(SocketProtocolFamily protocol) {
397         return new LinuxSocket(newSocketStream0(protocol));
398     }
399 
400     public static LinuxSocket newSocketStream() {
401         return newSocketStream(isIPv6Preferred());
402     }
403 
404     public static LinuxSocket newSocketDgram(boolean ipv6) {
405         return new LinuxSocket(newSocketDgram0(ipv6));
406     }
407 
408     /**
409      * @deprecated use {@link #newSocketDgram(SocketProtocolFamily)}
410      */
411     @Deprecated
412     public static LinuxSocket newSocketDgram(InternetProtocolFamily family) {
413         return new LinuxSocket(newSocketDgram0(family));
414     }
415 
416     public static LinuxSocket newSocketDgram(SocketProtocolFamily family) {
417         return new LinuxSocket(newSocketDgram0(family));
418     }
419 
420     public static LinuxSocket newSocketDgram() {
421         return newSocketDgram(isIPv6Preferred());
422     }
423 
424     public static LinuxSocket newSocketDomain() {
425         return new LinuxSocket(newSocketDomain0());
426     }
427 
428     public static LinuxSocket newSocketDomainDgram() {
429         return new LinuxSocket(newSocketDomainDgram0());
430     }
431 
432     private static native int newVSockStreamFd();
433     private static native int bindVSock(int fd, int cid, int port);
434     private static native int connectVSock(int fd, int cid, int port);
435     private static native byte[] remoteVSockAddress(int fd);
436     private static native byte[] localVSockAddress(int fd);
437 
438     private static native void joinGroup(int fd, boolean ipv6, byte[] group, byte[] interfaceAddress,
439                                          int scopeId, int interfaceIndex) throws IOException;
440     private static native void joinSsmGroup(int fd, boolean ipv6, byte[] group, byte[] interfaceAddress,
441                                             int scopeId, int interfaceIndex, byte[] source) throws IOException;
442     private static native void leaveGroup(int fd, boolean ipv6, byte[] group, byte[] interfaceAddress,
443                                           int scopeId, int interfaceIndex) throws IOException;
444     private static native void leaveSsmGroup(int fd, boolean ipv6, byte[] group, byte[] interfaceAddress,
445                                              int scopeId, int interfaceIndex, byte[] source) throws IOException;
446     private static native long sendFile(int socketFd, DefaultFileRegion src, long baseOffset,
447                                         long offset, long length) throws IOException;
448 
449     private static native int getTcpDeferAccept(int fd) throws IOException;
450     private static native int isTcpQuickAck(int fd) throws IOException;
451     private static native int isTcpCork(int fd) throws IOException;
452     private static native int getSoBusyPoll(int fd) throws IOException;
453     private static native int getTcpNotSentLowAt(int fd) throws IOException;
454     private static native int getTcpKeepIdle(int fd) throws IOException;
455     private static native int getTcpKeepIntvl(int fd) throws IOException;
456     private static native int getTcpKeepCnt(int fd) throws IOException;
457     private static native int getTcpUserTimeout(int fd) throws IOException;
458     private static native int getTimeToLive(int fd) throws IOException;
459     private static native int isIpFreeBind(int fd) throws IOException;
460     private static native int isIpTransparent(int fd) throws IOException;
461     private static native int isIpRecvOrigDestAddr(int fd) throws IOException;
462     private static native void getTcpInfo(int fd, long[] array) throws IOException;
463     private static native PeerCredentials getPeerCredentials(int fd) throws IOException;
464 
465     private static native void setTcpDeferAccept(int fd, int deferAccept) throws IOException;
466     private static native void setTcpQuickAck(int fd, int quickAck) throws IOException;
467     private static native void setTcpCork(int fd, int tcpCork) throws IOException;
468     private static native void setSoBusyPoll(int fd, int loopMicros) throws IOException;
469     private static native void setTcpNotSentLowAt(int fd, int tcpNotSentLowAt) throws IOException;
470     private static native void setTcpFastOpen(int fd, int tcpFastopenBacklog) throws IOException;
471     private static native void setTcpKeepIdle(int fd, int seconds) throws IOException;
472     private static native void setTcpKeepIntvl(int fd, int seconds) throws IOException;
473     private static native void setTcpKeepCnt(int fd, int probes) throws IOException;
474     private static native void setTcpUserTimeout(int fd, int milliseconds)throws IOException;
475     private static native void setIpFreeBind(int fd, int freeBind) throws IOException;
476     private static native void setIpTransparent(int fd, int transparent) throws IOException;
477     private static native void setIpRecvOrigDestAddr(int fd, int transparent) throws IOException;
478     private static native void setTcpMd5Sig(
479             int fd, boolean ipv6, byte[] address, int scopeId, byte[] key) throws IOException;
480     private static native void setInterface(
481             int fd, boolean ipv6, byte[] interfaceAddress, int scopeId, int networkInterfaceIndex) throws IOException;
482     private static native int getInterface(int fd, boolean ipv6);
483     private static native int getIpMulticastLoop(int fd, boolean ipv6) throws IOException;
484     private static native void setIpMulticastLoop(int fd, boolean ipv6, int enabled) throws IOException;
485     private static native void setTimeToLive(int fd, int ttl) throws IOException;
486     private static native int isUdpGro(int fd) throws IOException;
487     private static native void setUdpGro(int fd, int gro) throws IOException;
488 }