]> Pileus Git - ~andy/fetchmail/blob - interface.c
Merge branch 'master' into next
[~andy/fetchmail] / interface.c
1 /*
2  * interface.c -- implements fetchmail 'interface' and 'monitor' commands
3  *
4  * This module was implemented by George M. Sipe <gsipe@pobox.com>
5  * or <gsipe@acm.org> and is:
6  *
7  *      Copyright (c) 1996,1997 by George M. Sipe
8  *
9  *      FreeBSD specific portions written by and Copyright (c) 1999 
10  *      Andy Doran <ad@psn.ie>.
11  *
12  * For license terms, see the file COPYING in this directory.
13  */
14
15 #include "fetchmail.h"
16 #ifdef CAN_MONITOR
17
18 #include <sys/types.h>
19 #include <sys/param.h>
20
21 #if defined(linux)
22 #include <sys/utsname.h>
23 #endif
24
25 #include <stdio.h>
26 #include <string.h>
27 #include <stdlib.h>
28 #include <unistd.h>
29 #include <sys/ioctl.h>
30 #include <sys/socket.h>
31 #include <netinet/in.h>
32 #include <arpa/inet.h>
33 #include <net/if.h>
34 #if defined(__FreeBSD__)
35 #if defined __FreeBSD_USE_KVM
36 #include <net/if_var.h>
37 #include <kvm.h>
38 #include <nlist.h>
39 #include <sys/fcntl.h>
40 #else /* !defined __FreeBSD_USE_KVM */
41 #include <sys/sysctl.h>
42 #include <net/route.h>
43 #include <net/if_dl.h>
44 #endif /* defined __FreeBSD_USE_KVM */
45 #endif /* defined __FreeBSD__ */
46 #include "socket.h"
47 #include "gettext.h"
48 #include "tunable.h"
49
50 typedef struct {
51         struct in_addr addr, dstaddr, netmask;
52         int rx_packets, tx_packets;
53 } ifinfo_t;
54
55 struct interface_pair_s {
56         struct in_addr interface_address;
57         struct in_addr interface_mask;
58 } *interface_pair;
59
60 /*
61  * Count of packets to see on an interface before monitor considers it up.
62  * Needed because when pppd shuts down the link, the packet counts go up
63  * by two (one rx and one tx?, maybe).  A value of 2 seems to do the trick,
64  * but we'll give it some extra.
65  */
66 #define MONITOR_SLOP            5
67
68 #ifdef linux
69 #define have_interface_init
70
71 static const char *netdevfmt;
72
73 void interface_init(void)
74 /* figure out which /proc/net/dev format to use */
75 {
76     struct utsname utsname;
77
78     /* Linux 2.2 -- transmit packet count in 10th field */
79     netdevfmt = "%d %d %*d %*d %*d %d %*d %*d %*d %d %*d %*d %d";
80
81     if (uname(&utsname) < 0)
82         return;
83     else
84     {
85         int major, minor;
86
87         if (sscanf(utsname.release, "%d.%d.%*d", &major, &minor) >= 2
88                                         && (major < 2 || (major == 2 && minor < 2)))
89             /* pre-linux-2.2 format -- transmit packet count in 8th field */
90             netdevfmt = "%d %d %*d %*d %*d %d %*d %d %*d %*d %*d %*d %d";
91     }
92 }
93
94 static int _get_ifinfoGT_(int socket_fd, FILE *stats_file, const char *ifname,
95                 ifinfo_t *ifinfo)
96 /* get active network interface information - return non-zero upon success */
97 {
98         int namelen = strlen(ifname);
99         struct ifreq request;
100         char *cp, buffer[256];
101         int found = 0;
102         int counts[4];
103
104         /* initialize result */
105         memset((char *) ifinfo, 0, sizeof(ifinfo_t));
106
107         /* get the packet I/O counts */
108         while (fgets(buffer, sizeof(buffer) - 1, stats_file)) {
109                 for (cp = buffer; *cp && *cp == ' '; ++cp);
110                 if (!strncmp(cp, ifname, namelen) &&
111                                 cp[namelen] == ':') {
112                         cp += namelen + 1;
113                         if (sscanf(cp, netdevfmt,
114                                    counts, counts+1, counts+2, 
115                                    counts+3,&found)>4) { /* found = dummy */
116                                 /* newer kernel with byte counts */
117                                 ifinfo->rx_packets=counts[1];
118                                 ifinfo->tx_packets=counts[3];
119                         } else {
120                                 /* older kernel, no byte counts */
121                                 ifinfo->rx_packets=counts[0];
122                                 ifinfo->tx_packets=counts[2];
123                         }
124                         found = 1;
125                 }
126         }
127         if (!found) return (FALSE);
128
129         /* see if the interface is up */
130         strcpy(request.ifr_name, ifname);
131         if (ioctl(socket_fd, SIOCGIFFLAGS, &request) < 0)
132                 return(FALSE);
133         if (!(request.ifr_flags & IFF_RUNNING))
134                 return(FALSE);
135
136         /* get the (local) IP address */
137         strcpy(request.ifr_name, ifname);
138         if (ioctl(socket_fd, SIOCGIFADDR, &request) < 0)
139                 return(FALSE);
140         ifinfo->addr = ((struct sockaddr_in *) (&request.ifr_addr))->sin_addr;
141
142         /* get the PPP destination (remote) IP address */
143         ifinfo->dstaddr.s_addr = 0;
144         strcpy(request.ifr_name, ifname);
145         if (ioctl(socket_fd, SIOCGIFDSTADDR, &request) >= 0)
146                 ifinfo->dstaddr = ((struct sockaddr_in *)
147                                         (&request.ifr_dstaddr))->sin_addr;
148
149         /* get the netmask */
150         strcpy(request.ifr_name, ifname);
151         if (ioctl(socket_fd, SIOCGIFNETMASK, &request) >= 0) {
152           ifinfo->netmask = ((struct sockaddr_in *)
153                              (&request.ifr_netmask))->sin_addr;
154           return (TRUE);
155         }
156
157         return(FALSE);
158 }
159
160 static int get_ifinfo(const char *ifname, ifinfo_t *ifinfo)
161 {
162         int socket_fd = socket(AF_INET, SOCK_DGRAM, 0);
163         FILE *stats_file = fopen("/proc/net/dev", "r");
164         int result;
165
166         if (socket_fd < 0 || !stats_file)
167                 result = FALSE;
168         else
169         {
170             char *tmp = xstrdup(ifname);
171             char *sp = strchr(tmp, '/');
172             /* hide slash and trailing info from ifname */
173             if (sp)
174                 *sp = '\0';
175             result = _get_ifinfoGT_(socket_fd, stats_file, tmp, ifinfo);
176             free(tmp);
177         }
178         if (socket_fd >= 0)
179             SockClose(socket_fd);
180         if (stats_file)
181             fclose(stats_file); /* not checking should be safe, mode was "r" */
182         return(result);
183 }
184
185 #elif defined __FreeBSD__
186
187 #if defined __FreeBSD_USE_KVM
188
189 static kvm_t *kvmfd;
190 static struct nlist symbols[] = 
191 {
192         {"_ifnet"},
193         {NULL}
194 };
195 static u_long   ifnet_savedaddr;
196 static gid_t    if_rgid;
197 static gid_t    if_egid;
198
199 void 
200 interface_set_gids(gid_t egid, gid_t rgid)
201 {
202         if_rgid = rgid;
203         if_egid = egid;
204 }
205
206 static int 
207 openkvm(void)
208 {
209         if ((kvmfd = kvm_open(NULL, NULL, NULL, O_RDONLY, NULL)) == NULL)
210                 return FALSE;
211         
212         if (kvm_nlist(kvmfd, symbols) < 0)
213                 return FALSE;
214            
215         if (kvm_read(kvmfd, (unsigned long) symbols[0].n_value, &ifnet_savedaddr, sizeof(unsigned long)) == -1)
216                 return FALSE;
217                 
218         return TRUE;
219 }
220
221 static int 
222 get_ifinfo(const char *ifname, ifinfo_t *ifinfo)
223 {
224         char                    tname[16];
225         char                    iname[16];
226         struct ifnet            ifnet;
227         unsigned long           ifnet_addr = ifnet_savedaddr;
228         struct ifnethead        ifnethead;
229         struct ifaddrhead       ifaddrhead;
230         struct ifaddr           ifaddr;
231         unsigned long           ifaddr_addr;
232         struct sockaddr         sa;
233         unsigned long           sa_addr;
234         uint                    i;
235         
236         if (if_egid)
237                 setegid(if_egid);
238         
239         for (i = 0; ifname[i] && ifname[i] != '/' && i < sizeof(iname) - 1; i++)
240                 iname[i] = ifname[i];
241                 
242         iname[i] = '\0';
243         
244         if (!kvmfd)
245         {
246                 if (!openkvm())
247                 {
248                         report(stderr, 0, GT_("Unable to open kvm interface. Make sure fetchmail is SGID kmem."));
249                         if (if_egid)
250                                 setegid(if_rgid);
251                         exit(1);
252                 }
253         }
254
255         kvm_read(kvmfd, ifnet_savedaddr, (char *) &ifnethead, sizeof ifnethead);
256         ifnet_addr = (u_long) ifnethead.tqh_first;
257
258         while (ifnet_addr)
259         {
260                 kvm_read(kvmfd, ifnet_addr, &ifnet, sizeof(ifnet));
261                 kvm_read(kvmfd, (unsigned long) ifnet.if_name, tname, sizeof tname);
262                 snprintf(tname + strlen(tname), sizeof(tname) - strlen(tname), "%d", ifnet.if_unit);
263
264                 if (!strcmp(tname, iname))
265                 {
266                         if (!(ifnet.if_flags & IFF_UP))
267                         {
268                                 if (if_egid)
269                                         setegid(if_rgid);
270                                 return 0;
271                         }
272                                 
273                         ifinfo->rx_packets = ifnet.if_ipackets;
274                         ifinfo->tx_packets = ifnet.if_opackets;
275
276                         ifaddr_addr = (u_long) ifnet.if_addrhead.tqh_first;
277                         
278                         while(ifaddr_addr)
279                         {
280                                 kvm_read(kvmfd, ifaddr_addr, &ifaddr, sizeof(ifaddr));
281                                 kvm_read(kvmfd, (u_long)ifaddr.ifa_addr, &sa, sizeof(sa));
282                                 
283                                 if (sa.sa_family != AF_INET)
284                                 {
285                                         ifaddr_addr = (u_long) ifaddr.ifa_link.tqe_next;
286                                         continue;
287                                 }
288                         
289                                 ifinfo->addr.s_addr = *(u_long *)(sa.sa_data + 2);
290                                 kvm_read(kvmfd, (u_long)ifaddr.ifa_dstaddr, &sa, sizeof(sa));
291                                 ifinfo->dstaddr.s_addr = *(u_long *)(sa.sa_data + 2);
292                                 kvm_read(kvmfd, (u_long)ifaddr.ifa_netmask, &sa, sizeof(sa));
293                                 ifinfo->netmask.s_addr = *(u_long *)(sa.sa_data + 2);
294
295                                 if (if_egid)
296                                         setegid(if_rgid);
297
298                                 return 1;
299                         }
300                         
301                         if (if_egid)
302                                 setegid(if_rgid);
303                         
304                         return 0;
305                 }
306
307                 ifnet_addr = (u_long) ifnet.if_link.tqe_next;
308         }
309
310         if (if_egid)
311                 setegid(if_rgid);
312         
313         return 0;
314 }
315
316 #else /* Do not use KVM on FreeBSD */
317
318 /*
319  * Expand the compacted form of addresses as returned via the
320  * configuration read via sysctl().
321  */
322
323 static void
324 rt_xaddrs(caddr_t cp, caddr_t cplim, struct rt_addrinfo *rtinfo)
325 {
326     struct sockaddr *sa;
327     int i;
328
329 #define ROUNDUP(a) \
330         ((a) > 0 ? (1 + (((a) - 1) | (sizeof(long) - 1))) : sizeof(long))
331 #define ADVANCE(x, n) (x += ROUNDUP((n)->sa_len))
332
333     memset(rtinfo->rti_info, 0, sizeof(rtinfo->rti_info));
334     for (i = 0; (i < RTAX_MAX) && (cp < cplim); i++) {
335         if ((rtinfo->rti_addrs & (1 << i)) == 0)
336             continue;
337         rtinfo->rti_info[i] = sa = (struct sockaddr *)cp;
338         ADVANCE(cp, sa);
339     }
340
341 #undef ROUNDUP
342 #undef ADVANCE
343 }
344
345 static int
346 get_ifinfo(const char *ifname, ifinfo_t *ifinfo)
347 {
348     uint                i;
349     int                 rc = 0;
350     int                 ifindex = -1;
351     size_t              needed;
352     char                *buf = NULL;
353     char                *lim = NULL;
354     char                *next = NULL;
355     struct if_msghdr    *ifm;
356     struct ifa_msghdr   *ifam;
357     struct sockaddr_in  *sin;
358     struct sockaddr_dl  *sdl;
359     struct rt_addrinfo  info;
360     char                iname[16];
361     int                 mib[6];
362
363     memset(ifinfo, 0, sizeof(ifinfo));
364
365     /* trim interface name */
366
367     for (i = 0; i < sizeof(iname) && ifname[i] && ifname[i] != '/'; i++)
368         iname[i] = ifname[i];
369         
370     if (i == 0 || i == sizeof(iname))
371     {
372         report(stderr, GT_("Unable to parse interface name from %s"), ifname);
373         return 0;
374     }
375
376     iname[i] = 0;
377
378
379     /* get list of existing interfaces */
380
381     mib[0] = CTL_NET;
382     mib[1] = PF_ROUTE;
383     mib[2] = 0;
384     mib[3] = AF_INET;           /* Only IP addresses please. */
385     mib[4] = NET_RT_IFLIST;
386     mib[5] = 0;                 /* List all interfaces. */
387
388
389     /* Get interface data. */
390
391     if (sysctl(mib, 6, NULL, &needed, NULL, 0) == -1)
392     {
393         report(stderr, 
394             GT_("get_ifinfo: sysctl (iflist estimate) failed"));
395         exit(1);
396     }
397     if ((buf = (char *)malloc(needed)) == NULL)
398     {
399         report(stderr, 
400             GT_("get_ifinfo: malloc failed"));
401         exit(1);
402     }
403     if (sysctl(mib, 6, buf, &needed, NULL, 0) == -1)
404     {
405         report(stderr, 
406             GT_("get_ifinfo: sysctl (iflist) failed"));
407         exit(1);
408     }
409
410     lim = buf+needed;
411
412
413     /* first look for the interface information */
414
415     next = buf;
416     while (next < lim)
417     {
418         ifm = (struct if_msghdr *)next;
419         next += ifm->ifm_msglen;
420
421         if (ifm->ifm_version != RTM_VERSION) 
422         {
423             report(stderr, 
424                 GT_("Routing message version %d not understood."),
425                 ifm->ifm_version);
426             exit(1);
427         }
428
429         if (ifm->ifm_type == RTM_IFINFO)
430         {
431             sdl = (struct sockaddr_dl *)(ifm + 1);
432
433             if (!(strlen(iname) == sdl->sdl_nlen 
434                 && strncmp(iname, sdl->sdl_data, sdl->sdl_nlen) == 0))
435             {
436                 continue;
437             }
438
439             if ( !(ifm->ifm_flags & IFF_UP) )
440             {
441                 /* the interface is down */
442                 goto get_ifinfo_end;
443             }
444
445             ifindex = ifm->ifm_index;
446             ifinfo->rx_packets = ifm->ifm_data.ifi_ipackets;
447             ifinfo->tx_packets = ifm->ifm_data.ifi_opackets;
448
449             break;
450         }
451     }
452
453     if (ifindex < 0)
454     {
455         /* we did not find an interface with a matching name */
456         report(stderr, GT_("No interface found with name %s"), iname);
457         goto get_ifinfo_end;
458     }
459
460     /* now look for the interface's IP address */
461
462     next = buf;
463     while (next < lim)
464     {
465         ifam = (struct ifa_msghdr *)next;
466         next += ifam->ifam_msglen;
467
468         if (ifindex > 0
469             && ifam->ifam_type == RTM_NEWADDR
470             && ifam->ifam_index == ifindex)
471         {
472             /* Expand the compacted addresses */
473             info.rti_addrs = ifam->ifam_addrs;
474             rt_xaddrs((char *)(ifam + 1), 
475                         ifam->ifam_msglen + (char *)ifam,
476                         &info);
477
478             /* Check for IPv4 address information only */
479             if (info.rti_info[RTAX_IFA]->sa_family != AF_INET)
480             {
481                 continue;
482             }
483
484             rc = 1;
485
486             sin = (struct sockaddr_in *)info.rti_info[RTAX_IFA];
487             if (sin)
488             {
489                 ifinfo->addr = sin->sin_addr;
490             }
491
492             sin = (struct sockaddr_in *)info.rti_info[RTAX_NETMASK];
493             if (sin)
494             {
495                 ifinfo->netmask = sin->sin_addr;
496             }
497
498             /* note: RTAX_BRD contains the address at the other
499              * end of a point-to-point link or the broadcast address
500              * of non point-to-point link
501              */
502             sin = (struct sockaddr_in *)info.rti_info[RTAX_BRD];
503             if (sin)
504             {
505                 ifinfo->dstaddr = sin->sin_addr;
506             }
507
508             break;
509         }
510     }
511
512     if (rc == 0)
513     {
514         report(stderr, GT_("No IP address found for %s"), iname);
515     }
516
517 get_ifinfo_end:
518     free(buf);
519     return rc;
520 }
521
522 #endif /* __FREEBSD_USE_SYSCTL_GET_IFFINFO */
523
524 #endif
525
526 #ifndef HAVE_INET_ATON
527 /*
528  * Note: This is not a true replacement for inet_aton(), as it won't
529  * do the right thing on "255.255.255.255" (which translates to -1 on
530  * most machines).  Fortunately this code will be used only if you're
531  * on an older Linux that lacks a real implementation.
532  */
533 #ifdef HAVE_NETINET_IN_SYSTM_H
534 # include <sys/types.h>
535 # include <netinet/in_systm.h>
536 #endif
537
538 #include <netinet/in.h>
539 #include <netinet/ip.h>
540 #include <arpa/inet.h>
541 #include <string.h>
542
543 static int inet_aton(const char *cp, struct in_addr *inp) {
544     long addr;
545
546     addr = inet_addr(cp);
547     if (addr == ((long) -1)) return 0;
548
549     memcpy(inp, &addr, sizeof(addr));
550     return 1;
551 }
552 #endif /* HAVE_INET_ATON */
553
554 void interface_parse(char *buf, struct hostdata *hp)
555 /* parse 'interface' specification */
556 {
557         char *cp1, *cp2;
558         char mask1[] = "255.255.255.255";
559
560         hp->interface = xstrdup(buf);
561
562         /* find and isolate just the IP address */
563         if (!(cp1 = strchr(buf, '/')))
564         {
565                 (void) report(stderr,
566                               GT_("missing IP interface address\n"));
567                 exit(PS_SYNTAX);
568         }
569         *cp1++ = '\000';
570
571         /* find and isolate just the netmask */
572         if (!(cp2 = strchr(cp1, '/')))
573                 cp2 = mask1;
574         else
575                 *cp2++ = '\000';
576
577         /* convert IP address and netmask */
578         hp->interface_pair = (struct interface_pair_s *)xmalloc(sizeof(struct interface_pair_s));
579         if (!inet_aton(cp1, &hp->interface_pair->interface_address))
580         {
581                 (void) report(stderr,
582                               GT_("invalid IP interface address\n"));
583                 exit(PS_SYNTAX);
584         }
585         if (!inet_aton(cp2, &hp->interface_pair->interface_mask))
586         {
587                 (void) report(stderr,
588                               GT_("invalid IP interface mask\n"));
589                 exit(PS_SYNTAX);
590         }
591         /* apply the mask now to the IP address (range) required */
592         hp->interface_pair->interface_address.s_addr &=
593                 hp->interface_pair->interface_mask.s_addr;
594
595         /* restore original interface string (for configuration dumper) */
596         *--cp1 = '/';
597         return;
598 }
599
600 void interface_note_activity(struct hostdata *hp)
601 /* save interface I/O counts */
602 {
603         ifinfo_t ifinfo;
604         struct query *ctl;
605
606         /* if not monitoring link, all done */
607         if (!hp->monitor)
608                 return;
609
610         /* get the current I/O stats for the monitored link */
611         if (get_ifinfo(hp->monitor, &ifinfo))
612                 /* update this and preceeding host entries using the link
613                    (they were already set during this pass but the I/O
614                    count has now changed and they need to be re-updated)
615                 */
616                 for (ctl = querylist; ctl; ctl = ctl->next) {
617                         if (ctl->server.monitor && !strcmp(hp->monitor, ctl->server.monitor))
618                                 ctl->server.monitor_io =
619                                         ifinfo.rx_packets + ifinfo.tx_packets;
620                         /* do NOT update host entries following this one */
621                         if (&ctl->server == hp)
622                                 break;
623                 }
624
625 #ifdef  ACTIVITY_DEBUG
626         (void) report(stdout, 
627                       GT_("activity on %s -noted- as %d\n"), 
628                       hp->monitor, hp->monitor_io);
629 #endif
630 }
631
632 int interface_approve(struct hostdata *hp, flag domonitor)
633 /* return TRUE if OK to poll, FALSE otherwise */
634 {
635         ifinfo_t ifinfo;
636
637         /* check interface IP address (range), if specified */
638         if (hp->interface) {
639                 /* get interface info */
640                 if (!get_ifinfo(hp->interface, &ifinfo)) {
641                         (void) report(stdout, 
642                                       GT_("skipping poll of %s, %s down\n"),
643                                       hp->pollname, hp->interface);
644                         return(FALSE);
645                 }
646                 /* check the IP addresses (range) */
647                 if      (!(
648                                 /* check remote IP address */
649                                 ((ifinfo.dstaddr.s_addr != 0) &&
650                                 (ifinfo.dstaddr.s_addr &
651                                 hp->interface_pair->interface_mask.s_addr) ==
652                                 hp->interface_pair->interface_address.s_addr)
653                                 ||
654                                 /* check local IP address */
655                                 ((ifinfo.addr.s_addr &
656                                 hp->interface_pair->interface_mask.s_addr) ==
657                                 hp->interface_pair->interface_address.s_addr)
658                         ) )
659                 {
660                         (void) report(stdout,
661                                 GT_("skipping poll of %s, %s IP address excluded\n"),
662                                 hp->pollname, hp->interface);
663                         return(FALSE);
664                 }
665         }
666
667         /* if not monitoring link, all done */
668         if (!domonitor || !hp->monitor)
669                 return(TRUE);
670
671 #ifdef  ACTIVITY_DEBUG
672         (void) report(stdout, 
673                       GT_("activity on %s checked as %d\n"), 
674                       hp->monitor, hp->monitor_io);
675 #endif
676         /* if monitoring, check link for activity if it is up */
677         if (get_ifinfo(hp->monitor, &ifinfo))
678         {
679             int diff = (ifinfo.rx_packets + ifinfo.tx_packets)
680                                                         - hp->monitor_io;
681
682             /*
683              * There are three cases here:
684              *
685              * (a) If the new packet count is less than the recorded one,
686              * probably pppd was restarted while fetchmail was running.
687              * Don't skip.
688              *
689              * (b) newpacket count is greater than the old packet count,
690              * but the difference is small and may just reflect the overhead
691              * of a link shutdown.  Skip.
692              *
693              * (c) newpacket count is greater than the old packet count,
694              * and the difference is large. Connection is live.  Don't skip.
695              */
696             if (diff >= 0 && diff <= MONITOR_SLOP)
697             {
698                 (void) report(stdout, 
699                               GT_("skipping poll of %s, %s inactive\n"),
700                               hp->pollname, hp->monitor);
701                 return(FALSE);
702             }
703         }
704
705 #ifdef ACTIVITY_DEBUG
706        report(stdout, GT_("activity on %s was %d, is %d\n"),
707              hp->monitor, hp->monitor_io,
708              ifinfo.rx_packets + ifinfo.tx_packets);
709 #endif
710
711         return(TRUE);
712 }
713 #endif /* CAN_MONITOR */
714
715 #ifndef have_interface_init
716 void interface_init(void) {}
717 #endif