route.c revision 58032
1/*
2 *	      PPP Routing related Module
3 *
4 *	    Written by Toshiharu OHNO (tony-o@iij.ad.jp)
5 *
6 *   Copyright (C) 1994, Internet Initiative Japan, Inc. All rights reserverd.
7 *
8 * Redistribution and use in source and binary forms are permitted
9 * provided that the above copyright notice and this paragraph are
10 * duplicated in all such forms and that any documentation,
11 * advertising materials, and other materials related to such
12 * distribution and use acknowledge that the software was developed
13 * by the Internet Initiative Japan, Inc.  The name of the
14 * IIJ may not be used to endorse or promote products derived
15 * from this software without specific prior written permission.
16 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
17 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
18 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
19 *
20 * $FreeBSD: head/usr.sbin/ppp/route.c 58032 2000-03-14 01:46:44Z brian $
21 *
22 */
23
24#include <sys/param.h>
25#include <sys/socket.h>
26#include <net/if_types.h>
27#include <net/route.h>
28#include <net/if.h>
29#include <netinet/in.h>
30#include <arpa/inet.h>
31#include <net/if_dl.h>
32#include <netinet/in_systm.h>
33#include <netinet/ip.h>
34#include <sys/un.h>
35#ifndef NOINET6
36#include <netinet6/in6.h>
37#endif
38#include <netdb.h>
39
40#include <errno.h>
41#include <stdio.h>
42#include <stdlib.h>
43#include <string.h>
44#include <sys/sysctl.h>
45#include <termios.h>
46
47#include "layer.h"
48#include "defs.h"
49#include "command.h"
50#include "mbuf.h"
51#include "log.h"
52#include "iplist.h"
53#include "timer.h"
54#include "throughput.h"
55#include "lqr.h"
56#include "hdlc.h"
57#include "fsm.h"
58#include "lcp.h"
59#include "ccp.h"
60#include "link.h"
61#include "slcompress.h"
62#include "ipcp.h"
63#include "filter.h"
64#include "descriptor.h"
65#include "mp.h"
66#ifndef NORADIUS
67#include "radius.h"
68#endif
69#include "bundle.h"
70#include "route.h"
71#include "prompt.h"
72#include "iface.h"
73
74
75static void
76p_sockaddr(struct prompt *prompt, struct sockaddr *phost,
77           struct sockaddr *pmask, int width)
78{
79  char buf[29];
80  struct sockaddr_in *ihost4 = (struct sockaddr_in *)phost;
81  struct sockaddr_in *mask4 = (struct sockaddr_in *)pmask;
82  struct sockaddr_dl *dl = (struct sockaddr_dl *)phost;
83
84  if (log_IsKept(LogDEBUG)) {
85    char tmp[50];
86
87    log_Printf(LogDEBUG, "Found the following sockaddr:\n");
88    log_Printf(LogDEBUG, "  Family %d, len %d\n",
89               (int)phost->sa_family, (int)phost->sa_len);
90    inet_ntop(phost->sa_family, phost->sa_data, tmp, sizeof tmp);
91    log_Printf(LogDEBUG, "  Addr %s\n", tmp);
92    if (pmask) {
93      inet_ntop(pmask->sa_family, pmask->sa_data, tmp, sizeof tmp);
94      log_Printf(LogDEBUG, "  Mask %s\n", tmp);
95    }
96  }
97
98  switch (phost->sa_family) {
99  case AF_INET:
100    if (!phost)
101      buf[0] = '\0';
102    else if (ihost4->sin_addr.s_addr == INADDR_ANY)
103      strcpy(buf, "default");
104    else if (!pmask)
105      strcpy(buf, inet_ntoa(ihost4->sin_addr));
106    else {
107      u_int32_t msk = ntohl(mask4->sin_addr.s_addr);
108      u_int32_t tst;
109      int bits;
110      int len;
111      struct sockaddr_in net;
112
113      for (tst = 1, bits = 32; tst; tst <<= 1, bits--)
114        if (msk & tst)
115          break;
116
117      for (tst <<= 1; tst; tst <<= 1)
118        if (!(msk & tst))
119          break;
120
121      net.sin_addr.s_addr = ihost4->sin_addr.s_addr & mask4->sin_addr.s_addr;
122      strcpy(buf, inet_ntoa(net.sin_addr));
123      for (len = strlen(buf); len > 3; buf[len -= 2] = '\0')
124        if (strcmp(buf + len - 2, ".0"))
125          break;
126
127      if (tst)    /* non-contiguous :-( */
128        sprintf(buf + strlen(buf),"&0x%08lx", (u_long)msk);
129      else
130        sprintf(buf + strlen(buf), "/%d", bits);
131    }
132    break;
133
134  case AF_LINK:
135    if (dl->sdl_nlen)
136      snprintf(buf, sizeof buf, "%.*s", dl->sdl_nlen, dl->sdl_data);
137    else if (dl->sdl_alen) {
138      if (dl->sdl_type == IFT_ETHER) {
139        if (dl->sdl_alen < sizeof buf / 3) {
140          int f;
141          u_char *MAC;
142
143          MAC = (u_char *)dl->sdl_data + dl->sdl_nlen;
144          for (f = 0; f < dl->sdl_alen; f++)
145            sprintf(buf+f*3, "%02x:", MAC[f]);
146          buf[f*3-1] = '\0';
147        } else
148	  strcpy(buf, "??:??:??:??:??:??");
149      } else
150        sprintf(buf, "<IFT type %d>", dl->sdl_type);
151    }  else if (dl->sdl_slen)
152      sprintf(buf, "<slen %d?>", dl->sdl_slen);
153    else
154      sprintf(buf, "link#%d", dl->sdl_index);
155    break;
156
157#ifndef NOINET6
158  case AF_INET6:
159    if (!phost)
160      buf[0] = '\0';
161    else {
162      const u_char masks[] = { 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe };
163      struct sockaddr_in6 *ihost6 = (struct sockaddr_in6 *)phost;
164      struct sockaddr_in6 *mask6 = (struct sockaddr_in6 *)pmask;
165      int masklen, len;
166      const u_char *c;
167
168      /* XXX: ?????!?!?!!!!!  This is horrible ! */
169      if (IN6_IS_ADDR_LINKLOCAL(&ihost6->sin6_addr) ||
170          IN6_IS_ADDR_MC_LINKLOCAL(&ihost6->sin6_addr)) {
171        ihost6->sin6_scope_id =
172          ntohs(*(u_short *)&ihost6->sin6_addr.s6_addr[2]);
173        *(u_short *)&ihost6->sin6_addr.s6_addr[2] = 0;
174      }
175
176      if (mask6) {
177        const u_char *p, *end;
178
179        p = (const u_char *)&mask6->sin6_addr;
180        end = p + 16;
181        for (masklen = 0, end = p + 16; p < end && *p == 0xff; p++)
182          masklen += 8;
183
184        if (p < end) {
185          for (c = masks; c < masks + sizeof masks; c++)
186            if (*c == *p) {
187              masklen += c - masks;
188              break;
189            }
190        }
191      } else
192        masklen = 128;
193
194      if (masklen == 0 && IN6_IS_ADDR_UNSPECIFIED(&ihost6->sin6_addr))
195        snprintf(buf, sizeof buf, "default");
196      else {
197        getnameinfo(phost, ihost6->sin6_len, buf, sizeof buf,
198                    NULL, 0, NI_WITHSCOPEID | NI_NUMERICHOST);
199        if (mask6 && (len = strlen(buf)) < sizeof buf - 1)
200          snprintf(buf + len, sizeof buf - len, "/%d", masklen);
201      }
202    }
203    break;
204#endif
205
206  default:
207    sprintf(buf, "<AF type %d>", phost->sa_family);
208    break;
209  }
210
211  prompt_Printf(prompt, "%-*s ", width-1, buf);
212}
213
214static struct bits {
215  u_int32_t b_mask;
216  char b_val;
217} bits[] = {
218  { RTF_UP, 'U' },
219  { RTF_GATEWAY, 'G' },
220  { RTF_HOST, 'H' },
221  { RTF_REJECT, 'R' },
222  { RTF_DYNAMIC, 'D' },
223  { RTF_MODIFIED, 'M' },
224  { RTF_DONE, 'd' },
225  { RTF_CLONING, 'C' },
226  { RTF_XRESOLVE, 'X' },
227  { RTF_LLINFO, 'L' },
228  { RTF_STATIC, 'S' },
229  { RTF_PROTO1, '1' },
230  { RTF_PROTO2, '2' },
231  { RTF_BLACKHOLE, 'B' },
232#ifdef RTF_WASCLONED
233  { RTF_WASCLONED, 'W' },
234#endif
235#ifdef RTF_PRCLONING
236  { RTF_PRCLONING, 'c' },
237#endif
238#ifdef RTF_PROTO3
239  { RTF_PROTO3, '3' },
240#endif
241#ifdef RTF_BROADCAST
242  { RTF_BROADCAST, 'b' },
243#endif
244  { 0, '\0' }
245};
246
247#ifndef RTF_WASCLONED
248#define RTF_WASCLONED (0)
249#endif
250
251static void
252p_flags(struct prompt *prompt, u_int32_t f, int max)
253{
254  char name[33], *flags;
255  register struct bits *p = bits;
256
257  if (max > sizeof name - 1)
258    max = sizeof name - 1;
259
260  for (flags = name; p->b_mask && flags - name < max; p++)
261    if (p->b_mask & f)
262      *flags++ = p->b_val;
263  *flags = '\0';
264  prompt_Printf(prompt, "%-*.*s", max, max, name);
265}
266
267const char *
268Index2Nam(int idx)
269{
270  /*
271   * XXX: Maybe we should select() on the routing socket so that we can
272   *      notice interfaces that come & go (PCCARD support).
273   *      Or we could even support a signal that resets these so that
274   *      the PCCARD insert/remove events can signal ppp.
275   */
276  static char **ifs;		/* Figure these out once */
277  static int nifs, debug_done;	/* Figure out how many once, and debug once */
278
279  if (idx > nifs || (idx > 0 && ifs[idx-1] == NULL)) {
280    int mib[6], have, had;
281    size_t needed;
282    char *buf, *ptr, *end;
283    struct sockaddr_dl *dl;
284    struct if_msghdr *ifm;
285
286    if (ifs) {
287      free(ifs);
288      ifs = NULL;
289      nifs = 0;
290    }
291    debug_done = 0;
292
293    mib[0] = CTL_NET;
294    mib[1] = PF_ROUTE;
295    mib[2] = 0;
296    mib[3] = 0;
297    mib[4] = NET_RT_IFLIST;
298    mib[5] = 0;
299
300    if (sysctl(mib, 6, NULL, &needed, NULL, 0) < 0) {
301      log_Printf(LogERROR, "Index2Nam: sysctl: estimate: %s\n",
302                 strerror(errno));
303      return "???";
304    }
305    if ((buf = malloc(needed)) == NULL)
306      return "???";
307    if (sysctl(mib, 6, buf, &needed, NULL, 0) < 0) {
308      free(buf);
309      return "???";
310    }
311    end = buf + needed;
312
313    have = 0;
314    for (ptr = buf; ptr < end; ptr += ifm->ifm_msglen) {
315      ifm = (struct if_msghdr *)ptr;
316      if (ifm->ifm_type != RTM_IFINFO)
317        break;
318      dl = (struct sockaddr_dl *)(ifm + 1);
319      if (ifm->ifm_index > 0) {
320        if (ifm->ifm_index > have) {
321          char **newifs;
322
323          had = have;
324          have = ifm->ifm_index + 5;
325          if (had)
326            newifs = (char **)realloc(ifs, sizeof(char *) * have);
327          else
328            newifs = (char **)malloc(sizeof(char *) * have);
329          if (!newifs) {
330            log_Printf(LogDEBUG, "Index2Nam: %s\n", strerror(errno));
331            nifs = 0;
332            if (ifs) {
333              free(ifs);
334              ifs = NULL;
335            }
336            free(buf);
337            return "???";
338          }
339          ifs = newifs;
340          memset(ifs + had, '\0', sizeof(char *) * (have - had));
341        }
342        if (ifs[ifm->ifm_index-1] == NULL) {
343          ifs[ifm->ifm_index-1] = (char *)malloc(dl->sdl_nlen+1);
344          memcpy(ifs[ifm->ifm_index-1], dl->sdl_data, dl->sdl_nlen);
345          ifs[ifm->ifm_index-1][dl->sdl_nlen] = '\0';
346          if (nifs < ifm->ifm_index)
347            nifs = ifm->ifm_index;
348        }
349      } else if (log_IsKept(LogDEBUG))
350        log_Printf(LogDEBUG, "Skipping out-of-range interface %d!\n",
351                  ifm->ifm_index);
352    }
353    free(buf);
354  }
355
356  if (log_IsKept(LogDEBUG) && !debug_done) {
357    int f;
358
359    log_Printf(LogDEBUG, "Found the following interfaces:\n");
360    for (f = 0; f < nifs; f++)
361      if (ifs[f] != NULL)
362        log_Printf(LogDEBUG, " Index %d, name \"%s\"\n", f+1, ifs[f]);
363    debug_done = 1;
364  }
365
366  if (idx < 1 || idx > nifs || ifs[idx-1] == NULL)
367    return "???";
368
369  return ifs[idx-1];
370}
371
372void
373route_ParseHdr(struct rt_msghdr *rtm, struct sockaddr *sa[RTAX_MAX])
374{
375  char *wp;
376  int rtax;
377
378  wp = (char *)(rtm + 1);
379
380  for (rtax = 0; rtax < RTAX_MAX; rtax++)
381    if (rtm->rtm_addrs & (1 << rtax)) {
382      sa[rtax] = (struct sockaddr *)wp;
383      wp += ROUNDUP(sa[rtax]->sa_len);
384    } else
385      sa[rtax] = NULL;
386}
387
388int
389route_Show(struct cmdargs const *arg)
390{
391  struct rt_msghdr *rtm;
392  struct sockaddr *sa[RTAX_MAX];
393  char *sp, *ep, *cp;
394  size_t needed;
395  int mib[6];
396
397  mib[0] = CTL_NET;
398  mib[1] = PF_ROUTE;
399  mib[2] = 0;
400  mib[3] = 0;
401  mib[4] = NET_RT_DUMP;
402  mib[5] = 0;
403  if (sysctl(mib, 6, NULL, &needed, NULL, 0) < 0) {
404    log_Printf(LogERROR, "route_Show: sysctl: estimate: %s\n", strerror(errno));
405    return (1);
406  }
407  sp = malloc(needed);
408  if (sp == NULL)
409    return (1);
410  if (sysctl(mib, 6, sp, &needed, NULL, 0) < 0) {
411    log_Printf(LogERROR, "route_Show: sysctl: getroute: %s\n", strerror(errno));
412    free(sp);
413    return (1);
414  }
415  ep = sp + needed;
416
417  prompt_Printf(arg->prompt, "%-20s%-20sFlags  Netif\n",
418                "Destination", "Gateway");
419  for (cp = sp; cp < ep; cp += rtm->rtm_msglen) {
420    rtm = (struct rt_msghdr *)cp;
421
422    route_ParseHdr(rtm, sa);
423
424    if (sa[RTAX_DST] && sa[RTAX_GATEWAY]) {
425      p_sockaddr(arg->prompt, sa[RTAX_DST], sa[RTAX_NETMASK], 20);
426      p_sockaddr(arg->prompt, sa[RTAX_GATEWAY], NULL, 20);
427
428      p_flags(arg->prompt, rtm->rtm_flags, 6);
429      prompt_Printf(arg->prompt, " %s\n", Index2Nam(rtm->rtm_index));
430    } else
431      prompt_Printf(arg->prompt, "<can't parse routing entry>\n");
432  }
433  free(sp);
434  return 0;
435}
436
437/*
438 *  Delete routes associated with our interface
439 */
440void
441route_IfDelete(struct bundle *bundle, int all)
442{
443  struct rt_msghdr *rtm;
444  struct sockaddr *sa[RTAX_MAX];
445  struct sockaddr_in **in;
446  struct in_addr sa_none;
447  int pass;
448  size_t needed;
449  char *sp, *cp, *ep;
450  int mib[6];
451
452  log_Printf(LogDEBUG, "route_IfDelete (%d)\n", bundle->iface->index);
453  sa_none.s_addr = INADDR_ANY;
454  in = (struct sockaddr_in **)sa;
455
456  mib[0] = CTL_NET;
457  mib[1] = PF_ROUTE;
458  mib[2] = 0;
459  mib[3] = 0;
460  mib[4] = NET_RT_DUMP;
461  mib[5] = 0;
462  if (sysctl(mib, 6, NULL, &needed, NULL, 0) < 0) {
463    log_Printf(LogERROR, "route_IfDelete: sysctl: estimate: %s\n",
464	      strerror(errno));
465    return;
466  }
467
468  sp = malloc(needed);
469  if (sp == NULL)
470    return;
471
472  if (sysctl(mib, 6, sp, &needed, NULL, 0) < 0) {
473    log_Printf(LogERROR, "route_IfDelete: sysctl: getroute: %s\n",
474	      strerror(errno));
475    free(sp);
476    return;
477  }
478  ep = sp + needed;
479
480  for (pass = 0; pass < 2; pass++) {
481    /*
482     * We do 2 passes.  The first deletes all cloned routes.  The second
483     * deletes all non-cloned routes.  This is done to avoid
484     * potential errors from trying to delete route X after route Y where
485     * route X was cloned from route Y (and is no longer there 'cos it
486     * may have gone with route Y).
487     */
488    if (RTF_WASCLONED == 0 && pass == 0)
489      /* So we can't tell ! */
490      continue;
491    for (cp = sp; cp < ep; cp += rtm->rtm_msglen) {
492      rtm = (struct rt_msghdr *)cp;
493      route_ParseHdr(rtm, sa);
494      if (sa[RTAX_DST]) {
495        log_Printf(LogDEBUG, "route_IfDelete: addrs: %x, Netif: %d (%s),"
496                  " flags: %x, dst: %s ?\n", rtm->rtm_addrs, rtm->rtm_index,
497                  Index2Nam(rtm->rtm_index), rtm->rtm_flags,
498	          inet_ntoa(((struct sockaddr_in *)sa[RTAX_DST])->sin_addr));
499        if (sa[RTAX_GATEWAY] && rtm->rtm_index == bundle->iface->index &&
500	    (all || (rtm->rtm_flags & RTF_GATEWAY))) {
501          if (sa[RTAX_GATEWAY]->sa_family == AF_INET ||
502              sa[RTAX_GATEWAY]->sa_family == AF_LINK) {
503            if ((pass == 0 && (rtm->rtm_flags & RTF_WASCLONED)) ||
504                (pass == 1 && !(rtm->rtm_flags & RTF_WASCLONED))) {
505              log_Printf(LogDEBUG, "route_IfDelete: Remove it (pass %d)\n",
506                         pass);
507              bundle_SetRoute(bundle, RTM_DELETE, in[RTAX_DST]->sin_addr,
508                              sa_none, sa_none, 0, 0);
509            } else
510              log_Printf(LogDEBUG, "route_IfDelete: Skip it (pass %d)\n", pass);
511          } else
512            log_Printf(LogDEBUG,
513                      "route_IfDelete: Can't remove routes of %d family !\n",
514                      sa[RTAX_GATEWAY]->sa_family);
515        }
516      }
517    }
518  }
519  free(sp);
520}
521
522int
523GetIfIndex(char *name)
524{
525  int idx;
526  const char *got;
527
528  idx = 1;
529  while (strcmp(got = Index2Nam(idx), "???"))
530    if (!strcmp(got, name))
531      return idx;
532    else
533      idx++;
534  return -1;
535}
536
537void
538route_Change(struct bundle *bundle, struct sticky_route *r,
539             struct in_addr me, struct in_addr peer)
540{
541  struct in_addr none, del;
542
543  none.s_addr = INADDR_ANY;
544  for (; r; r = r->next) {
545    if ((r->type & ROUTE_DSTMYADDR) && r->dst.s_addr != me.s_addr) {
546      del.s_addr = r->dst.s_addr & r->mask.s_addr;
547      bundle_SetRoute(bundle, RTM_DELETE, del, none, none, 1, 0);
548      r->dst = me;
549      if (r->type & ROUTE_GWHISADDR)
550        r->gw = peer;
551    } else if ((r->type & ROUTE_DSTHISADDR) && r->dst.s_addr != peer.s_addr) {
552      del.s_addr = r->dst.s_addr & r->mask.s_addr;
553      bundle_SetRoute(bundle, RTM_DELETE, del, none, none, 1, 0);
554      r->dst = peer;
555      if (r->type & ROUTE_GWHISADDR)
556        r->gw = peer;
557    } else if ((r->type & ROUTE_GWHISADDR) && r->gw.s_addr != peer.s_addr)
558      r->gw = peer;
559    bundle_SetRoute(bundle, RTM_ADD, r->dst, r->gw, r->mask, 1, 0);
560  }
561}
562
563void
564route_Clean(struct bundle *bundle, struct sticky_route *r)
565{
566  struct in_addr none, del;
567
568  none.s_addr = INADDR_ANY;
569  for (; r; r = r->next) {
570    del.s_addr = r->dst.s_addr & r->mask.s_addr;
571    bundle_SetRoute(bundle, RTM_DELETE, del, none, none, 1, 0);
572  }
573}
574
575void
576route_Add(struct sticky_route **rp, int type, struct in_addr dst,
577          struct in_addr mask, struct in_addr gw)
578{
579  struct sticky_route *r;
580  int dsttype = type & ROUTE_DSTANY;
581
582  r = NULL;
583  while (*rp) {
584    if ((dsttype && dsttype == ((*rp)->type & ROUTE_DSTANY)) ||
585        (!dsttype && (*rp)->dst.s_addr == dst.s_addr)) {
586      /* Oops, we already have this route - unlink it */
587      free(r);			/* impossible really  */
588      r = *rp;
589      *rp = r->next;
590    } else
591      rp = &(*rp)->next;
592  }
593
594  if (!r)
595    r = (struct sticky_route *)malloc(sizeof(struct sticky_route));
596  r->type = type;
597  r->next = NULL;
598  r->dst = dst;
599  r->mask = mask;
600  r->gw = gw;
601  *rp = r;
602}
603
604void
605route_Delete(struct sticky_route **rp, int type, struct in_addr dst)
606{
607  struct sticky_route *r;
608  int dsttype = type & ROUTE_DSTANY;
609
610  for (; *rp; rp = &(*rp)->next) {
611    if ((dsttype && dsttype == ((*rp)->type & ROUTE_DSTANY)) ||
612        (!dsttype && dst.s_addr == ((*rp)->dst.s_addr & (*rp)->mask.s_addr))) {
613      r = *rp;
614      *rp = r->next;
615      free(r);
616      break;
617    }
618  }
619}
620
621void
622route_DeleteAll(struct sticky_route **rp)
623{
624  struct sticky_route *r, *rn;
625
626  for (r = *rp; r; r = rn) {
627    rn = r->next;
628    free(r);
629  }
630  *rp = NULL;
631}
632
633void
634route_ShowSticky(struct prompt *p, struct sticky_route *r, const char *tag,
635                 int indent)
636{
637  int def;
638  int tlen = strlen(tag);
639
640  if (tlen + 2 > indent)
641    prompt_Printf(p, "%s:\n%*s", tag, indent, "");
642  else
643    prompt_Printf(p, "%s:%*s", tag, indent - tlen - 1, "");
644
645  for (; r; r = r->next) {
646    def = r->dst.s_addr == INADDR_ANY && r->mask.s_addr == INADDR_ANY;
647
648    prompt_Printf(p, "%*sadd ", tlen ? 0 : indent, "");
649    tlen = 0;
650    if (r->type & ROUTE_DSTMYADDR)
651      prompt_Printf(p, "MYADDR");
652    else if (r->type & ROUTE_DSTHISADDR)
653      prompt_Printf(p, "HISADDR");
654    else if (!def)
655      prompt_Printf(p, "%s", inet_ntoa(r->dst));
656
657    if (def)
658      prompt_Printf(p, "default ");
659    else
660      prompt_Printf(p, " %s ", inet_ntoa(r->mask));
661
662    if (r->type & ROUTE_GWHISADDR)
663      prompt_Printf(p, "HISADDR\n");
664    else
665      prompt_Printf(p, "%s\n", inet_ntoa(r->gw));
666  }
667}
668