If no source IP, or AF_UNSPEC, use sendto(). This works around
[freeradius.git] / src / lib / udpfromto.c
1 /*
2  *   This library is free software; you can redistribute it and/or
3  *   modify it under the terms of the GNU Lesser General Public
4  *   License as published by the Free Software Foundation; either
5  *   version 2.1 of the License, or (at your option) any later version.
6  *
7  *   This library is distributed in the hope that it will be useful,
8  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
9  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
10  *   Lesser General Public License for more details.
11  *
12  *   You should have received a copy of the GNU Lesser General Public
13  *   License along with this library; if not, write to the Free Software
14  *   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
15  *
16  *  Helper functions to get/set addresses of UDP packets
17  *  based on recvfromto by Miquel van Smoorenburg
18  *
19  * recvfromto   Like recvfrom, but also stores the destination
20  *              IP address. Useful on multihomed hosts.
21  *
22  *              Should work on Linux and BSD.
23  *
24  *              Copyright (C) 2002 Miquel van Smoorenburg.
25  *
26  *              This program is free software; you can redistribute it and/or
27  *              modify it under the terms of the GNU Lesser General Public
28  *              License as published by the Free Software Foundation; either
29  *              version 2 of the License, or (at your option) any later version.
30  *
31  * sendfromto   added 18/08/2003, Jan Berkel <jan@sitadelle.com>
32  *              Works on Linux and FreeBSD (5.x)
33  *
34  * Version: $Id$
35  */
36
37 #include <freeradius-devel/autoconf.h>
38
39 #ifdef WITH_UDPFROMTO
40 static const char rcsid[] = "$Id$";
41
42 #include <sys/types.h>
43
44 #ifdef HAVE_SYS_UIO_H
45 #include <sys/uio.h>
46 #endif
47
48 #include <netinet/in.h>
49 #include <errno.h>
50 #include <unistd.h>
51 #include <fcntl.h>
52 #include <string.h>
53
54 #include <freeradius-devel/udpfromto.h>
55
56 int udpfromto_init(int s)
57 {
58         int err = -1, opt = 1;
59         errno = ENOSYS;
60 #ifdef HAVE_IP_PKTINFO
61         /* Set the IP_PKTINFO option (Linux). */
62         err = setsockopt(s, SOL_IP, IP_PKTINFO, &opt, sizeof(opt));
63 #endif
64
65 #ifdef HAVE_IP_RECVDSTADDR
66         /*
67          * Set the IP_RECVDSTADDR option (BSD).
68          * Note: IP_RECVDSTADDR == IP_SENDSRCADDR
69          */
70         err = setsockopt(s, IPPROTO_IP, IP_RECVDSTADDR, &opt, sizeof(opt));
71 #endif
72         return err;
73 }
74
75 int recvfromto(int s, void *buf, size_t len, int flags,
76         struct sockaddr *from, socklen_t *fromlen,
77         struct sockaddr *to, socklen_t *tolen)
78 {
79 #if defined(HAVE_IP_PKTINFO) || defined(HAVE_IP_RECVDSTADDR)
80         struct msghdr msgh;
81         struct cmsghdr *cmsg;
82         struct iovec iov;
83         char cbuf[256];
84         int err;
85
86         /*
87          *      If from or to are set, they must be big enough
88          *      to store a struct sockaddr_in.
89          */
90         if ((from && (!fromlen || *fromlen < sizeof(struct sockaddr_in))) ||
91             (to   && (!tolen   || *tolen   < sizeof(struct sockaddr_in)))) {
92                 errno = EINVAL;
93                 return -1;
94         }
95
96         /*
97          *      IP_PKTINFO / IP_RECVDSTADDR don't provide sin_port so we have to
98          *      retrieve it using getsockname().
99          */
100         if (to) {
101                 struct sockaddr_in si;
102                 socklen_t l = sizeof(si);
103
104                 ((struct sockaddr_in *)to)->sin_family = AF_INET;
105                 ((struct sockaddr_in *)to)->sin_port = 0;
106                 l = sizeof(si);
107                 if (getsockname(s, (struct sockaddr *)&si, &l) == 0) {
108                         ((struct sockaddr_in *)to)->sin_port = si.sin_port;
109                         ((struct sockaddr_in *)to)->sin_addr = si.sin_addr;
110                 }
111                 if (tolen) *tolen = sizeof(struct sockaddr_in);
112         }
113
114         /* Set up iov and msgh structures. */
115         memset(&msgh, 0, sizeof(struct msghdr));
116         iov.iov_base = buf;
117         iov.iov_len  = len;
118         msgh.msg_control = cbuf;
119         msgh.msg_controllen = sizeof(cbuf);
120         msgh.msg_name = from;
121         msgh.msg_namelen = fromlen ? *fromlen : 0;
122         msgh.msg_iov  = &iov;
123         msgh.msg_iovlen = 1;
124         msgh.msg_flags = 0;
125
126         /* Receive one packet. */
127         if ((err = recvmsg(s, &msgh, flags)) < 0) {
128                 return err;
129         }
130         if (fromlen) *fromlen = msgh.msg_namelen;
131
132         /* Process auxiliary received data in msgh */
133         for (cmsg = CMSG_FIRSTHDR(&msgh);
134              cmsg != NULL;
135              cmsg = CMSG_NXTHDR(&msgh,cmsg)) {
136
137 # ifdef HAVE_IP_PKTINFO
138                 if (cmsg->cmsg_level == SOL_IP
139                     && cmsg->cmsg_type == IP_PKTINFO) {
140                         struct in_pktinfo *i =
141                                 (struct in_pktinfo *)CMSG_DATA(cmsg);
142                         if (to) {
143                                 ((struct sockaddr_in *)to)->sin_addr =
144                                         i->ipi_addr;
145                                 if (tolen) *tolen = sizeof(struct sockaddr_in);
146                         }
147                         break;
148                 }
149 # endif
150
151 # ifdef HAVE_IP_RECVDSTADDR
152                 if (cmsg->cmsg_level == IPPROTO_IP
153                     && cmsg->cmsg_type == IP_RECVDSTADDR) {
154                         struct in_addr *i = (struct in_addr *)CMSG_DATA(cmsg);
155                         if (to) {
156                                 ((struct sockaddr_in *)to)->sin_addr = *i;
157                                 if (tolen) *tolen = sizeof(struct sockaddr_in);
158                         }
159                         break;
160                 }
161 # endif
162         }
163         return err;
164 #else
165         /* fallback: call recvfrom */
166         return recvfrom(s, buf, len, flags, from, fromlen);
167 #endif /* defined(HAVE_IP_PKTINFO) || defined(HAVE_IP_RECVDSTADDR) */
168 }
169
170 int sendfromto(int s, void *buf, size_t len, int flags,
171                           struct sockaddr *from, socklen_t fromlen,
172                           struct sockaddr *to, socklen_t tolen)
173 {
174 #if defined(HAVE_IP_PKTINFO) || defined(HAVE_IP_SENDSRCADDR)
175         struct msghdr msgh;
176         struct cmsghdr *cmsg;
177         struct iovec iov;
178 # ifdef HAVE_IP_PKTINFO
179         char cmsgbuf[CMSG_SPACE(sizeof(struct in_pktinfo))];
180         struct in_pktinfo pktinfo, *pktinfo_ptr;
181         memset(&pktinfo, 0, sizeof(struct in_pktinfo));
182 # endif
183         struct sockaddr_in      *s4;
184
185 # ifdef HAVE_IP_SENDSRCADDR
186         char cmsgbuf[CMSG_SPACE(sizeof(struct in_addr))];
187 # endif
188
189         s4 = (struct sockaddr_in *) from;
190
191         /*
192          *      Source is unset, empty, or unspecified,
193          *      fall back to sendto().
194          */
195         if (!s4 || (fromlen == 0) || (s4->sin_family == AF_UNSPEC)) {
196                 return sendto(s, buf, len, flags, to, tolen);
197         }
198
199         /* Set up iov and msgh structures. */
200         memset(&msgh, 0, sizeof(struct msghdr));
201         iov.iov_base = buf;
202         iov.iov_len = len;
203         msgh.msg_iov = &iov;
204         msgh.msg_iovlen = 1;
205         msgh.msg_control = cmsgbuf;
206         msgh.msg_controllen = sizeof(cmsgbuf);
207         msgh.msg_name = to;
208         msgh.msg_namelen = tolen;
209
210         cmsg = CMSG_FIRSTHDR(&msgh);
211
212 # ifdef HAVE_IP_PKTINFO
213         cmsg->cmsg_level = SOL_IP;
214         cmsg->cmsg_type = IP_PKTINFO;
215         cmsg->cmsg_len = CMSG_LEN(sizeof(struct in_pktinfo));
216         pktinfo.ipi_spec_dst = ((struct sockaddr_in *)from)->sin_addr;
217         pktinfo_ptr = (struct in_pktinfo *)CMSG_DATA(cmsg);
218         memcpy(pktinfo_ptr, &pktinfo, sizeof(struct in_pktinfo));
219 # endif
220 # ifdef HAVE_IP_SENDSRCADDR
221         cmsg->cmsg_level = IPPROTO_IP;
222         cmsg->cmsg_type = IP_SENDSRCADDR;
223         cmsg->cmsg_len = CMSG_LEN(sizeof(struct in_addr));
224         memcpy((struct in_addr *)CMSG_DATA(cmsg),
225                &((struct sockaddr_in *)from)->sin_addr, sizeof(struct in_addr));
226 # endif
227
228         return sendmsg(s, &msgh, flags);
229 #else
230         /* fallback: call sendto() */
231         return sendto(s, buf, len, flags, to, tolen);
232 #endif  /* defined(HAVE_IP_PKTINFO) || defined (HAVE_IP_SENDSRCADDR) */
233 }
234
235
236 #ifdef TESTING
237 /*
238  *      Small test program to test recvfromto/sendfromto
239  *
240  *      use a virtual IP address as first argument to test
241  *
242  *      reply packet should originate from virtual IP and not
243  *      from the default interface the alias is bound to
244  */
245
246 #include <stdio.h>
247 #include <stdlib.h>
248 #include <arpa/inet.h>
249 #include <sys/types.h>
250 #include <sys/wait.h>
251
252 #define DEF_PORT 20000          /* default port to listen on */
253 #define DESTIP "127.0.0.1"      /* send packet to localhost per default */
254 #define TESTSTRING "foo"        /* what to send */
255 #define TESTLEN 4                       /* 4 bytes */
256
257 int main(int argc, char **argv)
258 {
259         struct sockaddr_in from, to, in;
260         char buf[TESTLEN];
261         char *destip = DESTIP;
262         int port = DEF_PORT;
263         int n, server_socket, client_socket, fl, tl, pid;
264
265         if (argc > 1) destip = argv[1];
266         if (argc > 2) port = atoi(argv[2]);
267
268         in.sin_family = AF_INET;
269         in.sin_addr.s_addr = INADDR_ANY;
270         in.sin_port = htons(port);
271         fl = tl = sizeof(struct sockaddr_in);
272         memset(&from, 0, sizeof(from));
273         memset(&to,   0, sizeof(to));
274
275         switch(pid = fork()) {
276                 case -1:
277                         perror("fork");
278                         return 0;
279                 case 0:
280                         /* child */
281                         usleep(100000);
282                         goto client;
283         }
284
285         /* parent: server */
286         server_socket = socket(PF_INET, SOCK_DGRAM, 0);
287         if (udpfromto_init(server_socket) != 0) {
288                 perror("udpfromto_init\n");
289                 waitpid(pid, NULL, WNOHANG);
290                 return 0;
291         }
292
293         if (bind(server_socket, (struct sockaddr *)&in, sizeof(in)) < 0) {
294                 perror("server: bind");
295                 waitpid(pid, NULL, WNOHANG);
296                 return 0;
297         }
298
299         printf("server: waiting for packets on INADDR_ANY:%d\n", port);
300         if ((n = recvfromto(server_socket, buf, sizeof(buf), 0,
301             (struct sockaddr *)&from, &fl,
302             (struct sockaddr *)&to, &tl)) < 0) {
303                 perror("server: recvfromto");
304                 waitpid(pid, NULL, WNOHANG);
305                 return 0;
306         }
307
308         printf("server: received a packet of %d bytes [%s] ", n, buf);
309         printf("(src ip:port %s:%d ",
310                 inet_ntoa(from.sin_addr), ntohs(from.sin_port));
311         printf(" dst ip:port %s:%d)\n",
312                 inet_ntoa(to.sin_addr), ntohs(to.sin_port));
313
314         printf("server: replying from address packet was received on to source address\n");
315
316         if ((n = sendfromto(server_socket, buf, n, 0,
317                 (struct sockaddr *)&to, tl,
318                 (struct sockaddr *)&from, fl)) < 0) {
319                 perror("server: sendfromto");
320         }
321
322         waitpid(pid, NULL, 0);
323         return 0;
324
325 client:
326         close(server_socket);
327         client_socket = socket(PF_INET, SOCK_DGRAM, 0);
328         if (udpfromto_init(client_socket) != 0) {
329                 perror("udpfromto_init");
330                 _exit(0);
331         }
332         /* bind client on different port */
333         in.sin_port = htons(port+1);
334         if (bind(client_socket, (struct sockaddr *)&in, sizeof(in)) < 0) {
335                 perror("client: bind");
336                 _exit(0);
337         }
338
339         in.sin_port = htons(port);
340         in.sin_addr.s_addr = inet_addr(destip);
341
342         printf("client: sending packet to %s:%d\n", destip, port);
343         if (sendto(client_socket, TESTSTRING, TESTLEN, 0,
344                         (struct sockaddr *)&in, sizeof(in)) < 0) {
345                 perror("client: sendto");
346                 _exit(0);
347         }
348
349         printf("client: waiting for reply from server on INADDR_ANY:%d\n", port+1);
350
351         if ((n = recvfromto(client_socket, buf, sizeof(buf), 0,
352             (struct sockaddr *)&from, &fl,
353             (struct sockaddr *)&to, &tl)) < 0) {
354                 perror("client: recvfromto");
355                 _exit(0);
356         }
357
358         printf("client: received a packet of %d bytes [%s] ", n, buf);
359         printf("(src ip:port %s:%d",
360                 inet_ntoa(from.sin_addr), ntohs(from.sin_port));
361         printf(" dst ip:port %s:%d)\n",
362                 inet_ntoa(to.sin_addr), ntohs(to.sin_port));
363
364         _exit(0);
365 }
366
367 #endif /* TESTING */
368 #endif /* WITH_UDPFROMTO */