aboutsummaryrefslogtreecommitdiffstats
path: root/src/net/java/sip/communicator/impl/netaddr/BsdLocalhostRetriever.java
blob: d87d8926704bc0ac97a4bd3b0d6e684ed5f5179a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
package net.java.sip.communicator.impl.netaddr;

import java.io.*;
import java.net.*;
import java.util.*;

import com.sun.jna.*;
import com.sun.jna.ptr.*;

/**
 * Utility class to lookup the local source address of a UDP socket on BSD-like
 * platforms (i.e. @{link sockaddr_in} has the <tt>sin_len</tt> member) using
 * JNA. Other platforms (including Windows) could be used by introducing new
 * {@link sockaddr} subclasses without the len member.
 * 
 * @author Ingo Bauersachs
 */
public class BsdLocalhostRetriever
{
    /**
     * JNA interface to LibC.
     */
    public static interface LibC
        extends Library
    {
        static final LibC INSTANCE = (LibC) Native.loadLibrary("c", LibC.class);

        public static final int AF_INET = 2;
        public static final int AF_INET6 = 30;

        public static final int SOCK_DGRAM = 2;

        // see the man pages for the mapped C functions
        int socket(int domain, int type, int protocol);
        int connect(int s, sockaddr name, int namelen);
        int getsockname(int fd, sockaddr addr, IntByReference len);
        int close(int fd);
        String strerror(int error);

        public static class CException extends IOException
        {
            private static final long serialVersionUID = 2988769925077172885L;

            public CException()
            {
                super(LibC.INSTANCE.strerror(Native.getLastError()));
            }
        }
    }

    /**
     * Corresponds to the C structure sockaddr with some utility functions.
     */
    public abstract static class sockaddr
        extends Structure
    {
        /**
         * Creates a C sockaddr_in or sockaddr_in6 based on the type of the
         * passed socket address.
         * 
         * @param socket The socket address to map.
         * @return The mapped socket address.
         */
        public static sockaddr create(InetSocketAddress socket)
        {
            InetAddress address = socket.getAddress();
            if (address instanceof Inet4Address)
            {
                sockaddr_in v4 = new sockaddr_in();
                v4.sin_addr = address.getAddress();
                v4.sin_port = (short) socket.getPort();
                v4.sin_len = (byte) Native.getNativeSize(v4.getClass(), v4);
                return v4;
            }
            else if (address instanceof Inet6Address)
            {
                sockaddr_in6 v6 = new sockaddr_in6();
                v6.sin6_addr = address.getAddress();
                v6.sin6_port = (short) socket.getPort();
                v6.sin6_len = (byte) Native.getNativeSize(v6.getClass(), v6);
                return v6;
            }
            else
            {
                throw new IllegalArgumentException("Unsupported address type");
            }
        }

        /**
         * Gets the socket type.
         * @return {@link LibC#AF_INET} or {@link LibC#AF_INET6}.
         */
        public abstract int getFamily();

        /**
         * Creates a new sockaddr instance of the same type.
         * @return {@link sockaddr_in} or {@link sockaddr_in6}
         */
        public abstract sockaddr createEmpty();

        /**
         * Gets an {@link InetAddress} from the sin[6]_addr member.
         * 
         * @return an {@link InetAddress} with only the address set.
         * @throws UnknownHostException When the data in the structure does not
         *             represent a valid IPv4 or IPv6 address.
         */
        public abstract InetAddress getAddress() throws UnknownHostException;

        /**
         * Gets the native size of this structure.
         * @return the native size of this structure.
         */
        public int getSize()
        {
            return Native.getNativeSize(this.getClass(), this);
        }
    }

    /**
     * JNA mapping of <tt>sockaddr_in</tt>.
     */
    public final static class sockaddr_in
        extends sockaddr
    {
        public byte sin_len;
        public byte sin_family;
        public short sin_port;
        public byte[] sin_addr;
        public byte[] sin_zero;

        public sockaddr_in()
        {
            sin_family = LibC.AF_INET;
            sin_addr = new byte[4];
            sin_zero = new byte[8];
        }

        @Override
        public sockaddr createEmpty()
        {
            sockaddr_in v4 = new sockaddr_in();
            v4.sin_len = (byte) Native.getNativeSize(v4.getClass(), v4);
            return v4;
        }

        @Override
        public InetAddress getAddress() throws UnknownHostException
        {
            return InetAddress.getByAddress(sin_addr);
        }

        @Override
        public int getFamily()
        {
            return LibC.AF_INET;
        }

        @Override
        protected List getFieldOrder()
        {
            return
                Arrays.asList(
                        new String[]
                        {
                            "sin_len",
                            "sin_family",
                            "sin_port",
                            "sin_addr",
                            "sin_zero"
                        });
        }
    }

    /**
     * JNA mapping of <tt>sockaddr_in6</tt>
     */
    public final static class sockaddr_in6
        extends sockaddr
    {
        public byte sin6_len;
        public byte sin6_family;
        public short sin6_port;
        public int sin6_flowinfo;
        public byte[] sin6_addr;
        public int sin6_scope_id;

        public sockaddr_in6()
        {
            sin6_family = LibC.AF_INET6;
            sin6_addr = new byte[16];
        }

        @Override
        public sockaddr createEmpty()
        {
            sockaddr_in6 v6 = new sockaddr_in6();
            v6.sin6_len = (byte) Native.getNativeSize(v6.getClass(), v6);
            return v6;
        }

        @Override
        public InetAddress getAddress() throws UnknownHostException
        {
            return InetAddress.getByAddress(sin6_addr);
        }

        @Override
        public int getFamily()
        {
            return LibC.AF_INET6;
        }

        @Override
        protected List getFieldOrder()
        {
            return
                Arrays.asList(
                        new String[]
                        {
                            "sin6_len",
                            "sin6_family",
                            "sin6_port",
                            "sin6_flowinfo",
                            "sin6_addr",
                            "sin6_scope_id"
                        });
        }
    }

    /**
     * Gets the local address of a UDP socket that connects to the given
     * address.
     * 
     * @param dest The destination to which the socket connects.
     * @return The local address of the connecting socket.
     * @throws IOException When the socket cannot be created, connected or
     *             returns an invalid local address.
     */
    public static InetAddress getLocalSocketAddress(InetSocketAddress dest)
        throws IOException
    {
        sockaddr addr = sockaddr.create(dest);
        int fd = LibC.INSTANCE.socket(addr.getFamily(), LibC.SOCK_DGRAM, 0);
        if (fd == -1)
        {
            throw new LibC.CException();
        }

        try
        {
            int err = LibC.INSTANCE.connect(fd, addr, addr.getSize());
            if (err != 0)
            {
                throw new LibC.CException();
            }

            sockaddr local = addr.createEmpty();
            IntByReference size = new IntByReference(local.getSize());
            err = LibC.INSTANCE.getsockname(fd, local, size);
            if (err != 0)
            {
                throw new LibC.CException();
            }

            return local.getAddress();
        }
        finally
        {
            LibC.INSTANCE.close(fd);
        }
    }
}