PUD: fix setting up network interface.
[olsrd.git] / lib / pud / src / networkInterfaces.c
1 #include "networkInterfaces.h"
2
3 /* Plugin includes */
4 #include "pud.h"
5 #include "configuration.h"
6 #include "netTools.h"
7
8 /* OLSRD includes */
9 #include "olsr.h"
10 #include "interfaces.h"
11
12 /* System includes */
13 #include <unistd.h>
14 #include <fcntl.h>
15
16 /*
17  * Main IP MAC address
18  */
19
20 /** the MAC address of the main IP address */
21 static unsigned char mac[PUD_NODEIDTYPE_MAC_BYTES] = { 0 };
22
23 /** true when the MAC address of the main IP address has been retrieved */
24 static bool macSet = false;
25
26 /**
27  * @return
28  * the MAC address of the main IP address
29  */
30 unsigned char * getMainIpMacAddress(void) {
31         if (!macSet) {
32                 struct ifreq ifr;
33                 unsigned char * macInIfr;
34
35                 struct interface *mainInterface = if_ifwithaddr(&olsr_cnf->main_addr);
36                 if (!mainInterface) {
37                         pudError(true, "Could not get the main interface");
38                         return NULL;
39                 }
40                 macInIfr = getHardwareAddress(mainInterface->int_name, olsr_cnf->ip_version, &ifr);
41                 if (!macInIfr) {
42                         pudError(true, "Could not get the MAC address of the main interface");
43                         return NULL;
44                 }
45                 memcpy(&mac[0], &macInIfr[0], PUD_NODEIDTYPE_MAC_BYTES);
46                 macSet = true;
47         }
48
49         return &mac[0];
50 }
51
52 /*
53  * RX interfaces
54  */
55
56 /** The list of network interface objects, receiving GPS NMEA sentences */
57 static TRxTxNetworkInterface *rxNetworkInterfacesListHead = NULL;
58
59 /** Pointer to the last network interface object, receiving GPS NMEA sentences */
60 static TRxTxNetworkInterface *lastRxNetworkInterface = NULL;
61
62 /**
63  @return
64  The list of network interface objects, receiving GPS NMEA sentences
65  */
66 TRxTxNetworkInterface *getRxNetworkInterfaces(void) {
67         return rxNetworkInterfacesListHead;
68 }
69
70 /**
71  Create a receive socket for a network interface
72
73  @param networkInterface
74  The network interface object. This function expects it to be filled with all
75  information, except for the socket descriptor.
76  @param rxSocketHandlerFunction
77  The function that handles reception of data on the network interface
78  @param rxMcAddr
79  The receive multicast address
80
81  @return
82  - the socket descriptor (>= 0)
83  - -1 if an error occurred
84  */
85 static int createRxSocket(TRxTxNetworkInterface * networkInterface,
86                 socket_handler_func rxSocketHandlerFunction, union olsr_sockaddr * rxMcAddr) {
87         int ipFamilySetting;
88         int ipProtoSetting;
89         int ipMcLoopSetting;
90         int ipAddMembershipSetting;
91
92         union olsr_sockaddr address;
93         void * addr;
94         size_t addrSize;
95
96         int rxSocket = -1;
97
98         int socketReuseFlagValue = 1;
99         int mcLoopValue = 1;
100
101         assert(networkInterface != NULL);
102         assert(rxSocketHandlerFunction != NULL);
103         assert(strncmp((char *) &networkInterface->name[0], "",
104                                         sizeof(networkInterface->name)) != 0);
105
106         memset(&address, 0, sizeof(address));
107         if (rxMcAddr->in.sa_family == AF_INET) {
108                 assert(rxMcAddr->in4.sin_addr.s_addr != INADDR_ANY);
109
110                 ipFamilySetting = AF_INET;
111                 ipProtoSetting = IPPROTO_IP;
112                 ipMcLoopSetting = IP_MULTICAST_LOOP;
113                 ipAddMembershipSetting = IP_ADD_MEMBERSHIP;
114
115                 address.in4.sin_family = ipFamilySetting;
116                 address.in4.sin_addr.s_addr = INADDR_ANY;
117                 address.in4.sin_port = getRxMcPort();
118                 addr = &address.in4;
119                 addrSize = sizeof(struct sockaddr_in);
120         } else {
121                 assert(rxMcAddr->in6.sin6_addr.s6_addr != in6addr_any.s6_addr);
122
123                 ipFamilySetting = AF_INET6;
124                 ipProtoSetting = IPPROTO_IPV6;
125                 ipMcLoopSetting = IPV6_MULTICAST_LOOP;
126                 ipAddMembershipSetting = IPV6_ADD_MEMBERSHIP;
127
128                 address.in6.sin6_family = ipFamilySetting;
129                 address.in6.sin6_addr = in6addr_any;
130                 address.in6.sin6_port = getRxMcPort();
131                 addr = &address.in6;
132                 addrSize = sizeof(struct sockaddr_in6);
133         }
134
135         /* Create a datagram socket on which to receive. */
136         errno = 0;
137         rxSocket = socket(ipFamilySetting, SOCK_DGRAM, 0);
138         if (rxSocket < 0) {
139                 pudError(true, "Could not create a receive socket for interface %s",
140                                 networkInterface->name);
141                 goto bail;
142         }
143
144         /* Enable SO_REUSEADDR to allow multiple applications to receive the same
145          * multicast messages */
146         errno = 0;
147         if (setsockopt(rxSocket, SOL_SOCKET, SO_REUSEADDR, &socketReuseFlagValue,
148                         sizeof(socketReuseFlagValue)) < 0) {
149                 pudError(true, "Could not set the reuse flag on the receive socket for"
150                         " interface %s", networkInterface->name);
151                 goto bail;
152         }
153
154         /* Bind to the proper port number with the IP address INADDR_ANY
155          * (INADDR_ANY is really required here, do not change it) */
156         errno = 0;
157         if (bind(rxSocket, addr, addrSize) < 0) {
158                 pudError(true, "Could not bind the receive socket for interface"
159                         " %s to port %u", networkInterface->name, ntohs(getRxMcPort()));
160                 goto bail;
161         }
162
163         /* Enable multicast local loopback */
164         errno = 0;
165         if (setsockopt(rxSocket, ipProtoSetting, ipMcLoopSetting, &mcLoopValue,
166                         sizeof(mcLoopValue)) < 0) {
167                 pudError(true, "Could not %s multicast loopback on the"
168                         " receive socket for interface %s", mcLoopValue ? "enable"
169                                 : "disable", networkInterface->name);
170                 goto bail;
171         }
172
173         /* Join the multicast group on the local interface. Note that this
174          * ADD_MEMBERSHIP option must be called for each local interface over
175          * which the multicast datagrams are to be received. */
176         if (ipFamilySetting == AF_INET) {
177                 struct ip_mreq mc_settings;
178
179                 struct ifreq ifr;
180                 struct in_addr * ifAddr = getIPv4Address(networkInterface->name, &ifr);
181                 if (!ifAddr) {
182                         pudError(true, "Could not get interface address of %s", networkInterface->name);
183                         goto bail;
184                 }
185
186                 (void) memset(&mc_settings, 0, sizeof(mc_settings));
187                 mc_settings.imr_multiaddr = rxMcAddr->in4.sin_addr;
188                 mc_settings.imr_interface = *ifAddr;
189                 errno = 0;
190                 if (setsockopt(rxSocket, ipProtoSetting, ipAddMembershipSetting,
191                                 &mc_settings, sizeof(mc_settings)) < 0) {
192                         pudError(true, "Could not subscribe interface %s to the configured"
193                                 " multicast group", networkInterface->name);
194                         goto bail;
195                 }
196         } else {
197                 struct ipv6_mreq mc6_settings;
198                 (void) memset(&mc6_settings, 0, sizeof(mc6_settings));
199                 mc6_settings.ipv6mr_multiaddr = rxMcAddr->in6.sin6_addr;
200                 mc6_settings.ipv6mr_interface = if_nametoindex(networkInterface->name);
201                 errno = 0;
202                 if (setsockopt(rxSocket, ipProtoSetting, ipAddMembershipSetting,
203                                 &mc6_settings, sizeof(mc6_settings)) < 0) {
204                         pudError(true, "Could not subscribe interface %s to the configured"
205                                 " multicast group", networkInterface->name);
206                         goto bail;
207                 }
208         }
209
210         add_olsr_socket(rxSocket, rxSocketHandlerFunction, NULL, networkInterface,
211                         SP_PR_READ);
212
213         return rxSocket;
214
215         bail: if (rxSocket >= 0) {
216                 close(rxSocket);
217         }
218         return -1;
219
220 }
221
222 /**
223  Create a receive interface and add it to the list of receive network interface
224  objects
225
226  @param ifName
227  the network interface name
228  @param rxSocketHandlerFunction
229  the function that handles reception of data on the network interface
230  @param rxMcAddr
231  The receive multicast address
232
233  @return
234  - true on success
235  - false on failure
236  */
237 static bool createRxInterface(const char * ifName,
238                 socket_handler_func rxSocketHandlerFunction, union olsr_sockaddr * rxMcAddr) {
239         int socketFd = -1;
240         TRxTxNetworkInterface * networkInterface = NULL;
241
242         if (ifName == NULL) {
243                 goto bail;
244         }
245
246         networkInterface = olsr_malloc(sizeof(TRxTxNetworkInterface),
247                         "TRxTxNetworkInterface (PUD)");
248         if (networkInterface == NULL) {
249                 goto bail;
250         }
251
252         memcpy(networkInterface->name, ifName, sizeof(networkInterface->name));
253         networkInterface->name[IFNAMSIZ] = '\0';
254         networkInterface->handler = NULL;
255         networkInterface->next = NULL;
256
257         /* networkInterface needs to be filled in when calling createRxSocket */
258         socketFd = createRxSocket(networkInterface, rxSocketHandlerFunction, rxMcAddr);
259         if (socketFd < 0) {
260                 goto bail;
261         }
262         networkInterface->socketFd = socketFd;
263         networkInterface->handler = rxSocketHandlerFunction;
264
265         /* Add new object to the end of the global list. */
266         if (rxNetworkInterfacesListHead == NULL) {
267                 rxNetworkInterfacesListHead = networkInterface;
268                 lastRxNetworkInterface = networkInterface;
269         } else {
270                 lastRxNetworkInterface->next = networkInterface;
271                 lastRxNetworkInterface = networkInterface;
272         }
273
274         return true;
275
276         bail: if (networkInterface != NULL) {
277                 free(networkInterface);
278         }
279         return false;
280
281 }
282
283 /*
284  * TX interfaces
285  */
286
287 /** The list of network interface objects, sending our NMEA sentences */
288 static TRxTxNetworkInterface *txNetworkInterfacesListHead = NULL;
289
290 /** Pointer to the last network interface object, sending our NMEA sentences */
291 static TRxTxNetworkInterface *lastTxNetworkInterface = NULL;
292
293 /**
294  @return
295  The list of network interface objects, sending our NMEA sentences
296  */
297 TRxTxNetworkInterface *getTxNetworkInterfaces(void) {
298         return txNetworkInterfacesListHead;
299 }
300
301 /**
302  Create a transmit socket for a network interface
303
304  @param networkInterface
305  The network interface object. This function expects it to be filled with all
306  information, except for the socket descriptor.
307  @param txMcAddr
308  The transmit multicast address
309
310  @return
311  - the socket descriptor (>= 0)
312  - -1 if an error occurred
313  */
314 static int createTxSocket(TRxTxNetworkInterface * networkInterface, union olsr_sockaddr * txMcAddr) {
315         int ipFamilySetting;
316         int ipProtoSetting;
317         int ipMcLoopSetting;
318         int ipMcIfSetting;
319         int ipTtlSetting;
320         unsigned int ifIndex;
321
322         union olsr_sockaddr address;
323         void * addr;
324         size_t addrSize;
325
326         int txSocket = -1;
327
328         int mcLoopValue = 0;
329         int txTtl = getTxTtl();
330
331         assert(networkInterface != NULL);
332         assert(strncmp((char *) &networkInterface->name[0], "",
333                                         sizeof(networkInterface->name)) != 0);
334
335         memset(&address, 0, sizeof(address));
336         if (txMcAddr->in.sa_family == AF_INET) {
337                 struct ifreq ifr;
338                 struct in_addr * ifAddr = getIPv4Address(networkInterface->name, &ifr);
339                 if (!ifAddr) {
340                         pudError(true, "Could not get interface address of %s", networkInterface->name);
341                         goto bail;
342                 }
343
344                 assert(txMcAddr->in4.sin_addr.s_addr != INADDR_ANY);
345
346                 ipFamilySetting = AF_INET;
347                 ipProtoSetting = IPPROTO_IP;
348                 ipMcLoopSetting = IP_MULTICAST_LOOP;
349                 ipMcIfSetting = IP_MULTICAST_IF;
350                 ipTtlSetting = IP_MULTICAST_TTL;
351                 ifIndex = 0;
352
353                 address.in4.sin_family = ipFamilySetting;
354                 address.in4.sin_addr = *ifAddr;
355                 address.in4.sin_port = getTxMcPort();
356                 addr = &address.in4;
357                 addrSize = sizeof(struct sockaddr_in);
358         } else {
359                 assert(txMcAddr->in6.sin6_addr.s6_addr != in6addr_any.s6_addr);
360
361                 ipFamilySetting = AF_INET6;
362                 ipProtoSetting = IPPROTO_IPV6;
363                 ipMcLoopSetting = IPV6_MULTICAST_LOOP;
364                 ipMcIfSetting = IPV6_MULTICAST_IF;
365                 ipTtlSetting = IPV6_MULTICAST_HOPS;
366                 ifIndex = if_nametoindex(networkInterface->name);
367
368                 addr = &ifIndex;
369                 addrSize = sizeof(ifIndex);
370         }
371
372         /*  Create a datagram socket on which to transmit */
373         errno = 0;
374         txSocket = socket(ipFamilySetting, SOCK_DGRAM, 0);
375         if (txSocket < 0) {
376                 pudError(true, "Could not create a transmit socket for interface %s",
377                                 networkInterface->name);
378                 goto bail;
379         }
380
381         /* Bind the socket to the desired interface */
382         errno = 0;
383         if (setsockopt(txSocket, ipProtoSetting, ipMcIfSetting, addr, addrSize) < 0) {
384                 pudError(true, "Could not set the multicast interface on the"
385                         " transmit socket to interface %s", networkInterface->name);
386                 goto bail;
387         }
388
389         /* Disable multicast local loopback */
390         errno = 0;
391         if (setsockopt(txSocket, ipProtoSetting, ipMcLoopSetting, &mcLoopValue,
392                         sizeof(mcLoopValue)) < 0) {
393                 pudError(true, "Could not %s multicast loopback on the"
394                         " transmit socket for interface %s", mcLoopValue ? "enable"
395                                 : "disable", networkInterface->name);
396                 goto bail;
397         }
398
399         /* Set the TTL on the socket */
400         errno = 0;
401         if (setsockopt(txSocket, ipProtoSetting, ipTtlSetting, &txTtl,
402                         sizeof(txTtl)) < 0) {
403                 pudError(true, "Could not set TTL on the transmit socket"
404                         " for interface %s", networkInterface->name);
405                 goto bail;
406         }
407
408         /* Set the no delay option on the socket */
409         errno = 0;
410         if (fcntl(txSocket, F_SETFL, O_NDELAY) < 0) {
411                 pudError(true, "Could not set the no delay option on the"
412                         " transmit socket for interface %s", networkInterface->name);
413                 goto bail;
414         }
415
416         return txSocket;
417
418         bail: if (txSocket >= 0) {
419                 close(txSocket);
420         }
421         return -1;
422 }
423
424 /**
425  Create a transmit interface and add it to the list of transmit network
426  interface objects
427
428  @param ifName
429  the network interface name
430  @param txMcAddr
431  the transmit multicast address
432
433  @return
434  - true on success
435  - false on failure
436  */
437 static bool createTxInterface(const char * ifName, union olsr_sockaddr * txMcAddr) {
438         int socketFd = -1;
439         TRxTxNetworkInterface * networkInterface = NULL;
440
441         if (ifName == NULL) {
442                 goto bail;
443         }
444
445         networkInterface = olsr_malloc(sizeof(TRxTxNetworkInterface),
446                         "TRxTxNetworkInterface (PUD)");
447         if (networkInterface == NULL) {
448                 goto bail;
449         }
450
451         memcpy(networkInterface->name, ifName, sizeof(networkInterface->name));
452         networkInterface->name[IFNAMSIZ] = '\0';
453         networkInterface->handler = NULL;
454         networkInterface->next = NULL;
455
456         /* networkInterface needs to be filled in when calling createTxSocket */
457         socketFd = createTxSocket(networkInterface, txMcAddr);
458         if (socketFd < 0) {
459                 goto bail;
460         }
461         networkInterface->socketFd = socketFd;
462
463         /* Add new object to the end of the global list. */
464         if (txNetworkInterfacesListHead == NULL) {
465                 txNetworkInterfacesListHead = networkInterface;
466                 lastTxNetworkInterface = networkInterface;
467         } else {
468                 lastTxNetworkInterface->next = networkInterface;
469                 lastTxNetworkInterface = networkInterface;
470         }
471
472         return true;
473
474         bail: if (networkInterface != NULL) {
475                 free(networkInterface);
476         }
477         return false;
478 }
479
480 /*
481  * Downlink interface
482  */
483
484 /** The socket fd, receiving downlinked messages */
485 static int downlinkSocketFd = -1;
486
487 /** the downlink handler function */
488 static socket_handler_func downlinkHandler = NULL;
489
490
491 /**
492  @return
493  The downlink socket fd. -1 when not valid.
494  */
495 int getDownlinkSocketFd(void) {
496         return downlinkSocketFd;
497 }
498
499 /**
500  Create an downlink socket
501
502  @param ipVersion
503  The IP version (AF_INET or AF_INET6) for the socket
504  @param rxSocketHandlerFunction
505  The socket handler function
506
507  @return
508  - the socket descriptor (>= 0)
509  - -1 if an error occurred
510  */
511 static int createDownlinkSocket(int ipVersion, socket_handler_func rxSocketHandlerFunction) {
512         union olsr_sockaddr address;
513         void * addr;
514         size_t addrSize;
515
516         int downlinkSocket = -1;
517
518         int socketReuseFlagValue = 1;
519
520         memset(&address, 0, sizeof(address));
521         if (ipVersion == AF_INET) {
522                 address.in4.sin_family = AF_INET;
523                 address.in4.sin_addr.s_addr = INADDR_ANY;
524                 address.in4.sin_port = getDownlinkPort();
525                 addr = &address.in4;
526                 addrSize = sizeof(struct sockaddr_in);
527         } else {
528                 address.in6.sin6_family = AF_INET6;
529                 address.in6.sin6_addr = in6addr_any;
530                 address.in6.sin6_port = getDownlinkPort();
531                 addr = &address.in6;
532                 addrSize = sizeof(struct sockaddr_in6);
533         }
534
535         /*  Create a datagram socket on which to receive */
536         errno = 0;
537         downlinkSocket = socket(ipVersion, SOCK_DGRAM, 0);
538         if (downlinkSocket < 0) {
539                 pudError(true, "Could not create the downlink socket");
540                 goto bail;
541         }
542
543         /* Enable SO_REUSEADDR to allow multiple applications to receive the same
544          * messages */
545         errno = 0;
546         if (setsockopt(downlinkSocket, SOL_SOCKET, SO_REUSEADDR, &socketReuseFlagValue,
547                         sizeof(socketReuseFlagValue)) < 0) {
548                 pudError(true, "Could not set REUSE option on the downlink socket");
549                 goto bail;
550         }
551
552         /* Bind to the proper port number with the IP address INADDR_ANY
553          * (INADDR_ANY is really required here, do not change it) */
554         errno = 0;
555         if (bind(downlinkSocket, addr, addrSize)) {
556                 pudError(true, "Could not bind downlink socket to port %d",
557                                 getDownlinkPort());
558                 goto bail;
559         }
560
561         add_olsr_socket(downlinkSocket, rxSocketHandlerFunction, NULL, NULL,
562                         SP_PR_READ);
563
564         downlinkHandler = rxSocketHandlerFunction;
565
566         return downlinkSocket;
567
568         bail: if (downlinkSocket >= 0) {
569                 close(downlinkSocket);
570         }
571         return -1;
572 }
573
574 /*
575  * Interface Functions
576  */
577
578 /**
579  Creates receive and transmit sockets and register the receive sockets with
580  the OLSR stack
581
582  @param rxSocketHandlerFunction
583  The function to call upon reception of data on a receive socket
584  @param rxSocketHandlerFunctionDownlink
585  The function to call upon reception of data on a downlink receive socket
586
587  @return
588  - true on success
589  - false on failure
590  */
591 bool createNetworkInterfaces(socket_handler_func rxSocketHandlerFunction,
592                 socket_handler_func rxSocketHandlerFunctionDownlink) {
593         union olsr_sockaddr * rxMcAddr = getRxMcAddr();
594         union olsr_sockaddr * txMcAddr = getTxMcAddr();
595         unsigned int count = 0;
596
597         /* loop over all configured rx interfaces */
598         count = getRxNonOlsrInterfaceCount();
599         while (count--) {
600                 if (!createRxInterface((char *)getRxNonOlsrInterfaceName(count), rxSocketHandlerFunction, rxMcAddr)) {
601                         /* creating a receive interface failed */
602                         return false;
603                 }
604         }
605
606         /* loop over all configured tx interfaces */
607         count = getTxNonOlsrInterfaceCount();
608         while (count--) {
609                 if (!createTxInterface((char *)getTxNonOlsrInterfaceName(count), txMcAddr)) {
610                         /* creating a transmit interface failed */
611                         return false;
612                 }
613         }
614
615         /* create uplink socket when needed */
616         if (isUplinkAddrSet()) {
617                 downlinkSocketFd = createDownlinkSocket(getUplinkAddr()->in.sa_family, rxSocketHandlerFunctionDownlink);
618                 if (downlinkSocketFd == -1) {
619                         return false;
620                 }
621         } else {
622                 downlinkSocketFd = -1;
623         }
624
625         return true;
626 }
627
628 /**
629  Close and cleanup the network interfaces in the given list
630
631  @param networkInterface
632  the list of network interface to close and clean up
633  */
634 static void closeInterfaces(TRxTxNetworkInterface * networkInterface) {
635         TRxTxNetworkInterface * nextNetworkInterface = networkInterface;
636         while (nextNetworkInterface != NULL) {
637                 TRxTxNetworkInterface * iteratedNetworkInterface = nextNetworkInterface;
638                 if (iteratedNetworkInterface->socketFd >= 0) {
639                         if (iteratedNetworkInterface->handler) {
640                                 remove_olsr_socket(iteratedNetworkInterface->socketFd,
641                                                 iteratedNetworkInterface->handler, NULL);
642                         }
643                         close(iteratedNetworkInterface->socketFd);
644                         iteratedNetworkInterface->socketFd = -1;
645                 }
646                 nextNetworkInterface = iteratedNetworkInterface->next;
647                 iteratedNetworkInterface->next = NULL;
648                 free(iteratedNetworkInterface);
649         }
650 }
651
652 /**
653  Close and cleanup all receive and transmit network interfaces
654  */
655 void closeNetworkInterfaces(void) {
656         if (rxNetworkInterfacesListHead != NULL) {
657                 closeInterfaces(rxNetworkInterfacesListHead);
658                 rxNetworkInterfacesListHead = NULL;
659         }
660
661         if (txNetworkInterfacesListHead != NULL) {
662                 closeInterfaces(txNetworkInterfacesListHead);
663                 txNetworkInterfacesListHead = NULL;
664         }
665
666         if (downlinkSocketFd != -1 ) {
667                 if (downlinkHandler) {
668                         remove_olsr_socket (downlinkSocketFd, downlinkHandler, NULL);
669                         downlinkHandler = NULL;
670                 }
671                 close(downlinkSocketFd);
672                 downlinkSocketFd = -1;
673         }
674 }