]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/net/rtsock.c
routing: add public rt_is_exportable() version to check if
[FreeBSD/FreeBSD.git] / sys / net / rtsock.c
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1988, 1991, 1993
5  *      The Regents of the University of California.  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  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  *
31  *      @(#)rtsock.c    8.7 (Berkeley) 10/12/95
32  * $FreeBSD$
33  */
34 #include "opt_ddb.h"
35 #include "opt_route.h"
36 #include "opt_inet.h"
37 #include "opt_inet6.h"
38
39 #include <sys/param.h>
40 #include <sys/jail.h>
41 #include <sys/kernel.h>
42 #include <sys/eventhandler.h>
43 #include <sys/domain.h>
44 #include <sys/lock.h>
45 #include <sys/malloc.h>
46 #include <sys/mbuf.h>
47 #include <sys/priv.h>
48 #include <sys/proc.h>
49 #include <sys/protosw.h>
50 #include <sys/rmlock.h>
51 #include <sys/rwlock.h>
52 #include <sys/signalvar.h>
53 #include <sys/socket.h>
54 #include <sys/socketvar.h>
55 #include <sys/sysctl.h>
56 #include <sys/systm.h>
57
58 #include <net/if.h>
59 #include <net/if_var.h>
60 #include <net/if_dl.h>
61 #include <net/if_llatbl.h>
62 #include <net/if_types.h>
63 #include <net/netisr.h>
64 #include <net/raw_cb.h>
65 #include <net/route.h>
66 #include <net/route/route_ctl.h>
67 #include <net/route/route_var.h>
68 #include <net/vnet.h>
69
70 #include <netinet/in.h>
71 #include <netinet/if_ether.h>
72 #include <netinet/ip_carp.h>
73 #ifdef INET6
74 #include <netinet6/in6_var.h>
75 #include <netinet6/ip6_var.h>
76 #include <netinet6/scope6_var.h>
77 #endif
78 #include <net/route/nhop.h>
79
80 #define DEBUG_MOD_NAME  rtsock
81 #define DEBUG_MAX_LEVEL LOG_DEBUG
82 #include <net/route/route_debug.h>
83 _DECLARE_DEBUG(LOG_INFO);
84
85 #ifdef COMPAT_FREEBSD32
86 #include <sys/mount.h>
87 #include <compat/freebsd32/freebsd32.h>
88
89 struct if_msghdr32 {
90         uint16_t ifm_msglen;
91         uint8_t ifm_version;
92         uint8_t ifm_type;
93         int32_t ifm_addrs;
94         int32_t ifm_flags;
95         uint16_t ifm_index;
96         uint16_t _ifm_spare1;
97         struct  if_data ifm_data;
98 };
99
100 struct if_msghdrl32 {
101         uint16_t ifm_msglen;
102         uint8_t ifm_version;
103         uint8_t ifm_type;
104         int32_t ifm_addrs;
105         int32_t ifm_flags;
106         uint16_t ifm_index;
107         uint16_t _ifm_spare1;
108         uint16_t ifm_len;
109         uint16_t ifm_data_off;
110         uint32_t _ifm_spare2;
111         struct  if_data ifm_data;
112 };
113
114 struct ifa_msghdrl32 {
115         uint16_t ifam_msglen;
116         uint8_t ifam_version;
117         uint8_t ifam_type;
118         int32_t ifam_addrs;
119         int32_t ifam_flags;
120         uint16_t ifam_index;
121         uint16_t _ifam_spare1;
122         uint16_t ifam_len;
123         uint16_t ifam_data_off;
124         int32_t ifam_metric;
125         struct  if_data ifam_data;
126 };
127
128 #define SA_SIZE32(sa)                                           \
129     (  (((struct sockaddr *)(sa))->sa_len == 0) ?               \
130         sizeof(int)             :                               \
131         1 + ( (((struct sockaddr *)(sa))->sa_len - 1) | (sizeof(int) - 1) ) )
132
133 #endif /* COMPAT_FREEBSD32 */
134
135 struct linear_buffer {
136         char            *base;  /* Base allocated memory pointer */
137         uint32_t        offset; /* Currently used offset */
138         uint32_t        size;   /* Total buffer size */
139 };
140 #define SCRATCH_BUFFER_SIZE     1024
141
142 #define RTS_PID_LOG(_l, _fmt, ...)      RT_LOG_##_l(_l, "PID %d: " _fmt, curproc ? curproc->p_pid : 0, ## __VA_ARGS__)
143
144 MALLOC_DEFINE(M_RTABLE, "routetbl", "routing tables");
145
146 /* NB: these are not modified */
147 static struct   sockaddr route_src = { 2, PF_ROUTE, };
148 static struct   sockaddr sa_zero   = { sizeof(sa_zero), AF_INET, };
149
150 /* These are external hooks for CARP. */
151 int     (*carp_get_vhid_p)(struct ifaddr *);
152
153 /*
154  * Used by rtsock/raw_input callback code to decide whether to filter the update
155  * notification to a socket bound to a particular FIB.
156  */
157 #define RTS_FILTER_FIB  M_PROTO8
158
159 typedef struct {
160         int     ip_count;       /* attached w/ AF_INET */
161         int     ip6_count;      /* attached w/ AF_INET6 */
162         int     any_count;      /* total attached */
163 } route_cb_t;
164 VNET_DEFINE_STATIC(route_cb_t, route_cb);
165 #define V_route_cb VNET(route_cb)
166
167 struct mtx rtsock_mtx;
168 MTX_SYSINIT(rtsock, &rtsock_mtx, "rtsock route_cb lock", MTX_DEF);
169
170 #define RTSOCK_LOCK()   mtx_lock(&rtsock_mtx)
171 #define RTSOCK_UNLOCK() mtx_unlock(&rtsock_mtx)
172 #define RTSOCK_LOCK_ASSERT()    mtx_assert(&rtsock_mtx, MA_OWNED)
173
174 SYSCTL_NODE(_net, OID_AUTO, route, CTLFLAG_RD | CTLFLAG_MPSAFE, 0, "");
175
176 struct walkarg {
177         int     family;
178         int     w_tmemsize;
179         int     w_op, w_arg;
180         caddr_t w_tmem;
181         struct sysctl_req *w_req;
182         struct sockaddr *dst;
183         struct sockaddr *mask;
184 };
185
186 static void     rts_input(struct mbuf *m);
187 static struct mbuf *rtsock_msg_mbuf(int type, struct rt_addrinfo *rtinfo);
188 static int      rtsock_msg_buffer(int type, struct rt_addrinfo *rtinfo,
189                         struct walkarg *w, int *plen);
190 static int      rt_xaddrs(caddr_t cp, caddr_t cplim,
191                         struct rt_addrinfo *rtinfo);
192 static int      cleanup_xaddrs(struct rt_addrinfo *info, struct linear_buffer *lb);
193 static int      sysctl_dumpentry(struct rtentry *rt, void *vw);
194 static int      sysctl_dumpnhop(struct rtentry *rt, struct nhop_object *nh,
195                         uint32_t weight, struct walkarg *w);
196 static int      sysctl_iflist(int af, struct walkarg *w);
197 static int      sysctl_ifmalist(int af, struct walkarg *w);
198 static int      route_output(struct mbuf *m, struct socket *so, ...);
199 static void     rt_getmetrics(const struct rtentry *rt,
200                         const struct nhop_object *nh, struct rt_metrics *out);
201 static void     rt_dispatch(struct mbuf *, sa_family_t);
202 static void     rt_ifannouncemsg(struct ifnet *ifp, int what);
203 static int      handle_rtm_get(struct rt_addrinfo *info, u_int fibnum,
204                         struct rt_msghdr *rtm, struct rib_cmd_info *rc);
205 static int      update_rtm_from_rc(struct rt_addrinfo *info,
206                         struct rt_msghdr **prtm, int alloc_len,
207                         struct rib_cmd_info *rc, struct nhop_object *nh);
208 static void     send_rtm_reply(struct socket *so, struct rt_msghdr *rtm,
209                         struct mbuf *m, sa_family_t saf, u_int fibnum,
210                         int rtm_errno);
211 static void     rtsock_notify_event(uint32_t fibnum, const struct rib_cmd_info *rc);
212 static void     rtsock_ifmsg(struct ifnet *ifp, int if_flags_mask);
213
214 static struct netisr_handler rtsock_nh = {
215         .nh_name = "rtsock",
216         .nh_handler = rts_input,
217         .nh_proto = NETISR_ROUTE,
218         .nh_policy = NETISR_POLICY_SOURCE,
219 };
220
221 static int
222 sysctl_route_netisr_maxqlen(SYSCTL_HANDLER_ARGS)
223 {
224         int error, qlimit;
225
226         netisr_getqlimit(&rtsock_nh, &qlimit);
227         error = sysctl_handle_int(oidp, &qlimit, 0, req);
228         if (error || !req->newptr)
229                 return (error);
230         if (qlimit < 1)
231                 return (EINVAL);
232         return (netisr_setqlimit(&rtsock_nh, qlimit));
233 }
234 SYSCTL_PROC(_net_route, OID_AUTO, netisr_maxqlen,
235     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
236     0, 0, sysctl_route_netisr_maxqlen, "I",
237     "maximum routing socket dispatch queue length");
238
239 static void
240 vnet_rts_init(void)
241 {
242         int tmp;
243
244         if (IS_DEFAULT_VNET(curvnet)) {
245                 if (TUNABLE_INT_FETCH("net.route.netisr_maxqlen", &tmp))
246                         rtsock_nh.nh_qlimit = tmp;
247                 netisr_register(&rtsock_nh);
248         }
249 #ifdef VIMAGE
250          else
251                 netisr_register_vnet(&rtsock_nh);
252 #endif
253 }
254 VNET_SYSINIT(vnet_rtsock, SI_SUB_PROTO_DOMAIN, SI_ORDER_THIRD,
255     vnet_rts_init, 0);
256
257 #ifdef VIMAGE
258 static void
259 vnet_rts_uninit(void)
260 {
261
262         netisr_unregister_vnet(&rtsock_nh);
263 }
264 VNET_SYSUNINIT(vnet_rts_uninit, SI_SUB_PROTO_DOMAIN, SI_ORDER_THIRD,
265     vnet_rts_uninit, 0);
266 #endif
267
268 static void
269 report_route_event(const struct rib_cmd_info *rc, void *_cbdata)
270 {
271         uint32_t fibnum = (uint32_t)(uintptr_t)_cbdata;
272         struct nhop_object *nh;
273
274         nh = rc->rc_cmd == RTM_DELETE ? rc->rc_nh_old : rc->rc_nh_new;
275         rt_routemsg(rc->rc_cmd, rc->rc_rt, nh, fibnum);
276 }
277
278 static void
279 rts_handle_route_event(uint32_t fibnum, const struct rib_cmd_info *rc)
280 {
281 #ifdef ROUTE_MPATH
282         if ((rc->rc_nh_new && NH_IS_NHGRP(rc->rc_nh_new)) ||
283             (rc->rc_nh_old && NH_IS_NHGRP(rc->rc_nh_old))) {
284                 rib_decompose_notification(rc, report_route_event,
285                     (void *)(uintptr_t)fibnum);
286         } else
287 #endif
288                 report_route_event(rc, (void *)(uintptr_t)fibnum);
289 }
290 static struct rtbridge rtsbridge = {
291         .route_f = rts_handle_route_event,
292         .ifmsg_f = rtsock_ifmsg,
293 };
294 static struct rtbridge *rtsbridge_orig_p;
295
296 static void
297 rtsock_notify_event(uint32_t fibnum, const struct rib_cmd_info *rc)
298 {
299         netlink_callback_p->route_f(fibnum, rc);
300 }
301
302 static void
303 rtsock_init(void)
304 {
305         rtsbridge_orig_p = rtsock_callback_p;
306         rtsock_callback_p = &rtsbridge;
307 }
308 SYSINIT(rtsock_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_THIRD, rtsock_init, NULL);
309
310 static void
311 rts_handle_ifnet_arrival(void *arg __unused, struct ifnet *ifp)
312 {
313         rt_ifannouncemsg(ifp, IFAN_ARRIVAL);
314 }
315 EVENTHANDLER_DEFINE(ifnet_arrival_event, rts_handle_ifnet_arrival, NULL, 0);
316
317 static void
318 rts_handle_ifnet_departure(void *arg __unused, struct ifnet *ifp)
319 {
320         rt_ifannouncemsg(ifp, IFAN_DEPARTURE);
321 }
322 EVENTHANDLER_DEFINE(ifnet_departure_event, rts_handle_ifnet_departure, NULL, 0);
323
324 static int
325 raw_input_rts_cb(struct mbuf *m, struct sockproto *proto, struct sockaddr *src,
326     struct rawcb *rp)
327 {
328         int fibnum;
329
330         KASSERT(m != NULL, ("%s: m is NULL", __func__));
331         KASSERT(proto != NULL, ("%s: proto is NULL", __func__));
332         KASSERT(rp != NULL, ("%s: rp is NULL", __func__));
333
334         /* No filtering requested. */
335         if ((m->m_flags & RTS_FILTER_FIB) == 0)
336                 return (0);
337
338         /* Check if it is a rts and the fib matches the one of the socket. */
339         fibnum = M_GETFIB(m);
340         if (proto->sp_family != PF_ROUTE ||
341             rp->rcb_socket == NULL ||
342             rp->rcb_socket->so_fibnum == fibnum)
343                 return (0);
344
345         /* Filtering requested and no match, the socket shall be skipped. */
346         return (1);
347 }
348
349 static void
350 rts_input(struct mbuf *m)
351 {
352         struct sockproto route_proto;
353         unsigned short *family;
354         struct m_tag *tag;
355
356         route_proto.sp_family = PF_ROUTE;
357         tag = m_tag_find(m, PACKET_TAG_RTSOCKFAM, NULL);
358         if (tag != NULL) {
359                 family = (unsigned short *)(tag + 1);
360                 route_proto.sp_protocol = *family;
361                 m_tag_delete(m, tag);
362         } else
363                 route_proto.sp_protocol = 0;
364
365         raw_input_ext(m, &route_proto, &route_src, raw_input_rts_cb);
366 }
367
368 /*
369  * It really doesn't make any sense at all for this code to share much
370  * with raw_usrreq.c, since its functionality is so restricted.  XXX
371  */
372 static void
373 rts_abort(struct socket *so)
374 {
375
376         raw_usrreqs.pru_abort(so);
377 }
378
379 static void
380 rts_close(struct socket *so)
381 {
382
383         raw_usrreqs.pru_close(so);
384 }
385
386 /* pru_accept is EOPNOTSUPP */
387
388 static int
389 rts_attach(struct socket *so, int proto, struct thread *td)
390 {
391         struct rawcb *rp;
392         int error;
393
394         KASSERT(so->so_pcb == NULL, ("rts_attach: so_pcb != NULL"));
395
396         /* XXX */
397         rp = malloc(sizeof *rp, M_PCB, M_WAITOK | M_ZERO);
398
399         so->so_pcb = (caddr_t)rp;
400         so->so_fibnum = td->td_proc->p_fibnum;
401         error = raw_attach(so, proto);
402         rp = sotorawcb(so);
403         if (error) {
404                 so->so_pcb = NULL;
405                 free(rp, M_PCB);
406                 return error;
407         }
408         RTSOCK_LOCK();
409         switch(rp->rcb_proto.sp_protocol) {
410         case AF_INET:
411                 V_route_cb.ip_count++;
412                 break;
413         case AF_INET6:
414                 V_route_cb.ip6_count++;
415                 break;
416         }
417         V_route_cb.any_count++;
418         RTSOCK_UNLOCK();
419         soisconnected(so);
420         so->so_options |= SO_USELOOPBACK;
421         return 0;
422 }
423
424 static int
425 rts_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
426 {
427
428         return (raw_usrreqs.pru_bind(so, nam, td)); /* xxx just EINVAL */
429 }
430
431 static int
432 rts_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
433 {
434
435         return (raw_usrreqs.pru_connect(so, nam, td)); /* XXX just EINVAL */
436 }
437
438 /* pru_connect2 is EOPNOTSUPP */
439 /* pru_control is EOPNOTSUPP */
440
441 static void
442 rts_detach(struct socket *so)
443 {
444         struct rawcb *rp = sotorawcb(so);
445
446         KASSERT(rp != NULL, ("rts_detach: rp == NULL"));
447
448         RTSOCK_LOCK();
449         switch(rp->rcb_proto.sp_protocol) {
450         case AF_INET:
451                 V_route_cb.ip_count--;
452                 break;
453         case AF_INET6:
454                 V_route_cb.ip6_count--;
455                 break;
456         }
457         V_route_cb.any_count--;
458         RTSOCK_UNLOCK();
459         raw_usrreqs.pru_detach(so);
460 }
461
462 static int
463 rts_disconnect(struct socket *so)
464 {
465
466         return (raw_usrreqs.pru_disconnect(so));
467 }
468
469 /* pru_listen is EOPNOTSUPP */
470
471 static int
472 rts_peeraddr(struct socket *so, struct sockaddr **nam)
473 {
474
475         return (raw_usrreqs.pru_peeraddr(so, nam));
476 }
477
478 /* pru_rcvd is EOPNOTSUPP */
479 /* pru_rcvoob is EOPNOTSUPP */
480
481 static int
482 rts_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *nam,
483          struct mbuf *control, struct thread *td)
484 {
485
486         return (raw_usrreqs.pru_send(so, flags, m, nam, control, td));
487 }
488
489 /* pru_sense is null */
490
491 static int
492 rts_shutdown(struct socket *so)
493 {
494
495         return (raw_usrreqs.pru_shutdown(so));
496 }
497
498 static int
499 rts_sockaddr(struct socket *so, struct sockaddr **nam)
500 {
501
502         return (raw_usrreqs.pru_sockaddr(so, nam));
503 }
504
505 static struct pr_usrreqs route_usrreqs = {
506         .pru_abort =            rts_abort,
507         .pru_attach =           rts_attach,
508         .pru_bind =             rts_bind,
509         .pru_connect =          rts_connect,
510         .pru_detach =           rts_detach,
511         .pru_disconnect =       rts_disconnect,
512         .pru_peeraddr =         rts_peeraddr,
513         .pru_send =             rts_send,
514         .pru_shutdown =         rts_shutdown,
515         .pru_sockaddr =         rts_sockaddr,
516         .pru_close =            rts_close,
517 };
518
519 #ifndef _SOCKADDR_UNION_DEFINED
520 #define _SOCKADDR_UNION_DEFINED
521 /*
522  * The union of all possible address formats we handle.
523  */
524 union sockaddr_union {
525         struct sockaddr         sa;
526         struct sockaddr_in      sin;
527         struct sockaddr_in6     sin6;
528 };
529 #endif /* _SOCKADDR_UNION_DEFINED */
530
531 static int
532 rtm_get_jailed(struct rt_addrinfo *info, struct ifnet *ifp,
533     struct nhop_object *nh, union sockaddr_union *saun, struct ucred *cred)
534 {
535 #if defined(INET) || defined(INET6)
536         struct epoch_tracker et;
537 #endif
538
539         /* First, see if the returned address is part of the jail. */
540         if (prison_if(cred, nh->nh_ifa->ifa_addr) == 0) {
541                 info->rti_info[RTAX_IFA] = nh->nh_ifa->ifa_addr;
542                 return (0);
543         }
544
545         switch (info->rti_info[RTAX_DST]->sa_family) {
546 #ifdef INET
547         case AF_INET:
548         {
549                 struct in_addr ia;
550                 struct ifaddr *ifa;
551                 int found;
552
553                 found = 0;
554                 /*
555                  * Try to find an address on the given outgoing interface
556                  * that belongs to the jail.
557                  */
558                 NET_EPOCH_ENTER(et);
559                 CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
560                         struct sockaddr *sa;
561                         sa = ifa->ifa_addr;
562                         if (sa->sa_family != AF_INET)
563                                 continue;
564                         ia = ((struct sockaddr_in *)sa)->sin_addr;
565                         if (prison_check_ip4(cred, &ia) == 0) {
566                                 found = 1;
567                                 break;
568                         }
569                 }
570                 NET_EPOCH_EXIT(et);
571                 if (!found) {
572                         /*
573                          * As a last resort return the 'default' jail address.
574                          */
575                         ia = ((struct sockaddr_in *)nh->nh_ifa->ifa_addr)->
576                             sin_addr;
577                         if (prison_get_ip4(cred, &ia) != 0)
578                                 return (ESRCH);
579                 }
580                 bzero(&saun->sin, sizeof(struct sockaddr_in));
581                 saun->sin.sin_len = sizeof(struct sockaddr_in);
582                 saun->sin.sin_family = AF_INET;
583                 saun->sin.sin_addr.s_addr = ia.s_addr;
584                 info->rti_info[RTAX_IFA] = (struct sockaddr *)&saun->sin;
585                 break;
586         }
587 #endif
588 #ifdef INET6
589         case AF_INET6:
590         {
591                 struct in6_addr ia6;
592                 struct ifaddr *ifa;
593                 int found;
594
595                 found = 0;
596                 /*
597                  * Try to find an address on the given outgoing interface
598                  * that belongs to the jail.
599                  */
600                 NET_EPOCH_ENTER(et);
601                 CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
602                         struct sockaddr *sa;
603                         sa = ifa->ifa_addr;
604                         if (sa->sa_family != AF_INET6)
605                                 continue;
606                         bcopy(&((struct sockaddr_in6 *)sa)->sin6_addr,
607                             &ia6, sizeof(struct in6_addr));
608                         if (prison_check_ip6(cred, &ia6) == 0) {
609                                 found = 1;
610                                 break;
611                         }
612                 }
613                 NET_EPOCH_EXIT(et);
614                 if (!found) {
615                         /*
616                          * As a last resort return the 'default' jail address.
617                          */
618                         ia6 = ((struct sockaddr_in6 *)nh->nh_ifa->ifa_addr)->
619                             sin6_addr;
620                         if (prison_get_ip6(cred, &ia6) != 0)
621                                 return (ESRCH);
622                 }
623                 bzero(&saun->sin6, sizeof(struct sockaddr_in6));
624                 saun->sin6.sin6_len = sizeof(struct sockaddr_in6);
625                 saun->sin6.sin6_family = AF_INET6;
626                 bcopy(&ia6, &saun->sin6.sin6_addr, sizeof(struct in6_addr));
627                 if (sa6_recoverscope(&saun->sin6) != 0)
628                         return (ESRCH);
629                 info->rti_info[RTAX_IFA] = (struct sockaddr *)&saun->sin6;
630                 break;
631         }
632 #endif
633         default:
634                 return (ESRCH);
635         }
636         return (0);
637 }
638
639 static int
640 fill_blackholeinfo(struct rt_addrinfo *info, union sockaddr_union *saun)
641 {
642         struct ifaddr *ifa;
643         sa_family_t saf;
644
645         if (V_loif == NULL) {
646                 RTS_PID_LOG(LOG_INFO, "Unable to add blackhole/reject nhop without loopback");
647                 return (ENOTSUP);
648         }
649         info->rti_ifp = V_loif;
650
651         saf = info->rti_info[RTAX_DST]->sa_family;
652
653         CK_STAILQ_FOREACH(ifa, &info->rti_ifp->if_addrhead, ifa_link) {
654                 if (ifa->ifa_addr->sa_family == saf) {
655                         info->rti_ifa = ifa;
656                         break;
657                 }
658         }
659         if (info->rti_ifa == NULL) {
660                 RTS_PID_LOG(LOG_INFO, "Unable to find ifa for blackhole/reject nhop");
661                 return (ENOTSUP);
662         }
663
664         bzero(saun, sizeof(union sockaddr_union));
665         switch (saf) {
666 #ifdef INET
667         case AF_INET:
668                 saun->sin.sin_family = AF_INET;
669                 saun->sin.sin_len = sizeof(struct sockaddr_in);
670                 saun->sin.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
671                 break;
672 #endif
673 #ifdef INET6
674         case AF_INET6:
675                 saun->sin6.sin6_family = AF_INET6;
676                 saun->sin6.sin6_len = sizeof(struct sockaddr_in6);
677                 saun->sin6.sin6_addr = in6addr_loopback;
678                 break;
679 #endif
680         default:
681                 RTS_PID_LOG(LOG_INFO, "unsupported family: %d", saf);
682                 return (ENOTSUP);
683         }
684         info->rti_info[RTAX_GATEWAY] = &saun->sa;
685         info->rti_flags |= RTF_GATEWAY;
686
687         return (0);
688 }
689
690 /*
691  * Fills in @info based on userland-provided @rtm message.
692  *
693  * Returns 0 on success.
694  */
695 static int
696 fill_addrinfo(struct rt_msghdr *rtm, int len, struct linear_buffer *lb, u_int fibnum,
697     struct rt_addrinfo *info)
698 {
699         int error;
700         sa_family_t saf;
701
702         rtm->rtm_pid = curproc->p_pid;
703         info->rti_addrs = rtm->rtm_addrs;
704
705         info->rti_mflags = rtm->rtm_inits;
706         info->rti_rmx = &rtm->rtm_rmx;
707
708         /*
709          * rt_xaddrs() performs s6_addr[2] := sin6_scope_id for AF_INET6
710          * link-local address because rtrequest requires addresses with
711          * embedded scope id.
712          */
713         if (rt_xaddrs((caddr_t)(rtm + 1), len + (caddr_t)rtm, info))
714                 return (EINVAL);
715
716         info->rti_flags = rtm->rtm_flags;
717         error = cleanup_xaddrs(info, lb);
718         if (error != 0)
719                 return (error);
720         saf = info->rti_info[RTAX_DST]->sa_family;
721         /*
722          * Verify that the caller has the appropriate privilege; RTM_GET
723          * is the only operation the non-superuser is allowed.
724          */
725         if (rtm->rtm_type != RTM_GET) {
726                 error = priv_check(curthread, PRIV_NET_ROUTE);
727                 if (error != 0)
728                         return (error);
729         }
730
731         /*
732          * The given gateway address may be an interface address.
733          * For example, issuing a "route change" command on a route
734          * entry that was created from a tunnel, and the gateway
735          * address given is the local end point. In this case the 
736          * RTF_GATEWAY flag must be cleared or the destination will
737          * not be reachable even though there is no error message.
738          */
739         if (info->rti_info[RTAX_GATEWAY] != NULL &&
740             info->rti_info[RTAX_GATEWAY]->sa_family != AF_LINK) {
741                 struct rt_addrinfo ginfo;
742                 struct sockaddr *gdst;
743                 struct sockaddr_storage ss;
744
745                 bzero(&ginfo, sizeof(ginfo));
746                 bzero(&ss, sizeof(ss));
747                 ss.ss_len = sizeof(ss);
748
749                 ginfo.rti_info[RTAX_GATEWAY] = (struct sockaddr *)&ss;
750                 gdst = info->rti_info[RTAX_GATEWAY];
751
752                 /* 
753                  * A host route through the loopback interface is 
754                  * installed for each interface adddress. In pre 8.0
755                  * releases the interface address of a PPP link type
756                  * is not reachable locally. This behavior is fixed as 
757                  * part of the new L2/L3 redesign and rewrite work. The
758                  * signature of this interface address route is the
759                  * AF_LINK sa_family type of the gateway, and the
760                  * rt_ifp has the IFF_LOOPBACK flag set.
761                  */
762                 if (rib_lookup_info(fibnum, gdst, NHR_REF, 0, &ginfo) == 0) {
763                         if (ss.ss_family == AF_LINK &&
764                             ginfo.rti_ifp->if_flags & IFF_LOOPBACK) {
765                                 info->rti_flags &= ~RTF_GATEWAY;
766                                 info->rti_flags |= RTF_GWFLAG_COMPAT;
767                         }
768                         rib_free_info(&ginfo);
769                 }
770         }
771
772         return (0);
773 }
774
775 static struct nhop_object *
776 select_nhop(struct nhop_object *nh, const struct sockaddr *gw)
777 {
778         if (!NH_IS_NHGRP(nh))
779                 return (nh);
780 #ifdef ROUTE_MPATH
781         const struct weightened_nhop *wn;
782         uint32_t num_nhops;
783         wn = nhgrp_get_nhops((struct nhgrp_object *)nh, &num_nhops);
784         if (gw == NULL)
785                 return (wn[0].nh);
786         for (int i = 0; i < num_nhops; i++) {
787                 if (match_nhop_gw(wn[i].nh, gw))
788                         return (wn[i].nh);
789         }
790 #endif
791         return (NULL);
792 }
793
794 /*
795  * Handles RTM_GET message from routing socket, returning matching rt.
796  *
797  * Returns:
798  * 0 on success, with locked and referenced matching rt in @rt_nrt
799  * errno of failure
800  */
801 static int
802 handle_rtm_get(struct rt_addrinfo *info, u_int fibnum,
803     struct rt_msghdr *rtm, struct rib_cmd_info *rc)
804 {
805         RIB_RLOCK_TRACKER;
806         struct rib_head *rnh;
807         struct nhop_object *nh;
808         sa_family_t saf;
809
810         saf = info->rti_info[RTAX_DST]->sa_family;
811
812         rnh = rt_tables_get_rnh(fibnum, saf);
813         if (rnh == NULL)
814                 return (EAFNOSUPPORT);
815
816         RIB_RLOCK(rnh);
817
818         /*
819          * By (implicit) convention host route (one without netmask)
820          * means longest-prefix-match request and the route with netmask
821          * means exact-match lookup.
822          * As cleanup_xaddrs() cleans up info flags&addrs for the /32,/128
823          * prefixes, use original data to check for the netmask presence.
824          */
825         if ((rtm->rtm_addrs & RTA_NETMASK) == 0) {
826                 /*
827                  * Provide longest prefix match for
828                  * address lookup (no mask).
829                  * 'route -n get addr'
830                  */
831                 rc->rc_rt = (struct rtentry *) rnh->rnh_matchaddr(
832                     info->rti_info[RTAX_DST], &rnh->head);
833         } else
834                 rc->rc_rt = (struct rtentry *) rnh->rnh_lookup(
835                     info->rti_info[RTAX_DST],
836                     info->rti_info[RTAX_NETMASK], &rnh->head);
837
838         if (rc->rc_rt == NULL) {
839                 RIB_RUNLOCK(rnh);
840                 return (ESRCH);
841         }
842
843         nh = select_nhop(rt_get_raw_nhop(rc->rc_rt), info->rti_info[RTAX_GATEWAY]);
844         if (nh == NULL) {
845                 RIB_RUNLOCK(rnh);
846                 return (ESRCH);
847         }
848         /*
849          * If performing proxied L2 entry insertion, and
850          * the actual PPP host entry is found, perform
851          * another search to retrieve the prefix route of
852          * the local end point of the PPP link.
853          * TODO: move this logic to userland.
854          */
855         if (rtm->rtm_flags & RTF_ANNOUNCE) {
856                 struct sockaddr_storage laddr;
857
858                 if (nh->nh_ifp != NULL &&
859                     nh->nh_ifp->if_type == IFT_PROPVIRTUAL) {
860                         struct ifaddr *ifa;
861
862                         ifa = ifa_ifwithnet(info->rti_info[RTAX_DST], 1,
863                                         RT_ALL_FIBS);
864                         if (ifa != NULL)
865                                 rt_maskedcopy(ifa->ifa_addr,
866                                               (struct sockaddr *)&laddr,
867                                               ifa->ifa_netmask);
868                 } else
869                         rt_maskedcopy(nh->nh_ifa->ifa_addr,
870                                       (struct sockaddr *)&laddr,
871                                       nh->nh_ifa->ifa_netmask);
872                 /* 
873                  * refactor rt and no lock operation necessary
874                  */
875                 rc->rc_rt = (struct rtentry *)rnh->rnh_matchaddr(
876                     (struct sockaddr *)&laddr, &rnh->head);
877                 if (rc->rc_rt == NULL) {
878                         RIB_RUNLOCK(rnh);
879                         return (ESRCH);
880                 }
881                 nh = select_nhop(rt_get_raw_nhop(rc->rc_rt), info->rti_info[RTAX_GATEWAY]);
882                 if (nh == NULL) {
883                         RIB_RUNLOCK(rnh);
884                         return (ESRCH);
885                 }
886         }
887         rc->rc_nh_new = nh;
888         rc->rc_nh_weight = rc->rc_rt->rt_weight;
889         RIB_RUNLOCK(rnh);
890
891         return (0);
892 }
893
894 static void
895 init_sockaddrs_family(int family, struct sockaddr *dst, struct sockaddr *mask)
896 {
897 #ifdef INET
898         if (family == AF_INET) {
899                 struct sockaddr_in *dst4 = (struct sockaddr_in *)dst;
900                 struct sockaddr_in *mask4 = (struct sockaddr_in *)mask;
901
902                 bzero(dst4, sizeof(struct sockaddr_in));
903                 bzero(mask4, sizeof(struct sockaddr_in));
904
905                 dst4->sin_family = AF_INET;
906                 dst4->sin_len = sizeof(struct sockaddr_in);
907                 mask4->sin_family = AF_INET;
908                 mask4->sin_len = sizeof(struct sockaddr_in);
909         }
910 #endif
911 #ifdef INET6
912         if (family == AF_INET6) {
913                 struct sockaddr_in6 *dst6 = (struct sockaddr_in6 *)dst;
914                 struct sockaddr_in6 *mask6 = (struct sockaddr_in6 *)mask;
915
916                 bzero(dst6, sizeof(struct sockaddr_in6));
917                 bzero(mask6, sizeof(struct sockaddr_in6));
918
919                 dst6->sin6_family = AF_INET6;
920                 dst6->sin6_len = sizeof(struct sockaddr_in6);
921                 mask6->sin6_family = AF_INET6;
922                 mask6->sin6_len = sizeof(struct sockaddr_in6);
923         }
924 #endif
925 }
926
927 static void
928 export_rtaddrs(const struct rtentry *rt, struct sockaddr *dst,
929     struct sockaddr *mask)
930 {
931 #ifdef INET
932         if (dst->sa_family == AF_INET) {
933                 struct sockaddr_in *dst4 = (struct sockaddr_in *)dst;
934                 struct sockaddr_in *mask4 = (struct sockaddr_in *)mask;
935                 uint32_t scopeid = 0;
936                 rt_get_inet_prefix_pmask(rt, &dst4->sin_addr, &mask4->sin_addr,
937                     &scopeid);
938                 return;
939         }
940 #endif
941 #ifdef INET6
942         if (dst->sa_family == AF_INET6) {
943                 struct sockaddr_in6 *dst6 = (struct sockaddr_in6 *)dst;
944                 struct sockaddr_in6 *mask6 = (struct sockaddr_in6 *)mask;
945                 uint32_t scopeid = 0;
946                 rt_get_inet6_prefix_pmask(rt, &dst6->sin6_addr,
947                     &mask6->sin6_addr, &scopeid);
948                 dst6->sin6_scope_id = scopeid;
949                 return;
950         }
951 #endif
952 }
953
954 static int
955 update_rtm_from_info(struct rt_addrinfo *info, struct rt_msghdr **prtm,
956     int alloc_len)
957 {
958         struct rt_msghdr *rtm, *orig_rtm = NULL;
959         struct walkarg w;
960         int len;
961
962         rtm = *prtm;
963         /* Check if we need to realloc storage */
964         rtsock_msg_buffer(rtm->rtm_type, info, NULL, &len);
965         if (len > alloc_len) {
966                 struct rt_msghdr *tmp_rtm;
967
968                 tmp_rtm = malloc(len, M_TEMP, M_NOWAIT);
969                 if (tmp_rtm == NULL)
970                         return (ENOBUFS);
971                 bcopy(rtm, tmp_rtm, rtm->rtm_msglen);
972                 orig_rtm = rtm;
973                 rtm = tmp_rtm;
974                 alloc_len = len;
975
976                 /*
977                  * Delay freeing original rtm as info contains
978                  * data referencing it.
979                  */
980         }
981
982         w.w_tmem = (caddr_t)rtm;
983         w.w_tmemsize = alloc_len;
984         rtsock_msg_buffer(rtm->rtm_type, info, &w, &len);
985         rtm->rtm_addrs = info->rti_addrs;
986
987         if (orig_rtm != NULL)
988                 free(orig_rtm, M_TEMP);
989         *prtm = rtm;
990         return (0);
991 }
992
993
994 /*
995  * Update sockaddrs, flags, etc in @prtm based on @rc data.
996  * rtm can be reallocated.
997  *
998  * Returns 0 on success, along with pointer to (potentially reallocated)
999  *  rtm.
1000  *
1001  */
1002 static int
1003 update_rtm_from_rc(struct rt_addrinfo *info, struct rt_msghdr **prtm,
1004     int alloc_len, struct rib_cmd_info *rc, struct nhop_object *nh)
1005 {
1006         union sockaddr_union saun;
1007         struct rt_msghdr *rtm;
1008         struct ifnet *ifp;
1009         int error;
1010
1011         rtm = *prtm;
1012         union sockaddr_union sa_dst, sa_mask;
1013         int family = info->rti_info[RTAX_DST]->sa_family;
1014         init_sockaddrs_family(family, &sa_dst.sa, &sa_mask.sa);
1015         export_rtaddrs(rc->rc_rt, &sa_dst.sa, &sa_mask.sa);
1016
1017         info->rti_info[RTAX_DST] = &sa_dst.sa;
1018         info->rti_info[RTAX_NETMASK] = rt_is_host(rc->rc_rt) ? NULL : &sa_mask.sa;
1019         info->rti_info[RTAX_GATEWAY] = &nh->gw_sa;
1020         info->rti_info[RTAX_GENMASK] = 0;
1021         ifp = nh->nh_ifp;
1022         if (rtm->rtm_addrs & (RTA_IFP | RTA_IFA)) {
1023                 if (ifp) {
1024                         info->rti_info[RTAX_IFP] =
1025                             ifp->if_addr->ifa_addr;
1026                         error = rtm_get_jailed(info, ifp, nh,
1027                             &saun, curthread->td_ucred);
1028                         if (error != 0)
1029                                 return (error);
1030                         if (ifp->if_flags & IFF_POINTOPOINT)
1031                                 info->rti_info[RTAX_BRD] =
1032                                     nh->nh_ifa->ifa_dstaddr;
1033                         rtm->rtm_index = ifp->if_index;
1034                 } else {
1035                         info->rti_info[RTAX_IFP] = NULL;
1036                         info->rti_info[RTAX_IFA] = NULL;
1037                 }
1038         } else if (ifp != NULL)
1039                 rtm->rtm_index = ifp->if_index;
1040
1041         if ((error = update_rtm_from_info(info, prtm, alloc_len)) != 0)
1042                 return (error);
1043
1044         rtm = *prtm;
1045         rtm->rtm_flags = rc->rc_rt->rte_flags | nhop_get_rtflags(nh);
1046         if (rtm->rtm_flags & RTF_GWFLAG_COMPAT)
1047                 rtm->rtm_flags = RTF_GATEWAY | 
1048                         (rtm->rtm_flags & ~RTF_GWFLAG_COMPAT);
1049         rt_getmetrics(rc->rc_rt, nh, &rtm->rtm_rmx);
1050         rtm->rtm_rmx.rmx_weight = rc->rc_nh_weight;
1051
1052         return (0);
1053 }
1054
1055 #ifdef ROUTE_MPATH
1056 static void
1057 save_del_notification(const struct rib_cmd_info *rc, void *_cbdata)
1058 {
1059         struct rib_cmd_info *rc_new = (struct rib_cmd_info *)_cbdata;
1060
1061         if (rc->rc_cmd == RTM_DELETE)
1062                 *rc_new = *rc;
1063 }
1064
1065 static void
1066 save_add_notification(const struct rib_cmd_info *rc, void *_cbdata)
1067 {
1068         struct rib_cmd_info *rc_new = (struct rib_cmd_info *)_cbdata;
1069
1070         if (rc->rc_cmd == RTM_ADD)
1071                 *rc_new = *rc;
1072 }
1073 #endif
1074
1075 static struct sockaddr *
1076 alloc_sockaddr_aligned(struct linear_buffer *lb, int len)
1077 {
1078         len = roundup2(len, sizeof(uint64_t));
1079         if (lb->offset + len > lb->size)
1080                 return (NULL);
1081         struct sockaddr *sa = (struct sockaddr *)(lb->base + lb->offset);
1082         lb->offset += len;
1083         return (sa);
1084 }
1085
1086 /*ARGSUSED*/
1087 static int
1088 route_output(struct mbuf *m, struct socket *so, ...)
1089 {
1090         struct rt_msghdr *rtm = NULL;
1091         struct rtentry *rt = NULL;
1092         struct rt_addrinfo info;
1093         struct epoch_tracker et;
1094 #ifdef INET6
1095         struct sockaddr_storage ss;
1096         struct sockaddr_in6 *sin6;
1097         int i, rti_need_deembed = 0;
1098 #endif
1099         int alloc_len = 0, len, error = 0, fibnum;
1100         sa_family_t saf = AF_UNSPEC;
1101         struct rib_cmd_info rc;
1102         struct nhop_object *nh;
1103
1104         fibnum = so->so_fibnum;
1105 #define senderr(e) { error = e; goto flush;}
1106         if (m == NULL || ((m->m_len < sizeof(long)) &&
1107                        (m = m_pullup(m, sizeof(long))) == NULL))
1108                 return (ENOBUFS);
1109         if ((m->m_flags & M_PKTHDR) == 0)
1110                 panic("route_output");
1111         NET_EPOCH_ENTER(et);
1112         len = m->m_pkthdr.len;
1113         if (len < sizeof(*rtm) ||
1114             len != mtod(m, struct rt_msghdr *)->rtm_msglen)
1115                 senderr(EINVAL);
1116
1117         /*
1118          * Most of current messages are in range 200-240 bytes,
1119          * minimize possible re-allocation on reply using larger size
1120          * buffer aligned on 1k boundaty.
1121          */
1122         alloc_len = roundup2(len, 1024);
1123         int total_len = alloc_len + SCRATCH_BUFFER_SIZE;
1124         if ((rtm = malloc(total_len, M_TEMP, M_NOWAIT)) == NULL)
1125                 senderr(ENOBUFS);
1126
1127         m_copydata(m, 0, len, (caddr_t)rtm);
1128         bzero(&info, sizeof(info));
1129         nh = NULL;
1130         struct linear_buffer lb = {
1131                 .base = (char *)rtm + alloc_len,
1132                 .size = SCRATCH_BUFFER_SIZE,
1133         };
1134
1135         if (rtm->rtm_version != RTM_VERSION) {
1136                 /* Do not touch message since format is unknown */
1137                 free(rtm, M_TEMP);
1138                 rtm = NULL;
1139                 senderr(EPROTONOSUPPORT);
1140         }
1141
1142         /*
1143          * Starting from here, it is possible
1144          * to alter original message and insert
1145          * caller PID and error value.
1146          */
1147
1148         if ((error = fill_addrinfo(rtm, len, &lb, fibnum, &info)) != 0) {
1149                 senderr(error);
1150         }
1151         /* fill_addringo() embeds scope into IPv6 addresses */
1152 #ifdef INET6
1153         rti_need_deembed = 1;
1154 #endif
1155
1156         saf = info.rti_info[RTAX_DST]->sa_family;
1157
1158         /* support for new ARP code */
1159         if (rtm->rtm_flags & RTF_LLDATA) {
1160                 error = lla_rt_output(rtm, &info);
1161                 goto flush;
1162         }
1163
1164         union sockaddr_union gw_saun;
1165         int blackhole_flags = rtm->rtm_flags & (RTF_BLACKHOLE|RTF_REJECT);
1166         if (blackhole_flags != 0) {
1167                 if (blackhole_flags != (RTF_BLACKHOLE | RTF_REJECT))
1168                         error = fill_blackholeinfo(&info, &gw_saun);
1169                 else {
1170                         RTS_PID_LOG(LOG_DEBUG, "both BLACKHOLE and REJECT flags specifiied");
1171                         error = EINVAL;
1172                 }
1173                 if (error != 0)
1174                         senderr(error);
1175         }
1176
1177         switch (rtm->rtm_type) {
1178         case RTM_ADD:
1179         case RTM_CHANGE:
1180                 if (rtm->rtm_type == RTM_ADD) {
1181                         if (info.rti_info[RTAX_GATEWAY] == NULL) {
1182                                 RTS_PID_LOG(LOG_DEBUG, "RTM_ADD w/o gateway");
1183                                 senderr(EINVAL);
1184                         }
1185                 }
1186                 error = rib_action(fibnum, rtm->rtm_type, &info, &rc);
1187                 if (error == 0) {
1188                         rtsock_notify_event(fibnum, &rc);
1189 #ifdef ROUTE_MPATH
1190                         if (NH_IS_NHGRP(rc.rc_nh_new) ||
1191                             (rc.rc_nh_old && NH_IS_NHGRP(rc.rc_nh_old))) {
1192                                 struct rib_cmd_info rc_simple = {};
1193                                 rib_decompose_notification(&rc,
1194                                     save_add_notification, (void *)&rc_simple);
1195                                 rc = rc_simple;
1196                         }
1197 #endif
1198                         /* nh MAY be empty if RTM_CHANGE request is no-op */
1199                         nh = rc.rc_nh_new;
1200                         if (nh != NULL) {
1201                                 rtm->rtm_index = nh->nh_ifp->if_index;
1202                                 rtm->rtm_flags = rc.rc_rt->rte_flags | nhop_get_rtflags(nh);
1203                         }
1204                 }
1205                 break;
1206
1207         case RTM_DELETE:
1208                 error = rib_action(fibnum, RTM_DELETE, &info, &rc);
1209                 if (error == 0) {
1210                         rtsock_notify_event(fibnum, &rc);
1211 #ifdef ROUTE_MPATH
1212                         if (NH_IS_NHGRP(rc.rc_nh_old) ||
1213                             (rc.rc_nh_new && NH_IS_NHGRP(rc.rc_nh_new))) {
1214                                 struct rib_cmd_info rc_simple = {};
1215                                 rib_decompose_notification(&rc,
1216                                     save_del_notification, (void *)&rc_simple);
1217                                 rc = rc_simple;
1218                         }
1219 #endif
1220                         nh = rc.rc_nh_old;
1221                 }
1222                 break;
1223
1224         case RTM_GET:
1225                 error = handle_rtm_get(&info, fibnum, rtm, &rc);
1226                 if (error != 0)
1227                         senderr(error);
1228                 nh = rc.rc_nh_new;
1229
1230                 if (!rt_is_exportable(rc.rc_rt, curthread->td_ucred))
1231                         senderr(ESRCH);
1232                 break;
1233
1234         default:
1235                 senderr(EOPNOTSUPP);
1236         }
1237
1238         if (error == 0 && nh != NULL) {
1239                 error = update_rtm_from_rc(&info, &rtm, alloc_len, &rc, nh);
1240                 /*
1241                  * Note that some sockaddr pointers may have changed to
1242                  * point to memory outsize @rtm. Some may be pointing
1243                  * to the on-stack variables.
1244                  * Given that, any pointer in @info CANNOT BE USED.
1245                  */
1246
1247                 /*
1248                  * scopeid deembedding has been performed while
1249                  * writing updated rtm in rtsock_msg_buffer().
1250                  * With that in mind, skip deembedding procedure below.
1251                  */
1252 #ifdef INET6
1253                 rti_need_deembed = 0;
1254 #endif
1255         }
1256
1257 flush:
1258         NET_EPOCH_EXIT(et);
1259         rt = NULL;
1260
1261 #ifdef INET6
1262         if (rtm != NULL) {
1263                 if (rti_need_deembed) {
1264                         /* sin6_scope_id is recovered before sending rtm. */
1265                         sin6 = (struct sockaddr_in6 *)&ss;
1266                         for (i = 0; i < RTAX_MAX; i++) {
1267                                 if (info.rti_info[i] == NULL)
1268                                         continue;
1269                                 if (info.rti_info[i]->sa_family != AF_INET6)
1270                                         continue;
1271                                 bcopy(info.rti_info[i], sin6, sizeof(*sin6));
1272                                 if (sa6_recoverscope(sin6) == 0)
1273                                         bcopy(sin6, info.rti_info[i],
1274                                                     sizeof(*sin6));
1275                         }
1276                         if (update_rtm_from_info(&info, &rtm, alloc_len) != 0) {
1277                                 if (error != 0)
1278                                         error = ENOBUFS;
1279                         }
1280                 }
1281         }
1282 #endif
1283         send_rtm_reply(so, rtm, m, saf, fibnum, error);
1284
1285         return (error);
1286 }
1287
1288 /*
1289  * Sends the prepared reply message in @rtm to all rtsock clients.
1290  * Frees @m and @rtm.
1291  *
1292  */
1293 static void
1294 send_rtm_reply(struct socket *so, struct rt_msghdr *rtm, struct mbuf *m,
1295     sa_family_t saf, u_int fibnum, int rtm_errno)
1296 {
1297         struct rawcb *rp = NULL;
1298
1299         /*
1300          * Check to see if we don't want our own messages.
1301          */
1302         if ((so->so_options & SO_USELOOPBACK) == 0) {
1303                 if (V_route_cb.any_count <= 1) {
1304                         if (rtm != NULL)
1305                                 free(rtm, M_TEMP);
1306                         m_freem(m);
1307                         return;
1308                 }
1309                 /* There is another listener, so construct message */
1310                 rp = sotorawcb(so);
1311         }
1312
1313         if (rtm != NULL) {
1314                 if (rtm_errno!= 0)
1315                         rtm->rtm_errno = rtm_errno;
1316                 else
1317                         rtm->rtm_flags |= RTF_DONE;
1318
1319                 m_copyback(m, 0, rtm->rtm_msglen, (caddr_t)rtm);
1320                 if (m->m_pkthdr.len < rtm->rtm_msglen) {
1321                         m_freem(m);
1322                         m = NULL;
1323                 } else if (m->m_pkthdr.len > rtm->rtm_msglen)
1324                         m_adj(m, rtm->rtm_msglen - m->m_pkthdr.len);
1325
1326                 free(rtm, M_TEMP);
1327         }
1328         if (m != NULL) {
1329                 M_SETFIB(m, fibnum);
1330                 m->m_flags |= RTS_FILTER_FIB;
1331                 if (rp) {
1332                         /*
1333                          * XXX insure we don't get a copy by
1334                          * invalidating our protocol
1335                          */
1336                         unsigned short family = rp->rcb_proto.sp_family;
1337                         rp->rcb_proto.sp_family = 0;
1338                         rt_dispatch(m, saf);
1339                         rp->rcb_proto.sp_family = family;
1340                 } else
1341                         rt_dispatch(m, saf);
1342         }
1343 }
1344
1345 static void
1346 rt_getmetrics(const struct rtentry *rt, const struct nhop_object *nh,
1347     struct rt_metrics *out)
1348 {
1349
1350         bzero(out, sizeof(*out));
1351         out->rmx_mtu = nh->nh_mtu;
1352         out->rmx_weight = rt->rt_weight;
1353         out->rmx_nhidx = nhop_get_idx(nh);
1354         /* Kernel -> userland timebase conversion. */
1355         out->rmx_expire = nhop_get_expire(nh) ?
1356             nhop_get_expire(nh) - time_uptime + time_second : 0;
1357 }
1358
1359 /*
1360  * Extract the addresses of the passed sockaddrs.
1361  * Do a little sanity checking so as to avoid bad memory references.
1362  * This data is derived straight from userland.
1363  */
1364 static int
1365 rt_xaddrs(caddr_t cp, caddr_t cplim, struct rt_addrinfo *rtinfo)
1366 {
1367         struct sockaddr *sa;
1368         int i;
1369
1370         for (i = 0; i < RTAX_MAX && cp < cplim; i++) {
1371                 if ((rtinfo->rti_addrs & (1 << i)) == 0)
1372                         continue;
1373                 sa = (struct sockaddr *)cp;
1374                 /*
1375                  * It won't fit.
1376                  */
1377                 if (cp + sa->sa_len > cplim) {
1378                         RTS_PID_LOG(LOG_DEBUG, "sa_len too big for sa type %d", i);
1379                         return (EINVAL);
1380                 }
1381                 /*
1382                  * there are no more.. quit now
1383                  * If there are more bits, they are in error.
1384                  * I've seen this. route(1) can evidently generate these. 
1385                  * This causes kernel to core dump.
1386                  * for compatibility, If we see this, point to a safe address.
1387                  */
1388                 if (sa->sa_len == 0) {
1389                         rtinfo->rti_info[i] = &sa_zero;
1390                         return (0); /* should be EINVAL but for compat */
1391                 }
1392                 /* accept it */
1393 #ifdef INET6
1394                 if (sa->sa_family == AF_INET6)
1395                         sa6_embedscope((struct sockaddr_in6 *)sa,
1396                             V_ip6_use_defzone);
1397 #endif
1398                 rtinfo->rti_info[i] = sa;
1399                 cp += SA_SIZE(sa);
1400         }
1401         return (0);
1402 }
1403
1404 #ifdef INET
1405 static inline void
1406 fill_sockaddr_inet(struct sockaddr_in *sin, struct in_addr addr)
1407 {
1408
1409         const struct sockaddr_in nsin = {
1410                 .sin_family = AF_INET,
1411                 .sin_len = sizeof(struct sockaddr_in),
1412                 .sin_addr = addr,
1413         };
1414         *sin = nsin;
1415 }
1416 #endif
1417
1418 #ifdef INET6
1419 static inline void
1420 fill_sockaddr_inet6(struct sockaddr_in6 *sin6, const struct in6_addr *addr6,
1421     uint32_t scopeid)
1422 {
1423
1424         const struct sockaddr_in6 nsin6 = {
1425                 .sin6_family = AF_INET6,
1426                 .sin6_len = sizeof(struct sockaddr_in6),
1427                 .sin6_addr = *addr6,
1428                 .sin6_scope_id = scopeid,
1429         };
1430         *sin6 = nsin6;
1431 }
1432 #endif
1433
1434 /*
1435  * Checks if gateway is suitable for lltable operations.
1436  * Lltable code requires AF_LINK gateway with ifindex
1437  *  and mac address specified.
1438  * Returns 0 on success.
1439  */
1440 static int
1441 cleanup_xaddrs_lladdr(struct rt_addrinfo *info)
1442 {
1443         struct sockaddr_dl *sdl = (struct sockaddr_dl *)info->rti_info[RTAX_GATEWAY];
1444
1445         if (sdl->sdl_family != AF_LINK)
1446                 return (EINVAL);
1447
1448         if (sdl->sdl_index == 0) {
1449                 RTS_PID_LOG(LOG_DEBUG, "AF_LINK gateway w/o ifindex");
1450                 return (EINVAL);
1451         }
1452
1453         if (offsetof(struct sockaddr_dl, sdl_data) + sdl->sdl_nlen + sdl->sdl_alen > sdl->sdl_len) {
1454                 RTS_PID_LOG(LOG_DEBUG, "AF_LINK gw: sdl_nlen/sdl_alen too large");
1455                 return (EINVAL);
1456         }
1457
1458         return (0);
1459 }
1460
1461 static int
1462 cleanup_xaddrs_gateway(struct rt_addrinfo *info, struct linear_buffer *lb)
1463 {
1464         struct sockaddr *gw = info->rti_info[RTAX_GATEWAY];
1465         struct sockaddr *sa;
1466
1467         if (info->rti_flags & RTF_LLDATA)
1468                 return (cleanup_xaddrs_lladdr(info));
1469
1470         switch (gw->sa_family) {
1471 #ifdef INET
1472         case AF_INET:
1473                 {
1474                         struct sockaddr_in *gw_sin = (struct sockaddr_in *)gw;
1475
1476                         /* Ensure reads do not go beyoud SA boundary */
1477                         if (SA_SIZE(gw) < offsetof(struct sockaddr_in, sin_zero)) {
1478                                 RTS_PID_LOG(LOG_DEBUG, "gateway sin_len too small: %d",
1479                                     gw->sa_len);
1480                                 return (EINVAL);
1481                         }
1482                         sa = alloc_sockaddr_aligned(lb, sizeof(struct sockaddr_in));
1483                         if (sa == NULL)
1484                                 return (ENOBUFS);
1485                         fill_sockaddr_inet((struct sockaddr_in *)sa, gw_sin->sin_addr);
1486                         info->rti_info[RTAX_GATEWAY] = sa;
1487                 }
1488                 break;
1489 #endif
1490 #ifdef INET6
1491         case AF_INET6:
1492                 {
1493                         struct sockaddr_in6 *gw_sin6 = (struct sockaddr_in6 *)gw;
1494                         if (gw_sin6->sin6_len < sizeof(struct sockaddr_in6)) {
1495                                 RTS_PID_LOG(LOG_DEBUG, "gateway sin6_len too small: %d",
1496                                     gw->sa_len);
1497                                 return (EINVAL);
1498                         }
1499                         fill_sockaddr_inet6(gw_sin6, &gw_sin6->sin6_addr, 0);
1500                         break;
1501                 }
1502 #endif
1503         case AF_LINK:
1504                 {
1505                         struct sockaddr_dl *gw_sdl;
1506
1507                         size_t sdl_min_len = offsetof(struct sockaddr_dl, sdl_data);
1508                         gw_sdl = (struct sockaddr_dl *)gw;
1509                         if (gw_sdl->sdl_len < sdl_min_len) {
1510                                 RTS_PID_LOG(LOG_DEBUG, "gateway sdl_len too small: %d",
1511                                     gw_sdl->sdl_len);
1512                                 return (EINVAL);
1513                         }
1514                         sa = alloc_sockaddr_aligned(lb, sizeof(struct sockaddr_dl_short));
1515                         if (sa == NULL)
1516                                 return (ENOBUFS);
1517
1518                         const struct sockaddr_dl_short sdl = {
1519                                 .sdl_family = AF_LINK,
1520                                 .sdl_len = sizeof(struct sockaddr_dl_short),
1521                                 .sdl_index = gw_sdl->sdl_index,
1522                         };
1523                         *((struct sockaddr_dl_short *)sa) = sdl;
1524                         info->rti_info[RTAX_GATEWAY] = sa;
1525                         break;
1526                 }
1527         }
1528
1529         return (0);
1530 }
1531
1532 static void
1533 remove_netmask(struct rt_addrinfo *info)
1534 {
1535         info->rti_info[RTAX_NETMASK] = NULL;
1536         info->rti_flags |= RTF_HOST;
1537         info->rti_addrs &= ~RTA_NETMASK;
1538 }
1539
1540 #ifdef INET
1541 static int
1542 cleanup_xaddrs_inet(struct rt_addrinfo *info, struct linear_buffer *lb)
1543 {
1544         struct sockaddr_in *dst_sa, *mask_sa;
1545         const int sa_len = sizeof(struct sockaddr_in);
1546         struct in_addr dst, mask;
1547
1548         /* Check & fixup dst/netmask combination first */
1549         dst_sa = (struct sockaddr_in *)info->rti_info[RTAX_DST];
1550         mask_sa = (struct sockaddr_in *)info->rti_info[RTAX_NETMASK];
1551
1552         /* Ensure reads do not go beyound the buffer size */
1553         if (SA_SIZE(dst_sa) < offsetof(struct sockaddr_in, sin_zero)) {
1554                 RTS_PID_LOG(LOG_DEBUG, "prefix dst sin_len too small: %d",
1555                     dst_sa->sin_len);
1556                 return (EINVAL);
1557         }
1558
1559         if ((mask_sa != NULL) && mask_sa->sin_len < sizeof(struct sockaddr_in)) {
1560                 /*
1561                  * Some older routing software encode mask length into the
1562                  * sin_len, thus resulting in "truncated" sockaddr.
1563                  */
1564                 int len = mask_sa->sin_len - offsetof(struct sockaddr_in, sin_addr);
1565                 if (len >= 0) {
1566                         mask.s_addr = 0;
1567                         if (len > sizeof(struct in_addr))
1568                                 len = sizeof(struct in_addr);
1569                         memcpy(&mask, &mask_sa->sin_addr, len);
1570                 } else {
1571                         RTS_PID_LOG(LOG_DEBUG, "prefix mask sin_len too small: %d",
1572                             mask_sa->sin_len);
1573                         return (EINVAL);
1574                 }
1575         } else
1576                 mask.s_addr = mask_sa ? mask_sa->sin_addr.s_addr : INADDR_BROADCAST;
1577
1578         dst.s_addr = htonl(ntohl(dst_sa->sin_addr.s_addr) & ntohl(mask.s_addr));
1579
1580         /* Construct new "clean" dst/mask sockaddresses */
1581         if ((dst_sa = (struct sockaddr_in *)alloc_sockaddr_aligned(lb, sa_len)) == NULL)
1582                 return (ENOBUFS);
1583         fill_sockaddr_inet(dst_sa, dst);
1584         info->rti_info[RTAX_DST] = (struct sockaddr *)dst_sa;
1585
1586         if (mask.s_addr != INADDR_BROADCAST) {
1587                 if ((mask_sa = (struct sockaddr_in *)alloc_sockaddr_aligned(lb, sa_len)) == NULL)
1588                         return (ENOBUFS);
1589                 fill_sockaddr_inet(mask_sa, mask);
1590                 info->rti_info[RTAX_NETMASK] = (struct sockaddr *)mask_sa;
1591                 info->rti_flags &= ~RTF_HOST;
1592         } else
1593                 remove_netmask(info);
1594
1595         /* Check gateway */
1596         if (info->rti_info[RTAX_GATEWAY] != NULL)
1597                 return (cleanup_xaddrs_gateway(info, lb));
1598
1599         return (0);
1600 }
1601 #endif
1602
1603 #ifdef INET6
1604 static int
1605 cleanup_xaddrs_inet6(struct rt_addrinfo *info, struct linear_buffer *lb)
1606 {
1607         struct sockaddr *sa;
1608         struct sockaddr_in6 *dst_sa, *mask_sa;
1609         struct in6_addr mask, *dst;
1610         const int sa_len = sizeof(struct sockaddr_in6);
1611
1612         /* Check & fixup dst/netmask combination first */
1613         dst_sa = (struct sockaddr_in6 *)info->rti_info[RTAX_DST];
1614         mask_sa = (struct sockaddr_in6 *)info->rti_info[RTAX_NETMASK];
1615
1616         if (dst_sa->sin6_len < sizeof(struct sockaddr_in6)) {
1617                 RTS_PID_LOG(LOG_DEBUG, "prefix dst sin6_len too small: %d",
1618                     dst_sa->sin6_len);
1619                 return (EINVAL);
1620         }
1621
1622         if (mask_sa && mask_sa->sin6_len < sizeof(struct sockaddr_in6)) {
1623                 /*
1624                  * Some older routing software encode mask length into the
1625                  * sin6_len, thus resulting in "truncated" sockaddr.
1626                  */
1627                 int len = mask_sa->sin6_len - offsetof(struct sockaddr_in6, sin6_addr);
1628                 if (len >= 0) {
1629                         bzero(&mask, sizeof(mask));
1630                         if (len > sizeof(struct in6_addr))
1631                                 len = sizeof(struct in6_addr);
1632                         memcpy(&mask, &mask_sa->sin6_addr, len);
1633                 } else {
1634                         RTS_PID_LOG(LOG_DEBUG, "rtsock: prefix mask sin6_len too small: %d",
1635                             mask_sa->sin6_len);
1636                         return (EINVAL);
1637                 }
1638         } else
1639                 mask = mask_sa ? mask_sa->sin6_addr : in6mask128;
1640
1641         dst = &dst_sa->sin6_addr;
1642         IN6_MASK_ADDR(dst, &mask);
1643
1644         if ((sa = alloc_sockaddr_aligned(lb, sa_len)) == NULL)
1645                 return (ENOBUFS);
1646         fill_sockaddr_inet6((struct sockaddr_in6 *)sa, dst, 0);
1647         info->rti_info[RTAX_DST] = sa;
1648
1649         if (!IN6_ARE_ADDR_EQUAL(&mask, &in6mask128)) {
1650                 if ((sa = alloc_sockaddr_aligned(lb, sa_len)) == NULL)
1651                         return (ENOBUFS);
1652                 fill_sockaddr_inet6((struct sockaddr_in6 *)sa, &mask, 0);
1653                 info->rti_info[RTAX_NETMASK] = sa;
1654                 info->rti_flags &= ~RTF_HOST;
1655         } else
1656                 remove_netmask(info);
1657
1658         /* Check gateway */
1659         if (info->rti_info[RTAX_GATEWAY] != NULL)
1660                 return (cleanup_xaddrs_gateway(info, lb));
1661
1662         return (0);
1663 }
1664 #endif
1665
1666 static int
1667 cleanup_xaddrs(struct rt_addrinfo *info, struct linear_buffer *lb)
1668 {
1669         int error = EAFNOSUPPORT;
1670
1671         if (info->rti_info[RTAX_DST] == NULL) {
1672                 RTS_PID_LOG(LOG_DEBUG, "prefix dst is not set");
1673                 return (EINVAL);
1674         }
1675
1676         if (info->rti_flags & RTF_LLDATA) {
1677                 /*
1678                  * arp(8)/ndp(8) sends RTA_NETMASK for the associated
1679                  * prefix along with the actual address in RTA_DST.
1680                  * Remove netmask to avoid unnecessary address masking.
1681                  */
1682                 remove_netmask(info);
1683         }
1684
1685         switch (info->rti_info[RTAX_DST]->sa_family) {
1686 #ifdef INET
1687         case AF_INET:
1688                 error = cleanup_xaddrs_inet(info, lb);
1689                 break;
1690 #endif
1691 #ifdef INET6
1692         case AF_INET6:
1693                 error = cleanup_xaddrs_inet6(info, lb);
1694                 break;
1695 #endif
1696         }
1697
1698         return (error);
1699 }
1700
1701 /*
1702  * Fill in @dmask with valid netmask leaving original @smask
1703  * intact. Mostly used with radix netmasks.
1704  */
1705 struct sockaddr *
1706 rtsock_fix_netmask(const struct sockaddr *dst, const struct sockaddr *smask,
1707     struct sockaddr_storage *dmask)
1708 {
1709         if (dst == NULL || smask == NULL)
1710                 return (NULL);
1711
1712         memset(dmask, 0, dst->sa_len);
1713         memcpy(dmask, smask, smask->sa_len);
1714         dmask->ss_len = dst->sa_len;
1715         dmask->ss_family = dst->sa_family;
1716
1717         return ((struct sockaddr *)dmask);
1718 }
1719
1720 /*
1721  * Writes information related to @rtinfo object to newly-allocated mbuf.
1722  * Assumes MCLBYTES is enough to construct any message.
1723  * Used for OS notifications of vaious events (if/ifa announces,etc)
1724  *
1725  * Returns allocated mbuf or NULL on failure.
1726  */
1727 static struct mbuf *
1728 rtsock_msg_mbuf(int type, struct rt_addrinfo *rtinfo)
1729 {
1730         struct sockaddr_storage ss;
1731         struct rt_msghdr *rtm;
1732         struct mbuf *m;
1733         int i;
1734         struct sockaddr *sa;
1735 #ifdef INET6
1736         struct sockaddr_in6 *sin6;
1737 #endif
1738         int len, dlen;
1739
1740         switch (type) {
1741         case RTM_DELADDR:
1742         case RTM_NEWADDR:
1743                 len = sizeof(struct ifa_msghdr);
1744                 break;
1745
1746         case RTM_DELMADDR:
1747         case RTM_NEWMADDR:
1748                 len = sizeof(struct ifma_msghdr);
1749                 break;
1750
1751         case RTM_IFINFO:
1752                 len = sizeof(struct if_msghdr);
1753                 break;
1754
1755         case RTM_IFANNOUNCE:
1756         case RTM_IEEE80211:
1757                 len = sizeof(struct if_announcemsghdr);
1758                 break;
1759
1760         default:
1761                 len = sizeof(struct rt_msghdr);
1762         }
1763
1764         /* XXXGL: can we use MJUMPAGESIZE cluster here? */
1765         KASSERT(len <= MCLBYTES, ("%s: message too big", __func__));
1766         if (len > MHLEN)
1767                 m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
1768         else
1769                 m = m_gethdr(M_NOWAIT, MT_DATA);
1770         if (m == NULL)
1771                 return (m);
1772
1773         m->m_pkthdr.len = m->m_len = len;
1774         rtm = mtod(m, struct rt_msghdr *);
1775         bzero((caddr_t)rtm, len);
1776         for (i = 0; i < RTAX_MAX; i++) {
1777                 if ((sa = rtinfo->rti_info[i]) == NULL)
1778                         continue;
1779                 rtinfo->rti_addrs |= (1 << i);
1780
1781                 dlen = SA_SIZE(sa);
1782                 KASSERT(dlen <= sizeof(ss),
1783                     ("%s: sockaddr size overflow", __func__));
1784                 bzero(&ss, sizeof(ss));
1785                 bcopy(sa, &ss, sa->sa_len);
1786                 sa = (struct sockaddr *)&ss;
1787 #ifdef INET6
1788                 if (sa->sa_family == AF_INET6) {
1789                         sin6 = (struct sockaddr_in6 *)sa;
1790                         (void)sa6_recoverscope(sin6);
1791                 }
1792 #endif
1793                 m_copyback(m, len, dlen, (caddr_t)sa);
1794                 len += dlen;
1795         }
1796         if (m->m_pkthdr.len != len) {
1797                 m_freem(m);
1798                 return (NULL);
1799         }
1800         rtm->rtm_msglen = len;
1801         rtm->rtm_version = RTM_VERSION;
1802         rtm->rtm_type = type;
1803         return (m);
1804 }
1805
1806 /*
1807  * Writes information related to @rtinfo object to preallocated buffer.
1808  * Stores needed size in @plen. If @w is NULL, calculates size without
1809  * writing.
1810  * Used for sysctl dumps and rtsock answers (RTM_DEL/RTM_GET) generation.
1811  *
1812  * Returns 0 on success.
1813  *
1814  */
1815 static int
1816 rtsock_msg_buffer(int type, struct rt_addrinfo *rtinfo, struct walkarg *w, int *plen)
1817 {
1818         struct sockaddr_storage ss;
1819         int len, buflen = 0, dlen, i;
1820         caddr_t cp = NULL;
1821         struct rt_msghdr *rtm = NULL;
1822 #ifdef INET6
1823         struct sockaddr_in6 *sin6;
1824 #endif
1825 #ifdef COMPAT_FREEBSD32
1826         bool compat32 = false;
1827 #endif
1828
1829         switch (type) {
1830         case RTM_DELADDR:
1831         case RTM_NEWADDR:
1832                 if (w != NULL && w->w_op == NET_RT_IFLISTL) {
1833 #ifdef COMPAT_FREEBSD32
1834                         if (w->w_req->flags & SCTL_MASK32) {
1835                                 len = sizeof(struct ifa_msghdrl32);
1836                                 compat32 = true;
1837                         } else
1838 #endif
1839                                 len = sizeof(struct ifa_msghdrl);
1840                 } else
1841                         len = sizeof(struct ifa_msghdr);
1842                 break;
1843
1844         case RTM_IFINFO:
1845 #ifdef COMPAT_FREEBSD32
1846                 if (w != NULL && w->w_req->flags & SCTL_MASK32) {
1847                         if (w->w_op == NET_RT_IFLISTL)
1848                                 len = sizeof(struct if_msghdrl32);
1849                         else
1850                                 len = sizeof(struct if_msghdr32);
1851                         compat32 = true;
1852                         break;
1853                 }
1854 #endif
1855                 if (w != NULL && w->w_op == NET_RT_IFLISTL)
1856                         len = sizeof(struct if_msghdrl);
1857                 else
1858                         len = sizeof(struct if_msghdr);
1859                 break;
1860
1861         case RTM_NEWMADDR:
1862                 len = sizeof(struct ifma_msghdr);
1863                 break;
1864
1865         default:
1866                 len = sizeof(struct rt_msghdr);
1867         }
1868
1869         if (w != NULL) {
1870                 rtm = (struct rt_msghdr *)w->w_tmem;
1871                 buflen = w->w_tmemsize - len;
1872                 cp = (caddr_t)w->w_tmem + len;
1873         }
1874
1875         rtinfo->rti_addrs = 0;
1876         for (i = 0; i < RTAX_MAX; i++) {
1877                 struct sockaddr *sa;
1878
1879                 if ((sa = rtinfo->rti_info[i]) == NULL)
1880                         continue;
1881                 rtinfo->rti_addrs |= (1 << i);
1882 #ifdef COMPAT_FREEBSD32
1883                 if (compat32)
1884                         dlen = SA_SIZE32(sa);
1885                 else
1886 #endif
1887                         dlen = SA_SIZE(sa);
1888                 if (cp != NULL && buflen >= dlen) {
1889                         KASSERT(dlen <= sizeof(ss),
1890                             ("%s: sockaddr size overflow", __func__));
1891                         bzero(&ss, sizeof(ss));
1892                         bcopy(sa, &ss, sa->sa_len);
1893                         sa = (struct sockaddr *)&ss;
1894 #ifdef INET6
1895                         if (sa->sa_family == AF_INET6) {
1896                                 sin6 = (struct sockaddr_in6 *)sa;
1897                                 (void)sa6_recoverscope(sin6);
1898                         }
1899 #endif
1900                         bcopy((caddr_t)sa, cp, (unsigned)dlen);
1901                         cp += dlen;
1902                         buflen -= dlen;
1903                 } else if (cp != NULL) {
1904                         /*
1905                          * Buffer too small. Count needed size
1906                          * and return with error.
1907                          */
1908                         cp = NULL;
1909                 }
1910
1911                 len += dlen;
1912         }
1913
1914         if (cp != NULL) {
1915                 dlen = ALIGN(len) - len;
1916                 if (buflen < dlen)
1917                         cp = NULL;
1918                 else {
1919                         bzero(cp, dlen);
1920                         cp += dlen;
1921                         buflen -= dlen;
1922                 }
1923         }
1924         len = ALIGN(len);
1925
1926         if (cp != NULL) {
1927                 /* fill header iff buffer is large enough */
1928                 rtm->rtm_version = RTM_VERSION;
1929                 rtm->rtm_type = type;
1930                 rtm->rtm_msglen = len;
1931         }
1932
1933         *plen = len;
1934
1935         if (w != NULL && cp == NULL)
1936                 return (ENOBUFS);
1937
1938         return (0);
1939 }
1940
1941 /*
1942  * This routine is called to generate a message from the routing
1943  * socket indicating that a redirect has occurred, a routing lookup
1944  * has failed, or that a protocol has detected timeouts to a particular
1945  * destination.
1946  */
1947 void
1948 rt_missmsg_fib(int type, struct rt_addrinfo *rtinfo, int flags, int error,
1949     int fibnum)
1950 {
1951         struct rt_msghdr *rtm;
1952         struct mbuf *m;
1953         struct sockaddr *sa = rtinfo->rti_info[RTAX_DST];
1954
1955         if (V_route_cb.any_count == 0)
1956                 return;
1957         m = rtsock_msg_mbuf(type, rtinfo);
1958         if (m == NULL)
1959                 return;
1960
1961         if (fibnum != RT_ALL_FIBS) {
1962                 KASSERT(fibnum >= 0 && fibnum < rt_numfibs, ("%s: fibnum out "
1963                     "of range 0 <= %d < %d", __func__, fibnum, rt_numfibs));
1964                 M_SETFIB(m, fibnum);
1965                 m->m_flags |= RTS_FILTER_FIB;
1966         }
1967
1968         rtm = mtod(m, struct rt_msghdr *);
1969         rtm->rtm_flags = RTF_DONE | flags;
1970         rtm->rtm_errno = error;
1971         rtm->rtm_addrs = rtinfo->rti_addrs;
1972         rt_dispatch(m, sa ? sa->sa_family : AF_UNSPEC);
1973 }
1974
1975 void
1976 rt_missmsg(int type, struct rt_addrinfo *rtinfo, int flags, int error)
1977 {
1978
1979         rt_missmsg_fib(type, rtinfo, flags, error, RT_ALL_FIBS);
1980 }
1981
1982 /*
1983  * This routine is called to generate a message from the routing
1984  * socket indicating that the status of a network interface has changed.
1985  */
1986 static void
1987 rtsock_ifmsg(struct ifnet *ifp, int if_flags_mask __unused)
1988 {
1989         struct if_msghdr *ifm;
1990         struct mbuf *m;
1991         struct rt_addrinfo info;
1992
1993         if (V_route_cb.any_count == 0)
1994                 return;
1995         bzero((caddr_t)&info, sizeof(info));
1996         m = rtsock_msg_mbuf(RTM_IFINFO, &info);
1997         if (m == NULL)
1998                 return;
1999         ifm = mtod(m, struct if_msghdr *);
2000         ifm->ifm_index = ifp->if_index;
2001         ifm->ifm_flags = ifp->if_flags | ifp->if_drv_flags;
2002         if_data_copy(ifp, &ifm->ifm_data);
2003         ifm->ifm_addrs = 0;
2004         rt_dispatch(m, AF_UNSPEC);
2005 }
2006
2007 /*
2008  * Announce interface address arrival/withdraw.
2009  * Please do not call directly, use rt_addrmsg().
2010  * Assume input data to be valid.
2011  * Returns 0 on success.
2012  */
2013 int
2014 rtsock_addrmsg(int cmd, struct ifaddr *ifa, int fibnum)
2015 {
2016         struct rt_addrinfo info;
2017         struct sockaddr *sa;
2018         int ncmd;
2019         struct mbuf *m;
2020         struct ifa_msghdr *ifam;
2021         struct ifnet *ifp = ifa->ifa_ifp;
2022         struct sockaddr_storage ss;
2023
2024         if (V_route_cb.any_count == 0)
2025                 return (0);
2026
2027         ncmd = cmd == RTM_ADD ? RTM_NEWADDR : RTM_DELADDR;
2028
2029         bzero((caddr_t)&info, sizeof(info));
2030         info.rti_info[RTAX_IFA] = sa = ifa->ifa_addr;
2031         info.rti_info[RTAX_IFP] = ifp->if_addr->ifa_addr;
2032         info.rti_info[RTAX_NETMASK] = rtsock_fix_netmask(
2033             info.rti_info[RTAX_IFA], ifa->ifa_netmask, &ss);
2034         info.rti_info[RTAX_BRD] = ifa->ifa_dstaddr;
2035         if ((m = rtsock_msg_mbuf(ncmd, &info)) == NULL)
2036                 return (ENOBUFS);
2037         ifam = mtod(m, struct ifa_msghdr *);
2038         ifam->ifam_index = ifp->if_index;
2039         ifam->ifam_metric = ifa->ifa_ifp->if_metric;
2040         ifam->ifam_flags = ifa->ifa_flags;
2041         ifam->ifam_addrs = info.rti_addrs;
2042
2043         if (fibnum != RT_ALL_FIBS) {
2044                 M_SETFIB(m, fibnum);
2045                 m->m_flags |= RTS_FILTER_FIB;
2046         }
2047
2048         rt_dispatch(m, sa ? sa->sa_family : AF_UNSPEC);
2049
2050         return (0);
2051 }
2052
2053 /*
2054  * Announce route addition/removal to rtsock based on @rt data.
2055  * Callers are advives to use rt_routemsg() instead of using this
2056  *  function directly.
2057  * Assume @rt data is consistent.
2058  *
2059  * Returns 0 on success.
2060  */
2061 int
2062 rtsock_routemsg(int cmd, struct rtentry *rt, struct nhop_object *nh,
2063     int fibnum)
2064 {
2065         union sockaddr_union dst, mask;
2066         struct rt_addrinfo info;
2067
2068         if (V_route_cb.any_count == 0)
2069                 return (0);
2070
2071         int family = rt_get_family(rt);
2072         init_sockaddrs_family(family, &dst.sa, &mask.sa);
2073         export_rtaddrs(rt, &dst.sa, &mask.sa);
2074
2075         bzero((caddr_t)&info, sizeof(info));
2076         info.rti_info[RTAX_DST] = &dst.sa;
2077         info.rti_info[RTAX_NETMASK] = &mask.sa;
2078         info.rti_info[RTAX_GATEWAY] = &nh->gw_sa;
2079         info.rti_flags = rt->rte_flags | nhop_get_rtflags(nh);
2080         info.rti_ifp = nh->nh_ifp;
2081
2082         return (rtsock_routemsg_info(cmd, &info, fibnum));
2083 }
2084
2085 int
2086 rtsock_routemsg_info(int cmd, struct rt_addrinfo *info, int fibnum)
2087 {
2088         struct rt_msghdr *rtm;
2089         struct sockaddr *sa;
2090         struct mbuf *m;
2091
2092         if (V_route_cb.any_count == 0)
2093                 return (0);
2094
2095         if (info->rti_flags & RTF_HOST)
2096                 info->rti_info[RTAX_NETMASK] = NULL;
2097
2098         m = rtsock_msg_mbuf(cmd, info);
2099         if (m == NULL)
2100                 return (ENOBUFS);
2101
2102         if (fibnum != RT_ALL_FIBS) {
2103                 KASSERT(fibnum >= 0 && fibnum < rt_numfibs, ("%s: fibnum out "
2104                     "of range 0 <= %d < %d", __func__, fibnum, rt_numfibs));
2105                 M_SETFIB(m, fibnum);
2106                 m->m_flags |= RTS_FILTER_FIB;
2107         }
2108
2109         rtm = mtod(m, struct rt_msghdr *);
2110         rtm->rtm_addrs = info->rti_addrs;
2111         if (info->rti_ifp != NULL)
2112                 rtm->rtm_index = info->rti_ifp->if_index;
2113         /* Add RTF_DONE to indicate command 'completion' required by API */
2114         info->rti_flags |= RTF_DONE;
2115         /* Reported routes has to be up */
2116         if (cmd == RTM_ADD || cmd == RTM_CHANGE)
2117                 info->rti_flags |= RTF_UP;
2118         rtm->rtm_flags = info->rti_flags;
2119
2120         sa = info->rti_info[RTAX_DST];
2121         rt_dispatch(m, sa ? sa->sa_family : AF_UNSPEC);
2122
2123         return (0);
2124 }
2125
2126 /*
2127  * This is the analogue to the rt_newaddrmsg which performs the same
2128  * function but for multicast group memberhips.  This is easier since
2129  * there is no route state to worry about.
2130  */
2131 void
2132 rt_newmaddrmsg(int cmd, struct ifmultiaddr *ifma)
2133 {
2134         struct rt_addrinfo info;
2135         struct mbuf *m = NULL;
2136         struct ifnet *ifp = ifma->ifma_ifp;
2137         struct ifma_msghdr *ifmam;
2138
2139         if (V_route_cb.any_count == 0)
2140                 return;
2141
2142         bzero((caddr_t)&info, sizeof(info));
2143         info.rti_info[RTAX_IFA] = ifma->ifma_addr;
2144         if (ifp && ifp->if_addr)
2145                 info.rti_info[RTAX_IFP] = ifp->if_addr->ifa_addr;
2146         else
2147                 info.rti_info[RTAX_IFP] = NULL;
2148         /*
2149          * If a link-layer address is present, present it as a ``gateway''
2150          * (similarly to how ARP entries, e.g., are presented).
2151          */
2152         info.rti_info[RTAX_GATEWAY] = ifma->ifma_lladdr;
2153         m = rtsock_msg_mbuf(cmd, &info);
2154         if (m == NULL)
2155                 return;
2156         ifmam = mtod(m, struct ifma_msghdr *);
2157         KASSERT(ifp != NULL, ("%s: link-layer multicast address w/o ifp\n",
2158             __func__));
2159         ifmam->ifmam_index = ifp->if_index;
2160         ifmam->ifmam_addrs = info.rti_addrs;
2161         rt_dispatch(m, ifma->ifma_addr ? ifma->ifma_addr->sa_family : AF_UNSPEC);
2162 }
2163
2164 static struct mbuf *
2165 rt_makeifannouncemsg(struct ifnet *ifp, int type, int what,
2166         struct rt_addrinfo *info)
2167 {
2168         struct if_announcemsghdr *ifan;
2169         struct mbuf *m;
2170
2171         if (V_route_cb.any_count == 0)
2172                 return NULL;
2173         bzero((caddr_t)info, sizeof(*info));
2174         m = rtsock_msg_mbuf(type, info);
2175         if (m != NULL) {
2176                 ifan = mtod(m, struct if_announcemsghdr *);
2177                 ifan->ifan_index = ifp->if_index;
2178                 strlcpy(ifan->ifan_name, ifp->if_xname,
2179                         sizeof(ifan->ifan_name));
2180                 ifan->ifan_what = what;
2181         }
2182         return m;
2183 }
2184
2185 /*
2186  * This is called to generate routing socket messages indicating
2187  * IEEE80211 wireless events.
2188  * XXX we piggyback on the RTM_IFANNOUNCE msg format in a clumsy way.
2189  */
2190 void
2191 rt_ieee80211msg(struct ifnet *ifp, int what, void *data, size_t data_len)
2192 {
2193         struct mbuf *m;
2194         struct rt_addrinfo info;
2195
2196         m = rt_makeifannouncemsg(ifp, RTM_IEEE80211, what, &info);
2197         if (m != NULL) {
2198                 /*
2199                  * Append the ieee80211 data.  Try to stick it in the
2200                  * mbuf containing the ifannounce msg; otherwise allocate
2201                  * a new mbuf and append.
2202                  *
2203                  * NB: we assume m is a single mbuf.
2204                  */
2205                 if (data_len > M_TRAILINGSPACE(m)) {
2206                         struct mbuf *n = m_get(M_NOWAIT, MT_DATA);
2207                         if (n == NULL) {
2208                                 m_freem(m);
2209                                 return;
2210                         }
2211                         bcopy(data, mtod(n, void *), data_len);
2212                         n->m_len = data_len;
2213                         m->m_next = n;
2214                 } else if (data_len > 0) {
2215                         bcopy(data, mtod(m, u_int8_t *) + m->m_len, data_len);
2216                         m->m_len += data_len;
2217                 }
2218                 if (m->m_flags & M_PKTHDR)
2219                         m->m_pkthdr.len += data_len;
2220                 mtod(m, struct if_announcemsghdr *)->ifan_msglen += data_len;
2221                 rt_dispatch(m, AF_UNSPEC);
2222         }
2223 }
2224
2225 /*
2226  * This is called to generate routing socket messages indicating
2227  * network interface arrival and departure.
2228  */
2229 static void
2230 rt_ifannouncemsg(struct ifnet *ifp, int what)
2231 {
2232         struct mbuf *m;
2233         struct rt_addrinfo info;
2234
2235         m = rt_makeifannouncemsg(ifp, RTM_IFANNOUNCE, what, &info);
2236         if (m != NULL)
2237                 rt_dispatch(m, AF_UNSPEC);
2238 }
2239
2240 static void
2241 rt_dispatch(struct mbuf *m, sa_family_t saf)
2242 {
2243         struct m_tag *tag;
2244
2245         /*
2246          * Preserve the family from the sockaddr, if any, in an m_tag for
2247          * use when injecting the mbuf into the routing socket buffer from
2248          * the netisr.
2249          */
2250         if (saf != AF_UNSPEC) {
2251                 tag = m_tag_get(PACKET_TAG_RTSOCKFAM, sizeof(unsigned short),
2252                     M_NOWAIT);
2253                 if (tag == NULL) {
2254                         m_freem(m);
2255                         return;
2256                 }
2257                 *(unsigned short *)(tag + 1) = saf;
2258                 m_tag_prepend(m, tag);
2259         }
2260 #ifdef VIMAGE
2261         if (V_loif)
2262                 m->m_pkthdr.rcvif = V_loif;
2263         else {
2264                 m_freem(m);
2265                 return;
2266         }
2267 #endif
2268         netisr_queue(NETISR_ROUTE, m);  /* mbuf is free'd on failure. */
2269 }
2270
2271 /*
2272  * This is used in dumping the kernel table via sysctl().
2273  */
2274 static int
2275 sysctl_dumpentry(struct rtentry *rt, void *vw)
2276 {
2277         struct walkarg *w = vw;
2278         struct nhop_object *nh;
2279
2280         NET_EPOCH_ASSERT();
2281
2282         if (!rt_is_exportable(rt, w->w_req->td->td_ucred))
2283                 return (0);
2284
2285         export_rtaddrs(rt, w->dst, w->mask);
2286         nh = rt_get_raw_nhop(rt);
2287 #ifdef ROUTE_MPATH
2288         if (NH_IS_NHGRP(nh)) {
2289                 const struct weightened_nhop *wn;
2290                 uint32_t num_nhops;
2291                 int error;
2292                 wn = nhgrp_get_nhops((struct nhgrp_object *)nh, &num_nhops);
2293                 for (int i = 0; i < num_nhops; i++) {
2294                         error = sysctl_dumpnhop(rt, wn[i].nh, wn[i].weight, w);
2295                         if (error != 0)
2296                                 return (error);
2297                 }
2298         } else
2299 #endif
2300                 sysctl_dumpnhop(rt, nh, rt->rt_weight, w);
2301
2302         return (0);
2303 }
2304
2305
2306 static int
2307 sysctl_dumpnhop(struct rtentry *rt, struct nhop_object *nh, uint32_t weight,
2308     struct walkarg *w)
2309 {
2310         struct rt_addrinfo info;
2311         int error = 0, size;
2312         uint32_t rtflags;
2313
2314         rtflags = nhop_get_rtflags(nh);
2315
2316         if (w->w_op == NET_RT_FLAGS && !(rtflags & w->w_arg))
2317                 return (0);
2318
2319         bzero((caddr_t)&info, sizeof(info));
2320         info.rti_info[RTAX_DST] = w->dst;
2321         info.rti_info[RTAX_GATEWAY] = &nh->gw_sa;
2322         info.rti_info[RTAX_NETMASK] = (rtflags & RTF_HOST) ? NULL : w->mask;
2323         info.rti_info[RTAX_GENMASK] = 0;
2324         if (nh->nh_ifp && !(nh->nh_ifp->if_flags & IFF_DYING)) {
2325                 info.rti_info[RTAX_IFP] = nh->nh_ifp->if_addr->ifa_addr;
2326                 info.rti_info[RTAX_IFA] = nh->nh_ifa->ifa_addr;
2327                 if (nh->nh_ifp->if_flags & IFF_POINTOPOINT)
2328                         info.rti_info[RTAX_BRD] = nh->nh_ifa->ifa_dstaddr;
2329         }
2330         if ((error = rtsock_msg_buffer(RTM_GET, &info, w, &size)) != 0)
2331                 return (error);
2332         if (w->w_req && w->w_tmem) {
2333                 struct rt_msghdr *rtm = (struct rt_msghdr *)w->w_tmem;
2334
2335                 bzero(&rtm->rtm_index,
2336                     sizeof(*rtm) - offsetof(struct rt_msghdr, rtm_index));
2337
2338                 /*
2339                  * rte flags may consist of RTF_HOST (duplicated in nhop rtflags)
2340                  * and RTF_UP (if entry is linked, which is always true here).
2341                  * Given that, use nhop rtflags & add RTF_UP.
2342                  */
2343                 rtm->rtm_flags = rtflags | RTF_UP;
2344                 if (rtm->rtm_flags & RTF_GWFLAG_COMPAT)
2345                         rtm->rtm_flags = RTF_GATEWAY | 
2346                                 (rtm->rtm_flags & ~RTF_GWFLAG_COMPAT);
2347                 rt_getmetrics(rt, nh, &rtm->rtm_rmx);
2348                 rtm->rtm_rmx.rmx_weight = weight;
2349                 rtm->rtm_index = nh->nh_ifp->if_index;
2350                 rtm->rtm_addrs = info.rti_addrs;
2351                 error = SYSCTL_OUT(w->w_req, (caddr_t)rtm, size);
2352                 return (error);
2353         }
2354         return (error);
2355 }
2356
2357 static int
2358 sysctl_iflist_ifml(struct ifnet *ifp, const struct if_data *src_ifd,
2359     struct rt_addrinfo *info, struct walkarg *w, int len)
2360 {
2361         struct if_msghdrl *ifm;
2362         struct if_data *ifd;
2363
2364         ifm = (struct if_msghdrl *)w->w_tmem;
2365
2366 #ifdef COMPAT_FREEBSD32
2367         if (w->w_req->flags & SCTL_MASK32) {
2368                 struct if_msghdrl32 *ifm32;
2369
2370                 ifm32 = (struct if_msghdrl32 *)ifm;
2371                 ifm32->ifm_addrs = info->rti_addrs;
2372                 ifm32->ifm_flags = ifp->if_flags | ifp->if_drv_flags;
2373                 ifm32->ifm_index = ifp->if_index;
2374                 ifm32->_ifm_spare1 = 0;
2375                 ifm32->ifm_len = sizeof(*ifm32);
2376                 ifm32->ifm_data_off = offsetof(struct if_msghdrl32, ifm_data);
2377                 ifm32->_ifm_spare2 = 0;
2378                 ifd = &ifm32->ifm_data;
2379         } else
2380 #endif
2381         {
2382                 ifm->ifm_addrs = info->rti_addrs;
2383                 ifm->ifm_flags = ifp->if_flags | ifp->if_drv_flags;
2384                 ifm->ifm_index = ifp->if_index;
2385                 ifm->_ifm_spare1 = 0;
2386                 ifm->ifm_len = sizeof(*ifm);
2387                 ifm->ifm_data_off = offsetof(struct if_msghdrl, ifm_data);
2388                 ifm->_ifm_spare2 = 0;
2389                 ifd = &ifm->ifm_data;
2390         }
2391
2392         memcpy(ifd, src_ifd, sizeof(*ifd));
2393
2394         return (SYSCTL_OUT(w->w_req, (caddr_t)ifm, len));
2395 }
2396
2397 static int
2398 sysctl_iflist_ifm(struct ifnet *ifp, const struct if_data *src_ifd,
2399     struct rt_addrinfo *info, struct walkarg *w, int len)
2400 {
2401         struct if_msghdr *ifm;
2402         struct if_data *ifd;
2403
2404         ifm = (struct if_msghdr *)w->w_tmem;
2405
2406 #ifdef COMPAT_FREEBSD32
2407         if (w->w_req->flags & SCTL_MASK32) {
2408                 struct if_msghdr32 *ifm32;
2409
2410                 ifm32 = (struct if_msghdr32 *)ifm;
2411                 ifm32->ifm_addrs = info->rti_addrs;
2412                 ifm32->ifm_flags = ifp->if_flags | ifp->if_drv_flags;
2413                 ifm32->ifm_index = ifp->if_index;
2414                 ifm32->_ifm_spare1 = 0;
2415                 ifd = &ifm32->ifm_data;
2416         } else
2417 #endif
2418         {
2419                 ifm->ifm_addrs = info->rti_addrs;
2420                 ifm->ifm_flags = ifp->if_flags | ifp->if_drv_flags;
2421                 ifm->ifm_index = ifp->if_index;
2422                 ifm->_ifm_spare1 = 0;
2423                 ifd = &ifm->ifm_data;
2424         }
2425
2426         memcpy(ifd, src_ifd, sizeof(*ifd));
2427
2428         return (SYSCTL_OUT(w->w_req, (caddr_t)ifm, len));
2429 }
2430
2431 static int
2432 sysctl_iflist_ifaml(struct ifaddr *ifa, struct rt_addrinfo *info,
2433     struct walkarg *w, int len)
2434 {
2435         struct ifa_msghdrl *ifam;
2436         struct if_data *ifd;
2437
2438         ifam = (struct ifa_msghdrl *)w->w_tmem;
2439
2440 #ifdef COMPAT_FREEBSD32
2441         if (w->w_req->flags & SCTL_MASK32) {
2442                 struct ifa_msghdrl32 *ifam32;
2443
2444                 ifam32 = (struct ifa_msghdrl32 *)ifam;
2445                 ifam32->ifam_addrs = info->rti_addrs;
2446                 ifam32->ifam_flags = ifa->ifa_flags;
2447                 ifam32->ifam_index = ifa->ifa_ifp->if_index;
2448                 ifam32->_ifam_spare1 = 0;
2449                 ifam32->ifam_len = sizeof(*ifam32);
2450                 ifam32->ifam_data_off =
2451                     offsetof(struct ifa_msghdrl32, ifam_data);
2452                 ifam32->ifam_metric = ifa->ifa_ifp->if_metric;
2453                 ifd = &ifam32->ifam_data;
2454         } else
2455 #endif
2456         {
2457                 ifam->ifam_addrs = info->rti_addrs;
2458                 ifam->ifam_flags = ifa->ifa_flags;
2459                 ifam->ifam_index = ifa->ifa_ifp->if_index;
2460                 ifam->_ifam_spare1 = 0;
2461                 ifam->ifam_len = sizeof(*ifam);
2462                 ifam->ifam_data_off = offsetof(struct ifa_msghdrl, ifam_data);
2463                 ifam->ifam_metric = ifa->ifa_ifp->if_metric;
2464                 ifd = &ifam->ifam_data;
2465         }
2466
2467         bzero(ifd, sizeof(*ifd));
2468         ifd->ifi_datalen = sizeof(struct if_data);
2469         ifd->ifi_ipackets = counter_u64_fetch(ifa->ifa_ipackets);
2470         ifd->ifi_opackets = counter_u64_fetch(ifa->ifa_opackets);
2471         ifd->ifi_ibytes = counter_u64_fetch(ifa->ifa_ibytes);
2472         ifd->ifi_obytes = counter_u64_fetch(ifa->ifa_obytes);
2473
2474         /* Fixup if_data carp(4) vhid. */
2475         if (carp_get_vhid_p != NULL)
2476                 ifd->ifi_vhid = (*carp_get_vhid_p)(ifa);
2477
2478         return (SYSCTL_OUT(w->w_req, w->w_tmem, len));
2479 }
2480
2481 static int
2482 sysctl_iflist_ifam(struct ifaddr *ifa, struct rt_addrinfo *info,
2483     struct walkarg *w, int len)
2484 {
2485         struct ifa_msghdr *ifam;
2486
2487         ifam = (struct ifa_msghdr *)w->w_tmem;
2488         ifam->ifam_addrs = info->rti_addrs;
2489         ifam->ifam_flags = ifa->ifa_flags;
2490         ifam->ifam_index = ifa->ifa_ifp->if_index;
2491         ifam->_ifam_spare1 = 0;
2492         ifam->ifam_metric = ifa->ifa_ifp->if_metric;
2493
2494         return (SYSCTL_OUT(w->w_req, w->w_tmem, len));
2495 }
2496
2497 static int
2498 sysctl_iflist(int af, struct walkarg *w)
2499 {
2500         struct ifnet *ifp;
2501         struct ifaddr *ifa;
2502         struct if_data ifd;
2503         struct rt_addrinfo info;
2504         int len, error = 0;
2505         struct sockaddr_storage ss;
2506
2507         bzero((caddr_t)&info, sizeof(info));
2508         bzero(&ifd, sizeof(ifd));
2509         CK_STAILQ_FOREACH(ifp, &V_ifnet, if_link) {
2510                 if (w->w_arg && w->w_arg != ifp->if_index)
2511                         continue;
2512                 if_data_copy(ifp, &ifd);
2513                 ifa = ifp->if_addr;
2514                 info.rti_info[RTAX_IFP] = ifa->ifa_addr;
2515                 error = rtsock_msg_buffer(RTM_IFINFO, &info, w, &len);
2516                 if (error != 0)
2517                         goto done;
2518                 info.rti_info[RTAX_IFP] = NULL;
2519                 if (w->w_req && w->w_tmem) {
2520                         if (w->w_op == NET_RT_IFLISTL)
2521                                 error = sysctl_iflist_ifml(ifp, &ifd, &info, w,
2522                                     len);
2523                         else
2524                                 error = sysctl_iflist_ifm(ifp, &ifd, &info, w,
2525                                     len);
2526                         if (error)
2527                                 goto done;
2528                 }
2529                 while ((ifa = CK_STAILQ_NEXT(ifa, ifa_link)) != NULL) {
2530                         if (af && af != ifa->ifa_addr->sa_family)
2531                                 continue;
2532                         if (prison_if(w->w_req->td->td_ucred,
2533                             ifa->ifa_addr) != 0)
2534                                 continue;
2535                         info.rti_info[RTAX_IFA] = ifa->ifa_addr;
2536                         info.rti_info[RTAX_NETMASK] = rtsock_fix_netmask(
2537                             ifa->ifa_addr, ifa->ifa_netmask, &ss);
2538                         info.rti_info[RTAX_BRD] = ifa->ifa_dstaddr;
2539                         error = rtsock_msg_buffer(RTM_NEWADDR, &info, w, &len);
2540                         if (error != 0)
2541                                 goto done;
2542                         if (w->w_req && w->w_tmem) {
2543                                 if (w->w_op == NET_RT_IFLISTL)
2544                                         error = sysctl_iflist_ifaml(ifa, &info,
2545                                             w, len);
2546                                 else
2547                                         error = sysctl_iflist_ifam(ifa, &info,
2548                                             w, len);
2549                                 if (error)
2550                                         goto done;
2551                         }
2552                 }
2553                 info.rti_info[RTAX_IFA] = NULL;
2554                 info.rti_info[RTAX_NETMASK] = NULL;
2555                 info.rti_info[RTAX_BRD] = NULL;
2556         }
2557 done:
2558         return (error);
2559 }
2560
2561 static int
2562 sysctl_ifmalist(int af, struct walkarg *w)
2563 {
2564         struct rt_addrinfo info;
2565         struct ifaddr *ifa;
2566         struct ifmultiaddr *ifma;
2567         struct ifnet *ifp;
2568         int error, len;
2569
2570         NET_EPOCH_ASSERT();
2571
2572         error = 0;
2573         bzero((caddr_t)&info, sizeof(info));
2574
2575         CK_STAILQ_FOREACH(ifp, &V_ifnet, if_link) {
2576                 if (w->w_arg && w->w_arg != ifp->if_index)
2577                         continue;
2578                 ifa = ifp->if_addr;
2579                 info.rti_info[RTAX_IFP] = ifa ? ifa->ifa_addr : NULL;
2580                 CK_STAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
2581                         if (af && af != ifma->ifma_addr->sa_family)
2582                                 continue;
2583                         if (prison_if(w->w_req->td->td_ucred,
2584                             ifma->ifma_addr) != 0)
2585                                 continue;
2586                         info.rti_info[RTAX_IFA] = ifma->ifma_addr;
2587                         info.rti_info[RTAX_GATEWAY] =
2588                             (ifma->ifma_addr->sa_family != AF_LINK) ?
2589                             ifma->ifma_lladdr : NULL;
2590                         error = rtsock_msg_buffer(RTM_NEWMADDR, &info, w, &len);
2591                         if (error != 0)
2592                                 break;
2593                         if (w->w_req && w->w_tmem) {
2594                                 struct ifma_msghdr *ifmam;
2595
2596                                 ifmam = (struct ifma_msghdr *)w->w_tmem;
2597                                 ifmam->ifmam_index = ifma->ifma_ifp->if_index;
2598                                 ifmam->ifmam_flags = 0;
2599                                 ifmam->ifmam_addrs = info.rti_addrs;
2600                                 ifmam->_ifmam_spare1 = 0;
2601                                 error = SYSCTL_OUT(w->w_req, w->w_tmem, len);
2602                                 if (error != 0)
2603                                         break;
2604                         }
2605                 }
2606                 if (error != 0)
2607                         break;
2608         }
2609         return (error);
2610 }
2611
2612 static void
2613 rtable_sysctl_dump(uint32_t fibnum, int family, struct walkarg *w)
2614 {
2615         union sockaddr_union sa_dst, sa_mask;
2616
2617         w->family = family;
2618         w->dst = (struct sockaddr *)&sa_dst;
2619         w->mask = (struct sockaddr *)&sa_mask;
2620
2621         init_sockaddrs_family(family, w->dst, w->mask);
2622
2623         rib_walk(fibnum, family, false, sysctl_dumpentry, w);
2624 }
2625
2626 static int
2627 sysctl_rtsock(SYSCTL_HANDLER_ARGS)
2628 {
2629         struct epoch_tracker et;
2630         int     *name = (int *)arg1;
2631         u_int   namelen = arg2;
2632         struct rib_head *rnh = NULL; /* silence compiler. */
2633         int     i, lim, error = EINVAL;
2634         int     fib = 0;
2635         u_char  af;
2636         struct  walkarg w;
2637
2638         if (namelen < 3)
2639                 return (EINVAL);
2640
2641         name++;
2642         namelen--;
2643         if (req->newptr)
2644                 return (EPERM);
2645         if (name[1] == NET_RT_DUMP || name[1] == NET_RT_NHOP || name[1] == NET_RT_NHGRP) {
2646                 if (namelen == 3)
2647                         fib = req->td->td_proc->p_fibnum;
2648                 else if (namelen == 4)
2649                         fib = (name[3] == RT_ALL_FIBS) ?
2650                             req->td->td_proc->p_fibnum : name[3];
2651                 else
2652                         return ((namelen < 3) ? EISDIR : ENOTDIR);
2653                 if (fib < 0 || fib >= rt_numfibs)
2654                         return (EINVAL);
2655         } else if (namelen != 3)
2656                 return ((namelen < 3) ? EISDIR : ENOTDIR);
2657         af = name[0];
2658         if (af > AF_MAX)
2659                 return (EINVAL);
2660         bzero(&w, sizeof(w));
2661         w.w_op = name[1];
2662         w.w_arg = name[2];
2663         w.w_req = req;
2664
2665         error = sysctl_wire_old_buffer(req, 0);
2666         if (error)
2667                 return (error);
2668
2669         /*
2670          * Allocate reply buffer in advance.
2671          * All rtsock messages has maximum length of u_short.
2672          */
2673         w.w_tmemsize = 65536;
2674         w.w_tmem = malloc(w.w_tmemsize, M_TEMP, M_WAITOK);
2675
2676         NET_EPOCH_ENTER(et);
2677         switch (w.w_op) {
2678         case NET_RT_DUMP:
2679         case NET_RT_FLAGS:
2680                 if (af == 0) {                  /* dump all tables */
2681                         i = 1;
2682                         lim = AF_MAX;
2683                 } else                          /* dump only one table */
2684                         i = lim = af;
2685
2686                 /*
2687                  * take care of llinfo entries, the caller must
2688                  * specify an AF
2689                  */
2690                 if (w.w_op == NET_RT_FLAGS &&
2691                     (w.w_arg == 0 || w.w_arg & RTF_LLINFO)) {
2692                         if (af != 0)
2693                                 error = lltable_sysctl_dumparp(af, w.w_req);
2694                         else
2695                                 error = EINVAL;
2696                         break;
2697                 }
2698                 /*
2699                  * take care of routing entries
2700                  */
2701                 for (error = 0; error == 0 && i <= lim; i++) {
2702                         rnh = rt_tables_get_rnh(fib, i);
2703                         if (rnh != NULL) {
2704                                 rtable_sysctl_dump(fib, i, &w);
2705                         } else if (af != 0)
2706                                 error = EAFNOSUPPORT;
2707                 }
2708                 break;
2709         case NET_RT_NHOP:
2710         case NET_RT_NHGRP:
2711                 /* Allow dumping one specific af/fib at a time */
2712                 if (namelen < 4) {
2713                         error = EINVAL;
2714                         break;
2715                 }
2716                 fib = name[3];
2717                 if (fib < 0 || fib > rt_numfibs) {
2718                         error = EINVAL;
2719                         break;
2720                 }
2721                 rnh = rt_tables_get_rnh(fib, af);
2722                 if (rnh == NULL) {
2723                         error = EAFNOSUPPORT;
2724                         break;
2725                 }
2726                 if (w.w_op == NET_RT_NHOP)
2727                         error = nhops_dump_sysctl(rnh, w.w_req);
2728                 else
2729 #ifdef ROUTE_MPATH
2730                         error = nhgrp_dump_sysctl(rnh, w.w_req);
2731 #else
2732                         error = ENOTSUP;
2733 #endif
2734                 break;
2735         case NET_RT_IFLIST:
2736         case NET_RT_IFLISTL:
2737                 error = sysctl_iflist(af, &w);
2738                 break;
2739
2740         case NET_RT_IFMALIST:
2741                 error = sysctl_ifmalist(af, &w);
2742                 break;
2743         }
2744         NET_EPOCH_EXIT(et);
2745
2746         free(w.w_tmem, M_TEMP);
2747         return (error);
2748 }
2749
2750 static SYSCTL_NODE(_net, PF_ROUTE, routetable, CTLFLAG_RD | CTLFLAG_MPSAFE,
2751     sysctl_rtsock, "Return route tables and interface/address lists");
2752
2753 /*
2754  * Definitions of protocols supported in the ROUTE domain.
2755  */
2756
2757 static struct domain routedomain;               /* or at least forward */
2758
2759 static struct protosw routesw[] = {
2760 {
2761         .pr_type =              SOCK_RAW,
2762         .pr_domain =            &routedomain,
2763         .pr_flags =             PR_ATOMIC|PR_ADDR,
2764         .pr_output =            route_output,
2765         .pr_ctlinput =          raw_ctlinput,
2766         .pr_init =              raw_init,
2767         .pr_usrreqs =           &route_usrreqs
2768 }
2769 };
2770
2771 static struct domain routedomain = {
2772         .dom_family =           PF_ROUTE,
2773         .dom_name =             "route",
2774         .dom_protosw =          routesw,
2775         .dom_protoswNPROTOSW =  &routesw[nitems(routesw)]
2776 };
2777
2778 VNET_DOMAIN_SET(route);