iface.c revision 76214
1/*-
2 * Copyright (c) 1998 Brian Somers <brian@Awfulhak.org>
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in the
12 *    documentation and/or other materials provided with the distribution.
13 *
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24 * SUCH DAMAGE.
25 *
26 * $FreeBSD: head/usr.sbin/ppp/iface.c 76214 2001-05-02 16:35:24Z brian $
27 */
28
29#include <sys/param.h>
30#include <sys/socket.h>
31#include <netinet/in.h>
32#include <net/if.h>
33#include <net/if_dl.h>
34#include <net/route.h>
35#include <arpa/inet.h>
36#include <netinet/in_systm.h>
37#include <netinet/ip.h>
38#include <sys/un.h>
39
40#include <errno.h>
41#include <string.h>
42#include <stdio.h>
43#include <stdlib.h>
44#include <sys/ioctl.h>
45#include <sys/sysctl.h>
46#include <termios.h>
47#include <unistd.h>
48
49#include "layer.h"
50#include "defs.h"
51#include "command.h"
52#include "mbuf.h"
53#include "log.h"
54#include "id.h"
55#include "timer.h"
56#include "fsm.h"
57#include "iplist.h"
58#include "lqr.h"
59#include "hdlc.h"
60#include "throughput.h"
61#include "slcompress.h"
62#include "descriptor.h"
63#include "ipcp.h"
64#include "filter.h"
65#include "lcp.h"
66#include "ccp.h"
67#include "link.h"
68#include "mp.h"
69#ifndef NORADIUS
70#include "radius.h"
71#endif
72#include "bundle.h"
73#include "prompt.h"
74#include "iface.h"
75
76
77static int
78bitsinmask(struct in_addr mask)
79{
80  u_int32_t bitmask, maskaddr;
81  int bits;
82
83  bitmask = 0xffffffff;
84  maskaddr = ntohl(mask.s_addr);
85  for (bits = 32; bits >= 0; bits--) {
86    if (maskaddr == bitmask)
87      break;
88    bitmask &= ~(1 << (32 - bits));
89  }
90
91  return bits;
92}
93
94struct iface *
95iface_Create(const char *name)
96{
97  int mib[6], s, maxtries, err;
98  size_t needed, namelen;
99  char *buf, *ptr, *end;
100  struct if_msghdr *ifm;
101  struct ifa_msghdr *ifam;
102  struct sockaddr_dl *dl;
103  struct sockaddr *sa[RTAX_MAX];
104  struct iface *iface;
105  struct iface_addr *addr;
106
107  s = socket(AF_INET, SOCK_DGRAM, 0);
108  if (s < 0) {
109    fprintf(stderr, "iface_Create: socket(): %s\n", strerror(errno));
110    return NULL;
111  }
112
113  mib[0] = CTL_NET;
114  mib[1] = PF_ROUTE;
115  mib[2] = 0;
116  mib[3] = 0;
117  mib[4] = NET_RT_IFLIST;
118  mib[5] = 0;
119
120  maxtries = 20;
121  err = 0;
122  do {
123    if (maxtries-- == 0 || (err && err != ENOMEM)) {
124      fprintf(stderr, "iface_Create: sysctl: %s\n", strerror(err));
125      close(s);
126      return NULL;
127    }
128
129    if (sysctl(mib, 6, NULL, &needed, NULL, 0) < 0) {
130      fprintf(stderr, "iface_Create: sysctl: estimate: %s\n",
131                strerror(errno));
132      close(s);
133      return NULL;
134    }
135
136    if ((buf = (char *)malloc(needed)) == NULL) {
137      fprintf(stderr, "iface_Create: malloc failed: %s\n", strerror(errno));
138      close(s);
139      return NULL;
140    }
141
142    if (sysctl(mib, 6, buf, &needed, NULL, 0) < 0) {
143      err = errno;
144      free(buf);
145      buf = NULL;
146    }
147  } while (buf == NULL);
148
149  ptr = buf;
150  end = buf + needed;
151  iface = NULL;
152  namelen = strlen(name);
153
154  while (ptr < end && iface == NULL) {
155    ifm = (struct if_msghdr *)ptr;			/* On if_msghdr */
156    if (ifm->ifm_type != RTM_IFINFO)
157      break;
158    dl = (struct sockaddr_dl *)(ifm + 1);		/* Single _dl at end */
159    if (dl->sdl_nlen == namelen && !strncmp(name, dl->sdl_data, namelen)) {
160      iface = (struct iface *)malloc(sizeof *iface);
161      if (iface == NULL) {
162        fprintf(stderr, "iface_Create: malloc: %s\n", strerror(errno));
163        return NULL;
164      }
165      iface->name = strdup(name);
166      iface->flags = ifm->ifm_flags;
167      iface->index = ifm->ifm_index;
168      iface->in_addrs = 0;
169      iface->in_addr = NULL;
170    }
171    ptr += ifm->ifm_msglen;				/* First ifa_msghdr */
172    for (; ptr < end; ptr += ifam->ifam_msglen) {
173      ifam = (struct ifa_msghdr *)ptr;			/* Next if address */
174
175      if (ifam->ifam_type != RTM_NEWADDR)		/* finished this if */
176        break;
177
178      if (iface != NULL && ifam->ifam_addrs & RTA_IFA) {
179        /* Found a configured interface ! */
180        iface_ParseHdr(ifam, sa);
181
182        if (sa[RTAX_IFA] && sa[RTAX_IFA]->sa_family == AF_INET) {
183          /* Record the address */
184
185          addr = (struct iface_addr *)realloc
186            (iface->in_addr, (iface->in_addrs + 1) * sizeof iface->in_addr[0]);
187          if (addr == NULL)
188            break;
189          iface->in_addr = addr;
190
191          addr += iface->in_addrs;
192          iface->in_addrs++;
193
194          addr->ifa = ((struct sockaddr_in *)sa[RTAX_IFA])->sin_addr;
195
196          if (sa[RTAX_BRD])
197            addr->brd = ((struct sockaddr_in *)sa[RTAX_BRD])->sin_addr;
198          else
199            addr->brd.s_addr = INADDR_ANY;
200
201          if (sa[RTAX_NETMASK])
202            addr->mask = ((struct sockaddr_in *)sa[RTAX_NETMASK])->sin_addr;
203          else
204            addr->mask.s_addr = INADDR_ANY;
205
206          addr->bits = bitsinmask(addr->mask);
207        }
208      }
209    }
210  }
211
212  free(buf);
213  close(s);
214
215  return iface;
216}
217
218static void
219iface_addr_Zap(const char *name, struct iface_addr *addr)
220{
221  struct ifaliasreq ifra;
222  struct sockaddr_in *me, *peer;
223  int s;
224
225  s = ID0socket(AF_INET, SOCK_DGRAM, 0);
226  if (s < 0)
227    log_Printf(LogERROR, "iface_addr_Zap: socket(): %s\n", strerror(errno));
228  else {
229    memset(&ifra, '\0', sizeof ifra);
230    strncpy(ifra.ifra_name, name, sizeof ifra.ifra_name - 1);
231    me = (struct sockaddr_in *)&ifra.ifra_addr;
232    peer = (struct sockaddr_in *)&ifra.ifra_broadaddr;
233    me->sin_family = peer->sin_family = AF_INET;
234    me->sin_len = peer->sin_len = sizeof(struct sockaddr_in);
235    me->sin_addr = addr->ifa;
236    peer->sin_addr = addr->brd;
237    log_Printf(LogDEBUG, "Delete %s\n", inet_ntoa(addr->ifa));
238    if (ID0ioctl(s, SIOCDIFADDR, &ifra) < 0)
239      log_Printf(LogWARN, "iface_addr_Zap: ioctl(SIOCDIFADDR, %s): %s\n",
240                 inet_ntoa(addr->ifa), strerror(errno));
241    close(s);
242  }
243}
244
245void
246iface_inClear(struct iface *iface, int how)
247{
248  int n, addrs;
249
250  if (iface->in_addrs) {
251    addrs = n = how == IFACE_CLEAR_ALL ? 0 : 1;
252    for (; n < iface->in_addrs; n++)
253      iface_addr_Zap(iface->name, iface->in_addr + n);
254
255    iface->in_addrs = addrs;
256    /* Don't bother realloc()ing - we have little to gain */
257  }
258}
259
260int
261iface_inAdd(struct iface *iface, struct in_addr ifa, struct in_addr mask,
262            struct in_addr brd, int how)
263{
264  int slot, s, chg, nochange;
265  struct ifaliasreq ifra;
266  struct sockaddr_in *me, *peer, *msk;
267  struct iface_addr *addr;
268
269  for (slot = 0; slot < iface->in_addrs; slot++)
270    if (iface->in_addr[slot].ifa.s_addr == ifa.s_addr) {
271      if (how & IFACE_FORCE_ADD)
272        break;
273      else
274        /* errno = EEXIST; */
275        return 0;
276    }
277
278  addr = (struct iface_addr *)realloc
279    (iface->in_addr, (iface->in_addrs + 1) * sizeof iface->in_addr[0]);
280  if (addr == NULL) {
281    log_Printf(LogERROR, "iface_inAdd: realloc: %s\n", strerror(errno));
282    return 0;
283  }
284  iface->in_addr = addr;
285
286  /*
287   * We've gotta be careful here.  If we try to add an address with the
288   * same destination as an existing interface, nothing will work.
289   * Instead, we tweak all previous address entries that match the
290   * to-be-added destination to 255.255.255.255 (w/ a similar netmask).
291   * There *may* be more than one - if the user has ``iface add''ed
292   * stuff previously.
293   */
294  nochange = 0;
295  s = -1;
296  for (chg = 0; chg < iface->in_addrs; chg++) {
297    if ((iface->in_addr[chg].brd.s_addr == brd.s_addr &&
298         brd.s_addr != INADDR_BROADCAST) || chg == slot) {
299      /*
300       * If we've found an entry that exactly matches what we want to add,
301       * don't remove it and then add it again.  If we do, it's possible
302       * that the kernel will (correctly) ``tidy up'' any routes that use
303       * the IP number as a destination.
304       */
305      if (chg == slot && iface->in_addr[chg].mask.s_addr == mask.s_addr) {
306        if (brd.s_addr == iface->in_addr[slot].brd.s_addr)
307          nochange = 1;
308        /*
309         * If only the destination address has changed, the SIOCAIFADDR
310         * we do after the current loop will change it.
311         */
312        continue;
313      }
314      if (s == -1 && (s = ID0socket(AF_INET, SOCK_DGRAM, 0)) == -1) {
315        log_Printf(LogERROR, "iface_inAdd: socket(): %s\n", strerror(errno));
316        return 0;
317      }
318
319      memset(&ifra, '\0', sizeof ifra);
320      strncpy(ifra.ifra_name, iface->name, sizeof ifra.ifra_name - 1);
321      me = (struct sockaddr_in *)&ifra.ifra_addr;
322      msk = (struct sockaddr_in *)&ifra.ifra_mask;
323      peer = (struct sockaddr_in *)&ifra.ifra_broadaddr;
324      me->sin_family = msk->sin_family = peer->sin_family = AF_INET;
325      me->sin_len = msk->sin_len = peer->sin_len = sizeof(struct sockaddr_in);
326      me->sin_addr = iface->in_addr[chg].ifa;
327      msk->sin_addr = iface->in_addr[chg].mask;
328      peer->sin_addr = iface->in_addr[chg].brd;
329      log_Printf(LogDEBUG, "Delete %s\n", inet_ntoa(me->sin_addr));
330      ID0ioctl(s, SIOCDIFADDR, &ifra);	/* Don't care if it fails... */
331      if (chg != slot) {
332        peer->sin_addr.s_addr = iface->in_addr[chg].brd.s_addr =
333          msk->sin_addr.s_addr = iface->in_addr[chg].mask.s_addr =
334            INADDR_BROADCAST;
335        iface->in_addr[chg].bits = 32;
336        log_Printf(LogDEBUG, "Add %s -> 255.255.255.255\n",
337                   inet_ntoa(me->sin_addr));
338        if (ID0ioctl(s, SIOCAIFADDR, &ifra) < 0 && errno != EEXIST) {
339          /* Oops - that's bad(ish) news !  We've lost an alias ! */
340          log_Printf(LogERROR, "iface_inAdd: ioctl(SIOCAIFADDR): %s: %s\n",
341               inet_ntoa(me->sin_addr), strerror(errno));
342          iface->in_addrs--;
343          bcopy(iface->in_addr + chg + 1, iface->in_addr + chg,
344                (iface->in_addrs - chg) * sizeof iface->in_addr[0]);
345          if (slot > chg)
346            slot--;
347          chg--;
348        }
349      }
350    }
351  }
352
353  if (!nochange) {
354    if (s == -1 && (s = ID0socket(AF_INET, SOCK_DGRAM, 0)) == -1) {
355      log_Printf(LogERROR, "iface_inAdd: socket(): %s\n", strerror(errno));
356      return 0;
357    }
358    memset(&ifra, '\0', sizeof ifra);
359    strncpy(ifra.ifra_name, iface->name, sizeof ifra.ifra_name - 1);
360    me = (struct sockaddr_in *)&ifra.ifra_addr;
361    msk = (struct sockaddr_in *)&ifra.ifra_mask;
362    peer = (struct sockaddr_in *)&ifra.ifra_broadaddr;
363    me->sin_family = msk->sin_family = peer->sin_family = AF_INET;
364    me->sin_len = msk->sin_len = peer->sin_len = sizeof(struct sockaddr_in);
365    me->sin_addr = ifa;
366    msk->sin_addr = mask;
367    peer->sin_addr = brd;
368
369    if (log_IsKept(LogDEBUG)) {
370      char buf[16];
371
372      strncpy(buf, inet_ntoa(brd), sizeof buf-1);
373      buf[sizeof buf - 1] = '\0';
374      log_Printf(LogDEBUG, "Add %s -> %s\n", inet_ntoa(ifa), buf);
375    }
376
377    /* An EEXIST failure w/ brd == INADDR_BROADCAST is ok (and works!) */
378    if (ID0ioctl(s, SIOCAIFADDR, &ifra) < 0 &&
379        (brd.s_addr != INADDR_BROADCAST || errno != EEXIST)) {
380      log_Printf(LogERROR, "iface_inAdd: ioctl(SIOCAIFADDR): %s: %s\n",
381                 inet_ntoa(ifa), strerror(errno));
382      ID0ioctl(s, SIOCDIFADDR, &ifra);	/* EEXIST ? */
383      close(s);
384      return 0;
385    }
386  }
387
388  if (s != -1)
389    close(s);
390
391  if (slot == iface->in_addrs) {
392    /* We're adding a new interface address */
393
394    if (how & IFACE_ADD_FIRST) {
395      /* Stuff it at the start of our list */
396      slot = 0;
397      bcopy(iface->in_addr, iface->in_addr + 1,
398            iface->in_addrs * sizeof iface->in_addr[0]);
399    }
400
401    iface->in_addrs++;
402  } else if (how & IFACE_ADD_FIRST) {
403    /* Shift it up to the first slot */
404    bcopy(iface->in_addr, iface->in_addr + 1, slot * sizeof iface->in_addr[0]);
405    slot = 0;
406  }
407
408  iface->in_addr[slot].ifa = ifa;
409  iface->in_addr[slot].mask = mask;
410  iface->in_addr[slot].brd = brd;
411  iface->in_addr[slot].bits = bitsinmask(iface->in_addr[slot].mask);
412
413  return 1;
414}
415
416int
417iface_inDelete(struct iface *iface, struct in_addr ip)
418{
419  int n;
420
421  for (n = 0; n < iface->in_addrs; n++)
422    if (iface->in_addr[n].ifa.s_addr == ip.s_addr) {
423      iface_addr_Zap(iface->name, iface->in_addr + n);
424      bcopy(iface->in_addr + n + 1, iface->in_addr + n,
425            (iface->in_addrs - n - 1) * sizeof iface->in_addr[0]);
426      iface->in_addrs--;
427      return 1;
428    }
429
430  return 0;
431}
432
433#define IFACE_ADDFLAGS 1
434#define IFACE_DELFLAGS 2
435
436static int
437iface_ChangeFlags(const char *ifname, int flags, int how)
438{
439  struct ifreq ifrq;
440  int s;
441
442  s = ID0socket(AF_INET, SOCK_DGRAM, 0);
443  if (s < 0) {
444    log_Printf(LogERROR, "iface_ChangeFlags: socket: %s\n", strerror(errno));
445    return 0;
446  }
447
448  memset(&ifrq, '\0', sizeof ifrq);
449  strncpy(ifrq.ifr_name, ifname, sizeof ifrq.ifr_name - 1);
450  ifrq.ifr_name[sizeof ifrq.ifr_name - 1] = '\0';
451  if (ID0ioctl(s, SIOCGIFFLAGS, &ifrq) < 0) {
452    log_Printf(LogERROR, "iface_ChangeFlags: ioctl(SIOCGIFFLAGS): %s\n",
453       strerror(errno));
454    close(s);
455    return 0;
456  }
457
458  if (how == IFACE_ADDFLAGS)
459    ifrq.ifr_flags |= flags;
460  else
461    ifrq.ifr_flags &= ~flags;
462
463  if (ID0ioctl(s, SIOCSIFFLAGS, &ifrq) < 0) {
464    log_Printf(LogERROR, "iface_ChangeFlags: ioctl(SIOCSIFFLAGS): %s\n",
465       strerror(errno));
466    close(s);
467    return 0;
468  }
469  close(s);
470
471  return 1;	/* Success */
472}
473
474int
475iface_SetFlags(const char *ifname, int flags)
476{
477  return iface_ChangeFlags(ifname, flags, IFACE_ADDFLAGS);
478}
479
480int
481iface_ClearFlags(const char *ifname, int flags)
482{
483  return iface_ChangeFlags(ifname, flags, IFACE_DELFLAGS);
484}
485
486void
487iface_Destroy(struct iface *iface)
488{
489  /*
490   * iface_Clear(iface, IFACE_CLEAR_ALL) must be called manually
491   * if that's what the user wants.  It's better to leave the interface
492   * allocated so that existing connections can continue to work.
493   */
494
495  if (iface != NULL) {
496    free(iface->name);
497    free(iface->in_addr);
498    free(iface);
499  }
500}
501
502#define if_entry(x) { IFF_##x, #x }
503
504struct {
505  int flag;
506  const char *value;
507} if_flags[] = {
508  if_entry(UP),
509  if_entry(BROADCAST),
510  if_entry(DEBUG),
511  if_entry(LOOPBACK),
512  if_entry(POINTOPOINT),
513  if_entry(RUNNING),
514  if_entry(NOARP),
515  if_entry(PROMISC),
516  if_entry(ALLMULTI),
517  if_entry(OACTIVE),
518  if_entry(SIMPLEX),
519  if_entry(LINK0),
520  if_entry(LINK1),
521  if_entry(LINK2),
522  if_entry(MULTICAST),
523  { 0, "???" }
524};
525
526int
527iface_Show(struct cmdargs const *arg)
528{
529  struct iface *iface = arg->bundle->iface, *current;
530  int f, flags;
531
532  current = iface_Create(iface->name);
533  flags = iface->flags = current->flags;
534  iface_Destroy(current);
535
536  prompt_Printf(arg->prompt, "%s (idx %d) <", iface->name, iface->index);
537  for (f = 0; f < sizeof if_flags / sizeof if_flags[0]; f++)
538    if ((if_flags[f].flag & flags) || (!if_flags[f].flag && flags)) {
539      prompt_Printf(arg->prompt, "%s%s", flags == iface->flags ? "" : ",",
540                    if_flags[f].value);
541      flags &= ~if_flags[f].flag;
542    }
543  prompt_Printf(arg->prompt, "> mtu %d has %d address%s:\n", arg->bundle->mtu,
544                iface->in_addrs, iface->in_addrs == 1 ? "" : "es");
545
546  for (f = 0; f < iface->in_addrs; f++) {
547    prompt_Printf(arg->prompt, "  %s", inet_ntoa(iface->in_addr[f].ifa));
548    if (iface->in_addr[f].bits >= 0)
549      prompt_Printf(arg->prompt, "/%d", iface->in_addr[f].bits);
550    if (iface->flags & IFF_POINTOPOINT)
551      prompt_Printf(arg->prompt, " -> %s", inet_ntoa(iface->in_addr[f].brd));
552    else if (iface->flags & IFF_BROADCAST)
553      prompt_Printf(arg->prompt, " broadcast %s",
554                    inet_ntoa(iface->in_addr[f].brd));
555    if (iface->in_addr[f].bits < 0)
556      prompt_Printf(arg->prompt, " (mask %s)",
557                    inet_ntoa(iface->in_addr[f].mask));
558    prompt_Printf(arg->prompt, "\n");
559  }
560
561  return 0;
562}
563
564void
565iface_ParseHdr(struct ifa_msghdr *ifam, struct sockaddr *sa[RTAX_MAX])
566{
567  char *wp;
568  int rtax;
569
570  wp = (char *)(ifam + 1);
571
572  for (rtax = 0; rtax < RTAX_MAX; rtax++)
573    if (ifam->ifam_addrs & (1 << rtax)) {
574      sa[rtax] = (struct sockaddr *)wp;
575      wp += ROUNDUP(sa[rtax]->sa_len);
576    } else
577      sa[rtax] = NULL;
578}
579