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