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