a7d26b9356ed0a5b93b620f2439bdfa009e63424
[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 enable multicast loopback on the"
168                         " receive socket for interface %s", networkInterface->name);
169                 goto bail;
170         }
171
172         /* Join the multicast group on the local interface. Note that this
173          * ADD_MEMBERSHIP option must be called for each local interface over
174          * which the multicast datagrams are to be received. */
175         if (ipFamilySetting == AF_INET) {
176                 struct ip_mreq mc_settings;
177
178                 struct ifreq ifr;
179                 struct in_addr * ifAddr = getIPv4Address(networkInterface->name, &ifr);
180                 if (!ifAddr) {
181                         pudError(true, "Could not get interface address of %s", networkInterface->name);
182                         goto bail;
183                 }
184
185                 (void) memset(&mc_settings, 0, sizeof(mc_settings));
186                 mc_settings.imr_multiaddr = rxMcAddr->in4.sin_addr;
187                 mc_settings.imr_interface = *ifAddr;
188                 errno = 0;
189                 if (setsockopt(rxSocket, ipProtoSetting, ipAddMembershipSetting,
190                                 &mc_settings, sizeof(mc_settings)) < 0) {
191                         pudError(true, "Could not subscribe interface %s to the configured"
192                                 " multicast group", networkInterface->name);
193                         goto bail;
194                 }
195         } else {
196                 struct ipv6_mreq mc6_settings;
197                 (void) memset(&mc6_settings, 0, sizeof(mc6_settings));
198                 mc6_settings.ipv6mr_multiaddr = rxMcAddr->in6.sin6_addr;
199                 mc6_settings.ipv6mr_interface = if_nametoindex(networkInterface->name);
200                 errno = 0;
201                 if (setsockopt(rxSocket, ipProtoSetting, ipAddMembershipSetting,
202                                 &mc6_settings, sizeof(mc6_settings)) < 0) {
203                         pudError(true, "Could not subscribe interface %s to the configured"
204                                 " multicast group", networkInterface->name);
205                         goto bail;
206                 }
207         }
208
209         add_olsr_socket(rxSocket, rxSocketHandlerFunction, NULL, networkInterface,
210                         SP_PR_READ);
211
212         return rxSocket;
213
214         bail: if (rxSocket >= 0) {
215                 close(rxSocket);
216         }
217         return -1;
218
219 }
220
221 /**
222  Create a receive interface and add it to the list of receive network interface
223  objects
224
225  @param ifName
226  the network interface name
227  @param rxSocketHandlerFunction
228  the function that handles reception of data on the network interface
229  @param rxMcAddr
230  The receive multicast address
231
232  @return
233  - true on success
234  - false on failure
235  */
236 static bool createRxInterface(const char * ifName,
237                 socket_handler_func rxSocketHandlerFunction, union olsr_sockaddr * rxMcAddr) {
238         int socketFd = -1;
239         TRxTxNetworkInterface * networkInterface = NULL;
240
241         if (ifName == NULL) {
242                 goto bail;
243         }
244
245         networkInterface = olsr_malloc(sizeof(TRxTxNetworkInterface),
246                         "TRxTxNetworkInterface (PUD)");
247         if (networkInterface == NULL) {
248                 goto bail;
249         }
250
251         memcpy(networkInterface->name, ifName, sizeof(networkInterface->name));
252         networkInterface->name[IFNAMSIZ] = '\0';
253         networkInterface->handler = NULL;
254         networkInterface->next = NULL;
255
256         /* networkInterface needs to be filled in when calling createRxSocket */
257         socketFd = createRxSocket(networkInterface, rxSocketHandlerFunction, rxMcAddr);
258         if (socketFd < 0) {
259                 goto bail;
260         }
261         networkInterface->socketFd = socketFd;
262         networkInterface->handler = rxSocketHandlerFunction;
263
264         /* Add new object to the end of the global list. */
265         if (rxNetworkInterfacesListHead == NULL) {
266                 rxNetworkInterfacesListHead = networkInterface;
267                 lastRxNetworkInterface = networkInterface;
268         } else {
269                 lastRxNetworkInterface->next = networkInterface;
270                 lastRxNetworkInterface = networkInterface;
271         }
272
273         return true;
274
275         bail: if (networkInterface != NULL) {
276                 free(networkInterface);
277         }
278         return false;
279
280 }
281
282 /*
283  * TX interfaces
284  */
285
286 /** The list of network interface objects, sending our NMEA sentences */
287 static TRxTxNetworkInterface *txNetworkInterfacesListHead = NULL;
288
289 /** Pointer to the last network interface object, sending our NMEA sentences */
290 static TRxTxNetworkInterface *lastTxNetworkInterface = NULL;
291
292 /**
293  @return
294  The list of network interface objects, sending our NMEA sentences
295  */
296 TRxTxNetworkInterface *getTxNetworkInterfaces(void) {
297         return txNetworkInterfacesListHead;
298 }
299
300 /**
301  Create a transmit socket for a network interface
302
303  @param networkInterface
304  The network interface object. This function expects it to be filled with all
305  information, except for the socket descriptor.
306  @param txMcAddr
307  The transmit multicast address
308
309  @return
310  - the socket descriptor (>= 0)
311  - -1 if an error occurred
312  */
313 static int createTxSocket(TRxTxNetworkInterface * networkInterface, union olsr_sockaddr * txMcAddr) {
314         int ipFamilySetting;
315         int ipProtoSetting;
316         int ipMcLoopSetting;
317         int ipMcIfSetting;
318         int ipTtlSetting;
319         unsigned int ifIndex;
320
321         union olsr_sockaddr address;
322         void * addr;
323         size_t addrSize;
324
325         int txSocket = -1;
326
327         int mcLoopValue = 1;
328         int txTtl = getTxTtl();
329
330         assert(networkInterface != NULL);
331         assert(strncmp((char *) &networkInterface->name[0], "",
332                                         sizeof(networkInterface->name)) != 0);
333
334         memset(&address, 0, sizeof(address));
335         if (txMcAddr->in.sa_family == AF_INET) {
336                 struct ifreq ifr;
337                 struct in_addr * ifAddr = getIPv4Address(networkInterface->name, &ifr);
338                 if (!ifAddr) {
339                         pudError(true, "Could not get interface address of %s", networkInterface->name);
340                         goto bail;
341                 }
342
343                 assert(txMcAddr->in4.sin_addr.s_addr != INADDR_ANY);
344
345                 ipFamilySetting = AF_INET;
346                 ipProtoSetting = IPPROTO_IP;
347                 ipMcLoopSetting = IP_MULTICAST_LOOP;
348                 ipMcIfSetting = IP_MULTICAST_IF;
349                 ipTtlSetting = IP_MULTICAST_TTL;
350                 ifIndex = 0;
351
352                 address.in4.sin_family = ipFamilySetting;
353                 address.in4.sin_addr = *ifAddr;
354                 address.in4.sin_port = getTxMcPort();
355                 addr = &address.in4;
356                 addrSize = sizeof(struct sockaddr_in);
357         } else {
358                 assert(txMcAddr->in6.sin6_addr.s6_addr != in6addr_any.s6_addr);
359
360                 ipFamilySetting = AF_INET6;
361                 ipProtoSetting = IPPROTO_IPV6;
362                 ipMcLoopSetting = IPV6_MULTICAST_LOOP;
363                 ipMcIfSetting = IPV6_MULTICAST_IF;
364                 ipTtlSetting = IPV6_MULTICAST_HOPS;
365                 ifIndex = if_nametoindex(networkInterface->name);
366
367                 addr = &ifIndex;
368                 addrSize = sizeof(ifIndex);
369         }
370
371         /*  Create a datagram socket on which to transmit */
372         errno = 0;
373         txSocket = socket(ipFamilySetting, SOCK_DGRAM, 0);
374         if (txSocket < 0) {
375                 pudError(true, "Could not create a transmit socket for interface %s",
376                                 networkInterface->name);
377                 goto bail;
378         }
379
380         /* Bind the socket to the desired interface */
381         errno = 0;
382         if (setsockopt(txSocket, ipProtoSetting, ipMcIfSetting, addr, addrSize) < 0) {
383                 pudError(true, "Could not set the multicast interface on the"
384                         " transmit socket to interface %s", networkInterface->name);
385                 goto bail;
386         }
387
388         /* Disable multicast local loopback */
389         errno = 0;
390         if (setsockopt(txSocket, ipProtoSetting, ipMcLoopSetting, &mcLoopValue,
391                         sizeof(mcLoopValue)) < 0) {
392                 pudError(true, "Could not disable multicast loopback on the"
393                         " transmit socket for interface %s", networkInterface->name);
394                 goto bail;
395         }
396
397         /* Set the TTL on the socket */
398         errno = 0;
399         if (setsockopt(txSocket, ipProtoSetting, ipTtlSetting, &txTtl,
400                         sizeof(txTtl)) < 0) {
401                 pudError(true, "Could not set TTL on the transmit socket"
402                         " for interface %s", networkInterface->name);
403                 goto bail;
404         }
405
406         /* Set the no delay option on the socket */
407         errno = 0;
408         if (fcntl(txSocket, F_SETFL, O_NDELAY) < 0) {
409                 pudError(true, "Could not set the no delay option on the"
410                         " transmit socket for interface %s", networkInterface->name);
411                 goto bail;
412         }
413
414         return txSocket;
415
416         bail: if (txSocket >= 0) {
417                 close(txSocket);
418         }
419         return -1;
420 }
421
422 /**
423  Create a transmit interface and add it to the list of transmit network
424  interface objects
425
426  @param ifName
427  the network interface name
428  @param txMcAddr
429  the transmit multicast address
430
431  @return
432  - true on success
433  - false on failure
434  */
435 static bool createTxInterface(const char * ifName, union olsr_sockaddr * txMcAddr) {
436         int socketFd = -1;
437         TRxTxNetworkInterface * networkInterface = NULL;
438
439         if (ifName == NULL) {
440                 goto bail;
441         }
442
443         networkInterface = olsr_malloc(sizeof(TRxTxNetworkInterface),
444                         "TRxTxNetworkInterface (PUD)");
445         if (networkInterface == NULL) {
446                 goto bail;
447         }
448
449         memcpy(networkInterface->name, ifName, sizeof(networkInterface->name));
450         networkInterface->name[IFNAMSIZ] = '\0';
451         networkInterface->handler = NULL;
452         networkInterface->next = NULL;
453
454         /* networkInterface needs to be filled in when calling createTxSocket */
455         socketFd = createTxSocket(networkInterface, txMcAddr);
456         if (socketFd < 0) {
457                 goto bail;
458         }
459         networkInterface->socketFd = socketFd;
460
461         /* Add new object to the end of the global list. */
462         if (txNetworkInterfacesListHead == NULL) {
463                 txNetworkInterfacesListHead = networkInterface;
464                 lastTxNetworkInterface = networkInterface;
465         } else {
466                 lastTxNetworkInterface->next = networkInterface;
467                 lastTxNetworkInterface = networkInterface;
468         }
469
470         return true;
471
472         bail: if (networkInterface != NULL) {
473                 free(networkInterface);
474         }
475         return false;
476 }
477
478 /*
479  * Downlink interface
480  */
481
482 /** The socket fd, receiving downlinked messages */
483 static int downlinkSocketFd = -1;
484
485 /** the downlink handler function */
486 static socket_handler_func downlinkHandler = NULL;
487
488
489 /**
490  @return
491  The downlink socket fd. -1 when not valid.
492  */
493 int getDownlinkSocketFd(void) {
494         return downlinkSocketFd;
495 }
496
497 /**
498  Create an downlink socket
499
500  @param ipVersion
501  The IP version (AF_INET or AF_INET6) for the socket
502  @param rxSocketHandlerFunction
503  The socket handler function
504
505  @return
506  - the socket descriptor (>= 0)
507  - -1 if an error occurred
508  */
509 static int createDownlinkSocket(int ipVersion, socket_handler_func rxSocketHandlerFunction) {
510         union olsr_sockaddr address;
511         void * addr;
512         size_t addrSize;
513
514         int downlinkSocket = -1;
515
516         int socketReuseFlagValue = 1;
517
518         memset(&address, 0, sizeof(address));
519         if (ipVersion == AF_INET) {
520                 address.in4.sin_family = AF_INET;
521                 address.in4.sin_addr.s_addr = INADDR_ANY;
522                 address.in4.sin_port = getDownlinkPort();
523                 addr = &address.in4;
524                 addrSize = sizeof(struct sockaddr_in);
525         } else {
526                 address.in6.sin6_family = AF_INET6;
527                 address.in6.sin6_addr = in6addr_any;
528                 address.in6.sin6_port = getDownlinkPort();
529                 addr = &address.in6;
530                 addrSize = sizeof(struct sockaddr_in6);
531         }
532
533         /*  Create a datagram socket on which to receive */
534         errno = 0;
535         downlinkSocket = socket(ipVersion, SOCK_DGRAM, 0);
536         if (downlinkSocket < 0) {
537                 pudError(true, "Could not create the downlink socket");
538                 goto bail;
539         }
540
541         /* Enable SO_REUSEADDR to allow multiple applications to receive the same
542          * messages */
543         errno = 0;
544         if (setsockopt(downlinkSocket, SOL_SOCKET, SO_REUSEADDR, &socketReuseFlagValue,
545                         sizeof(socketReuseFlagValue)) < 0) {
546                 pudError(true, "Could not set REUSE option on the downlink socket");
547                 goto bail;
548         }
549
550         /* Bind to the proper port number with the IP address INADDR_ANY
551          * (INADDR_ANY is really required here, do not change it) */
552         errno = 0;
553         if (bind(downlinkSocket, addr, addrSize)) {
554                 pudError(true, "Could not bind downlink socket to port %d",
555                                 getDownlinkPort());
556                 goto bail;
557         }
558
559         add_olsr_socket(downlinkSocket, rxSocketHandlerFunction, NULL, NULL,
560                         SP_PR_READ);
561
562         downlinkHandler = rxSocketHandlerFunction;
563
564         return downlinkSocket;
565
566         bail: if (downlinkSocket >= 0) {
567                 close(downlinkSocket);
568         }
569         return -1;
570 }
571
572 /*
573  * Interface Functions
574  */
575
576 /**
577  Creates receive and transmit sockets and register the receive sockets with
578  the OLSR stack
579
580  @param rxSocketHandlerFunction
581  The function to call upon reception of data on a receive socket
582  @param rxSocketHandlerFunctionDownlink
583  The function to call upon reception of data on a downlink receive socket
584
585  @return
586  - true on success
587  - false on failure
588  */
589 bool createNetworkInterfaces(socket_handler_func rxSocketHandlerFunction,
590                 socket_handler_func rxSocketHandlerFunctionDownlink) {
591         union olsr_sockaddr * rxMcAddr = getRxMcAddr();
592         union olsr_sockaddr * txMcAddr = getTxMcAddr();
593         unsigned int count = 0;
594
595         /* loop over all configured rx interfaces */
596         count = getRxNonOlsrInterfaceCount();
597         while (count--) {
598                 if (!createRxInterface((char *)getRxNonOlsrInterfaceName(count), rxSocketHandlerFunction, rxMcAddr)) {
599                         /* creating a receive interface failed */
600                         return false;
601                 }
602         }
603
604         /* loop over all configured tx interfaces */
605         count = getTxNonOlsrInterfaceCount();
606         while (count--) {
607                 if (!createTxInterface((char *)getTxNonOlsrInterfaceName(count), txMcAddr)) {
608                         /* creating a transmit interface failed */
609                         return false;
610                 }
611         }
612
613         /* create uplink socket when needed */
614         if (isUplinkAddrSet()) {
615                 downlinkSocketFd = createDownlinkSocket(getUplinkAddr()->in.sa_family, rxSocketHandlerFunctionDownlink);
616                 if (downlinkSocketFd == -1) {
617                         return false;
618                 }
619         } else {
620                 downlinkSocketFd = -1;
621         }
622
623         return true;
624 }
625
626 /**
627  Close and cleanup the network interfaces in the given list
628
629  @param networkInterface
630  the list of network interface to close and clean up
631  */
632 static void closeInterfaces(TRxTxNetworkInterface * networkInterface) {
633         TRxTxNetworkInterface * nextNetworkInterface = networkInterface;
634         while (nextNetworkInterface != NULL) {
635                 TRxTxNetworkInterface * iteratedNetworkInterface = nextNetworkInterface;
636                 if (iteratedNetworkInterface->socketFd >= 0) {
637                         if (iteratedNetworkInterface->handler) {
638                                 remove_olsr_socket(iteratedNetworkInterface->socketFd,
639                                                 iteratedNetworkInterface->handler, NULL);
640                         }
641                         close(iteratedNetworkInterface->socketFd);
642                         iteratedNetworkInterface->socketFd = -1;
643                 }
644                 nextNetworkInterface = iteratedNetworkInterface->next;
645                 iteratedNetworkInterface->next = NULL;
646                 free(iteratedNetworkInterface);
647         }
648 }
649
650 /**
651  Close and cleanup all receive and transmit network interfaces
652  */
653 void closeNetworkInterfaces(void) {
654         if (rxNetworkInterfacesListHead != NULL) {
655                 closeInterfaces(rxNetworkInterfacesListHead);
656                 rxNetworkInterfacesListHead = NULL;
657         }
658
659         if (txNetworkInterfacesListHead != NULL) {
660                 closeInterfaces(txNetworkInterfacesListHead);
661                 txNetworkInterfacesListHead = NULL;
662         }
663
664         if (downlinkSocketFd != -1 ) {
665                 if (downlinkHandler) {
666                         remove_olsr_socket (downlinkSocketFd, downlinkHandler, NULL);
667                         downlinkHandler = NULL;
668                 }
669                 close(downlinkSocketFd);
670                 downlinkSocketFd = -1;
671         }
672 }