2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
4 * Copyright (c) 2021 Ng Peng Nam Sean
5 * Copyright (c) 2022 Alexander V. Chernikov <melifaro@FreeBSD.org>
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
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.
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 * This file contains socket and protocol bindings for netlink.
33 #include <sys/param.h>
34 #include <sys/kernel.h>
35 #include <sys/malloc.h>
37 #include <sys/rmlock.h>
38 #include <sys/domain.h>
40 #include <sys/protosw.h>
43 #include <sys/socket.h>
44 #include <sys/socketvar.h>
45 #include <sys/sysent.h>
46 #include <sys/syslog.h>
47 #include <sys/priv.h> /* priv_check */
49 #include <netlink/netlink.h>
50 #include <netlink/netlink_ctl.h>
51 #include <netlink/netlink_var.h>
53 #define DEBUG_MOD_NAME nl_domain
54 #define DEBUG_MAX_LEVEL LOG_DEBUG3
55 #include <netlink/netlink_debug.h>
56 _DECLARE_DEBUG(LOG_DEBUG);
58 _Static_assert((NLP_MAX_GROUPS % 64) == 0,
59 "NLP_MAX_GROUPS has to be multiple of 64");
60 _Static_assert(NLP_MAX_GROUPS >= 64,
61 "NLP_MAX_GROUPS has to be at least 64");
63 #define NLCTL_TRACKER struct rm_priotracker nl_tracker
64 #define NLCTL_RLOCK(_ctl) rm_rlock(&((_ctl)->ctl_lock), &nl_tracker)
65 #define NLCTL_RUNLOCK(_ctl) rm_runlock(&((_ctl)->ctl_lock), &nl_tracker)
67 #define NLCTL_WLOCK(_ctl) rm_wlock(&((_ctl)->ctl_lock))
68 #define NLCTL_WUNLOCK(_ctl) rm_wunlock(&((_ctl)->ctl_lock))
70 static u_long nl_sendspace = NLSNDQ;
71 SYSCTL_ULONG(_net_netlink, OID_AUTO, sendspace, CTLFLAG_RW, &nl_sendspace, 0,
72 "Default netlink socket send space");
74 static u_long nl_recvspace = NLSNDQ;
75 SYSCTL_ULONG(_net_netlink, OID_AUTO, recvspace, CTLFLAG_RW, &nl_recvspace, 0,
76 "Default netlink socket receive space");
78 extern u_long sb_max_adj;
80 static u_long nl_maxsockbuf = 512 * 1024 * 1024; /* 512M, XXX: init based on physmem */
84 nlp_get_pid(const struct nlpcb *nlp)
86 return (nlp->nl_process_id);
90 * Looks up a nlpcb struct based on the @portid. Need to claim nlsock_mtx.
91 * Returns nlpcb pointer if present else NULL
94 nl_port_lookup(uint32_t port_id)
98 CK_LIST_FOREACH(nlp, &V_nl_ctl->ctl_port_head, nl_port_next) {
99 if (nlp->nl_port == port_id)
106 nl_add_group_locked(struct nlpcb *nlp, unsigned int group_id)
108 MPASS(group_id <= NLP_MAX_GROUPS);
111 nlp->nl_groups[group_id / 64] |= (uint64_t)1 << (group_id % 64);
115 nl_del_group_locked(struct nlpcb *nlp, unsigned int group_id)
117 MPASS(group_id <= NLP_MAX_GROUPS);
120 nlp->nl_groups[group_id / 64] &= ~((uint64_t)1 << (group_id % 64));
124 nl_isset_group_locked(struct nlpcb *nlp, unsigned int group_id)
126 MPASS(group_id <= NLP_MAX_GROUPS);
129 return (nlp->nl_groups[group_id / 64] & ((uint64_t)1 << (group_id % 64)));
133 nl_get_groups_compat(struct nlpcb *nlp)
135 uint32_t groups_mask = 0;
137 for (int i = 0; i < 32; i++) {
138 if (nl_isset_group_locked(nlp, i + 1))
139 groups_mask |= (1 << i);
142 return (groups_mask);
146 * Broadcasts message @m to the protocol @proto group specified by @group_id
149 nl_send_group(struct mbuf *m, int num_messages, int proto, int group_id)
151 struct nlpcb *nlp_last = NULL;
155 IF_DEBUG_LEVEL(LOG_DEBUG2) {
156 struct nlmsghdr *hdr = mtod(m, struct nlmsghdr *);
157 NL_LOG(LOG_DEBUG2, "MCAST mbuf len %u msg type %d len %u to group %d/%d",
158 m->m_len, hdr->nlmsg_type, hdr->nlmsg_len, proto, group_id);
161 struct nl_control *ctl = atomic_load_ptr(&V_nl_ctl);
162 if (__predict_false(ctl == NULL)) {
164 * Can be the case when notification is sent within VNET
165 * which doesn't have any netlink sockets.
173 int io_flags = NL_IOF_UNTRANSLATED;
175 CK_LIST_FOREACH(nlp, &ctl->ctl_pcb_head, nl_next) {
176 if (nl_isset_group_locked(nlp, group_id) && nlp->nl_proto == proto) {
177 if (nlp_last != NULL) {
179 m_copy = m_copym(m, 0, M_COPYALL, M_NOWAIT);
181 nl_send_one(m_copy, nlp_last, num_messages, io_flags);
184 if (nlp_last->nl_socket != NULL)
185 sorwakeup(nlp_last->nl_socket);
186 NLP_UNLOCK(nlp_last);
192 if (nlp_last != NULL)
193 nl_send_one(m, nlp_last, num_messages, io_flags);
201 nl_has_listeners(int netlink_family, uint32_t groups_mask)
203 return (V_nl_ctl != NULL);
207 nlp_has_priv(struct nlpcb *nlp, int priv)
209 return (priv_check_cred(nlp->nl_cred, priv) == 0);
216 * app can open multiple netlink sockets.
217 * Start with current pid, if already taken,
218 * try random numbers in 65k..256k+65k space,
219 * avoiding clash with pids.
221 if (nl_port_lookup(curproc->p_pid) == NULL)
222 return (curproc->p_pid);
223 for (int i = 0; i < 16; i++) {
224 uint32_t nl_port = (arc4random() % 65536) + 65536 * 4;
225 if (nl_port_lookup(nl_port) == 0)
227 NL_LOG(LOG_DEBUG3, "tried %u\n", nl_port);
229 return (curproc->p_pid);
233 nl_bind_locked(struct nlpcb *nlp, struct sockaddr_nl *snl)
236 if (nlp->nl_port != snl->nl_pid) {
238 "bind() failed: program pid %d "
239 "is different from provided pid %d",
240 nlp->nl_port, snl->nl_pid);
241 return (EINVAL); // XXX: better error
244 if (snl->nl_pid == 0)
245 snl->nl_pid = nl_find_port();
246 if (nl_port_lookup(snl->nl_pid) != NULL)
248 nlp->nl_port = snl->nl_pid;
249 nlp->nl_bound = true;
250 CK_LIST_INSERT_HEAD(&V_nl_ctl->ctl_port_head, nlp, nl_port_next);
252 for (int i = 0; i < 32; i++) {
253 if (snl->nl_groups & ((uint32_t)1 << i))
254 nl_add_group_locked(nlp, i + 1);
256 nl_del_group_locked(nlp, i + 1);
263 nl_pru_attach(struct socket *so, int proto, struct thread *td)
268 if (__predict_false(netlink_unloading != 0))
269 return (EAFNOSUPPORT);
271 error = nl_verify_proto(proto);
275 bool is_linux = SV_PROC_ABI(td->td_proc) == SV_ABI_LINUX;
276 NL_LOG(LOG_DEBUG2, "socket %p, %sPID %d: attaching socket to %s",
277 so, is_linux ? "(linux) " : "", curproc->p_pid,
278 nl_get_proto_name(proto));
280 /* Create per-VNET state on first socket init */
281 struct nl_control *ctl = atomic_load_ptr(&V_nl_ctl);
283 ctl = vnet_nl_ctl_init();
284 KASSERT(V_nl_ctl != NULL, ("nl_attach: vnet_sock_init() failed"));
286 MPASS(sotonlpcb(so) == NULL);
288 nlp = malloc(sizeof(struct nlpcb), M_PCB, M_WAITOK | M_ZERO);
289 error = soreserve(so, nl_sendspace, nl_recvspace);
296 /* Copy so_cred to avoid having socket_var.h in every header */
297 nlp->nl_cred = so->so_cred;
298 nlp->nl_proto = proto;
299 nlp->nl_process_id = curproc->p_pid;
300 nlp->nl_linux = is_linux;
301 nlp->nl_active = true;
303 refcount_init(&nlp->nl_refcount, 1);
306 nlp->nl_taskqueue = taskqueue_create("netlink_socket", M_WAITOK,
307 taskqueue_thread_enqueue, &nlp->nl_taskqueue);
308 TASK_INIT(&nlp->nl_task, 0, nl_taskqueue_handler, nlp);
309 taskqueue_start_threads(&nlp->nl_taskqueue, 1, PWAIT,
310 "netlink_socket (PID %u)", nlp->nl_process_id);
313 /* XXX: check ctl is still alive */
314 CK_LIST_INSERT_HEAD(&ctl->ctl_pcb_head, nlp, nl_next);
323 nl_pru_abort(struct socket *so)
325 NL_LOG(LOG_DEBUG3, "socket %p, PID %d", so, curproc->p_pid);
326 MPASS(sotonlpcb(so) != NULL);
327 soisdisconnected(so);
331 nl_pru_bind(struct socket *so, struct sockaddr *sa, struct thread *td)
333 struct nl_control *ctl = atomic_load_ptr(&V_nl_ctl);
334 struct nlpcb *nlp = sotonlpcb(so);
335 struct sockaddr_nl *snl = (struct sockaddr_nl *)sa;
338 NL_LOG(LOG_DEBUG3, "socket %p, PID %d", so, curproc->p_pid);
339 if (snl->nl_len != sizeof(*snl)) {
340 NL_LOG(LOG_DEBUG, "socket %p, wrong sizeof(), ignoring bind()", so);
347 error = nl_bind_locked(nlp, snl);
350 NL_LOG(LOG_DEBUG2, "socket %p, bind() to %u, groups %u, error %d", so,
351 snl->nl_pid, snl->nl_groups, error);
358 nl_assign_port(struct nlpcb *nlp, uint32_t port_id)
360 struct nl_control *ctl = atomic_load_ptr(&V_nl_ctl);
361 struct sockaddr_nl snl = {
368 snl.nl_groups = nl_get_groups_compat(nlp);
369 error = nl_bind_locked(nlp, &snl);
373 NL_LOG(LOG_DEBUG3, "socket %p, port assign: %d, error: %d", nlp->nl_socket, port_id, error);
378 * nl_autobind_port binds a unused portid to @nlp
379 * @nlp: pcb data for the netlink socket
380 * @candidate_id: first id to consider
383 nl_autobind_port(struct nlpcb *nlp, uint32_t candidate_id)
385 struct nl_control *ctl = atomic_load_ptr(&V_nl_ctl);
386 uint32_t port_id = candidate_id;
391 for (int i = 0; i < 10; i++) {
392 NL_LOG(LOG_DEBUG3, "socket %p, trying to assign port %d", nlp->nl_socket, port_id);
394 exist = nl_port_lookup(port_id) != 0;
397 error = nl_assign_port(nlp, port_id);
398 if (error != EADDRINUSE)
403 NL_LOG(LOG_DEBUG3, "socket %p, autobind to %d, error: %d", nlp->nl_socket, port_id, error);
408 nl_pru_connect(struct socket *so, struct sockaddr *sa, struct thread *td)
410 struct sockaddr_nl *snl = (struct sockaddr_nl *)sa;
413 NL_LOG(LOG_DEBUG3, "socket %p, PID %d", so, curproc->p_pid);
414 if (snl->nl_len != sizeof(*snl)) {
415 NL_LOG(LOG_DEBUG, "socket %p, wrong sizeof(), ignoring bind()", so);
420 if (!nlp->nl_bound) {
421 int error = nl_autobind_port(nlp, td->td_proc->p_pid);
423 NL_LOG(LOG_DEBUG, "socket %p, nl_autobind() failed: %d", so, error);
427 /* XXX: Handle socket flags & multicast */
430 NL_LOG(LOG_DEBUG2, "socket %p, connect to %u", so, snl->nl_pid);
436 destroy_nlpcb(struct nlpcb *nlp)
440 NLP_LOCK_DESTROY(nlp);
445 destroy_nlpcb_epoch(epoch_context_t ctx)
449 nlp = __containerof(ctx, struct nlpcb, nl_epoch_ctx);
456 nl_pru_detach(struct socket *so)
458 struct nl_control *ctl = atomic_load_ptr(&V_nl_ctl);
459 MPASS(sotonlpcb(so) != NULL);
462 NL_LOG(LOG_DEBUG2, "detaching socket %p, PID %d", so, curproc->p_pid);
465 /* Mark as inactive so no new work can be enqueued */
467 bool was_bound = nlp->nl_bound;
468 nlp->nl_active = false;
471 /* Wait till all scheduled work has been completed */
472 taskqueue_drain_all(nlp->nl_taskqueue);
473 taskqueue_free(nlp->nl_taskqueue);
478 CK_LIST_REMOVE(nlp, nl_port_next);
479 NL_LOG(LOG_DEBUG3, "socket %p, unlinking bound pid %u", so, nlp->nl_port);
481 CK_LIST_REMOVE(nlp, nl_next);
482 nlp->nl_socket = NULL;
488 NL_LOG(LOG_DEBUG3, "socket %p, detached", so);
490 /* XXX: is delayed free needed? */
491 NET_EPOCH_CALL(destroy_nlpcb_epoch, &nlp->nl_epoch_ctx);
495 nl_pru_disconnect(struct socket *so)
497 NL_LOG(LOG_DEBUG3, "socket %p, PID %d", so, curproc->p_pid);
498 MPASS(sotonlpcb(so) != NULL);
503 nl_pru_peeraddr(struct socket *so, struct sockaddr **sa)
505 NL_LOG(LOG_DEBUG3, "socket %p, PID %d", so, curproc->p_pid);
506 MPASS(sotonlpcb(so) != NULL);
511 nl_pru_shutdown(struct socket *so)
513 NL_LOG(LOG_DEBUG3, "socket %p, PID %d", so, curproc->p_pid);
514 MPASS(sotonlpcb(so) != NULL);
520 nl_pru_sockaddr(struct socket *so, struct sockaddr **sa)
522 struct sockaddr_nl *snl;
524 snl = malloc(sizeof(struct sockaddr_nl), M_SONAME, M_WAITOK | M_ZERO);
525 /* TODO: set other fields */
526 snl->nl_len = sizeof(struct sockaddr_nl);
527 snl->nl_family = AF_NETLINK;
528 snl->nl_pid = sotonlpcb(so)->nl_port;
529 *sa = (struct sockaddr *)snl;
534 nl_pru_close(struct socket *so)
536 NL_LOG(LOG_DEBUG3, "socket %p, PID %d", so, curproc->p_pid);
537 MPASS(sotonlpcb(so) != NULL);
538 soisdisconnected(so);
542 nl_pru_output(struct mbuf *m, struct socket *so, ...)
545 if (__predict_false(m == NULL ||
546 ((m->m_len < sizeof(struct nlmsghdr)) &&
547 (m = m_pullup(m, sizeof(struct nlmsghdr))) == NULL)))
549 MPASS((m->m_flags & M_PKTHDR) != 0);
551 NL_LOG(LOG_DEBUG3, "sending message to kernel async processing");
552 nl_receive_async(m, so);
558 nl_pru_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *sa,
559 struct mbuf *control, struct thread *td)
561 NL_LOG(LOG_DEBUG2, "sending message to kernel");
563 if (__predict_false(control != NULL)) {
564 if (control->m_len) {
571 return (nl_pru_output(m, so));
575 nl_pru_rcvd(struct socket *so, int flags)
577 NL_LOG(LOG_DEBUG3, "socket %p, PID %d", so, curproc->p_pid);
578 MPASS(sotonlpcb(so) != NULL);
580 nl_on_transmit(sotonlpcb(so));
586 nl_getoptflag(int sopt_name)
589 case NETLINK_CAP_ACK:
590 return (NLF_CAP_ACK);
591 case NETLINK_EXT_ACK:
592 return (NLF_EXT_ACK);
593 case NETLINK_GET_STRICT_CHK:
601 nl_ctloutput(struct socket *so, struct sockopt *sopt)
603 struct nl_control *ctl = atomic_load_ptr(&V_nl_ctl);
604 struct nlpcb *nlp = sotonlpcb(so);
606 int optval, error = 0;
609 NL_LOG(LOG_DEBUG2, "%ssockopt(%p, %d)", (sopt->sopt_dir) ? "set" : "get",
610 so, sopt->sopt_name);
612 switch (sopt->sopt_dir) {
614 switch (sopt->sopt_name) {
615 case NETLINK_ADD_MEMBERSHIP:
616 case NETLINK_DROP_MEMBERSHIP:
617 sooptcopyin(sopt, &optval, sizeof(optval), sizeof(optval));
618 if (optval <= 0 || optval >= NLP_MAX_GROUPS) {
622 NL_LOG(LOG_DEBUG2, "ADD/DEL group %d", (uint32_t)optval);
625 if (sopt->sopt_name == NETLINK_ADD_MEMBERSHIP)
626 nl_add_group_locked(nlp, optval);
628 nl_del_group_locked(nlp, optval);
631 case NETLINK_CAP_ACK:
632 case NETLINK_EXT_ACK:
633 case NETLINK_GET_STRICT_CHK:
634 sooptcopyin(sopt, &optval, sizeof(optval), sizeof(optval));
636 flag = nl_getoptflag(sopt->sopt_name);
640 nlp->nl_flags |= flag;
642 nlp->nl_flags &= ~flag;
650 switch (sopt->sopt_name) {
651 case NETLINK_LIST_MEMBERSHIPS:
653 optval = nl_get_groups_compat(nlp);
655 error = sooptcopyout(sopt, &optval, sizeof(optval));
657 case NETLINK_CAP_ACK:
658 case NETLINK_EXT_ACK:
659 case NETLINK_GET_STRICT_CHK:
661 optval = (nlp->nl_flags & nl_getoptflag(sopt->sopt_name)) != 0;
663 error = sooptcopyout(sopt, &optval, sizeof(optval));
678 nl_setsbopt(struct socket *so, struct sockopt *sopt)
683 if (sopt->sopt_name != SO_RCVBUF)
684 return (sbsetopt(so, sopt));
686 /* Allow to override max buffer size in certain conditions */
688 error = sooptcopyin(sopt, &optval, sizeof optval, sizeof optval);
691 NL_LOG(LOG_DEBUG2, "socket %p, PID %d, SO_RCVBUF=%d", so, curproc->p_pid, optval);
692 if (optval > sb_max_adj) {
693 if (priv_check(curthread, PRIV_NET_ROUTE) != 0)
697 SOCK_RECVBUF_LOCK(so);
698 result = sbreserve_locked_limit(so, SO_RCV, optval, nl_maxsockbuf, curthread);
699 SOCK_RECVBUF_UNLOCK(so);
701 return (result ? 0 : ENOBUFS);
705 struct pr_usrreqs nl_usrreqs = {
706 .pru_abort = nl_pru_abort,
707 .pru_attach = nl_pru_attach,
708 .pru_bind = nl_pru_bind,
709 .pru_connect = nl_pru_connect,
710 .pru_detach = nl_pru_detach,
711 .pru_disconnect = nl_pru_disconnect,
712 .pru_peeraddr = nl_pru_peeraddr,
713 .pru_send = nl_pru_send,
714 //.pru_soreceive = soreceive_dgram,
715 //.pru_sosend = sosend_dgram,
716 .pru_shutdown = nl_pru_shutdown,
717 .pru_sockaddr = nl_pru_sockaddr,
718 //.pru_sosetlabel = in_pcbsosetlabel,
719 .pru_close = nl_pru_close,
722 static struct domain netlinkdomain;
724 static struct protosw netlinksw[] = {
727 .pr_domain = &netlinkdomain,
728 .pr_protocol = 0, // IPPROTO_UDP
729 .pr_flags = PR_ATOMIC | PR_ADDR | PR_WANTRCVD,
730 .pr_ctloutput = nl_ctloutput,
731 .pr_usrreqs = &nl_usrreqs,
734 .pr_type = SOCK_DGRAM,
735 .pr_domain = &netlinkdomain,
736 .pr_protocol = 0, // IPPROTO_UDP
737 .pr_flags = PR_ATOMIC | PR_ADDR | PR_WANTRCVD,
738 .pr_ctloutput = nl_ctloutput,
739 .pr_usrreqs = &nl_usrreqs,
743 static struct domain netlinkdomain = {
744 .dom_family = AF_NETLINK,
745 .dom_name = "netlink",
746 #ifdef DOMF_UNLOADABLE
747 .dom_flags = DOMF_UNLOADABLE,
749 .dom_protosw = &netlinksw[0],
750 .dom_protoswNPROTOSW = (&netlinksw[0] + 2),