xref: /freebsd/usr.sbin/ppp/route.c (revision a5921bc3653e2e286715e6fe8d473ec0d02da38c)
1 /*-
2  * Copyright (c) 1996 - 2001 Brian Somers <brian@Awfulhak.org>
3  *          based on work by Toshiharu OHNO <tony-o@iij.ad.jp>
4  *                           Internet Initiative Japan, Inc (IIJ)
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  *
28  * $FreeBSD$
29  */
30 
31 #include <sys/param.h>
32 #include <sys/socket.h>
33 #include <net/if_types.h>
34 #include <net/route.h>
35 #include <net/if.h>
36 #include <netinet/in.h>
37 #include <arpa/inet.h>
38 #include <net/if_dl.h>
39 #include <netinet/in_systm.h>
40 #include <netinet/ip.h>
41 #include <sys/un.h>
42 
43 #include <errno.h>
44 #include <stdarg.h>
45 #include <stdio.h>
46 #include <stdlib.h>
47 #include <string.h>
48 #include <sys/sysctl.h>
49 #include <termios.h>
50 #include <unistd.h>
51 
52 #include "layer.h"
53 #include "defs.h"
54 #include "command.h"
55 #include "mbuf.h"
56 #include "log.h"
57 #include "iplist.h"
58 #include "timer.h"
59 #include "throughput.h"
60 #include "lqr.h"
61 #include "hdlc.h"
62 #include "fsm.h"
63 #include "lcp.h"
64 #include "ccp.h"
65 #include "link.h"
66 #include "slcompress.h"
67 #include "ncpaddr.h"
68 #include "ipcp.h"
69 #include "filter.h"
70 #include "descriptor.h"
71 #include "mp.h"
72 #ifndef NORADIUS
73 #include "radius.h"
74 #endif
75 #include "ipv6cp.h"
76 #include "ncp.h"
77 #include "bundle.h"
78 #include "route.h"
79 #include "prompt.h"
80 #include "iface.h"
81 #include "id.h"
82 
83 
84 static void
85 p_sockaddr(struct prompt *prompt, struct sockaddr *phost,
86            struct sockaddr *pmask, int width)
87 {
88   struct ncprange range;
89   char buf[29];
90   struct sockaddr_dl *dl = (struct sockaddr_dl *)phost;
91 
92   if (log_IsKept(LogDEBUG)) {
93     char tmp[50];
94 
95     log_Printf(LogDEBUG, "Found the following sockaddr:\n");
96     log_Printf(LogDEBUG, "  Family %d, len %d\n",
97                (int)phost->sa_family, (int)phost->sa_len);
98     inet_ntop(phost->sa_family, phost->sa_data, tmp, sizeof tmp);
99     log_Printf(LogDEBUG, "  Addr %s\n", tmp);
100     if (pmask) {
101       inet_ntop(pmask->sa_family, pmask->sa_data, tmp, sizeof tmp);
102       log_Printf(LogDEBUG, "  Mask %s\n", tmp);
103     }
104   }
105 
106   switch (phost->sa_family) {
107   case AF_INET:
108 #ifndef NOINET6
109   case AF_INET6:
110 #endif
111     ncprange_setsa(&range, phost, pmask);
112     if (ncprange_isdefault(&range))
113       prompt_Printf(prompt, "%-*s ", width - 1, "default");
114     else
115       prompt_Printf(prompt, "%-*s ", width - 1, ncprange_ntoa(&range));
116     return;
117 
118   case AF_LINK:
119     if (dl->sdl_nlen)
120       snprintf(buf, sizeof buf, "%.*s", dl->sdl_nlen, dl->sdl_data);
121     else if (dl->sdl_alen) {
122       if (dl->sdl_type == IFT_ETHER) {
123         if (dl->sdl_alen < sizeof buf / 3) {
124           int f;
125           u_char *MAC;
126 
127           MAC = (u_char *)dl->sdl_data + dl->sdl_nlen;
128           for (f = 0; f < dl->sdl_alen; f++)
129             sprintf(buf+f*3, "%02x:", MAC[f]);
130           buf[f*3-1] = '\0';
131         } else
132           strcpy(buf, "??:??:??:??:??:??");
133       } else
134         sprintf(buf, "<IFT type %d>", dl->sdl_type);
135     }  else if (dl->sdl_slen)
136       sprintf(buf, "<slen %d?>", dl->sdl_slen);
137     else
138       sprintf(buf, "link#%d", dl->sdl_index);
139     break;
140 
141   default:
142     sprintf(buf, "<AF type %d>", phost->sa_family);
143     break;
144   }
145 
146   prompt_Printf(prompt, "%-*s ", width-1, buf);
147 }
148 
149 static struct bits {
150   u_int32_t b_mask;
151   char b_val;
152 } bits[] = {
153   { RTF_UP, 'U' },
154   { RTF_GATEWAY, 'G' },
155   { RTF_HOST, 'H' },
156   { RTF_REJECT, 'R' },
157   { RTF_DYNAMIC, 'D' },
158   { RTF_MODIFIED, 'M' },
159   { RTF_DONE, 'd' },
160   { RTF_XRESOLVE, 'X' },
161   { RTF_STATIC, 'S' },
162   { RTF_PROTO1, '1' },
163   { RTF_PROTO2, '2' },
164   { RTF_BLACKHOLE, 'B' },
165 #ifdef RTF_LLINFO
166   { RTF_LLINFO, 'L' },
167 #endif
168 #ifdef RTF_CLONING
169   { RTF_CLONING, 'C' },
170 #endif
171 #ifdef RTF_PROTO3
172   { RTF_PROTO3, '3' },
173 #endif
174 #ifdef RTF_BROADCAST
175   { RTF_BROADCAST, 'b' },
176 #endif
177   { 0, '\0' }
178 };
179 
180 static void
181 p_flags(struct prompt *prompt, u_int32_t f, unsigned max)
182 {
183   char name[33], *flags;
184   register struct bits *p = bits;
185 
186   if (max > sizeof name - 1)
187     max = sizeof name - 1;
188 
189   for (flags = name; p->b_mask && flags - name < (int)max; p++)
190     if (p->b_mask & f)
191       *flags++ = p->b_val;
192   *flags = '\0';
193   prompt_Printf(prompt, "%-*.*s", (int)max, (int)max, name);
194 }
195 
196 static int route_nifs = -1;
197 
198 const char *
199 Index2Nam(int idx)
200 {
201   /*
202    * XXX: Maybe we should select() on the routing socket so that we can
203    *      notice interfaces that come & go (PCCARD support).
204    *      Or we could even support a signal that resets these so that
205    *      the PCCARD insert/remove events can signal ppp.
206    */
207   static char **ifs;		/* Figure these out once */
208   static int debug_done;	/* Debug once */
209 
210   if (idx > route_nifs || (idx > 0 && ifs[idx-1] == NULL)) {
211     int mib[6], have, had;
212     size_t needed;
213     char *buf, *ptr, *end;
214     struct sockaddr_dl *dl;
215     struct if_msghdr *ifm;
216 
217     if (ifs) {
218       free(ifs);
219       ifs = NULL;
220       route_nifs = 0;
221     }
222     debug_done = 0;
223 
224     mib[0] = CTL_NET;
225     mib[1] = PF_ROUTE;
226     mib[2] = 0;
227     mib[3] = 0;
228     mib[4] = NET_RT_IFLIST;
229     mib[5] = 0;
230 
231     if (sysctl(mib, 6, NULL, &needed, NULL, 0) < 0) {
232       log_Printf(LogERROR, "Index2Nam: sysctl: estimate: %s\n",
233                  strerror(errno));
234       return NumStr(idx, NULL, 0);
235     }
236     if ((buf = malloc(needed)) == NULL)
237       return NumStr(idx, NULL, 0);
238     if (sysctl(mib, 6, buf, &needed, NULL, 0) < 0) {
239       free(buf);
240       return NumStr(idx, NULL, 0);
241     }
242     end = buf + needed;
243 
244     have = 0;
245     for (ptr = buf; ptr < end; ptr += ifm->ifm_msglen) {
246       ifm = (struct if_msghdr *)ptr;
247       if (ifm->ifm_type != RTM_IFINFO)
248         continue;
249       dl = (struct sockaddr_dl *)(ifm + 1);
250       if (ifm->ifm_index > 0) {
251         if (ifm->ifm_index > have) {
252           char **newifs;
253 
254           had = have;
255           have = ifm->ifm_index + 5;
256           if (had)
257             newifs = (char **)realloc(ifs, sizeof(char *) * have);
258           else
259             newifs = (char **)malloc(sizeof(char *) * have);
260           if (!newifs) {
261             log_Printf(LogDEBUG, "Index2Nam: %s\n", strerror(errno));
262             route_nifs = 0;
263             if (ifs) {
264               free(ifs);
265               ifs = NULL;
266             }
267             free(buf);
268             return NumStr(idx, NULL, 0);
269           }
270           ifs = newifs;
271           memset(ifs + had, '\0', sizeof(char *) * (have - had));
272         }
273         if (ifs[ifm->ifm_index-1] == NULL) {
274           ifs[ifm->ifm_index-1] = (char *)malloc(dl->sdl_nlen+1);
275           if (ifs[ifm->ifm_index-1] == NULL)
276 	    log_Printf(LogDEBUG, "Skipping interface %d: Out of memory\n",
277                   ifm->ifm_index);
278 	  else {
279 	    memcpy(ifs[ifm->ifm_index-1], dl->sdl_data, dl->sdl_nlen);
280 	    ifs[ifm->ifm_index-1][dl->sdl_nlen] = '\0';
281 	    if (route_nifs < ifm->ifm_index)
282 	      route_nifs = ifm->ifm_index;
283 	  }
284         }
285       } else if (log_IsKept(LogDEBUG))
286         log_Printf(LogDEBUG, "Skipping out-of-range interface %d!\n",
287                   ifm->ifm_index);
288     }
289     free(buf);
290   }
291 
292   if (log_IsKept(LogDEBUG) && !debug_done) {
293     int f;
294 
295     log_Printf(LogDEBUG, "Found the following interfaces:\n");
296     for (f = 0; f < route_nifs; f++)
297       if (ifs[f] != NULL)
298         log_Printf(LogDEBUG, " Index %d, name \"%s\"\n", f+1, ifs[f]);
299     debug_done = 1;
300   }
301 
302   if (idx < 1 || idx > route_nifs || ifs[idx-1] == NULL)
303     return NumStr(idx, NULL, 0);
304 
305   return ifs[idx-1];
306 }
307 
308 void
309 route_ParseHdr(struct rt_msghdr *rtm, struct sockaddr *sa[RTAX_MAX])
310 {
311   char *wp;
312   int rtax;
313 
314   wp = (char *)(rtm + 1);
315 
316   for (rtax = 0; rtax < RTAX_MAX; rtax++)
317     if (rtm->rtm_addrs & (1 << rtax)) {
318       sa[rtax] = (struct sockaddr *)wp;
319       wp += ROUNDUP(sa[rtax]->sa_len);
320       if (sa[rtax]->sa_family == 0)
321         sa[rtax] = NULL;	/* ??? */
322     } else
323       sa[rtax] = NULL;
324 }
325 
326 int
327 route_Show(struct cmdargs const *arg)
328 {
329   struct rt_msghdr *rtm;
330   struct sockaddr *sa[RTAX_MAX];
331   char *sp, *ep, *cp;
332   size_t needed;
333   int mib[6];
334 
335   mib[0] = CTL_NET;
336   mib[1] = PF_ROUTE;
337   mib[2] = 0;
338   mib[3] = 0;
339   mib[4] = NET_RT_DUMP;
340   mib[5] = 0;
341   if (sysctl(mib, 6, NULL, &needed, NULL, 0) < 0) {
342     log_Printf(LogERROR, "route_Show: sysctl: estimate: %s\n", strerror(errno));
343     return (1);
344   }
345   sp = malloc(needed);
346   if (sp == NULL)
347     return (1);
348   if (sysctl(mib, 6, sp, &needed, NULL, 0) < 0) {
349     log_Printf(LogERROR, "route_Show: sysctl: getroute: %s\n", strerror(errno));
350     free(sp);
351     return (1);
352   }
353   ep = sp + needed;
354 
355   prompt_Printf(arg->prompt, "%-20s%-20sFlags  Netif\n",
356                 "Destination", "Gateway");
357   for (cp = sp; cp < ep; cp += rtm->rtm_msglen) {
358     rtm = (struct rt_msghdr *)cp;
359 
360     route_ParseHdr(rtm, sa);
361 
362     if (sa[RTAX_DST] && sa[RTAX_GATEWAY]) {
363       p_sockaddr(arg->prompt, sa[RTAX_DST], sa[RTAX_NETMASK], 20);
364       p_sockaddr(arg->prompt, sa[RTAX_GATEWAY], NULL, 20);
365 
366       p_flags(arg->prompt, rtm->rtm_flags, 6);
367       prompt_Printf(arg->prompt, " %s\n", Index2Nam(rtm->rtm_index));
368     } else
369       prompt_Printf(arg->prompt, "<can't parse routing entry>\n");
370   }
371   free(sp);
372   return 0;
373 }
374 
375 /*
376  *  Delete routes associated with our interface
377  */
378 void
379 route_IfDelete(struct bundle *bundle, int all)
380 {
381   struct rt_msghdr *rtm;
382   struct sockaddr *sa[RTAX_MAX];
383   struct ncprange range;
384   int pass;
385   size_t needed;
386   char *sp, *cp, *ep;
387   int mib[6];
388 
389   log_Printf(LogDEBUG, "route_IfDelete (%d)\n", bundle->iface->index);
390 
391   mib[0] = CTL_NET;
392   mib[1] = PF_ROUTE;
393   mib[2] = 0;
394   mib[3] = 0;
395   mib[4] = NET_RT_DUMP;
396   mib[5] = 0;
397   if (sysctl(mib, 6, NULL, &needed, NULL, 0) < 0) {
398     log_Printf(LogERROR, "route_IfDelete: sysctl: estimate: %s\n",
399               strerror(errno));
400     return;
401   }
402 
403   sp = malloc(needed);
404   if (sp == NULL)
405     return;
406 
407   if (sysctl(mib, 6, sp, &needed, NULL, 0) < 0) {
408     log_Printf(LogERROR, "route_IfDelete: sysctl: getroute: %s\n",
409               strerror(errno));
410     free(sp);
411     return;
412   }
413   ep = sp + needed;
414 
415   for (pass = 0; pass < 2; pass++) {
416     /*
417      * We do 2 passes.  The first deletes all cloned routes.  The second
418      * deletes all non-cloned routes.  This is done to avoid
419      * potential errors from trying to delete route X after route Y where
420      * route X was cloned from route Y (and is no longer there 'cos it
421      * may have gone with route Y).
422      */
423     if (pass == 0)
424       /* So we can't tell ! */
425       continue;
426     for (cp = sp; cp < ep; cp += rtm->rtm_msglen) {
427       rtm = (struct rt_msghdr *)cp;
428       route_ParseHdr(rtm, sa);
429       if (rtm->rtm_index == bundle->iface->index &&
430           sa[RTAX_DST] && sa[RTAX_GATEWAY] &&
431           (sa[RTAX_DST]->sa_family == AF_INET
432 #ifndef NOINET6
433            || sa[RTAX_DST]->sa_family == AF_INET6
434 #endif
435            ) &&
436           (all || (rtm->rtm_flags & RTF_GATEWAY))) {
437         if (log_IsKept(LogDEBUG)) {
438           char gwstr[41];
439           struct ncpaddr gw;
440           ncprange_setsa(&range, sa[RTAX_DST], sa[RTAX_NETMASK]);
441           ncpaddr_setsa(&gw, sa[RTAX_GATEWAY]);
442           snprintf(gwstr, sizeof gwstr, "%s", ncpaddr_ntoa(&gw));
443           log_Printf(LogDEBUG, "Found %s %s\n", ncprange_ntoa(&range), gwstr);
444         }
445         if (sa[RTAX_GATEWAY]->sa_family == AF_INET ||
446 #ifndef NOINET6
447             sa[RTAX_GATEWAY]->sa_family == AF_INET6 ||
448 #endif
449             sa[RTAX_GATEWAY]->sa_family == AF_LINK) {
450           if (pass == 1) {
451             ncprange_setsa(&range, sa[RTAX_DST], sa[RTAX_NETMASK]);
452             rt_Set(bundle, RTM_DELETE, &range, NULL, 0, 0);
453           } else
454             log_Printf(LogDEBUG, "route_IfDelete: Skip it (pass %d)\n", pass);
455         } else
456           log_Printf(LogDEBUG,
457                     "route_IfDelete: Can't remove routes for family %d\n",
458                     sa[RTAX_GATEWAY]->sa_family);
459       }
460     }
461   }
462   free(sp);
463 }
464 
465 
466 /*
467  *  Update the MTU on all routes for the given interface
468  */
469 void
470 route_UpdateMTU(struct bundle *bundle)
471 {
472   struct rt_msghdr *rtm;
473   struct sockaddr *sa[RTAX_MAX];
474   struct ncprange dst;
475   size_t needed;
476   char *sp, *cp, *ep;
477   int mib[6];
478 
479   log_Printf(LogDEBUG, "route_UpdateMTU (%d)\n", bundle->iface->index);
480 
481   mib[0] = CTL_NET;
482   mib[1] = PF_ROUTE;
483   mib[2] = 0;
484   mib[3] = 0;
485   mib[4] = NET_RT_DUMP;
486   mib[5] = 0;
487   if (sysctl(mib, 6, NULL, &needed, NULL, 0) < 0) {
488     log_Printf(LogERROR, "route_IfDelete: sysctl: estimate: %s\n",
489               strerror(errno));
490     return;
491   }
492 
493   sp = malloc(needed);
494   if (sp == NULL)
495     return;
496 
497   if (sysctl(mib, 6, sp, &needed, NULL, 0) < 0) {
498     log_Printf(LogERROR, "route_IfDelete: sysctl: getroute: %s\n",
499               strerror(errno));
500     free(sp);
501     return;
502   }
503   ep = sp + needed;
504 
505   for (cp = sp; cp < ep; cp += rtm->rtm_msglen) {
506     rtm = (struct rt_msghdr *)cp;
507     route_ParseHdr(rtm, sa);
508     if (sa[RTAX_DST] && (sa[RTAX_DST]->sa_family == AF_INET
509 #ifndef NOINET6
510                          || sa[RTAX_DST]->sa_family == AF_INET6
511 #endif
512                         ) &&
513         sa[RTAX_GATEWAY] && rtm->rtm_index == bundle->iface->index) {
514       if (log_IsKept(LogTCPIP)) {
515         ncprange_setsa(&dst, sa[RTAX_DST], sa[RTAX_NETMASK]);
516         log_Printf(LogTCPIP, "route_UpdateMTU: Netif: %d (%s), dst %s,"
517                    " mtu %lu\n", rtm->rtm_index, Index2Nam(rtm->rtm_index),
518                    ncprange_ntoa(&dst), bundle->iface->mtu);
519       }
520       rt_Update(bundle, sa[RTAX_DST], sa[RTAX_GATEWAY], sa[RTAX_NETMASK],
521                 sa[RTAX_IFP], sa[RTAX_IFA]);
522     }
523   }
524 
525   free(sp);
526 }
527 
528 int
529 GetIfIndex(char *name)
530 {
531   int idx;
532 
533   idx = 1;
534   while (route_nifs == -1 || idx < route_nifs)
535     if (strcmp(Index2Nam(idx), name) == 0)
536       return idx;
537     else
538       idx++;
539   return -1;
540 }
541 
542 void
543 route_Change(struct bundle *bundle, struct sticky_route *r,
544              const struct ncpaddr *me, const struct ncpaddr *peer)
545 {
546   struct ncpaddr dst;
547 
548   for (; r; r = r->next) {
549     ncprange_getaddr(&r->dst, &dst);
550     if (ncpaddr_family(me) == AF_INET) {
551       if ((r->type & ROUTE_DSTMYADDR) && !ncpaddr_equal(&dst, me)) {
552         rt_Set(bundle, RTM_DELETE, &r->dst, NULL, 1, 0);
553         ncprange_sethost(&r->dst, me);
554         if (r->type & ROUTE_GWHISADDR)
555           ncpaddr_copy(&r->gw, peer);
556       } else if ((r->type & ROUTE_DSTHISADDR) && !ncpaddr_equal(&dst, peer)) {
557         rt_Set(bundle, RTM_DELETE, &r->dst, NULL, 1, 0);
558         ncprange_sethost(&r->dst, peer);
559         if (r->type & ROUTE_GWHISADDR)
560           ncpaddr_copy(&r->gw, peer);
561       } else if ((r->type & ROUTE_DSTDNS0) && !ncpaddr_equal(&dst, peer)) {
562         if (bundle->ncp.ipcp.ns.dns[0].s_addr == INADDR_NONE)
563           continue;
564         rt_Set(bundle, RTM_DELETE, &r->dst, NULL, 1, 0);
565         if (r->type & ROUTE_GWHISADDR)
566           ncpaddr_copy(&r->gw, peer);
567       } else if ((r->type & ROUTE_DSTDNS1) && !ncpaddr_equal(&dst, peer)) {
568         if (bundle->ncp.ipcp.ns.dns[1].s_addr == INADDR_NONE)
569           continue;
570         rt_Set(bundle, RTM_DELETE, &r->dst, NULL, 1, 0);
571         if (r->type & ROUTE_GWHISADDR)
572           ncpaddr_copy(&r->gw, peer);
573       } else if ((r->type & ROUTE_GWHISADDR) && !ncpaddr_equal(&r->gw, peer))
574         ncpaddr_copy(&r->gw, peer);
575 #ifndef NOINET6
576     } else if (ncpaddr_family(me) == AF_INET6) {
577       if ((r->type & ROUTE_DSTMYADDR6) && !ncpaddr_equal(&dst, me)) {
578         rt_Set(bundle, RTM_DELETE, &r->dst, NULL, 1, 0);
579         ncprange_sethost(&r->dst, me);
580         if (r->type & ROUTE_GWHISADDR)
581           ncpaddr_copy(&r->gw, peer);
582       } else if ((r->type & ROUTE_DSTHISADDR6) && !ncpaddr_equal(&dst, peer)) {
583         rt_Set(bundle, RTM_DELETE, &r->dst, NULL, 1, 0);
584         ncprange_sethost(&r->dst, peer);
585         if (r->type & ROUTE_GWHISADDR)
586           ncpaddr_copy(&r->gw, peer);
587       } else if ((r->type & ROUTE_GWHISADDR6) && !ncpaddr_equal(&r->gw, peer))
588         ncpaddr_copy(&r->gw, peer);
589 #endif
590     }
591     rt_Set(bundle, RTM_ADD, &r->dst, &r->gw, 1, 0);
592   }
593 }
594 
595 void
596 route_Add(struct sticky_route **rp, int type, const struct ncprange *dst,
597           const struct ncpaddr *gw)
598 {
599   struct sticky_route *r;
600   int dsttype = type & ROUTE_DSTANY;
601 
602   r = NULL;
603   while (*rp) {
604     if ((dsttype && dsttype == ((*rp)->type & ROUTE_DSTANY)) ||
605         (!dsttype && ncprange_equal(&(*rp)->dst, dst))) {
606       /* Oops, we already have this route - unlink it */
607       free(r);			/* impossible really  */
608       r = *rp;
609       *rp = r->next;
610     } else
611       rp = &(*rp)->next;
612   }
613 
614   if (r == NULL) {
615     r = (struct sticky_route *)malloc(sizeof(struct sticky_route));
616     if (r == NULL) {
617       log_Printf(LogERROR, "route_Add: Out of memory!\n");
618       return;
619     }
620   }
621   r->type = type;
622   r->next = NULL;
623   ncprange_copy(&r->dst, dst);
624   ncpaddr_copy(&r->gw, gw);
625   *rp = r;
626 }
627 
628 void
629 route_Delete(struct sticky_route **rp, int type, const struct ncprange *dst)
630 {
631   struct sticky_route *r;
632   int dsttype = type & ROUTE_DSTANY;
633 
634   for (; *rp; rp = &(*rp)->next) {
635     if ((dsttype && dsttype == ((*rp)->type & ROUTE_DSTANY)) ||
636         (!dsttype && ncprange_equal(dst, &(*rp)->dst))) {
637       r = *rp;
638       *rp = r->next;
639       free(r);
640       break;
641     }
642   }
643 }
644 
645 void
646 route_DeleteAll(struct sticky_route **rp)
647 {
648   struct sticky_route *r, *rn;
649 
650   for (r = *rp; r; r = rn) {
651     rn = r->next;
652     free(r);
653   }
654   *rp = NULL;
655 }
656 
657 void
658 route_ShowSticky(struct prompt *p, struct sticky_route *r, const char *tag,
659                  int indent)
660 {
661   int tlen = strlen(tag);
662 
663   if (tlen + 2 > indent)
664     prompt_Printf(p, "%s:\n%*s", tag, indent, "");
665   else
666     prompt_Printf(p, "%s:%*s", tag, indent - tlen - 1, "");
667 
668   for (; r; r = r->next) {
669     prompt_Printf(p, "%*sadd ", tlen ? 0 : indent, "");
670     tlen = 0;
671     if (r->type & ROUTE_DSTMYADDR)
672       prompt_Printf(p, "MYADDR");
673     else if (r->type & ROUTE_DSTMYADDR6)
674       prompt_Printf(p, "MYADDR6");
675     else if (r->type & ROUTE_DSTHISADDR)
676       prompt_Printf(p, "HISADDR");
677     else if (r->type & ROUTE_DSTHISADDR6)
678       prompt_Printf(p, "HISADDR6");
679     else if (r->type & ROUTE_DSTDNS0)
680       prompt_Printf(p, "DNS0");
681     else if (r->type & ROUTE_DSTDNS1)
682       prompt_Printf(p, "DNS1");
683     else if (ncprange_isdefault(&r->dst))
684       prompt_Printf(p, "default");
685     else
686       prompt_Printf(p, "%s", ncprange_ntoa(&r->dst));
687 
688     if (r->type & ROUTE_GWHISADDR)
689       prompt_Printf(p, " HISADDR\n");
690     else if (r->type & ROUTE_GWHISADDR6)
691       prompt_Printf(p, " HISADDR6\n");
692     else
693       prompt_Printf(p, " %s\n", ncpaddr_ntoa(&r->gw));
694   }
695 }
696 
697 struct rtmsg {
698   struct rt_msghdr m_rtm;
699   char m_space[256];
700 };
701 
702 static size_t
703 memcpy_roundup(char *cp, const void *data, size_t len)
704 {
705   size_t padlen;
706 
707   padlen = ROUNDUP(len);
708   memcpy(cp, data, len);
709   if (padlen > len)
710     memset(cp + len, '\0', padlen - len);
711 
712   return padlen;
713 }
714 
715 #if defined(__KAME__) && !defined(NOINET6)
716 static void
717 add_scope(struct sockaddr *sa, int ifindex)
718 {
719   struct sockaddr_in6 *sa6;
720 
721   if (sa->sa_family != AF_INET6)
722     return;
723   sa6 = (struct sockaddr_in6 *)sa;
724   if (!IN6_IS_ADDR_LINKLOCAL(&sa6->sin6_addr) &&
725       !IN6_IS_ADDR_MC_LINKLOCAL(&sa6->sin6_addr))
726     return;
727   if (*(u_int16_t *)&sa6->sin6_addr.s6_addr[2] != 0)
728     return;
729   *(u_int16_t *)&sa6->sin6_addr.s6_addr[2] = htons(ifindex);
730 }
731 #endif
732 
733 int
734 rt_Set(struct bundle *bundle, int cmd, const struct ncprange *dst,
735        const struct ncpaddr *gw, int bang, int quiet)
736 {
737   struct rtmsg rtmes;
738   int s, nb, wb;
739   char *cp;
740   const char *cmdstr;
741   struct sockaddr_storage sadst, samask, sagw;
742   int result = 1;
743 
744   if (bang)
745     cmdstr = (cmd == RTM_ADD ? "Add!" : "Delete!");
746   else
747     cmdstr = (cmd == RTM_ADD ? "Add" : "Delete");
748   s = ID0socket(PF_ROUTE, SOCK_RAW, 0);
749   if (s < 0) {
750     log_Printf(LogERROR, "rt_Set: socket(): %s\n", strerror(errno));
751     return result;
752   }
753   memset(&rtmes, '\0', sizeof rtmes);
754   rtmes.m_rtm.rtm_version = RTM_VERSION;
755   rtmes.m_rtm.rtm_type = cmd;
756   rtmes.m_rtm.rtm_addrs = RTA_DST;
757   rtmes.m_rtm.rtm_seq = ++bundle->routing_seq;
758   rtmes.m_rtm.rtm_pid = getpid();
759   rtmes.m_rtm.rtm_flags = RTF_UP | RTF_GATEWAY | RTF_STATIC;
760 
761   if (cmd == RTM_ADD) {
762     if (bundle->ncp.cfg.sendpipe > 0) {
763       rtmes.m_rtm.rtm_rmx.rmx_sendpipe = bundle->ncp.cfg.sendpipe;
764       rtmes.m_rtm.rtm_inits |= RTV_SPIPE;
765     }
766     if (bundle->ncp.cfg.recvpipe > 0) {
767       rtmes.m_rtm.rtm_rmx.rmx_recvpipe = bundle->ncp.cfg.recvpipe;
768       rtmes.m_rtm.rtm_inits |= RTV_RPIPE;
769     }
770   }
771 
772   ncprange_getsa(dst, &sadst, &samask);
773 #if defined(__KAME__) && !defined(NOINET6)
774   add_scope((struct sockaddr *)&sadst, bundle->iface->index);
775 #endif
776 
777   cp = rtmes.m_space;
778   cp += memcpy_roundup(cp, &sadst, sadst.ss_len);
779   if (cmd == RTM_ADD) {
780     if (gw == NULL) {
781       log_Printf(LogERROR, "rt_Set: Program error\n");
782       close(s);
783       return result;
784     }
785     ncpaddr_getsa(gw, &sagw);
786 #if defined(__KAME__) && !defined(NOINET6)
787     add_scope((struct sockaddr *)&sagw, bundle->iface->index);
788 #endif
789     if (ncpaddr_isdefault(gw)) {
790       if (!quiet)
791         log_Printf(LogERROR, "rt_Set: Cannot add a route with"
792                    " gateway 0.0.0.0\n");
793       close(s);
794       return result;
795     } else {
796       cp += memcpy_roundup(cp, &sagw, sagw.ss_len);
797       rtmes.m_rtm.rtm_addrs |= RTA_GATEWAY;
798     }
799   }
800 
801   if (!ncprange_ishost(dst)) {
802     cp += memcpy_roundup(cp, &samask, samask.ss_len);
803     rtmes.m_rtm.rtm_addrs |= RTA_NETMASK;
804   }
805 
806   nb = cp - (char *)&rtmes;
807   rtmes.m_rtm.rtm_msglen = nb;
808   wb = ID0write(s, &rtmes, nb);
809   if (wb < 0) {
810     log_Printf(LogTCPIP, "rt_Set failure:\n");
811     log_Printf(LogTCPIP, "rt_Set:  Cmd = %s\n", cmdstr);
812     log_Printf(LogTCPIP, "rt_Set:  Dst = %s\n", ncprange_ntoa(dst));
813     if (gw != NULL)
814       log_Printf(LogTCPIP, "rt_Set:  Gateway = %s\n", ncpaddr_ntoa(gw));
815 failed:
816     if (cmd == RTM_ADD && (rtmes.m_rtm.rtm_errno == EEXIST ||
817                            (rtmes.m_rtm.rtm_errno == 0 && errno == EEXIST))) {
818       if (!bang) {
819         log_Printf(LogWARN, "Add route failed: %s already exists\n",
820 		   ncprange_ntoa(dst));
821         result = 0;	/* Don't add to our dynamic list */
822       } else {
823         rtmes.m_rtm.rtm_type = cmd = RTM_CHANGE;
824         if ((wb = ID0write(s, &rtmes, nb)) < 0)
825           goto failed;
826       }
827     } else if (cmd == RTM_DELETE &&
828              (rtmes.m_rtm.rtm_errno == ESRCH ||
829               (rtmes.m_rtm.rtm_errno == 0 && errno == ESRCH))) {
830       if (!bang)
831         log_Printf(LogWARN, "Del route failed: %s: Non-existent\n",
832                   ncprange_ntoa(dst));
833     } else if (rtmes.m_rtm.rtm_errno == 0) {
834       if (!quiet || errno != ENETUNREACH)
835         log_Printf(LogWARN, "%s route failed: %s: errno: %s\n", cmdstr,
836                    ncprange_ntoa(dst), strerror(errno));
837     } else
838       log_Printf(LogWARN, "%s route failed: %s: %s\n",
839 		 cmdstr, ncprange_ntoa(dst), strerror(rtmes.m_rtm.rtm_errno));
840   }
841 
842   if (log_IsKept(LogDEBUG)) {
843     char gwstr[40];
844 
845     if (gw)
846       snprintf(gwstr, sizeof gwstr, "%s", ncpaddr_ntoa(gw));
847     else
848       snprintf(gwstr, sizeof gwstr, "<none>");
849     log_Printf(LogDEBUG, "wrote %d: cmd = %s, dst = %s, gateway = %s\n",
850                wb, cmdstr, ncprange_ntoa(dst), gwstr);
851   }
852   close(s);
853 
854   return result;
855 }
856 
857 void
858 rt_Update(struct bundle *bundle, const struct sockaddr *dst,
859           const struct sockaddr *gw, const struct sockaddr *mask,
860           const struct sockaddr *ifp, const struct sockaddr *ifa)
861 {
862   struct ncprange ncpdst;
863   struct rtmsg rtmes;
864   char *p;
865   int s, wb;
866 
867   s = ID0socket(PF_ROUTE, SOCK_RAW, 0);
868   if (s < 0) {
869     log_Printf(LogERROR, "rt_Update: socket(): %s\n", strerror(errno));
870     return;
871   }
872 
873   memset(&rtmes, '\0', sizeof rtmes);
874   rtmes.m_rtm.rtm_version = RTM_VERSION;
875   rtmes.m_rtm.rtm_type = RTM_CHANGE;
876   rtmes.m_rtm.rtm_addrs = 0;
877   rtmes.m_rtm.rtm_seq = ++bundle->routing_seq;
878   rtmes.m_rtm.rtm_pid = getpid();
879   rtmes.m_rtm.rtm_flags = RTF_UP | RTF_STATIC;
880 
881   if (bundle->ncp.cfg.sendpipe > 0) {
882     rtmes.m_rtm.rtm_rmx.rmx_sendpipe = bundle->ncp.cfg.sendpipe;
883     rtmes.m_rtm.rtm_inits |= RTV_SPIPE;
884   }
885 
886   if (bundle->ncp.cfg.recvpipe > 0) {
887     rtmes.m_rtm.rtm_rmx.rmx_recvpipe = bundle->ncp.cfg.recvpipe;
888     rtmes.m_rtm.rtm_inits |= RTV_RPIPE;
889   }
890 
891   rtmes.m_rtm.rtm_rmx.rmx_mtu = bundle->iface->mtu;
892   rtmes.m_rtm.rtm_inits |= RTV_MTU;
893   p = rtmes.m_space;
894 
895   if (dst) {
896     rtmes.m_rtm.rtm_addrs |= RTA_DST;
897     p += memcpy_roundup(p, dst, dst->sa_len);
898   }
899 
900   if (gw) {
901     rtmes.m_rtm.rtm_addrs |= RTA_GATEWAY;
902     p += memcpy_roundup(p, gw, gw->sa_len);
903   }
904 
905   if (mask) {
906     rtmes.m_rtm.rtm_addrs |= RTA_NETMASK;
907     p += memcpy_roundup(p, mask, mask->sa_len);
908   }
909 
910   if (ifa && ifp && ifp->sa_family == AF_LINK) {
911     rtmes.m_rtm.rtm_addrs |= RTA_IFP;
912     p += memcpy_roundup(p, ifp, ifp->sa_len);
913     rtmes.m_rtm.rtm_addrs |= RTA_IFA;
914     p += memcpy_roundup(p, ifa, ifa->sa_len);
915   }
916 
917   rtmes.m_rtm.rtm_msglen = p - (char *)&rtmes;
918 
919   wb = ID0write(s, &rtmes, rtmes.m_rtm.rtm_msglen);
920   if (wb < 0) {
921     ncprange_setsa(&ncpdst, dst, mask);
922 
923     log_Printf(LogTCPIP, "rt_Update failure:\n");
924     log_Printf(LogTCPIP, "rt_Update:  Dst = %s\n", ncprange_ntoa(&ncpdst));
925 
926     if (rtmes.m_rtm.rtm_errno == 0)
927       log_Printf(LogWARN, "%s: Change route failed: errno: %s\n",
928                  ncprange_ntoa(&ncpdst), strerror(errno));
929     else
930       log_Printf(LogWARN, "%s: Change route failed: %s\n",
931 		 ncprange_ntoa(&ncpdst), strerror(rtmes.m_rtm.rtm_errno));
932   }
933   close(s);
934 }
935