]> Pileus Git - ~andy/fetchmail/blob - interface.c
Merge branch 'legacy_63'
[~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         uint                    i;
234         
235         if (if_egid)
236                 setegid(if_egid);
237         
238         for (i = 0; ifname[i] && ifname[i] != '/' && i < sizeof(iname) - 1; i++)
239                 iname[i] = ifname[i];
240                 
241         iname[i] = '\0';
242         
243         if (!kvmfd)
244         {
245                 if (!openkvm())
246                 {
247                         report(stderr, 0, GT_("Unable to open kvm interface. Make sure fetchmail is SGID kmem."));
248                         if (if_egid)
249                                 setegid(if_rgid);
250                         exit(1);
251                 }
252         }
253
254         kvm_read(kvmfd, ifnet_savedaddr, (char *) &ifnethead, sizeof ifnethead);
255         ifnet_addr = (u_long) ifnethead.tqh_first;
256
257         while (ifnet_addr)
258         {
259                 kvm_read(kvmfd, ifnet_addr, &ifnet, sizeof(ifnet));
260                 kvm_read(kvmfd, (unsigned long) ifnet.if_name, tname, sizeof tname);
261                 snprintf(tname + strlen(tname), sizeof(tname) - strlen(tname), "%d", ifnet.if_unit);
262
263                 if (!strcmp(tname, iname))
264                 {
265                         if (!(ifnet.if_flags & IFF_UP))
266                         {
267                                 if (if_egid)
268                                         setegid(if_rgid);
269                                 return 0;
270                         }
271                                 
272                         ifinfo->rx_packets = ifnet.if_ipackets;
273                         ifinfo->tx_packets = ifnet.if_opackets;
274
275                         ifaddr_addr = (u_long) ifnet.if_addrhead.tqh_first;
276                         
277                         while(ifaddr_addr)
278                         {
279                                 kvm_read(kvmfd, ifaddr_addr, &ifaddr, sizeof(ifaddr));
280                                 kvm_read(kvmfd, (u_long)ifaddr.ifa_addr, &sa, sizeof(sa));
281                                 
282                                 if (sa.sa_family != AF_INET)
283                                 {
284                                         ifaddr_addr = (u_long) ifaddr.ifa_link.tqe_next;
285                                         continue;
286                                 }
287                         
288                                 ifinfo->addr.s_addr = *(u_long *)(sa.sa_data + 2);
289                                 kvm_read(kvmfd, (u_long)ifaddr.ifa_dstaddr, &sa, sizeof(sa));
290                                 ifinfo->dstaddr.s_addr = *(u_long *)(sa.sa_data + 2);
291                                 kvm_read(kvmfd, (u_long)ifaddr.ifa_netmask, &sa, sizeof(sa));
292                                 ifinfo->netmask.s_addr = *(u_long *)(sa.sa_data + 2);
293
294                                 if (if_egid)
295                                         setegid(if_rgid);
296
297                                 return 1;
298                         }
299                         
300                         if (if_egid)
301                                 setegid(if_rgid);
302                         
303                         return 0;
304                 }
305
306                 ifnet_addr = (u_long) ifnet.if_link.tqe_next;
307         }
308
309         if (if_egid)
310                 setegid(if_rgid);
311         
312         return 0;
313 }
314
315 #else /* Do not use KVM on FreeBSD */
316
317 /*
318  * Expand the compacted form of addresses as returned via the
319  * configuration read via sysctl().
320  */
321
322 static void
323 rt_xaddrs(caddr_t cp, caddr_t cplim, struct rt_addrinfo *rtinfo)
324 {
325     struct sockaddr *sa;
326     int i;
327
328 #define ROUNDUP(a) \
329         ((a) > 0 ? (1 + (((a) - 1) | (sizeof(long) - 1))) : sizeof(long))
330 #define ADVANCE(x, n) (x += ROUNDUP((n)->sa_len))
331
332     memset(rtinfo->rti_info, 0, sizeof(rtinfo->rti_info));
333     for (i = 0; (i < RTAX_MAX) && (cp < cplim); i++) {
334         if ((rtinfo->rti_addrs & (1 << i)) == 0)
335             continue;
336         rtinfo->rti_info[i] = sa = (struct sockaddr *)cp;
337         ADVANCE(cp, sa);
338     }
339
340 #undef ROUNDUP
341 #undef ADVANCE
342 }
343
344 static int
345 get_ifinfo(const char *ifname, ifinfo_t *ifinfo)
346 {
347     uint                i;
348     int                 rc = 0;
349     int                 ifindex = -1;
350     size_t              needed;
351     char                *buf = NULL;
352     char                *lim = NULL;
353     char                *next = NULL;
354     struct if_msghdr    *ifm;
355     struct ifa_msghdr   *ifam;
356     struct sockaddr_in  *sin;
357     struct sockaddr_dl  *sdl;
358     struct rt_addrinfo  info;
359     char                iname[16];
360     int                 mib[6];
361
362     memset(ifinfo, 0, sizeof(*ifinfo));
363
364     /* trim interface name */
365
366     for (i = 0; i < sizeof(iname) && ifname[i] && ifname[i] != '/'; i++)
367         iname[i] = ifname[i];
368         
369     if (i == 0 || i == sizeof(iname))
370     {
371         report(stderr, GT_("Unable to parse interface name from %s"), ifname);
372         return 0;
373     }
374
375     iname[i] = 0;
376
377
378     /* get list of existing interfaces */
379
380     mib[0] = CTL_NET;
381     mib[1] = PF_ROUTE;
382     mib[2] = 0;
383     mib[3] = AF_INET;           /* Only IP addresses please. */
384     mib[4] = NET_RT_IFLIST;
385     mib[5] = 0;                 /* List all interfaces. */
386
387
388     /* Get interface data. */
389
390     if (sysctl(mib, 6, NULL, &needed, NULL, 0) == -1)
391     {
392         report(stderr, 
393             GT_("get_ifinfo: sysctl (iflist estimate) failed"));
394         exit(1);
395     }
396     if ((buf = (char *)malloc(needed)) == NULL)
397     {
398         report(stderr, 
399             GT_("get_ifinfo: malloc failed"));
400         exit(1);
401     }
402     if (sysctl(mib, 6, buf, &needed, NULL, 0) == -1)
403     {
404         report(stderr, 
405             GT_("get_ifinfo: sysctl (iflist) failed"));
406         exit(1);
407     }
408
409     lim = buf+needed;
410
411
412     /* first look for the interface information */
413
414     next = buf;
415     while (next < lim)
416     {
417         ifm = (struct if_msghdr *)next;
418         next += ifm->ifm_msglen;
419
420         if (ifm->ifm_version != RTM_VERSION) 
421         {
422             report(stderr, 
423                 GT_("Routing message version %d not understood."),
424                 ifm->ifm_version);
425             exit(1);
426         }
427
428         if (ifm->ifm_type == RTM_IFINFO)
429         {
430             sdl = (struct sockaddr_dl *)(ifm + 1);
431
432             if (!(strlen(iname) == sdl->sdl_nlen 
433                 && strncmp(iname, sdl->sdl_data, sdl->sdl_nlen) == 0))
434             {
435                 continue;
436             }
437
438             if ( !(ifm->ifm_flags & IFF_UP) )
439             {
440                 /* the interface is down */
441                 goto get_ifinfo_end;
442             }
443
444             ifindex = ifm->ifm_index;
445             ifinfo->rx_packets = ifm->ifm_data.ifi_ipackets;
446             ifinfo->tx_packets = ifm->ifm_data.ifi_opackets;
447
448             break;
449         }
450     }
451
452     if (ifindex < 0)
453     {
454         /* we did not find an interface with a matching name */
455         report(stderr, GT_("No interface found with name %s"), iname);
456         goto get_ifinfo_end;
457     }
458
459     /* now look for the interface's IP address */
460
461     next = buf;
462     while (next < lim)
463     {
464         ifam = (struct ifa_msghdr *)next;
465         next += ifam->ifam_msglen;
466
467         if (ifindex > 0
468             && ifam->ifam_type == RTM_NEWADDR
469             && ifam->ifam_index == ifindex)
470         {
471             /* Expand the compacted addresses */
472             info.rti_addrs = ifam->ifam_addrs;
473             rt_xaddrs((char *)(ifam + 1), 
474                         ifam->ifam_msglen + (char *)ifam,
475                         &info);
476
477             /* Check for IPv4 address information only */
478             if (info.rti_info[RTAX_IFA]->sa_family != AF_INET)
479             {
480                 continue;
481             }
482
483             rc = 1;
484
485             sin = (struct sockaddr_in *)info.rti_info[RTAX_IFA];
486             if (sin)
487             {
488                 ifinfo->addr = sin->sin_addr;
489             }
490
491             sin = (struct sockaddr_in *)info.rti_info[RTAX_NETMASK];
492             if (sin)
493             {
494                 ifinfo->netmask = sin->sin_addr;
495             }
496
497             /* note: RTAX_BRD contains the address at the other
498              * end of a point-to-point link or the broadcast address
499              * of non point-to-point link
500              */
501             sin = (struct sockaddr_in *)info.rti_info[RTAX_BRD];
502             if (sin)
503             {
504                 ifinfo->dstaddr = sin->sin_addr;
505             }
506
507             break;
508         }
509     }
510
511     if (rc == 0)
512     {
513         report(stderr, GT_("No IP address found for %s"), iname);
514     }
515
516 get_ifinfo_end:
517     free(buf);
518     return rc;
519 }
520
521 #endif /* __FREEBSD_USE_SYSCTL_GET_IFFINFO */
522
523 #endif
524
525 #ifndef HAVE_INET_ATON
526 /*
527  * Note: This is not a true replacement for inet_aton(), as it won't
528  * do the right thing on "255.255.255.255" (which translates to -1 on
529  * most machines).  Fortunately this code will be used only if you're
530  * on an older Linux that lacks a real implementation.
531  */
532 #ifdef HAVE_NETINET_IN_SYSTM_H
533 # include <sys/types.h>
534 # include <netinet/in_systm.h>
535 #endif
536
537 #include <netinet/in.h>
538 #include <netinet/ip.h>
539 #include <arpa/inet.h>
540 #include <string.h>
541
542 static int inet_aton(const char *cp, struct in_addr *inp) {
543     long addr;
544
545     addr = inet_addr(cp);
546     if (addr == ((long) -1)) return 0;
547
548     memcpy(inp, &addr, sizeof(addr));
549     return 1;
550 }
551 #endif /* HAVE_INET_ATON */
552
553 void interface_parse(char *buf, struct hostdata *hp)
554 /* parse 'interface' specification */
555 {
556         char *cp1, *cp2;
557         char mask1[] = "255.255.255.255";
558
559         hp->interface = xstrdup(buf);
560
561         /* find and isolate just the IP address */
562         if (!(cp1 = strchr(buf, '/')))
563         {
564                 (void) report(stderr,
565                               GT_("missing IP interface address\n"));
566                 exit(PS_SYNTAX);
567         }
568         *cp1++ = '\000';
569
570         /* find and isolate just the netmask */
571         if (!(cp2 = strchr(cp1, '/')))
572                 cp2 = mask1;
573         else
574                 *cp2++ = '\000';
575
576         /* convert IP address and netmask */
577         hp->interface_pair = (struct interface_pair_s *)xmalloc(sizeof(struct interface_pair_s));
578         if (!inet_aton(cp1, &hp->interface_pair->interface_address))
579         {
580                 (void) report(stderr,
581                               GT_("invalid IP interface address\n"));
582                 exit(PS_SYNTAX);
583         }
584         if (!inet_aton(cp2, &hp->interface_pair->interface_mask))
585         {
586                 (void) report(stderr,
587                               GT_("invalid IP interface mask\n"));
588                 exit(PS_SYNTAX);
589         }
590         /* apply the mask now to the IP address (range) required */
591         hp->interface_pair->interface_address.s_addr &=
592                 hp->interface_pair->interface_mask.s_addr;
593
594         /* restore original interface string (for configuration dumper) */
595         *--cp1 = '/';
596         return;
597 }
598
599 void interface_note_activity(struct hostdata *hp)
600 /* save interface I/O counts */
601 {
602         ifinfo_t ifinfo;
603         struct query *ctl;
604
605         /* if not monitoring link, all done */
606         if (!hp->monitor)
607                 return;
608
609         /* get the current I/O stats for the monitored link */
610         if (get_ifinfo(hp->monitor, &ifinfo))
611                 /* update this and preceeding host entries using the link
612                    (they were already set during this pass but the I/O
613                    count has now changed and they need to be re-updated)
614                 */
615                 for (ctl = querylist; ctl; ctl = ctl->next) {
616                         if (ctl->server.monitor && !strcmp(hp->monitor, ctl->server.monitor))
617                                 ctl->server.monitor_io =
618                                         ifinfo.rx_packets + ifinfo.tx_packets;
619                         /* do NOT update host entries following this one */
620                         if (&ctl->server == hp)
621                                 break;
622                 }
623
624 #ifdef  ACTIVITY_DEBUG
625         (void) report(stdout, 
626                       GT_("activity on %s -noted- as %d\n"), 
627                       hp->monitor, hp->monitor_io);
628 #endif
629 }
630
631 int interface_approve(struct hostdata *hp, flag domonitor)
632 /* return TRUE if OK to poll, FALSE otherwise */
633 {
634         ifinfo_t ifinfo;
635
636         /* check interface IP address (range), if specified */
637         if (hp->interface) {
638                 /* get interface info */
639                 if (!get_ifinfo(hp->interface, &ifinfo)) {
640                         (void) report(stdout, 
641                                       GT_("skipping poll of %s, %s down\n"),
642                                       hp->pollname, hp->interface);
643                         return(FALSE);
644                 }
645                 /* check the IP addresses (range) */
646                 if      (!(
647                                 /* check remote IP address */
648                                 ((ifinfo.dstaddr.s_addr != 0) &&
649                                 (ifinfo.dstaddr.s_addr &
650                                 hp->interface_pair->interface_mask.s_addr) ==
651                                 hp->interface_pair->interface_address.s_addr)
652                                 ||
653                                 /* check local IP address */
654                                 ((ifinfo.addr.s_addr &
655                                 hp->interface_pair->interface_mask.s_addr) ==
656                                 hp->interface_pair->interface_address.s_addr)
657                         ) )
658                 {
659                         (void) report(stdout,
660                                 GT_("skipping poll of %s, %s IP address excluded\n"),
661                                 hp->pollname, hp->interface);
662                         return(FALSE);
663                 }
664         }
665
666         /* if not monitoring link, all done */
667         if (!domonitor || !hp->monitor)
668                 return(TRUE);
669
670 #ifdef  ACTIVITY_DEBUG
671         (void) report(stdout, 
672                       GT_("activity on %s checked as %d\n"), 
673                       hp->monitor, hp->monitor_io);
674 #endif
675         /* if monitoring, check link for activity if it is up */
676         if (get_ifinfo(hp->monitor, &ifinfo))
677         {
678             int diff = (ifinfo.rx_packets + ifinfo.tx_packets)
679                                                         - hp->monitor_io;
680
681             /*
682              * There are three cases here:
683              *
684              * (a) If the new packet count is less than the recorded one,
685              * probably pppd was restarted while fetchmail was running.
686              * Don't skip.
687              *
688              * (b) newpacket count is greater than the old packet count,
689              * but the difference is small and may just reflect the overhead
690              * of a link shutdown.  Skip.
691              *
692              * (c) newpacket count is greater than the old packet count,
693              * and the difference is large. Connection is live.  Don't skip.
694              */
695             if (diff >= 0 && diff <= MONITOR_SLOP)
696             {
697                 (void) report(stdout, 
698                               GT_("skipping poll of %s, %s inactive\n"),
699                               hp->pollname, hp->monitor);
700                 return(FALSE);
701             }
702         }
703
704 #ifdef ACTIVITY_DEBUG
705        report(stdout, GT_("activity on %s was %d, is %d\n"),
706              hp->monitor, hp->monitor_io,
707              ifinfo.rx_packets + ifinfo.tx_packets);
708 #endif
709
710         return(TRUE);
711 }
712 #endif /* CAN_MONITOR */
713
714 #ifndef have_interface_init
715 void interface_init(void) {}
716 #endif