xref: /freebsd/sys/netlink/netlink_domain.c (revision dd21556857e8d40f66bf5ad54754d9d52669ebf7)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2021 Ng Peng Nam Sean
5  * Copyright (c) 2022 Alexander V. Chernikov <melifaro@FreeBSD.org>
6  * Copyright (c) 2023 Gleb Smirnoff <glebius@FreeBSD.org>
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29 
30 /*
31  * This file contains socket and protocol bindings for netlink.
32  */
33 
34 #include <sys/param.h>
35 #include <sys/kernel.h>
36 #include <sys/malloc.h>
37 #include <sys/lock.h>
38 #include <sys/rmlock.h>
39 #include <sys/domain.h>
40 #include <sys/jail.h>
41 #include <sys/mbuf.h>
42 #include <sys/osd.h>
43 #include <sys/protosw.h>
44 #include <sys/proc.h>
45 #include <sys/ck.h>
46 #include <sys/socket.h>
47 #include <sys/socketvar.h>
48 #include <sys/sysent.h>
49 #include <sys/syslog.h>
50 #include <sys/priv.h>
51 #include <sys/uio.h>
52 
53 #include <netlink/netlink.h>
54 #include <netlink/netlink_ctl.h>
55 #include <netlink/netlink_var.h>
56 
57 #define	DEBUG_MOD_NAME	nl_domain
58 #define	DEBUG_MAX_LEVEL	LOG_DEBUG3
59 #include <netlink/netlink_debug.h>
60 _DECLARE_DEBUG(LOG_INFO);
61 
62 _Static_assert((NLP_MAX_GROUPS % 64) == 0,
63     "NLP_MAX_GROUPS has to be multiple of 64");
64 _Static_assert(NLP_MAX_GROUPS >= 64,
65     "NLP_MAX_GROUPS has to be at least 64");
66 
67 #define	NLCTL_TRACKER		struct rm_priotracker nl_tracker
68 #define	NLCTL_RLOCK(_ctl)	rm_rlock(&((_ctl)->ctl_lock), &nl_tracker)
69 #define	NLCTL_RUNLOCK(_ctl)	rm_runlock(&((_ctl)->ctl_lock), &nl_tracker)
70 
71 #define	NLCTL_WLOCK(_ctl)	rm_wlock(&((_ctl)->ctl_lock))
72 #define	NLCTL_WUNLOCK(_ctl)	rm_wunlock(&((_ctl)->ctl_lock))
73 
74 static u_long nl_sendspace = NLSNDQ;
75 SYSCTL_ULONG(_net_netlink, OID_AUTO, sendspace, CTLFLAG_RW, &nl_sendspace, 0,
76     "Default netlink socket send space");
77 
78 static u_long nl_recvspace = NLSNDQ;
79 SYSCTL_ULONG(_net_netlink, OID_AUTO, recvspace, CTLFLAG_RW, &nl_recvspace, 0,
80     "Default netlink socket receive space");
81 
82 extern u_long sb_max_adj;
83 static u_long nl_maxsockbuf = 512 * 1024 * 1024; /* 512M, XXX: init based on physmem */
84 static int sysctl_handle_nl_maxsockbuf(SYSCTL_HANDLER_ARGS);
85 SYSCTL_OID(_net_netlink, OID_AUTO, nl_maxsockbuf,
86     CTLTYPE_ULONG | CTLFLAG_RW | CTLFLAG_MPSAFE, &nl_maxsockbuf, 0,
87     sysctl_handle_nl_maxsockbuf, "LU",
88     "Maximum Netlink socket buffer size");
89 
90 
91 static unsigned int osd_slot_id = 0;
92 
93 void
94 nl_osd_register(void)
95 {
96 	osd_slot_id = osd_register(OSD_THREAD, NULL, NULL);
97 }
98 
99 void
100 nl_osd_unregister(void)
101 {
102 	osd_deregister(OSD_THREAD, osd_slot_id);
103 }
104 
105 struct nlpcb *
106 _nl_get_thread_nlp(struct thread *td)
107 {
108 	return (osd_get(OSD_THREAD, &td->td_osd, osd_slot_id));
109 }
110 
111 void
112 nl_set_thread_nlp(struct thread *td, struct nlpcb *nlp)
113 {
114 	NLP_LOG(LOG_DEBUG2, nlp, "Set thread %p nlp to %p (slot %u)", td, nlp, osd_slot_id);
115 	if (osd_set(OSD_THREAD, &td->td_osd, osd_slot_id, nlp) == 0)
116 		return;
117 	/* Failed, need to realloc */
118 	void **rsv = osd_reserve(osd_slot_id);
119 	osd_set_reserved(OSD_THREAD, &td->td_osd, osd_slot_id, rsv, nlp);
120 }
121 
122 /*
123  * Looks up a nlpcb struct based on the @portid. Need to claim nlsock_mtx.
124  * Returns nlpcb pointer if present else NULL
125  */
126 static struct nlpcb *
127 nl_port_lookup(uint32_t port_id)
128 {
129 	struct nlpcb *nlp;
130 
131 	CK_LIST_FOREACH(nlp, &V_nl_ctl->ctl_port_head, nl_port_next) {
132 		if (nlp->nl_port == port_id)
133 			return (nlp);
134 	}
135 	return (NULL);
136 }
137 
138 static void
139 nl_add_group_locked(struct nlpcb *nlp, unsigned int group_id)
140 {
141 	MPASS(group_id <= NLP_MAX_GROUPS);
142 	--group_id;
143 
144 	/* TODO: add family handler callback */
145 	if (!nlp_unconstrained_vnet(nlp))
146 		return;
147 
148 	BIT_SET(NLP_MAX_GROUPS, group_id, &nlp->nl_groups);
149 }
150 
151 static void
152 nl_del_group_locked(struct nlpcb *nlp, unsigned int group_id)
153 {
154 	MPASS(group_id <= NLP_MAX_GROUPS);
155 	--group_id;
156 
157 	BIT_CLR(NLP_MAX_GROUPS, group_id, &nlp->nl_groups);
158 }
159 
160 static bool
161 nl_isset_group_locked(struct nlpcb *nlp, unsigned int group_id)
162 {
163 	MPASS(group_id <= NLP_MAX_GROUPS);
164 	--group_id;
165 
166 	return (BIT_ISSET(NLP_MAX_GROUPS, group_id, &nlp->nl_groups));
167 }
168 
169 static uint32_t
170 nl_get_groups_compat(struct nlpcb *nlp)
171 {
172 	uint32_t groups_mask = 0;
173 
174 	for (int i = 0; i < 32; i++) {
175 		if (nl_isset_group_locked(nlp, i + 1))
176 			groups_mask |= (1 << i);
177 	}
178 
179 	return (groups_mask);
180 }
181 
182 static struct nl_buf *
183 nl_buf_copy(struct nl_buf *nb)
184 {
185 	struct nl_buf *copy;
186 
187 	copy = nl_buf_alloc(nb->buflen, M_NOWAIT);
188 	if (__predict_false(copy == NULL))
189 		return (NULL);
190 	memcpy(copy, nb, sizeof(*nb) + nb->buflen);
191 
192 	return (copy);
193 }
194 
195 /*
196  * Broadcasts in the writer's buffer.
197  */
198 bool
199 nl_send_group(struct nl_writer *nw)
200 {
201 	struct nl_buf *nb = nw->buf;
202 	struct nlpcb *nlp_last = NULL;
203 	struct nlpcb *nlp;
204 	NLCTL_TRACKER;
205 
206 	IF_DEBUG_LEVEL(LOG_DEBUG2) {
207 		struct nlmsghdr *hdr = (struct nlmsghdr *)nb->data;
208 		NL_LOG(LOG_DEBUG2, "MCAST len %u msg type %d len %u to group %d/%d",
209 		    nb->datalen, hdr->nlmsg_type, hdr->nlmsg_len,
210 		    nw->group.proto, nw->group.id);
211 	}
212 
213 	nw->buf = NULL;
214 
215 	struct nl_control *ctl = atomic_load_ptr(&V_nl_ctl);
216 	if (__predict_false(ctl == NULL)) {
217 		/*
218 		 * Can be the case when notification is sent within VNET
219 		 * which doesn't have any netlink sockets.
220 		 */
221 		nl_buf_free(nb);
222 		return (false);
223 	}
224 
225 	NLCTL_RLOCK(ctl);
226 
227 	CK_LIST_FOREACH(nlp, &ctl->ctl_pcb_head, nl_next) {
228 		if ((nw->group.priv == 0 || priv_check_cred(
229 		    nlp->nl_socket->so_cred, nw->group.priv) == 0) &&
230 		    nlp->nl_proto == nw->group.proto &&
231 		    nl_isset_group_locked(nlp, nw->group.id)) {
232 			if (nlp_last != NULL) {
233 				struct nl_buf *copy;
234 
235 				copy = nl_buf_copy(nb);
236 				if (copy != NULL) {
237 					nw->buf = copy;
238 					(void)nl_send(nw, nlp_last);
239 				} else {
240 					NLP_LOCK(nlp_last);
241 					if (nlp_last->nl_socket != NULL)
242 						sorwakeup(nlp_last->nl_socket);
243 					NLP_UNLOCK(nlp_last);
244 				}
245 			}
246 			nlp_last = nlp;
247 		}
248 	}
249 	if (nlp_last != NULL) {
250 		nw->buf = nb;
251 		(void)nl_send(nw, nlp_last);
252 	} else
253 		nl_buf_free(nb);
254 
255 	NLCTL_RUNLOCK(ctl);
256 
257 	return (true);
258 }
259 
260 bool
261 nl_has_listeners(uint16_t netlink_family, uint32_t groups_mask)
262 {
263 	return (V_nl_ctl != NULL);
264 }
265 
266 static uint32_t
267 nl_find_port(void)
268 {
269 	/*
270 	 * app can open multiple netlink sockets.
271 	 * Start with current pid, if already taken,
272 	 * try random numbers in 65k..256k+65k space,
273 	 * avoiding clash with pids.
274 	 */
275 	if (nl_port_lookup(curproc->p_pid) == NULL)
276 		return (curproc->p_pid);
277 	for (int i = 0; i < 16; i++) {
278 		uint32_t nl_port = (arc4random() % 65536) + 65536 * 4;
279 		if (nl_port_lookup(nl_port) == 0)
280 			return (nl_port);
281 		NL_LOG(LOG_DEBUG3, "tried %u\n", nl_port);
282 	}
283 	return (curproc->p_pid);
284 }
285 
286 static int
287 nl_bind_locked(struct nlpcb *nlp, struct sockaddr_nl *snl)
288 {
289 	if (nlp->nl_bound) {
290 		if (nlp->nl_port != snl->nl_pid) {
291 			NL_LOG(LOG_DEBUG,
292 			    "bind() failed: program pid %d "
293 			    "is different from provided pid %d",
294 			    nlp->nl_port, snl->nl_pid);
295 			return (EINVAL); // XXX: better error
296 		}
297 	} else {
298 		if (snl->nl_pid == 0)
299 			snl->nl_pid = nl_find_port();
300 		if (nl_port_lookup(snl->nl_pid) != NULL)
301 			return (EADDRINUSE);
302 		nlp->nl_port = snl->nl_pid;
303 		nlp->nl_bound = true;
304 		CK_LIST_INSERT_HEAD(&V_nl_ctl->ctl_port_head, nlp, nl_port_next);
305 	}
306 	for (int i = 0; i < 32; i++) {
307 		if (snl->nl_groups & ((uint32_t)1 << i))
308 			nl_add_group_locked(nlp, i + 1);
309 		else
310 			nl_del_group_locked(nlp, i + 1);
311 	}
312 
313 	return (0);
314 }
315 
316 static int
317 nl_pru_attach(struct socket *so, int proto, struct thread *td)
318 {
319 	struct nlpcb *nlp;
320 	int error;
321 
322 	if (__predict_false(netlink_unloading != 0))
323 		return (EAFNOSUPPORT);
324 
325 	error = nl_verify_proto(proto);
326 	if (error != 0)
327 		return (error);
328 
329 	bool is_linux = SV_PROC_ABI(td->td_proc) == SV_ABI_LINUX;
330 	NL_LOG(LOG_DEBUG2, "socket %p, %sPID %d: attaching socket to %s",
331 	    so, is_linux ? "(linux) " : "", curproc->p_pid,
332 	    nl_get_proto_name(proto));
333 
334 	/* Create per-VNET state on first socket init */
335 	struct nl_control *ctl = atomic_load_ptr(&V_nl_ctl);
336 	if (ctl == NULL)
337 		ctl = vnet_nl_ctl_init();
338 	KASSERT(V_nl_ctl != NULL, ("nl_attach: vnet_sock_init() failed"));
339 
340 	MPASS(sotonlpcb(so) == NULL);
341 
342 	nlp = malloc(sizeof(struct nlpcb), M_PCB, M_WAITOK | M_ZERO);
343 	error = soreserve(so, nl_sendspace, nl_recvspace);
344 	if (error != 0) {
345 		free(nlp, M_PCB);
346 		return (error);
347 	}
348 	TAILQ_INIT(&so->so_rcv.nl_queue);
349 	TAILQ_INIT(&so->so_snd.nl_queue);
350 	so->so_pcb = nlp;
351 	nlp->nl_socket = so;
352 	/* Copy so_cred to avoid having socket_var.h in every header */
353 	nlp->nl_cred = so->so_cred;
354 	nlp->nl_proto = proto;
355 	nlp->nl_process_id = curproc->p_pid;
356 	nlp->nl_linux = is_linux;
357 	nlp->nl_unconstrained_vnet = !jailed_without_vnet(so->so_cred);
358 	nlp->nl_need_thread_setup = true;
359 	NLP_LOCK_INIT(nlp);
360 	refcount_init(&nlp->nl_refcount, 1);
361 
362 	nlp->nl_taskqueue = taskqueue_create("netlink_socket", M_WAITOK,
363 	    taskqueue_thread_enqueue, &nlp->nl_taskqueue);
364 	TASK_INIT(&nlp->nl_task, 0, nl_taskqueue_handler, nlp);
365 	taskqueue_start_threads(&nlp->nl_taskqueue, 1, PWAIT,
366 	    "netlink_socket (PID %u)", nlp->nl_process_id);
367 
368 	NLCTL_WLOCK(ctl);
369 	/* XXX: check ctl is still alive */
370 	CK_LIST_INSERT_HEAD(&ctl->ctl_pcb_head, nlp, nl_next);
371 	NLCTL_WUNLOCK(ctl);
372 
373 	soisconnected(so);
374 
375 	return (0);
376 }
377 
378 static int
379 nl_pru_bind(struct socket *so, struct sockaddr *sa, struct thread *td)
380 {
381 	struct nl_control *ctl = atomic_load_ptr(&V_nl_ctl);
382 	struct nlpcb *nlp = sotonlpcb(so);
383 	struct sockaddr_nl *snl = (struct sockaddr_nl *)sa;
384 	int error;
385 
386 	NL_LOG(LOG_DEBUG3, "socket %p, PID %d", so, curproc->p_pid);
387 	if (snl->nl_len != sizeof(*snl)) {
388 		NL_LOG(LOG_DEBUG, "socket %p, wrong sizeof(), ignoring bind()", so);
389 		return (EINVAL);
390 	}
391 
392 
393 	NLCTL_WLOCK(ctl);
394 	NLP_LOCK(nlp);
395 	error = nl_bind_locked(nlp, snl);
396 	NLP_UNLOCK(nlp);
397 	NLCTL_WUNLOCK(ctl);
398 	NL_LOG(LOG_DEBUG2, "socket %p, bind() to %u, groups %u, error %d", so,
399 	    snl->nl_pid, snl->nl_groups, error);
400 
401 	return (error);
402 }
403 
404 
405 static int
406 nl_assign_port(struct nlpcb *nlp, uint32_t port_id)
407 {
408 	struct nl_control *ctl = atomic_load_ptr(&V_nl_ctl);
409 	struct sockaddr_nl snl = {
410 		.nl_pid = port_id,
411 	};
412 	int error;
413 
414 	NLCTL_WLOCK(ctl);
415 	NLP_LOCK(nlp);
416 	snl.nl_groups = nl_get_groups_compat(nlp);
417 	error = nl_bind_locked(nlp, &snl);
418 	NLP_UNLOCK(nlp);
419 	NLCTL_WUNLOCK(ctl);
420 
421 	NL_LOG(LOG_DEBUG3, "socket %p, port assign: %d, error: %d", nlp->nl_socket, port_id, error);
422 	return (error);
423 }
424 
425 /*
426  * nl_autobind_port binds a unused portid to @nlp
427  * @nlp: pcb data for the netlink socket
428  * @candidate_id: first id to consider
429  */
430 static int
431 nl_autobind_port(struct nlpcb *nlp, uint32_t candidate_id)
432 {
433 	struct nl_control *ctl = atomic_load_ptr(&V_nl_ctl);
434 	uint32_t port_id = candidate_id;
435 	NLCTL_TRACKER;
436 	bool exist;
437 	int error = EADDRINUSE;
438 
439 	for (int i = 0; i < 10; i++) {
440 		NL_LOG(LOG_DEBUG3, "socket %p, trying to assign port %d", nlp->nl_socket, port_id);
441 		NLCTL_RLOCK(ctl);
442 		exist = nl_port_lookup(port_id) != 0;
443 		NLCTL_RUNLOCK(ctl);
444 		if (!exist) {
445 			error = nl_assign_port(nlp, port_id);
446 			if (error != EADDRINUSE)
447 				break;
448 		}
449 		port_id++;
450 	}
451 	NL_LOG(LOG_DEBUG3, "socket %p, autobind to %d, error: %d", nlp->nl_socket, port_id, error);
452 	return (error);
453 }
454 
455 static int
456 nl_pru_connect(struct socket *so, struct sockaddr *sa, struct thread *td)
457 {
458 	struct sockaddr_nl *snl = (struct sockaddr_nl *)sa;
459 	struct nlpcb *nlp;
460 
461 	NL_LOG(LOG_DEBUG3, "socket %p, PID %d", so, curproc->p_pid);
462 	if (snl->nl_len != sizeof(*snl)) {
463 		NL_LOG(LOG_DEBUG, "socket %p, wrong sizeof(), ignoring bind()", so);
464 		return (EINVAL);
465 	}
466 
467 	nlp = sotonlpcb(so);
468 	if (!nlp->nl_bound) {
469 		int error = nl_autobind_port(nlp, td->td_proc->p_pid);
470 		if (error != 0) {
471 			NL_LOG(LOG_DEBUG, "socket %p, nl_autobind() failed: %d", so, error);
472 			return (error);
473 		}
474 	}
475 	/* XXX: Handle socket flags & multicast */
476 	soisconnected(so);
477 
478 	NL_LOG(LOG_DEBUG2, "socket %p, connect to %u", so, snl->nl_pid);
479 
480 	return (0);
481 }
482 
483 static void
484 destroy_nlpcb_epoch(epoch_context_t ctx)
485 {
486 	struct nlpcb *nlp;
487 
488 	nlp = __containerof(ctx, struct nlpcb, nl_epoch_ctx);
489 
490 	NLP_LOCK_DESTROY(nlp);
491 	free(nlp, M_PCB);
492 }
493 
494 static void
495 nl_close(struct socket *so)
496 {
497 	struct nl_control *ctl = atomic_load_ptr(&V_nl_ctl);
498 	MPASS(sotonlpcb(so) != NULL);
499 	struct nlpcb *nlp;
500 	struct nl_buf *nb;
501 
502 	NL_LOG(LOG_DEBUG2, "detaching socket %p, PID %d", so, curproc->p_pid);
503 	nlp = sotonlpcb(so);
504 
505 	/* Mark as inactive so no new work can be enqueued */
506 	NLP_LOCK(nlp);
507 	bool was_bound = nlp->nl_bound;
508 	NLP_UNLOCK(nlp);
509 
510 	/* Wait till all scheduled work has been completed  */
511 	taskqueue_drain_all(nlp->nl_taskqueue);
512 	taskqueue_free(nlp->nl_taskqueue);
513 
514 	NLCTL_WLOCK(ctl);
515 	NLP_LOCK(nlp);
516 	if (was_bound) {
517 		CK_LIST_REMOVE(nlp, nl_port_next);
518 		NL_LOG(LOG_DEBUG3, "socket %p, unlinking bound pid %u", so, nlp->nl_port);
519 	}
520 	CK_LIST_REMOVE(nlp, nl_next);
521 	nlp->nl_socket = NULL;
522 	NLP_UNLOCK(nlp);
523 	NLCTL_WUNLOCK(ctl);
524 
525 	so->so_pcb = NULL;
526 
527 	while ((nb = TAILQ_FIRST(&so->so_snd.nl_queue)) != NULL) {
528 		TAILQ_REMOVE(&so->so_snd.nl_queue, nb, tailq);
529 		nl_buf_free(nb);
530 	}
531 	while ((nb = TAILQ_FIRST(&so->so_rcv.nl_queue)) != NULL) {
532 		TAILQ_REMOVE(&so->so_rcv.nl_queue, nb, tailq);
533 		nl_buf_free(nb);
534 	}
535 
536 	NL_LOG(LOG_DEBUG3, "socket %p, detached", so);
537 
538 	/* XXX: is delayed free needed? */
539 	NET_EPOCH_CALL(destroy_nlpcb_epoch, &nlp->nl_epoch_ctx);
540 }
541 
542 static int
543 nl_pru_disconnect(struct socket *so)
544 {
545 	NL_LOG(LOG_DEBUG3, "socket %p, PID %d", so, curproc->p_pid);
546 	MPASS(sotonlpcb(so) != NULL);
547 	return (ENOTCONN);
548 }
549 
550 static int
551 nl_sockaddr(struct socket *so, struct sockaddr *sa)
552 {
553 
554 	*(struct sockaddr_nl *)sa = (struct sockaddr_nl ){
555 		/* TODO: set other fields */
556 		.nl_len = sizeof(struct sockaddr_nl),
557 		.nl_family = AF_NETLINK,
558 		.nl_pid = sotonlpcb(so)->nl_port,
559 	};
560 
561 	return (0);
562 }
563 
564 static int
565 nl_sosend(struct socket *so, struct sockaddr *addr, struct uio *uio,
566     struct mbuf *m, struct mbuf *control, int flags, struct thread *td)
567 {
568 	struct nlpcb *nlp = sotonlpcb(so);
569 	struct sockbuf *sb = &so->so_snd;
570 	struct nl_buf *nb;
571 	size_t len;
572 	int error;
573 
574 	MPASS(m == NULL && uio != NULL);
575 
576         NL_LOG(LOG_DEBUG2, "sending message to kernel");
577 
578 	if (__predict_false(control != NULL)) {
579 		m_freem(control);
580 		return (EINVAL);
581 	}
582 
583 	if (__predict_false(flags & MSG_OOB))	/* XXXGL: or just ignore? */
584 		return (EOPNOTSUPP);
585 
586 	if (__predict_false(uio->uio_resid < sizeof(struct nlmsghdr)))
587 		return (ENOBUFS);		/* XXXGL: any better error? */
588 
589 	NL_LOG(LOG_DEBUG3, "sending message to kernel async processing");
590 
591 	error = SOCK_IO_SEND_LOCK(so, SBLOCKWAIT(flags));
592 	if (error)
593 		return (error);
594 
595 	len = roundup2(uio->uio_resid, 8) + SCRATCH_BUFFER_SIZE;
596 	if (nlp->nl_linux)
597 		len += roundup2(uio->uio_resid, 8);
598 	nb = nl_buf_alloc(len, M_WAITOK);
599 	nb->datalen = uio->uio_resid;
600 	error = uiomove(&nb->data[0], uio->uio_resid, uio);
601 	if (__predict_false(error))
602 		goto out;
603 
604 	SOCK_SENDBUF_LOCK(so);
605 restart:
606 	if (sb->sb_hiwat - sb->sb_ccc >= nb->datalen) {
607 		TAILQ_INSERT_TAIL(&sb->nl_queue, nb, tailq);
608 		sb->sb_acc += nb->datalen;
609 		sb->sb_ccc += nb->datalen;
610 		nb = NULL;
611 	} else if ((so->so_state & SS_NBIO) ||
612 	    (flags & (MSG_NBIO | MSG_DONTWAIT)) != 0) {
613 		SOCK_SENDBUF_UNLOCK(so);
614 		error = EWOULDBLOCK;
615 		goto out;
616 	} else {
617 		if ((error = sbwait(so, SO_SND)) != 0) {
618 			SOCK_SENDBUF_UNLOCK(so);
619 			goto out;
620 		} else
621 			goto restart;
622 	}
623 	SOCK_SENDBUF_UNLOCK(so);
624 
625 	if (nb == NULL) {
626 		NL_LOG(LOG_DEBUG3, "enqueue %u bytes", nb->datalen);
627 		NLP_LOCK(nlp);
628 		nl_schedule_taskqueue(nlp);
629 		NLP_UNLOCK(nlp);
630 	}
631 
632 out:
633 	SOCK_IO_SEND_UNLOCK(so);
634 	if (nb != NULL)
635 		nl_buf_free(nb);
636 	return (error);
637 }
638 
639 /* Create control data for recvmsg(2) on Netlink socket. */
640 static struct mbuf *
641 nl_createcontrol(struct nlpcb *nlp)
642 {
643 	struct {
644 		struct nlattr nla;
645 		uint32_t val;
646 	} data[] = {
647 		{
648 			.nla.nla_len = sizeof(struct nlattr) + sizeof(uint32_t),
649 			.nla.nla_type = NLMSGINFO_ATTR_PROCESS_ID,
650 			.val = nlp->nl_process_id,
651 		},
652 		{
653 			.nla.nla_len = sizeof(struct nlattr) + sizeof(uint32_t),
654 			.nla.nla_type = NLMSGINFO_ATTR_PORT_ID,
655 			.val = nlp->nl_port,
656 		},
657 	};
658 
659 	return (sbcreatecontrol(data, sizeof(data), NETLINK_MSG_INFO,
660 	    SOL_NETLINK, M_WAITOK));
661 }
662 
663 static int
664 nl_soreceive(struct socket *so, struct sockaddr **psa, struct uio *uio,
665     struct mbuf **mp, struct mbuf **controlp, int *flagsp)
666 {
667 	static const struct sockaddr_nl nl_empty_src = {
668 		.nl_len = sizeof(struct sockaddr_nl),
669 		.nl_family = PF_NETLINK,
670 		.nl_pid = 0 /* comes from the kernel */
671 	};
672 	struct sockbuf *sb = &so->so_rcv;
673 	struct nlpcb *nlp = sotonlpcb(so);
674 	struct nl_buf *first, *last, *nb, *next;
675 	struct nlmsghdr *hdr;
676 	int flags, error;
677 	u_int len, overflow, partoff, partlen, msgrcv, datalen;
678 	bool nonblock, trunc, peek;
679 
680 	MPASS(mp == NULL && uio != NULL);
681 
682 	NL_LOG(LOG_DEBUG3, "socket %p, PID %d", so, curproc->p_pid);
683 
684 	if (psa != NULL)
685 		*psa = sodupsockaddr((const struct sockaddr *)&nl_empty_src,
686 		    M_WAITOK);
687 
688 	if (controlp != NULL && (nlp->nl_flags & NLF_MSG_INFO))
689 		*controlp = nl_createcontrol(nlp);
690 
691 	flags = flagsp != NULL ? *flagsp & ~MSG_TRUNC : 0;
692 	trunc = flagsp != NULL ? *flagsp & MSG_TRUNC : false;
693 	nonblock = (so->so_state & SS_NBIO) ||
694 	    (flags & (MSG_DONTWAIT | MSG_NBIO));
695 	peek = flags & MSG_PEEK;
696 
697 	error = SOCK_IO_RECV_LOCK(so, SBLOCKWAIT(flags));
698 	if (__predict_false(error))
699 		return (error);
700 
701 	len = 0;
702 	overflow = 0;
703 	msgrcv = 0;
704 	datalen = 0;
705 
706 	SOCK_RECVBUF_LOCK(so);
707 	while ((first = TAILQ_FIRST(&sb->nl_queue)) == NULL) {
708 		if (nonblock) {
709 			SOCK_RECVBUF_UNLOCK(so);
710 			SOCK_IO_RECV_UNLOCK(so);
711 			return (EWOULDBLOCK);
712 		}
713 		error = sbwait(so, SO_RCV);
714 		if (error) {
715 			SOCK_RECVBUF_UNLOCK(so);
716 			SOCK_IO_RECV_UNLOCK(so);
717 			return (error);
718 		}
719 	}
720 
721 	/*
722 	 * Netlink socket buffer consists of a queue of nl_bufs, but for the
723 	 * userland there should be no boundaries.  However, there are Netlink
724 	 * messages, that shouldn't be split.  Internal invariant is that a
725 	 * message never spans two nl_bufs.
726 	 * If a large userland buffer is provided, we would traverse the queue
727 	 * until either queue end is reached or the buffer is fulfilled.  If
728 	 * an application provides a buffer that isn't able to fit a single
729 	 * message, we would truncate it and lose its tail.  This is the only
730 	 * condition where we would lose data.  If buffer is able to fit at
731 	 * least one message, we would return it and won't truncate the next.
732 	 *
733 	 * We use same code for normal and MSG_PEEK case.  At first queue pass
734 	 * we scan nl_bufs and count lenght.  In case we can read entire buffer
735 	 * at one write everything is trivial.  In case we can not, we save
736 	 * pointer to the last (or partial) nl_buf and in the !peek case we
737 	 * split the queue into two pieces.  We can safely drop the queue lock,
738 	 * as kernel would only append nl_bufs to the end of the queue, and
739 	 * we are the exclusive owner of queue beginning due to sleepable lock.
740 	 * At the second pass we copy data out and in !peek case free nl_bufs.
741 	 */
742 	TAILQ_FOREACH(nb, &sb->nl_queue, tailq) {
743 		u_int offset;
744 
745 		MPASS(nb->offset < nb->datalen);
746 		offset = nb->offset;
747 		while (offset < nb->datalen) {
748 			hdr = (struct nlmsghdr *)&nb->data[offset];
749 			MPASS(nb->offset + hdr->nlmsg_len <= nb->datalen);
750 			if (uio->uio_resid < len + hdr->nlmsg_len) {
751 				overflow = len + hdr->nlmsg_len -
752 				    uio->uio_resid;
753 				partoff = nb->offset;
754 				if (offset > partoff) {
755 					partlen = offset - partoff;
756 					if (!peek) {
757 						nb->offset = offset;
758 						datalen += partlen;
759 					}
760 				} else if (len == 0 && uio->uio_resid > 0) {
761 					flags |= MSG_TRUNC;
762 					partlen = uio->uio_resid;
763 					if (peek)
764 						goto nospace;
765 					datalen += hdr->nlmsg_len;
766 					if (nb->offset + hdr->nlmsg_len ==
767 					    nb->datalen) {
768 						/*
769 						 * Avoid leaving empty nb.
770 						 * Process last nb normally.
771 						 * Trust uiomove() to care
772 						 * about negative uio_resid.
773 						 */
774 						nb = TAILQ_NEXT(nb, tailq);
775 						overflow = 0;
776 						partlen = 0;
777 					} else
778 						nb->offset += hdr->nlmsg_len;
779 					msgrcv++;
780 				} else
781 					partlen = 0;
782 				goto nospace;
783 			}
784 			len += hdr->nlmsg_len;
785 			offset += hdr->nlmsg_len;
786 			MPASS(offset <= nb->buflen);
787 			msgrcv++;
788 		}
789 		MPASS(offset == nb->datalen);
790 		datalen += nb->datalen - nb->offset;
791 	}
792 nospace:
793 	last = nb;
794 	if (!peek) {
795 		if (last == NULL)
796 			TAILQ_INIT(&sb->nl_queue);
797 		else {
798 			/* XXXGL: create TAILQ_SPLIT */
799 			TAILQ_FIRST(&sb->nl_queue) = last;
800 			last->tailq.tqe_prev = &TAILQ_FIRST(&sb->nl_queue);
801 		}
802 		MPASS(sb->sb_acc >= datalen);
803 		sb->sb_acc -= datalen;
804 		sb->sb_ccc -= datalen;
805 	}
806 	SOCK_RECVBUF_UNLOCK(so);
807 
808 	for (nb = first; nb != last; nb = next) {
809 		next = TAILQ_NEXT(nb, tailq);
810 		if (__predict_true(error == 0))
811 			error = uiomove(&nb->data[nb->offset],
812 			    (int)(nb->datalen - nb->offset), uio);
813 		if (!peek)
814 			nl_buf_free(nb);
815 	}
816 	if (last != NULL && partlen > 0 && __predict_true(error == 0))
817 		error = uiomove(&nb->data[partoff], (int)partlen, uio);
818 
819 	if (trunc && overflow > 0) {
820 		uio->uio_resid -= overflow;
821 		MPASS(uio->uio_resid < 0);
822 	} else
823 		MPASS(uio->uio_resid >= 0);
824 
825 	if (uio->uio_td)
826 		uio->uio_td->td_ru.ru_msgrcv += msgrcv;
827 
828 	if (flagsp != NULL)
829 		*flagsp |= flags;
830 
831 	SOCK_IO_RECV_UNLOCK(so);
832 
833 	nl_on_transmit(sotonlpcb(so));
834 
835 	return (error);
836 }
837 
838 static int
839 nl_getoptflag(int sopt_name)
840 {
841 	switch (sopt_name) {
842 	case NETLINK_CAP_ACK:
843 		return (NLF_CAP_ACK);
844 	case NETLINK_EXT_ACK:
845 		return (NLF_EXT_ACK);
846 	case NETLINK_GET_STRICT_CHK:
847 		return (NLF_STRICT);
848 	case NETLINK_MSG_INFO:
849 		return (NLF_MSG_INFO);
850 	}
851 
852 	return (0);
853 }
854 
855 static int
856 nl_ctloutput(struct socket *so, struct sockopt *sopt)
857 {
858 	struct nl_control *ctl = atomic_load_ptr(&V_nl_ctl);
859 	struct nlpcb *nlp = sotonlpcb(so);
860 	uint32_t flag;
861 	int optval, error = 0;
862 	NLCTL_TRACKER;
863 
864 	NL_LOG(LOG_DEBUG2, "%ssockopt(%p, %d)", (sopt->sopt_dir) ? "set" : "get",
865 	    so, sopt->sopt_name);
866 
867 	switch (sopt->sopt_dir) {
868 	case SOPT_SET:
869 		switch (sopt->sopt_name) {
870 		case NETLINK_ADD_MEMBERSHIP:
871 		case NETLINK_DROP_MEMBERSHIP:
872 			error = sooptcopyin(sopt, &optval, sizeof(optval), sizeof(optval));
873 			if (error != 0)
874 				break;
875 			if (optval <= 0 || optval >= NLP_MAX_GROUPS) {
876 				error = ERANGE;
877 				break;
878 			}
879 			NL_LOG(LOG_DEBUG2, "ADD/DEL group %d", (uint32_t)optval);
880 
881 			NLCTL_WLOCK(ctl);
882 			if (sopt->sopt_name == NETLINK_ADD_MEMBERSHIP)
883 				nl_add_group_locked(nlp, optval);
884 			else
885 				nl_del_group_locked(nlp, optval);
886 			NLCTL_WUNLOCK(ctl);
887 			break;
888 		case NETLINK_CAP_ACK:
889 		case NETLINK_EXT_ACK:
890 		case NETLINK_GET_STRICT_CHK:
891 		case NETLINK_MSG_INFO:
892 			error = sooptcopyin(sopt, &optval, sizeof(optval), sizeof(optval));
893 			if (error != 0)
894 				break;
895 
896 			flag = nl_getoptflag(sopt->sopt_name);
897 
898 			if ((flag == NLF_MSG_INFO) && nlp->nl_linux) {
899 				error = EINVAL;
900 				break;
901 			}
902 
903 			NLCTL_WLOCK(ctl);
904 			if (optval != 0)
905 				nlp->nl_flags |= flag;
906 			else
907 				nlp->nl_flags &= ~flag;
908 			NLCTL_WUNLOCK(ctl);
909 			break;
910 		default:
911 			error = ENOPROTOOPT;
912 		}
913 		break;
914 	case SOPT_GET:
915 		switch (sopt->sopt_name) {
916 		case NETLINK_LIST_MEMBERSHIPS:
917 			NLCTL_RLOCK(ctl);
918 			optval = nl_get_groups_compat(nlp);
919 			NLCTL_RUNLOCK(ctl);
920 			error = sooptcopyout(sopt, &optval, sizeof(optval));
921 			break;
922 		case NETLINK_CAP_ACK:
923 		case NETLINK_EXT_ACK:
924 		case NETLINK_GET_STRICT_CHK:
925 		case NETLINK_MSG_INFO:
926 			NLCTL_RLOCK(ctl);
927 			optval = (nlp->nl_flags & nl_getoptflag(sopt->sopt_name)) != 0;
928 			NLCTL_RUNLOCK(ctl);
929 			error = sooptcopyout(sopt, &optval, sizeof(optval));
930 			break;
931 		default:
932 			error = ENOPROTOOPT;
933 		}
934 		break;
935 	default:
936 		error = ENOPROTOOPT;
937 	}
938 
939 	return (error);
940 }
941 
942 static int
943 sysctl_handle_nl_maxsockbuf(SYSCTL_HANDLER_ARGS)
944 {
945 	int error = 0;
946 	u_long tmp_maxsockbuf = nl_maxsockbuf;
947 
948 	error = sysctl_handle_long(oidp, &tmp_maxsockbuf, arg2, req);
949 	if (error || !req->newptr)
950 		return (error);
951 	if (tmp_maxsockbuf < MSIZE + MCLBYTES)
952 		return (EINVAL);
953 	nl_maxsockbuf = tmp_maxsockbuf;
954 
955 	return (0);
956 }
957 
958 static int
959 nl_setsbopt(struct socket *so, struct sockopt *sopt)
960 {
961 	int error, optval;
962 	bool result;
963 
964 	if (sopt->sopt_name != SO_RCVBUF)
965 		return (sbsetopt(so, sopt));
966 
967 	/* Allow to override max buffer size in certain conditions */
968 
969 	error = sooptcopyin(sopt, &optval, sizeof optval, sizeof optval);
970 	if (error != 0)
971 		return (error);
972 	NL_LOG(LOG_DEBUG2, "socket %p, PID %d, SO_RCVBUF=%d", so, curproc->p_pid, optval);
973 	if (optval > sb_max_adj) {
974 		if (priv_check(curthread, PRIV_NET_ROUTE) != 0)
975 			return (EPERM);
976 	}
977 
978 	SOCK_RECVBUF_LOCK(so);
979 	result = sbreserve_locked_limit(so, SO_RCV, optval, nl_maxsockbuf, curthread);
980 	SOCK_RECVBUF_UNLOCK(so);
981 
982 	return (result ? 0 : ENOBUFS);
983 }
984 
985 #define	NETLINK_PROTOSW						\
986 	.pr_flags = PR_ATOMIC | PR_ADDR | PR_SOCKBUF,		\
987 	.pr_ctloutput = nl_ctloutput,				\
988 	.pr_setsbopt = nl_setsbopt,				\
989 	.pr_attach = nl_pru_attach,				\
990 	.pr_bind = nl_pru_bind,					\
991 	.pr_connect = nl_pru_connect,				\
992 	.pr_disconnect = nl_pru_disconnect,			\
993 	.pr_sosend = nl_sosend,					\
994 	.pr_soreceive = nl_soreceive,				\
995 	.pr_sockaddr = nl_sockaddr,				\
996 	.pr_close = nl_close
997 
998 static struct protosw netlink_raw_sw = {
999 	.pr_type = SOCK_RAW,
1000 	NETLINK_PROTOSW
1001 };
1002 
1003 static struct protosw netlink_dgram_sw = {
1004 	.pr_type = SOCK_DGRAM,
1005 	NETLINK_PROTOSW
1006 };
1007 
1008 static struct domain netlinkdomain = {
1009 	.dom_family = PF_NETLINK,
1010 	.dom_name = "netlink",
1011 	.dom_flags = DOMF_UNLOADABLE,
1012 	.dom_nprotosw =		2,
1013 	.dom_protosw =		{ &netlink_raw_sw, &netlink_dgram_sw },
1014 };
1015 
1016 DOMAIN_SET(netlink);
1017