xref: /freebsd/usr.sbin/ppp/route.c (revision ad30f8e79bd1007cc2476e491bd21b4f5e389e0a)
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 #ifdef RTF_CLONING
162   { RTF_CLONING, 'C' },
163 #endif
164   { RTF_STATIC, 'S' },
165   { RTF_PROTO1, '1' },
166   { RTF_PROTO2, '2' },
167   { RTF_BLACKHOLE, 'B' },
168 
169 #ifdef RTF_LLINFO
170   { RTF_LLINFO, 'L' },
171 #endif
172 #ifdef RTF_CLONING
173   { RTF_CLONING, 'C' },
174 #endif
175 #ifdef RTF_WASCLONED
176   { RTF_WASCLONED, 'W' },
177 #endif
178 #ifdef RTF_PRCLONING
179   { RTF_PRCLONING, 'c' },
180 #endif
181 #ifdef RTF_PROTO3
182   { RTF_PROTO3, '3' },
183 #endif
184 #ifdef RTF_BROADCAST
185   { RTF_BROADCAST, 'b' },
186 #endif
187   { 0, '\0' }
188 };
189 
190 #ifndef RTF_WASCLONED
191 #define RTF_WASCLONED (0)
192 #endif
193 
194 static void
195 p_flags(struct prompt *prompt, u_int32_t f, unsigned max)
196 {
197   char name[33], *flags;
198   register struct bits *p = bits;
199 
200   if (max > sizeof name - 1)
201     max = sizeof name - 1;
202 
203   for (flags = name; p->b_mask && flags - name < (int)max; p++)
204     if (p->b_mask & f)
205       *flags++ = p->b_val;
206   *flags = '\0';
207   prompt_Printf(prompt, "%-*.*s", (int)max, (int)max, name);
208 }
209 
210 static int route_nifs = -1;
211 
212 const char *
213 Index2Nam(int idx)
214 {
215   /*
216    * XXX: Maybe we should select() on the routing socket so that we can
217    *      notice interfaces that come & go (PCCARD support).
218    *      Or we could even support a signal that resets these so that
219    *      the PCCARD insert/remove events can signal ppp.
220    */
221   static char **ifs;		/* Figure these out once */
222   static int debug_done;	/* Debug once */
223 
224   if (idx > route_nifs || (idx > 0 && ifs[idx-1] == NULL)) {
225     int mib[6], have, had;
226     size_t needed;
227     char *buf, *ptr, *end;
228     struct sockaddr_dl *dl;
229     struct if_msghdr *ifm;
230 
231     if (ifs) {
232       free(ifs);
233       ifs = NULL;
234       route_nifs = 0;
235     }
236     debug_done = 0;
237 
238     mib[0] = CTL_NET;
239     mib[1] = PF_ROUTE;
240     mib[2] = 0;
241     mib[3] = 0;
242     mib[4] = NET_RT_IFLIST;
243     mib[5] = 0;
244 
245     if (sysctl(mib, 6, NULL, &needed, NULL, 0) < 0) {
246       log_Printf(LogERROR, "Index2Nam: sysctl: estimate: %s\n",
247                  strerror(errno));
248       return NumStr(idx, NULL, 0);
249     }
250     if ((buf = malloc(needed)) == NULL)
251       return NumStr(idx, NULL, 0);
252     if (sysctl(mib, 6, buf, &needed, NULL, 0) < 0) {
253       free(buf);
254       return NumStr(idx, NULL, 0);
255     }
256     end = buf + needed;
257 
258     have = 0;
259     for (ptr = buf; ptr < end; ptr += ifm->ifm_msglen) {
260       ifm = (struct if_msghdr *)ptr;
261       if (ifm->ifm_type != RTM_IFINFO)
262         continue;
263       dl = (struct sockaddr_dl *)(ifm + 1);
264       if (ifm->ifm_index > 0) {
265         if (ifm->ifm_index > have) {
266           char **newifs;
267 
268           had = have;
269           have = ifm->ifm_index + 5;
270           if (had)
271             newifs = (char **)realloc(ifs, sizeof(char *) * have);
272           else
273             newifs = (char **)malloc(sizeof(char *) * have);
274           if (!newifs) {
275             log_Printf(LogDEBUG, "Index2Nam: %s\n", strerror(errno));
276             route_nifs = 0;
277             if (ifs) {
278               free(ifs);
279               ifs = NULL;
280             }
281             free(buf);
282             return NumStr(idx, NULL, 0);
283           }
284           ifs = newifs;
285           memset(ifs + had, '\0', sizeof(char *) * (have - had));
286         }
287         if (ifs[ifm->ifm_index-1] == NULL) {
288           ifs[ifm->ifm_index-1] = (char *)malloc(dl->sdl_nlen+1);
289           if (ifs[ifm->ifm_index-1] == NULL)
290 	    log_Printf(LogDEBUG, "Skipping interface %d: Out of memory\n",
291                   ifm->ifm_index);
292 	  else {
293 	    memcpy(ifs[ifm->ifm_index-1], dl->sdl_data, dl->sdl_nlen);
294 	    ifs[ifm->ifm_index-1][dl->sdl_nlen] = '\0';
295 	    if (route_nifs < ifm->ifm_index)
296 	      route_nifs = ifm->ifm_index;
297 	  }
298         }
299       } else if (log_IsKept(LogDEBUG))
300         log_Printf(LogDEBUG, "Skipping out-of-range interface %d!\n",
301                   ifm->ifm_index);
302     }
303     free(buf);
304   }
305 
306   if (log_IsKept(LogDEBUG) && !debug_done) {
307     int f;
308 
309     log_Printf(LogDEBUG, "Found the following interfaces:\n");
310     for (f = 0; f < route_nifs; f++)
311       if (ifs[f] != NULL)
312         log_Printf(LogDEBUG, " Index %d, name \"%s\"\n", f+1, ifs[f]);
313     debug_done = 1;
314   }
315 
316   if (idx < 1 || idx > route_nifs || ifs[idx-1] == NULL)
317     return NumStr(idx, NULL, 0);
318 
319   return ifs[idx-1];
320 }
321 
322 void
323 route_ParseHdr(struct rt_msghdr *rtm, struct sockaddr *sa[RTAX_MAX])
324 {
325   char *wp;
326   int rtax;
327 
328   wp = (char *)(rtm + 1);
329 
330   for (rtax = 0; rtax < RTAX_MAX; rtax++)
331     if (rtm->rtm_addrs & (1 << rtax)) {
332       sa[rtax] = (struct sockaddr *)wp;
333       wp += ROUNDUP(sa[rtax]->sa_len);
334       if (sa[rtax]->sa_family == 0)
335         sa[rtax] = NULL;	/* ??? */
336     } else
337       sa[rtax] = NULL;
338 }
339 
340 int
341 route_Show(struct cmdargs const *arg)
342 {
343   struct rt_msghdr *rtm;
344   struct sockaddr *sa[RTAX_MAX];
345   char *sp, *ep, *cp;
346   size_t needed;
347   int mib[6];
348 
349   mib[0] = CTL_NET;
350   mib[1] = PF_ROUTE;
351   mib[2] = 0;
352   mib[3] = 0;
353   mib[4] = NET_RT_DUMP;
354   mib[5] = 0;
355   if (sysctl(mib, 6, NULL, &needed, NULL, 0) < 0) {
356     log_Printf(LogERROR, "route_Show: sysctl: estimate: %s\n", strerror(errno));
357     return (1);
358   }
359   sp = malloc(needed);
360   if (sp == NULL)
361     return (1);
362   if (sysctl(mib, 6, sp, &needed, NULL, 0) < 0) {
363     log_Printf(LogERROR, "route_Show: sysctl: getroute: %s\n", strerror(errno));
364     free(sp);
365     return (1);
366   }
367   ep = sp + needed;
368 
369   prompt_Printf(arg->prompt, "%-20s%-20sFlags  Netif\n",
370                 "Destination", "Gateway");
371   for (cp = sp; cp < ep; cp += rtm->rtm_msglen) {
372     rtm = (struct rt_msghdr *)cp;
373 
374     route_ParseHdr(rtm, sa);
375 
376     if (sa[RTAX_DST] && sa[RTAX_GATEWAY]) {
377       p_sockaddr(arg->prompt, sa[RTAX_DST], sa[RTAX_NETMASK], 20);
378       p_sockaddr(arg->prompt, sa[RTAX_GATEWAY], NULL, 20);
379 
380       p_flags(arg->prompt, rtm->rtm_flags, 6);
381       prompt_Printf(arg->prompt, " %s\n", Index2Nam(rtm->rtm_index));
382     } else
383       prompt_Printf(arg->prompt, "<can't parse routing entry>\n");
384   }
385   free(sp);
386   return 0;
387 }
388 
389 /*
390  *  Delete routes associated with our interface
391  */
392 void
393 route_IfDelete(struct bundle *bundle, int all)
394 {
395   struct rt_msghdr *rtm;
396   struct sockaddr *sa[RTAX_MAX];
397   struct ncprange range;
398   int pass;
399   size_t needed;
400   char *sp, *cp, *ep;
401   int mib[6];
402 
403   log_Printf(LogDEBUG, "route_IfDelete (%d)\n", bundle->iface->index);
404 
405   mib[0] = CTL_NET;
406   mib[1] = PF_ROUTE;
407   mib[2] = 0;
408   mib[3] = 0;
409   mib[4] = NET_RT_DUMP;
410   mib[5] = 0;
411   if (sysctl(mib, 6, NULL, &needed, NULL, 0) < 0) {
412     log_Printf(LogERROR, "route_IfDelete: sysctl: estimate: %s\n",
413               strerror(errno));
414     return;
415   }
416 
417   sp = malloc(needed);
418   if (sp == NULL)
419     return;
420 
421   if (sysctl(mib, 6, sp, &needed, NULL, 0) < 0) {
422     log_Printf(LogERROR, "route_IfDelete: sysctl: getroute: %s\n",
423               strerror(errno));
424     free(sp);
425     return;
426   }
427   ep = sp + needed;
428 
429   for (pass = 0; pass < 2; pass++) {
430     /*
431      * We do 2 passes.  The first deletes all cloned routes.  The second
432      * deletes all non-cloned routes.  This is done to avoid
433      * potential errors from trying to delete route X after route Y where
434      * route X was cloned from route Y (and is no longer there 'cos it
435      * may have gone with route Y).
436      */
437     if (RTF_WASCLONED == 0 && pass == 0)
438       /* So we can't tell ! */
439       continue;
440     for (cp = sp; cp < ep; cp += rtm->rtm_msglen) {
441       rtm = (struct rt_msghdr *)cp;
442       route_ParseHdr(rtm, sa);
443       if (rtm->rtm_index == bundle->iface->index &&
444           sa[RTAX_DST] && sa[RTAX_GATEWAY] &&
445           (sa[RTAX_DST]->sa_family == AF_INET
446 #ifndef NOINET6
447            || sa[RTAX_DST]->sa_family == AF_INET6
448 #endif
449            ) &&
450           (all || (rtm->rtm_flags & RTF_GATEWAY))) {
451         if (log_IsKept(LogDEBUG)) {
452           char gwstr[41];
453           struct ncpaddr gw;
454           ncprange_setsa(&range, sa[RTAX_DST], sa[RTAX_NETMASK]);
455           ncpaddr_setsa(&gw, sa[RTAX_GATEWAY]);
456           snprintf(gwstr, sizeof gwstr, "%s", ncpaddr_ntoa(&gw));
457           log_Printf(LogDEBUG, "Found %s %s\n", ncprange_ntoa(&range), gwstr);
458         }
459         if (sa[RTAX_GATEWAY]->sa_family == AF_INET ||
460 #ifndef NOINET6
461             sa[RTAX_GATEWAY]->sa_family == AF_INET6 ||
462 #endif
463             sa[RTAX_GATEWAY]->sa_family == AF_LINK) {
464           if ((pass == 0 && (rtm->rtm_flags & RTF_WASCLONED)) ||
465               (pass == 1 && !(rtm->rtm_flags & RTF_WASCLONED))) {
466             ncprange_setsa(&range, sa[RTAX_DST], sa[RTAX_NETMASK]);
467             rt_Set(bundle, RTM_DELETE, &range, NULL, 0, 0);
468           } else
469             log_Printf(LogDEBUG, "route_IfDelete: Skip it (pass %d)\n", pass);
470         } else
471           log_Printf(LogDEBUG,
472                     "route_IfDelete: Can't remove routes for family %d\n",
473                     sa[RTAX_GATEWAY]->sa_family);
474       }
475     }
476   }
477   free(sp);
478 }
479 
480 
481 /*
482  *  Update the MTU on all routes for the given interface
483  */
484 void
485 route_UpdateMTU(struct bundle *bundle)
486 {
487   struct rt_msghdr *rtm;
488   struct sockaddr *sa[RTAX_MAX];
489   struct ncprange dst;
490   size_t needed;
491   char *sp, *cp, *ep;
492   int mib[6];
493 
494   log_Printf(LogDEBUG, "route_UpdateMTU (%d)\n", bundle->iface->index);
495 
496   mib[0] = CTL_NET;
497   mib[1] = PF_ROUTE;
498   mib[2] = 0;
499   mib[3] = 0;
500   mib[4] = NET_RT_DUMP;
501   mib[5] = 0;
502   if (sysctl(mib, 6, NULL, &needed, NULL, 0) < 0) {
503     log_Printf(LogERROR, "route_IfDelete: sysctl: estimate: %s\n",
504               strerror(errno));
505     return;
506   }
507 
508   sp = malloc(needed);
509   if (sp == NULL)
510     return;
511 
512   if (sysctl(mib, 6, sp, &needed, NULL, 0) < 0) {
513     log_Printf(LogERROR, "route_IfDelete: sysctl: getroute: %s\n",
514               strerror(errno));
515     free(sp);
516     return;
517   }
518   ep = sp + needed;
519 
520   for (cp = sp; cp < ep; cp += rtm->rtm_msglen) {
521     rtm = (struct rt_msghdr *)cp;
522     route_ParseHdr(rtm, sa);
523     if (sa[RTAX_DST] && (sa[RTAX_DST]->sa_family == AF_INET
524 #ifndef NOINET6
525                          || sa[RTAX_DST]->sa_family == AF_INET6
526 #endif
527                         ) &&
528         sa[RTAX_GATEWAY] && rtm->rtm_index == bundle->iface->index) {
529       if (log_IsKept(LogTCPIP)) {
530         ncprange_setsa(&dst, sa[RTAX_DST], sa[RTAX_NETMASK]);
531         log_Printf(LogTCPIP, "route_UpdateMTU: Netif: %d (%s), dst %s,"
532                    " mtu %lu\n", rtm->rtm_index, Index2Nam(rtm->rtm_index),
533                    ncprange_ntoa(&dst), bundle->iface->mtu);
534       }
535       rt_Update(bundle, sa[RTAX_DST], sa[RTAX_GATEWAY], sa[RTAX_NETMASK],
536                 sa[RTAX_IFP], sa[RTAX_IFA]);
537     }
538   }
539 
540   free(sp);
541 }
542 
543 int
544 GetIfIndex(char *name)
545 {
546   int idx;
547 
548   idx = 1;
549   while (route_nifs == -1 || idx < route_nifs)
550     if (strcmp(Index2Nam(idx), name) == 0)
551       return idx;
552     else
553       idx++;
554   return -1;
555 }
556 
557 void
558 route_Change(struct bundle *bundle, struct sticky_route *r,
559              const struct ncpaddr *me, const struct ncpaddr *peer)
560 {
561   struct ncpaddr dst;
562 
563   for (; r; r = r->next) {
564     ncprange_getaddr(&r->dst, &dst);
565     if (ncpaddr_family(me) == AF_INET) {
566       if ((r->type & ROUTE_DSTMYADDR) && !ncpaddr_equal(&dst, me)) {
567         rt_Set(bundle, RTM_DELETE, &r->dst, NULL, 1, 0);
568         ncprange_sethost(&r->dst, me);
569         if (r->type & ROUTE_GWHISADDR)
570           ncpaddr_copy(&r->gw, peer);
571       } else if ((r->type & ROUTE_DSTHISADDR) && !ncpaddr_equal(&dst, peer)) {
572         rt_Set(bundle, RTM_DELETE, &r->dst, NULL, 1, 0);
573         ncprange_sethost(&r->dst, peer);
574         if (r->type & ROUTE_GWHISADDR)
575           ncpaddr_copy(&r->gw, peer);
576       } else if ((r->type & ROUTE_DSTDNS0) && !ncpaddr_equal(&dst, peer)) {
577         if (bundle->ncp.ipcp.ns.dns[0].s_addr == INADDR_NONE)
578           continue;
579         rt_Set(bundle, RTM_DELETE, &r->dst, NULL, 1, 0);
580         if (r->type & ROUTE_GWHISADDR)
581           ncpaddr_copy(&r->gw, peer);
582       } else if ((r->type & ROUTE_DSTDNS1) && !ncpaddr_equal(&dst, peer)) {
583         if (bundle->ncp.ipcp.ns.dns[1].s_addr == INADDR_NONE)
584           continue;
585         rt_Set(bundle, RTM_DELETE, &r->dst, NULL, 1, 0);
586         if (r->type & ROUTE_GWHISADDR)
587           ncpaddr_copy(&r->gw, peer);
588       } else if ((r->type & ROUTE_GWHISADDR) && !ncpaddr_equal(&r->gw, peer))
589         ncpaddr_copy(&r->gw, peer);
590 #ifndef NOINET6
591     } else if (ncpaddr_family(me) == AF_INET6) {
592       if ((r->type & ROUTE_DSTMYADDR6) && !ncpaddr_equal(&dst, me)) {
593         rt_Set(bundle, RTM_DELETE, &r->dst, NULL, 1, 0);
594         ncprange_sethost(&r->dst, me);
595         if (r->type & ROUTE_GWHISADDR)
596           ncpaddr_copy(&r->gw, peer);
597       } else if ((r->type & ROUTE_DSTHISADDR6) && !ncpaddr_equal(&dst, peer)) {
598         rt_Set(bundle, RTM_DELETE, &r->dst, NULL, 1, 0);
599         ncprange_sethost(&r->dst, peer);
600         if (r->type & ROUTE_GWHISADDR)
601           ncpaddr_copy(&r->gw, peer);
602       } else if ((r->type & ROUTE_GWHISADDR6) && !ncpaddr_equal(&r->gw, peer))
603         ncpaddr_copy(&r->gw, peer);
604 #endif
605     }
606     rt_Set(bundle, RTM_ADD, &r->dst, &r->gw, 1, 0);
607   }
608 }
609 
610 void
611 route_Add(struct sticky_route **rp, int type, const struct ncprange *dst,
612           const struct ncpaddr *gw)
613 {
614   struct sticky_route *r;
615   int dsttype = type & ROUTE_DSTANY;
616 
617   r = NULL;
618   while (*rp) {
619     if ((dsttype && dsttype == ((*rp)->type & ROUTE_DSTANY)) ||
620         (!dsttype && ncprange_equal(&(*rp)->dst, dst))) {
621       /* Oops, we already have this route - unlink it */
622       free(r);			/* impossible really  */
623       r = *rp;
624       *rp = r->next;
625     } else
626       rp = &(*rp)->next;
627   }
628 
629   if (r == NULL) {
630     r = (struct sticky_route *)malloc(sizeof(struct sticky_route));
631     if (r == NULL) {
632       log_Printf(LogERROR, "route_Add: Out of memory!\n");
633       return;
634     }
635   }
636   r->type = type;
637   r->next = NULL;
638   ncprange_copy(&r->dst, dst);
639   ncpaddr_copy(&r->gw, gw);
640   *rp = r;
641 }
642 
643 void
644 route_Delete(struct sticky_route **rp, int type, const struct ncprange *dst)
645 {
646   struct sticky_route *r;
647   int dsttype = type & ROUTE_DSTANY;
648 
649   for (; *rp; rp = &(*rp)->next) {
650     if ((dsttype && dsttype == ((*rp)->type & ROUTE_DSTANY)) ||
651         (!dsttype && ncprange_equal(dst, &(*rp)->dst))) {
652       r = *rp;
653       *rp = r->next;
654       free(r);
655       break;
656     }
657   }
658 }
659 
660 void
661 route_DeleteAll(struct sticky_route **rp)
662 {
663   struct sticky_route *r, *rn;
664 
665   for (r = *rp; r; r = rn) {
666     rn = r->next;
667     free(r);
668   }
669   *rp = NULL;
670 }
671 
672 void
673 route_ShowSticky(struct prompt *p, struct sticky_route *r, const char *tag,
674                  int indent)
675 {
676   int tlen = strlen(tag);
677 
678   if (tlen + 2 > indent)
679     prompt_Printf(p, "%s:\n%*s", tag, indent, "");
680   else
681     prompt_Printf(p, "%s:%*s", tag, indent - tlen - 1, "");
682 
683   for (; r; r = r->next) {
684     prompt_Printf(p, "%*sadd ", tlen ? 0 : indent, "");
685     tlen = 0;
686     if (r->type & ROUTE_DSTMYADDR)
687       prompt_Printf(p, "MYADDR");
688     else if (r->type & ROUTE_DSTMYADDR6)
689       prompt_Printf(p, "MYADDR6");
690     else if (r->type & ROUTE_DSTHISADDR)
691       prompt_Printf(p, "HISADDR");
692     else if (r->type & ROUTE_DSTHISADDR6)
693       prompt_Printf(p, "HISADDR6");
694     else if (r->type & ROUTE_DSTDNS0)
695       prompt_Printf(p, "DNS0");
696     else if (r->type & ROUTE_DSTDNS1)
697       prompt_Printf(p, "DNS1");
698     else if (ncprange_isdefault(&r->dst))
699       prompt_Printf(p, "default");
700     else
701       prompt_Printf(p, "%s", ncprange_ntoa(&r->dst));
702 
703     if (r->type & ROUTE_GWHISADDR)
704       prompt_Printf(p, " HISADDR\n");
705     else if (r->type & ROUTE_GWHISADDR6)
706       prompt_Printf(p, " HISADDR6\n");
707     else
708       prompt_Printf(p, " %s\n", ncpaddr_ntoa(&r->gw));
709   }
710 }
711 
712 struct rtmsg {
713   struct rt_msghdr m_rtm;
714   char m_space[256];
715 };
716 
717 static size_t
718 memcpy_roundup(char *cp, const void *data, size_t len)
719 {
720   size_t padlen;
721 
722   padlen = ROUNDUP(len);
723   memcpy(cp, data, len);
724   if (padlen > len)
725     memset(cp + len, '\0', padlen - len);
726 
727   return padlen;
728 }
729 
730 #if defined(__KAME__) && !defined(NOINET6)
731 static void
732 add_scope(struct sockaddr *sa, int ifindex)
733 {
734   struct sockaddr_in6 *sa6;
735 
736   if (sa->sa_family != AF_INET6)
737     return;
738   sa6 = (struct sockaddr_in6 *)sa;
739   if (!IN6_IS_ADDR_LINKLOCAL(&sa6->sin6_addr) &&
740       !IN6_IS_ADDR_MC_LINKLOCAL(&sa6->sin6_addr))
741     return;
742   if (*(u_int16_t *)&sa6->sin6_addr.s6_addr[2] != 0)
743     return;
744   *(u_int16_t *)&sa6->sin6_addr.s6_addr[2] = htons(ifindex);
745 }
746 #endif
747 
748 int
749 rt_Set(struct bundle *bundle, int cmd, const struct ncprange *dst,
750        const struct ncpaddr *gw, int bang, int quiet)
751 {
752   struct rtmsg rtmes;
753   int s, nb, wb;
754   char *cp;
755   const char *cmdstr;
756   struct sockaddr_storage sadst, samask, sagw;
757   int result = 1;
758 
759   if (bang)
760     cmdstr = (cmd == RTM_ADD ? "Add!" : "Delete!");
761   else
762     cmdstr = (cmd == RTM_ADD ? "Add" : "Delete");
763   s = ID0socket(PF_ROUTE, SOCK_RAW, 0);
764   if (s < 0) {
765     log_Printf(LogERROR, "rt_Set: socket(): %s\n", strerror(errno));
766     return result;
767   }
768   memset(&rtmes, '\0', sizeof rtmes);
769   rtmes.m_rtm.rtm_version = RTM_VERSION;
770   rtmes.m_rtm.rtm_type = cmd;
771   rtmes.m_rtm.rtm_addrs = RTA_DST;
772   rtmes.m_rtm.rtm_seq = ++bundle->routing_seq;
773   rtmes.m_rtm.rtm_pid = getpid();
774   rtmes.m_rtm.rtm_flags = RTF_UP | RTF_GATEWAY | RTF_STATIC;
775 
776   if (cmd == RTM_ADD) {
777     if (bundle->ncp.cfg.sendpipe > 0) {
778       rtmes.m_rtm.rtm_rmx.rmx_sendpipe = bundle->ncp.cfg.sendpipe;
779       rtmes.m_rtm.rtm_inits |= RTV_SPIPE;
780     }
781     if (bundle->ncp.cfg.recvpipe > 0) {
782       rtmes.m_rtm.rtm_rmx.rmx_recvpipe = bundle->ncp.cfg.recvpipe;
783       rtmes.m_rtm.rtm_inits |= RTV_RPIPE;
784     }
785   }
786 
787   ncprange_getsa(dst, &sadst, &samask);
788 #if defined(__KAME__) && !defined(NOINET6)
789   add_scope((struct sockaddr *)&sadst, bundle->iface->index);
790 #endif
791 
792   cp = rtmes.m_space;
793   cp += memcpy_roundup(cp, &sadst, sadst.ss_len);
794   if (cmd == RTM_ADD) {
795     if (gw == NULL) {
796       log_Printf(LogERROR, "rt_Set: Program error\n");
797       close(s);
798       return result;
799     }
800     ncpaddr_getsa(gw, &sagw);
801 #if defined(__KAME__) && !defined(NOINET6)
802     add_scope((struct sockaddr *)&sagw, bundle->iface->index);
803 #endif
804     if (ncpaddr_isdefault(gw)) {
805       if (!quiet)
806         log_Printf(LogERROR, "rt_Set: Cannot add a route with"
807                    " gateway 0.0.0.0\n");
808       close(s);
809       return result;
810     } else {
811       cp += memcpy_roundup(cp, &sagw, sagw.ss_len);
812       rtmes.m_rtm.rtm_addrs |= RTA_GATEWAY;
813     }
814   }
815 
816   if (!ncprange_ishost(dst)) {
817     cp += memcpy_roundup(cp, &samask, samask.ss_len);
818     rtmes.m_rtm.rtm_addrs |= RTA_NETMASK;
819   }
820 
821   nb = cp - (char *)&rtmes;
822   rtmes.m_rtm.rtm_msglen = nb;
823   wb = ID0write(s, &rtmes, nb);
824   if (wb < 0) {
825     log_Printf(LogTCPIP, "rt_Set failure:\n");
826     log_Printf(LogTCPIP, "rt_Set:  Cmd = %s\n", cmdstr);
827     log_Printf(LogTCPIP, "rt_Set:  Dst = %s\n", ncprange_ntoa(dst));
828     if (gw != NULL)
829       log_Printf(LogTCPIP, "rt_Set:  Gateway = %s\n", ncpaddr_ntoa(gw));
830 failed:
831     if (cmd == RTM_ADD && (rtmes.m_rtm.rtm_errno == EEXIST ||
832                            (rtmes.m_rtm.rtm_errno == 0 && errno == EEXIST))) {
833       if (!bang) {
834         log_Printf(LogWARN, "Add route failed: %s already exists\n",
835 		   ncprange_ntoa(dst));
836         result = 0;	/* Don't add to our dynamic list */
837       } else {
838         rtmes.m_rtm.rtm_type = cmd = RTM_CHANGE;
839         if ((wb = ID0write(s, &rtmes, nb)) < 0)
840           goto failed;
841       }
842     } else if (cmd == RTM_DELETE &&
843              (rtmes.m_rtm.rtm_errno == ESRCH ||
844               (rtmes.m_rtm.rtm_errno == 0 && errno == ESRCH))) {
845       if (!bang)
846         log_Printf(LogWARN, "Del route failed: %s: Non-existent\n",
847                   ncprange_ntoa(dst));
848     } else if (rtmes.m_rtm.rtm_errno == 0) {
849       if (!quiet || errno != ENETUNREACH)
850         log_Printf(LogWARN, "%s route failed: %s: errno: %s\n", cmdstr,
851                    ncprange_ntoa(dst), strerror(errno));
852     } else
853       log_Printf(LogWARN, "%s route failed: %s: %s\n",
854 		 cmdstr, ncprange_ntoa(dst), strerror(rtmes.m_rtm.rtm_errno));
855   }
856 
857   if (log_IsKept(LogDEBUG)) {
858     char gwstr[40];
859 
860     if (gw)
861       snprintf(gwstr, sizeof gwstr, "%s", ncpaddr_ntoa(gw));
862     else
863       snprintf(gwstr, sizeof gwstr, "<none>");
864     log_Printf(LogDEBUG, "wrote %d: cmd = %s, dst = %s, gateway = %s\n",
865                wb, cmdstr, ncprange_ntoa(dst), gwstr);
866   }
867   close(s);
868 
869   return result;
870 }
871 
872 void
873 rt_Update(struct bundle *bundle, const struct sockaddr *dst,
874           const struct sockaddr *gw, const struct sockaddr *mask,
875           const struct sockaddr *ifp, const struct sockaddr *ifa)
876 {
877   struct ncprange ncpdst;
878   struct rtmsg rtmes;
879   char *p;
880   int s, wb;
881 
882   s = ID0socket(PF_ROUTE, SOCK_RAW, 0);
883   if (s < 0) {
884     log_Printf(LogERROR, "rt_Update: socket(): %s\n", strerror(errno));
885     return;
886   }
887 
888   memset(&rtmes, '\0', sizeof rtmes);
889   rtmes.m_rtm.rtm_version = RTM_VERSION;
890   rtmes.m_rtm.rtm_type = RTM_CHANGE;
891   rtmes.m_rtm.rtm_addrs = 0;
892   rtmes.m_rtm.rtm_seq = ++bundle->routing_seq;
893   rtmes.m_rtm.rtm_pid = getpid();
894   rtmes.m_rtm.rtm_flags = RTF_UP | RTF_STATIC;
895 
896   if (bundle->ncp.cfg.sendpipe > 0) {
897     rtmes.m_rtm.rtm_rmx.rmx_sendpipe = bundle->ncp.cfg.sendpipe;
898     rtmes.m_rtm.rtm_inits |= RTV_SPIPE;
899   }
900 
901   if (bundle->ncp.cfg.recvpipe > 0) {
902     rtmes.m_rtm.rtm_rmx.rmx_recvpipe = bundle->ncp.cfg.recvpipe;
903     rtmes.m_rtm.rtm_inits |= RTV_RPIPE;
904   }
905 
906   rtmes.m_rtm.rtm_rmx.rmx_mtu = bundle->iface->mtu;
907   rtmes.m_rtm.rtm_inits |= RTV_MTU;
908   p = rtmes.m_space;
909 
910   if (dst) {
911     rtmes.m_rtm.rtm_addrs |= RTA_DST;
912     p += memcpy_roundup(p, dst, dst->sa_len);
913   }
914 
915   if (gw) {
916     rtmes.m_rtm.rtm_addrs |= RTA_GATEWAY;
917     p += memcpy_roundup(p, gw, gw->sa_len);
918   }
919 
920   if (mask) {
921     rtmes.m_rtm.rtm_addrs |= RTA_NETMASK;
922     p += memcpy_roundup(p, mask, mask->sa_len);
923   }
924 
925   if (ifa && ifp && ifp->sa_family == AF_LINK) {
926     rtmes.m_rtm.rtm_addrs |= RTA_IFP;
927     p += memcpy_roundup(p, ifp, ifp->sa_len);
928     rtmes.m_rtm.rtm_addrs |= RTA_IFA;
929     p += memcpy_roundup(p, ifa, ifa->sa_len);
930   }
931 
932   rtmes.m_rtm.rtm_msglen = p - (char *)&rtmes;
933 
934   wb = ID0write(s, &rtmes, rtmes.m_rtm.rtm_msglen);
935   if (wb < 0) {
936     ncprange_setsa(&ncpdst, dst, mask);
937 
938     log_Printf(LogTCPIP, "rt_Update failure:\n");
939     log_Printf(LogTCPIP, "rt_Update:  Dst = %s\n", ncprange_ntoa(&ncpdst));
940 
941     if (rtmes.m_rtm.rtm_errno == 0)
942       log_Printf(LogWARN, "%s: Change route failed: errno: %s\n",
943                  ncprange_ntoa(&ncpdst), strerror(errno));
944     else
945       log_Printf(LogWARN, "%s: Change route failed: %s\n",
946 		 ncprange_ntoa(&ncpdst), strerror(rtmes.m_rtm.rtm_errno));
947   }
948   close(s);
949 }
950