OSDN Git Service

2013.10.24
[uclinux-h8/uClinux-dist.git] / freeswan / pluto / server.c
1 /* get-next-event loop
2  * Copyright (C) 1997 Angelos D. Keromytis.
3  * Copyright (C) 1998-2002  D. Hugh Redelmeier.
4  *
5  * This program is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License as published by the
7  * Free Software Foundation; either version 2 of the License, or (at your
8  * option) any later version.  See <http://www.fsf.org/copyleft/gpl.txt>.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
12  * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
13  * for more details.
14  *
15  * RCSID $Id$
16  */
17
18 #include <stdio.h>
19 #include <stdlib.h>
20 #include <stddef.h>
21 #include <string.h>
22 #include <errno.h>
23 #include <signal.h>
24 #include <ctype.h>
25 #include <sys/types.h>
26 #include <sys/stat.h>
27 #include <sys/socket.h>
28 #include <sys/un.h>
29 #ifdef SOLARIS
30 # include <sys/sockio.h>        /* for Solaris 2.6: defines SIOCGIFCONF */
31 #endif
32 #include <netinet/in.h>
33 #include <arpa/inet.h>
34 #include <sys/time.h>
35 #include <netdb.h>
36 #include <unistd.h>
37 #include <fcntl.h>
38 #include <net/if.h>
39 #include <sys/ioctl.h>
40 #include <resolv.h>
41 #include <arpa/nameser.h>       /* missing from <resolv.h> on old systems */
42
43 #include <freeswan.h>
44
45 #include "constants.h"
46 #include "defs.h"
47 #include "state.h"
48 #include "id.h"
49 #include "x509.h"
50 #include "connections.h"        /* needs id.h */
51 #include "kernel.h"  /* for no_klips */
52 #include "log.h"
53 #include "server.h"
54 #include "timer.h"
55 #include "packet.h"
56 #include "demux.h"  /* needs packet.h */
57 #include "kernel_comm.h"
58 #include "preshared.h"
59 #include "adns.h"       /* needs <resolv.h> */
60 #include "dnskey.h"     /* needs preshared.h and adns.h */
61 #include "whack.h"      /* for RC_LOG_SERIOUS */
62
63 #include <pfkeyv2.h>
64 #include <pfkey.h>
65
66 #ifdef NAT_TRAVERSAL
67 #include "nat_traversal.h"
68 #endif
69
70 /*
71  *  Server main loop and socket initialization routines.
72  */
73
74 static const int on = TRUE;     /* by-reference parameter; constant, we hope */
75
76 /* control (whack) socket */
77 int ctl_fd = NULL_FD;   /* file descriptor of control (whack) socket */
78 struct sockaddr_un ctl_addr = { AF_UNIX, DEFAULT_CTLBASE CTL_SUFFIX };
79
80 /* Initialize the control socket.
81  * Note: this is called very early, so little infrastructure is available.
82  * It is important that the socket is created before the original
83  * Pluto process returns.
84  */
85 err_t
86 init_ctl_socket(void)
87 {
88     err_t failed = NULL;
89
90     delete_ctl_socket();        /* preventative medicine */
91     ctl_fd = socket(AF_UNIX, SOCK_STREAM, 0);
92     if (ctl_fd == -1)
93         failed = "create";
94     else if (fcntl(ctl_fd, F_SETFD, FD_CLOEXEC) == -1)
95         failed = "fcntl FD+CLOEXEC";
96     else if (setsockopt(ctl_fd, SOL_SOCKET, SO_REUSEADDR, (const void *)&on, sizeof(on)) < 0)
97         failed = "setsockopt";
98     else
99     {
100         /* to keep control socket secure, use umask */
101         mode_t ou = umask(~S_IRWXU);
102
103         if (bind(ctl_fd, (struct sockaddr *)&ctl_addr
104         , offsetof(struct sockaddr_un, sun_path) + strlen(ctl_addr.sun_path)) < 0)
105             failed = "bind";
106         umask(ou);
107     }
108
109     /* 5 is a haphazardly chosen limit for the backlog.
110      * Rumour has it that this is the max on BSD systems.
111      */
112     if (failed == NULL && listen(ctl_fd, 5) < 0)
113         failed = "listen() on";
114
115     return failed == NULL? NULL : builddiag("could not %s control socket: %d %s"
116             , failed, errno, strerror(errno));
117 }
118
119 void
120 delete_ctl_socket(void)
121 {
122     /* Is noting failure useful?  Not when used as preventative medicine. */
123     unlink(ctl_addr.sun_path);
124 }
125
126 bool listening = FALSE; /* should we pay attention to IKE messages? */
127
128 struct iface *interfaces = NULL;        /* public interfaces */
129
130 /* Initialize the interface sockets. */
131
132 static void
133 mark_ifaces_dead(void)
134 {
135     struct iface *p;
136
137     for (p = interfaces; p != NULL; p = p->next)
138         p->change = IFN_DELETE;
139 }
140
141 static void
142 free_dead_ifaces(void)
143 {
144     struct iface *p;
145     bool some_dead = FALSE
146         , some_new = FALSE;
147
148     for (p = interfaces; p != NULL; p = p->next)
149     {
150         if (p->change == IFN_DELETE)
151         {
152             log("shutting down interface %s/%s %s"
153                 , p->vname, p->rname, ip_str(&p->addr));
154             some_dead = TRUE;
155         }
156         else if (p->change == IFN_ADD)
157         {
158             some_new = TRUE;
159         }
160     }
161
162     if (some_dead)
163     {
164         struct iface **pp;
165
166         release_dead_interfaces();
167         for (pp = &interfaces; (p = *pp) != NULL; )
168         {
169             if (p->change == IFN_DELETE)
170             {
171                 *pp = p->next;  /* advance *pp */
172                 pfree(p->vname);
173                 pfree(p->rname);
174                 close(p->fd);
175                 pfree(p);
176             }
177             else
178             {
179                 pp = &p->next;  /* advance pp */
180             }
181         }
182     }
183
184     /* this must be done after the release_dead_interfaces
185      * in case some to the newly unoriented connections can
186      * become oriented here.
187      */
188     if (some_dead || some_new)
189         check_orientations();
190 }
191
192 void
193 free_ifaces(void)
194 {
195     mark_ifaces_dead();
196     free_dead_ifaces();
197 }
198
199 struct raw_iface {
200     ip_address addr;
201     char name[IFNAMSIZ + 20];   /* what would be a safe size? */
202     struct raw_iface *next;
203 };
204
205 /* Called to handle --interface <ifname>
206  * Semantics: if specified, only these (real) interfaces are considered.
207  */
208 static const char *pluto_ifn[10];
209 static int pluto_ifn_roof = 0;
210
211 bool
212 use_interface(const char *rifn)
213 {
214     if (pluto_ifn_roof >= (int)elemsof(pluto_ifn))
215     {
216         return FALSE;
217     }
218     else
219     {
220         pluto_ifn[pluto_ifn_roof++] = rifn;
221         return TRUE;
222     }
223 }
224
225 #ifndef IPSECDEVPREFIX
226 # define IPSECDEVPREFIX "ipsec"
227 #endif
228
229 static struct raw_iface *
230 find_raw_ifaces4(void)
231 {
232     int j;      /* index into buf */
233     int num;    /* number of interfaces */
234     struct ifconf ifconf;
235     struct ifreq *buf;  /* for list of interfaces */
236     struct raw_iface *rifaces = NULL;
237     int master_sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);    /* Get a UDP socket */
238
239     /* get list of interfaces with assigned IPv4 addresses from system */
240
241     if (master_sock == -1)
242         exit_log_errno((e, "socket() failed in find_raw_ifaces4()"));
243
244     if (setsockopt(master_sock, SOL_SOCKET, SO_REUSEADDR
245     , (const void *)&on, sizeof(on)) < 0)
246         exit_log_errno((e, "setsockopt() in find_raw_ifaces4()"));
247
248     /* bind the socket */
249     {
250         ip_address any;
251
252         happy(anyaddr(AF_INET, &any));
253         setportof(htons(pluto_port), &any);
254         if (bind(master_sock, sockaddrof(&any), sockaddrlenof(&any)) < 0)
255             exit_log_errno((e, "bind() failed in find_raw_ifaces4()"));
256     }
257
258     num = 100;
259     buf = NULL;
260     for (;;) {
261         /* Get local interfaces.  See netdevice(7). */
262         ifconf.ifc_len = num * sizeof(struct ifreq);
263         buf = (void *) realloc(buf, ifconf.ifc_len);
264         memset(buf, 0, num*sizeof(struct ifreq));
265         ifconf.ifc_buf = (void *) buf;
266
267         if (ioctl(master_sock, SIOCGIFCONF, &ifconf) == -1)
268             exit_log_errno((e, "ioctl(SIOCGIFCONF) in find_raw_ifaces4()"));
269
270         /* if we got back less than we asked for, we have them all */
271         if (ifconf.ifc_len < num * sizeof(struct ifreq))
272             break;
273
274         /* try again and ask for more this time */
275         num += 100;
276     }
277
278     /* Add an entry to rifaces for each interesting interface. */
279         for (j = 0; (j+1) * sizeof(struct ifreq) <= ifconf.ifc_len; j++)
280     {
281         struct raw_iface ri;
282         const struct sockaddr_in *rs = (struct sockaddr_in *) &buf[j].ifr_addr;
283         struct ifreq auxinfo;
284
285         /* ignore all but AF_INET interfaces */
286         if (rs->sin_family != AF_INET)
287             continue;   /* not interesting */
288
289         /* build a NUL-terminated copy of the rname field */
290         memcpy(ri.name, buf[j].ifr_name, IFNAMSIZ);
291         ri.name[IFNAMSIZ] = '\0';
292
293         /* ignore if our interface names were specified, and this isn't one */
294         if (pluto_ifn_roof != 0)
295         {
296             int i;
297
298             for (i = 0; i != pluto_ifn_roof; i++)
299                 if (streq(ri.name, pluto_ifn[i]))
300                     break;
301             if (i == pluto_ifn_roof)
302                 continue;       /* not found -- skip */
303         }
304
305         /* Find out stuff about this interface.  See netdevice(7). */
306         zero(&auxinfo); /* paranoia */
307         memcpy(auxinfo.ifr_name, buf[j].ifr_name, IFNAMSIZ);
308         if (ioctl(master_sock, SIOCGIFFLAGS, &auxinfo) == -1)
309             exit_log_errno((e
310                 , "ioctl(SIOCGIFFLAGS) for %s in find_raw_ifaces4()"
311                 , ri.name));
312         if (!(auxinfo.ifr_flags & IFF_UP))
313             continue;   /* ignore an interface that isn't UP */
314
315         /* ignore unconfigured interfaces */
316         if (rs->sin_addr.s_addr == 0)
317             continue;
318         
319         {
320                 int i = 0;
321                 int found = FALSE;
322                 
323                 for (i = 0; i < NUM_INTERFACES; i++) {
324                         if (((phys_interfaces[i] && !strcmp(phys_interfaces[i], ri.name))) ||
325                                 !strncmp("ipsec", ri.name, 5))
326                                 found = TRUE;
327                 }
328                 
329                 if (!found)
330                         continue;
331         }
332
333         happy(initaddr((const void *)&rs->sin_addr, sizeof(struct in_addr)
334             , AF_INET, &ri.addr));
335
336         DBG(DBG_CONTROL, DBG_log("found %s with address %s"
337             , ri.name, ip_str(&ri.addr)));
338         ri.next = rifaces;
339         rifaces = clone_thing(ri, "struct raw_iface");
340     }
341
342     close(master_sock);
343
344     if (buf)
345         free(buf);
346
347     return rifaces;
348 }
349
350 static struct raw_iface *
351 find_raw_ifaces6(void)
352 {
353
354     /* Get list of interfaces with IPv6 addresses from system from /proc/net/if_inet6).
355      *
356      * Documentation of format?
357      * RTFS: linux-2.2.16/net/ipv6/addrconf.c:iface_proc_info()
358      *       linux-2.4.9-13/net/ipv6/addrconf.c:iface_proc_info()
359      *
360      * Sample from Gerhard's laptop:
361      *  00000000000000000000000000000001 01 80 10 80       lo
362      *  30490009000000000000000000010002 02 40 00 80   ipsec0
363      *  30490009000000000000000000010002 07 40 00 80     eth0
364      *  fe80000000000000025004fffefd5484 02 0a 20 80   ipsec0
365      *  fe80000000000000025004fffefd5484 07 0a 20 80     eth0
366      *
367      * Each line contains:
368      * - IPv6 address: 16 bytes, in hex, no punctuation
369      * - ifindex: 1 byte, in hex
370      * - prefix_len: 1 byte, in hex
371      * - scope (e.g. global, link local): 1 byte, in hex
372      * - flags: 1 byte, in hex
373      * - device name: string, followed by '\n'
374      */
375     struct raw_iface *rifaces = NULL;
376     static const char proc_name[] = "/proc/net/if_inet6";
377     FILE *proc_sock = fopen(proc_name, "r");
378
379     if (proc_sock == NULL)
380     {
381         DBG(DBG_CONTROL, DBG_log("could not open %s", proc_name));
382     }
383     else
384     {
385         for (;;)
386         {
387             struct raw_iface ri;
388             unsigned short xb[8];       /* IPv6 address as 8 16-bit chunks */
389             char sb[8*5];       /* IPv6 address as string-with-colons */
390             unsigned int if_idx;        /* proc field, not used */
391             unsigned int plen;  /* proc field, not used */
392             unsigned int scope; /* proc field, used to exclude link-local */
393             unsigned int dad_status;    /* proc field, not used */
394             /* ??? I hate and distrust scanf -- DHR */
395             int r = fscanf(proc_sock
396                 , "%4hx%4hx%4hx%4hx%4hx%4hx%4hx%4hx"
397                   " %02x %02x %02x %02x %20s\n"
398                 , xb+0, xb+1, xb+2, xb+3, xb+4, xb+5, xb+6, xb+7
399                 , &if_idx, &plen, &scope, &dad_status, ri.name);
400
401             /* ??? we should diagnose any problems */
402             if (r != 13)
403                 break;
404
405             /* ignore addresses with link local scope.
406              * From linux-2.4.9-13/include/net/ipv6.h:
407              * IPV6_ADDR_LINKLOCAL      0x0020U
408              * IPV6_ADDR_SCOPE_MASK     0x00f0U
409              */
410             if ((scope & 0x00f0U) == 0x0020U)
411                 continue;
412
413             snprintf(sb, sizeof(sb)
414                 , "%04x:%04x:%04x:%04x:%04x:%04x:%04x:%04x"
415                 , xb[0], xb[1], xb[2], xb[3], xb[4], xb[5], xb[6], xb[7]);
416
417             happy(ttoaddr(sb, 0, AF_INET6, &ri.addr));
418
419             if (!isunspecaddr(&ri.addr))
420             {
421                 DBG(DBG_CONTROL
422                     , DBG_log("found %s with address %s"
423                         , ri.name, sb));
424                 ri.next = rifaces;
425                 rifaces = clone_thing(ri, "struct raw_iface");
426             }
427         }
428         fclose(proc_sock);
429     }
430
431     return rifaces;
432 }
433
434 #if 1
435 static int
436 create_socket(struct raw_iface *ifp, const char *v_name, int port)
437 {
438     int fd = socket(addrtypeof(&ifp->addr), SOCK_DGRAM, IPPROTO_UDP);
439     int fcntl_flags;
440
441     if (fd < 0)
442     {
443         log_errno((e, "socket() in process_raw_ifaces()"));
444         return -1;
445     }
446
447 #if 1
448     /* Set socket Nonblocking */
449     if ((fcntl_flags=fcntl(fd, F_GETFL)) >= 0) {
450         if (!(fcntl_flags & O_NONBLOCK)) {
451             fcntl_flags |= O_NONBLOCK;
452             fcntl(fd, F_SETFL, fcntl_flags);
453         }
454     }
455 #endif
456
457     if (fcntl(fd, F_SETFD, FD_CLOEXEC) == -1)
458     {
459         log_errno((e, "fcntl(,, FD_CLOEXEC) in process_raw_ifaces()"));
460         close(fd);
461         return -1;
462     }
463
464     if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR
465     , (const void *)&on, sizeof(on)) < 0)
466     {
467         log_errno((e, "setsockopt SO_REUSEADDR in process_raw_ifaces()"));
468         close(fd);
469         return -1;
470     }
471
472     /* To improve error reporting.  See ip(7). */
473 #if defined(IP_RECVERR) && defined(MSG_ERRQUEUE)
474     if (setsockopt(fd, SOL_IP, IP_RECVERR
475     , (const void *)&on, sizeof(on)) < 0)
476     {
477         log_errno((e, "setsockopt IP_RECVERR in process_raw_ifaces()"));
478         close(fd);
479         return -1;
480     }
481 #endif
482
483     /* With IPv6, there is no fragmentation after
484      * it leaves our interface.  PMTU discovery
485      * is mandatory but doesn't work well with IKE (why?).
486      * So we must set the IPV6_USE_MIN_MTU option.
487      * See draft-ietf-ipngwg-rfc2292bis-01.txt 11.1
488      */
489 #ifdef IPV6_USE_MIN_MTU /* YUCK: not always defined */
490     if (addrtypeof(&ifp->addr) == AF_INET6
491     && setsockopt(fd, SOL_SOCKET, IPV6_USE_MIN_MTU
492       , (const void *)&on, sizeof(on)) < 0)
493     {
494         log_errno((e, "setsockopt IPV6_USE_MIN_MTU in process_raw_ifaces()"));
495         close(fd);
496         return -1;
497     }
498 #endif
499
500     setportof(htons(port), &ifp->addr);
501     if (bind(fd, sockaddrof(&ifp->addr), sockaddrlenof(&ifp->addr)) < 0)
502     {
503         log_errno((e, "bind() for %s/%s %s:%u in process_raw_ifaces()"
504             , ifp->name, v_name
505             , ip_str(&ifp->addr), (unsigned) port));
506         close(fd);
507         return -1;
508     }
509     setportof(htons(pluto_port), &ifp->addr);
510     return fd;
511 }
512 #endif
513
514 static void
515 process_raw_ifaces(struct raw_iface *rifaces)
516 {
517     struct raw_iface *ifp;
518
519     /* Find all virtual/real interface pairs.
520      * For each real interface...
521      */
522     for (ifp = rifaces; ifp != NULL; ifp = ifp->next)
523     {
524         struct raw_iface *v = NULL;     /* matching ipsecX interface */
525         struct raw_iface fake_v;
526         bool after = FALSE; /* has vfp passed ifp on the list? */
527         bool bad = FALSE;
528         struct raw_iface *vfp;
529
530         /* ignore if virtual (ipsec*) interface */
531         if (strncmp(ifp->name, IPSECDEVPREFIX, sizeof(IPSECDEVPREFIX)-1) == 0)
532             continue;
533
534         for (vfp = rifaces; vfp != NULL; vfp = vfp->next)
535         {
536             if (vfp == ifp)
537             {
538                 after = TRUE;
539             }
540             else if (sameaddr(&ifp->addr, &vfp->addr))
541             {
542                 /* Different entries with matching IP addresses.
543                  * Many interesting cases.
544                  */
545                 if (strncmp(vfp->name, IPSECDEVPREFIX, sizeof(IPSECDEVPREFIX)-1) == 0)
546                 {
547                     if (v != NULL)
548                     {
549                         {
550                                 int i = 0;
551                                 int found = FALSE;
552                                 int found2 =FALSE;
553                                 
554                                 for (i = 0; i < NUM_INTERFACES; i++) {
555                                         if (phys_interfaces[i])
556                                                 if (!strcmp(phys_interfaces[i], v->name))
557                                                         found = TRUE;
558                                 }
559                                 
560                                 for (i = 0; i < NUM_INTERFACES; i++) {
561                                         if (phys_interfaces[i])
562                                                 if (!strcmp(phys_interfaces[i], vfp->name))
563                                                         found = TRUE;
564                                 }
565
566                                 if (found && found2) {
567                                         loglog(RC_LOG_SERIOUS
568                                             , "ipsec interfaces %s and %s share same address %s"
569                                             , v->name, vfp->name, ip_str(&ifp->addr));
570                                         bad = TRUE;
571                                 }
572                                 
573                                 if (!found && found2) {
574                                         v = vfp;
575                                 }
576                         }                       
577                     }
578                     else
579                     {
580                         v = vfp;        /* current winner */
581                     }
582                 }
583                 else
584                 {
585                     /* ugh: a second real interface with the same IP address
586                      * "after" allows us to avoid double reporting.
587                      */
588                     if (after)
589                     {
590                         loglog(RC_LOG_SERIOUS
591                             , "IP interfaces %s and %s share address %s!"
592                             , ifp->name, vfp->name, ip_str(&ifp->addr));
593                     }
594                     bad = TRUE;
595                 }
596             }
597         }
598
599         if (bad)
600             continue;
601
602         /* what if we didn't find a virtual interface? */
603         if (v == NULL)
604         {
605             if (no_klips)
606             {
607                 /* kludge for testing: invent a virtual device */
608                 static const char fvp[] = "virtual";
609                 fake_v = *ifp;
610                 passert(sizeof(fake_v.name) > sizeof(fvp));
611                 strcpy(fake_v.name, fvp);
612                 addrtot(&ifp->addr, 0, fake_v.name + sizeof(fvp) - 1
613                     , sizeof(fake_v.name) - (sizeof(fvp) - 1));
614                 v = &fake_v;
615             }
616             else
617             {
618                 DBG(DBG_CONTROL,
619                         DBG_log("IP interface %s %s has no matching ipsec* interface -- ignored"
620                             , ifp->name, ip_str(&ifp->addr)));
621                 continue;
622             }
623         }
624
625         /* We've got all we need; see if this is a new thing:
626          * search old interfaces list.
627          */
628         {
629             struct iface **p = &interfaces;
630
631             for (;;)
632             {
633                 struct iface *q = *p;
634
635                 /* search is over if at end of list */
636                 if (q == NULL)
637                 {
638                     /* matches nothing -- create a new entry */
639                     int fd = create_socket(ifp, v->name, pluto_port);
640                     if (fd < 0)
641                         break;
642
643 #ifdef NAT_TRAVERSAL
644                     if (nat_traversal_enabled) {
645                         nat_traversal_espinudp_socket(fd,
646                             ESPINUDP_WITH_NON_IKE);
647                     }
648 #endif
649
650                     q = alloc_thing(struct iface, "struct iface");
651                     q->rname = clone_str(ifp->name, "real device name");
652                     q->vname = clone_str(v->name, "virtual device name");
653                     q->addr = ifp->addr;
654                     q->fd = fd;
655                     q->next = interfaces;
656                     q->change = IFN_ADD;
657                     interfaces = q;
658                     log("adding interface %s/%s %s"
659                         , q->vname, q->rname, ip_str(&q->addr));
660
661 #ifdef NAT_TRAVERSAL
662                     if (nat_traversal_support_port_floating) {
663                         fd = create_socket(ifp, v->name, NAT_T_IKE_FLOAT_PORT);
664                         if (fd < 0)
665                             break;
666                         nat_traversal_espinudp_socket(fd,
667                             ESPINUDP_WITH_NON_ESP);
668                         q = alloc_thing(struct iface, "struct iface");
669                         q->rname = clone_str(ifp->name, "real device name");
670                         q->vname = clone_str(v->name, "virtual device name");
671                         q->addr = ifp->addr;
672                         setportof(htons(NAT_T_IKE_FLOAT_PORT), &q->addr);
673                         q->fd = fd;
674                         q->next = interfaces;
675                         q->change = IFN_ADD;
676                         q->ike_float = TRUE;
677                         interfaces = q;
678                         log("adding interface %s/%s %s:%d",
679                             q->vname, q->rname, ip_str(&q->addr), NAT_T_IKE_FLOAT_PORT);
680                     }
681 #endif
682                     break;
683                 }
684
685                 /* search over if matching old entry found */
686                 if (streq(q->rname, ifp->name)
687                 && streq(q->vname, v->name)
688                 && sameaddr(&q->addr, &ifp->addr))
689                 {
690                     /* matches -- rejuvinate old entry */
691                     q->change = IFN_KEEP;
692 #ifdef NAT_TRAVERSAL
693                     /* look for other interfaces to keep (due to NAT-T) */
694                     for (q = q->next ; q ; q = q->next) {
695                         if (streq(q->rname, ifp->name)
696                             && streq(q->vname, v->name)
697                             && sameaddr(&q->addr, &ifp->addr)) {
698                                 q->change = IFN_KEEP;
699                             }
700                     }
701 #endif
702                     break;
703                 }
704
705                 /* try again */
706                 p = &q->next;
707             } /* for (;;) */
708         }
709     }
710
711     /* delete the raw interfaces list */
712     while (rifaces != NULL)
713     {
714         struct raw_iface *t = rifaces;
715
716         rifaces = t->next;
717         pfree(t);
718     }
719 }
720
721 void
722 find_ifaces(void)
723 {
724     mark_ifaces_dead();
725     process_raw_ifaces(find_raw_ifaces4());
726     process_raw_ifaces(find_raw_ifaces6());
727
728     free_dead_ifaces();     /* ditch remaining old entries */
729
730     if (interfaces == NULL)
731         loglog(RC_LOG_SERIOUS, "no public interfaces found");
732 }
733
734 void
735 show_ifaces_status(void)
736 {
737     struct iface *p;
738
739     for (p = interfaces; p != NULL; p = p->next)
740         whack_log(RC_COMMENT, "interface %s/%s %s"
741             , p->vname, p->rname, ip_str(&p->addr));
742 }
743
744 static volatile sig_atomic_t sighupflag = FALSE;
745
746 static void
747 huphandler(int sig UNUSED)
748 {
749     sighupflag = TRUE;
750 }
751
752 static volatile sig_atomic_t sigtermflag = FALSE;
753
754 static void
755 termhandler(int sig UNUSED)
756 {
757     sigtermflag = TRUE;
758 }
759
760 /* call_server listens for incoming ISAKMP packets and Whack messages,
761  * and handles timer events.
762  */
763 void
764 call_server(void)
765 {
766     struct iface *ifp;
767
768     /* catch SIGHUP and SIGTERM */
769     {
770         int r;
771         struct sigaction act;
772
773         act.sa_handler = &huphandler;
774         sigemptyset(&act.sa_mask);
775         act.sa_flags = 0;       /* no SA_ONESHOT, no SA_RESTART, no nothing */
776         r = sigaction(SIGHUP, &act, NULL);
777         passert(r == 0);
778
779         act.sa_handler = &termhandler;
780         r = sigaction(SIGTERM, &act, NULL);
781         passert(r == 0);
782     }
783
784     for (;;)
785     {
786         fd_set readfds;
787         int ndes;
788
789         /* wait for next interesting thing */
790
791         for (;;)
792         {
793             long next_time = next_event();   /* time to any pending timer event */
794             int maxfd = ctl_fd;
795
796             if (sigtermflag)
797                 exit_pluto(0);
798
799             if (sighupflag)
800             {
801                 /* Ignorant folks think poking any daemon with SIGHUP
802                  * is polite.  We catch it and tell them otherwise.
803                  * There is one use: unsticking a hung recvfrom.
804                  * This sticking happens sometimes -- kernel bug?
805                  */
806                 sighupflag = FALSE;
807                 log("Pluto ignores SIGHUP -- perhaps you want \"whack --listen\"");
808             }
809
810             FD_ZERO(&readfds);
811             FD_SET(ctl_fd, &readfds);
812
813             if (adns_afd != NULL_FD)
814             {
815                 if (maxfd < adns_afd)
816                     maxfd = adns_afd;
817                 FD_SET(adns_afd, &readfds);
818             }
819
820 #ifdef KLIPS
821             if (!no_klips)
822             {
823                 pfkey_dequeue();
824                 if (maxfd < pfkeyfd)
825                     maxfd = pfkeyfd;
826                 passert(!FD_ISSET(pfkeyfd, &readfds));
827                 FD_SET(pfkeyfd, &readfds);
828             }
829 #endif
830
831             if (listening)
832             {
833                 for (ifp = interfaces; ifp != NULL; ifp = ifp->next)
834                 {
835                     if (maxfd < ifp->fd)
836                         maxfd = ifp->fd;
837                     passert(!FD_ISSET(ifp->fd, &readfds));
838                     FD_SET(ifp->fd, &readfds);
839                 }
840             }
841
842             if (next_time == -1)
843             {
844                 /* select without timer */
845
846                 ndes = select(maxfd + 1, &readfds, NULL, NULL, NULL);
847             }
848             else if (next_time == 0)
849             {
850                 /* timer without select: there is a timer event pending,
851                  * and it should fire now so don't bother to do the select.
852                  */
853                 ndes = 0;       /* signify timer expiration */
854             }
855             else
856             {
857                 /* select with timer */
858
859                 struct timeval tm;
860
861                 tm.tv_sec = next_time;
862                 tm.tv_usec = 0;
863                 ndes = select(maxfd + 1, &readfds, NULL, NULL, &tm);
864             }
865
866             if (ndes != -1)
867                 break;  /* success */
868
869             if (errno != EINTR)
870                 exit_log_errno((e, "select() failed in call_server()"));
871
872             /* retry if terminated by signal */
873         }
874
875         /* figure out what is interesting */
876
877         if (ndes == 0)
878         {
879             /* timer event */
880
881             DBG(DBG_CONTROL,
882                 DBG_log(BLANK_FORMAT);
883                 DBG_log("*time to handle event"));
884
885             handle_timer_event();
886             passert(GLOBALS_ARE_RESET());
887         }
888         else
889         {
890             /* at least one file descriptor is ready */
891
892             if (adns_afd != NULL_FD && FD_ISSET(adns_afd, &readfds))
893             {
894                 passert(ndes > 0);
895                 DBG(DBG_CONTROL,
896                     DBG_log(BLANK_FORMAT);
897                     DBG_log("*received adns message"));
898                 handle_adns_answer();
899                 passert(GLOBALS_ARE_RESET());
900                 ndes--;
901             }
902
903 #ifdef KLIPS
904             if (!no_klips && FD_ISSET(pfkeyfd, &readfds))
905             {
906                 passert(ndes > 0);
907                 DBG(DBG_CONTROL,
908                     DBG_log(BLANK_FORMAT);
909                     DBG_log("*received pfkey message"));
910                 pfkey_event();
911                 passert(GLOBALS_ARE_RESET());
912                 ndes--;
913             }
914 #endif
915
916             for (ifp = interfaces; ifp != NULL; ifp = ifp->next)
917             {
918                 if (FD_ISSET(ifp->fd, &readfds))
919                 {
920                     /* comm_handle will print DBG_CONTROL intro,
921                      * with more info than we have here.
922                      */
923
924                     passert(ndes > 0);
925                     comm_handle(ifp);
926                     passert(GLOBALS_ARE_RESET());
927                     ndes--;
928                 }
929             }
930
931             if (FD_ISSET(ctl_fd, &readfds))
932             {
933                 passert(ndes > 0);
934                 DBG(DBG_CONTROL,
935                     DBG_log(BLANK_FORMAT);
936                     DBG_log("*received whack message"));
937                 whack_handle(ctl_fd);
938                 passert(GLOBALS_ARE_RESET());
939                 ndes--;
940             }
941
942             passert(ndes == 0);
943         }
944     }
945 }