xref: /freebsd/sys/netlink/netlink_domain.c (revision 38c63bdc46252d4d8cd313dff4183ec4546d26d9)
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  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 
29 /*
30  * This file contains socket and protocol bindings for netlink.
31  */
32 
33 #include <sys/param.h>
34 #include <sys/kernel.h>
35 #include <sys/malloc.h>
36 #include <sys/lock.h>
37 #include <sys/rmlock.h>
38 #include <sys/domain.h>
39 #include <sys/jail.h>
40 #include <sys/mbuf.h>
41 #include <sys/osd.h>
42 #include <sys/protosw.h>
43 #include <sys/proc.h>
44 #include <sys/ck.h>
45 #include <sys/socket.h>
46 #include <sys/socketvar.h>
47 #include <sys/sysent.h>
48 #include <sys/syslog.h>
49 #include <sys/priv.h> /* priv_check */
50 
51 #include <netlink/netlink.h>
52 #include <netlink/netlink_ctl.h>
53 #include <netlink/netlink_var.h>
54 
55 #define	DEBUG_MOD_NAME	nl_domain
56 #define	DEBUG_MAX_LEVEL	LOG_DEBUG3
57 #include <netlink/netlink_debug.h>
58 _DECLARE_DEBUG(LOG_INFO);
59 
60 _Static_assert((NLP_MAX_GROUPS % 64) == 0,
61     "NLP_MAX_GROUPS has to be multiple of 64");
62 _Static_assert(NLP_MAX_GROUPS >= 64,
63     "NLP_MAX_GROUPS has to be at least 64");
64 
65 #define	NLCTL_TRACKER		struct rm_priotracker nl_tracker
66 #define	NLCTL_RLOCK(_ctl)	rm_rlock(&((_ctl)->ctl_lock), &nl_tracker)
67 #define	NLCTL_RUNLOCK(_ctl)	rm_runlock(&((_ctl)->ctl_lock), &nl_tracker)
68 
69 #define	NLCTL_WLOCK(_ctl)	rm_wlock(&((_ctl)->ctl_lock))
70 #define	NLCTL_WUNLOCK(_ctl)	rm_wunlock(&((_ctl)->ctl_lock))
71 
72 static u_long nl_sendspace = NLSNDQ;
73 SYSCTL_ULONG(_net_netlink, OID_AUTO, sendspace, CTLFLAG_RW, &nl_sendspace, 0,
74     "Default netlink socket send space");
75 
76 static u_long nl_recvspace = NLSNDQ;
77 SYSCTL_ULONG(_net_netlink, OID_AUTO, recvspace, CTLFLAG_RW, &nl_recvspace, 0,
78     "Default netlink socket receive space");
79 
80 extern u_long sb_max_adj;
81 static u_long nl_maxsockbuf = 512 * 1024 * 1024; /* 512M, XXX: init based on physmem */
82 static int sysctl_handle_nl_maxsockbuf(SYSCTL_HANDLER_ARGS);
83 SYSCTL_OID(_net_netlink, OID_AUTO, nl_maxsockbuf,
84     CTLTYPE_ULONG | CTLFLAG_RW | CTLFLAG_MPSAFE, &nl_maxsockbuf, 0,
85     sysctl_handle_nl_maxsockbuf, "LU",
86     "Maximum Netlink socket buffer size");
87 
88 
89 static unsigned int osd_slot_id = 0;
90 
91 void
92 nl_osd_register(void)
93 {
94 	osd_slot_id = osd_register(OSD_THREAD, NULL, NULL);
95 }
96 
97 void
98 nl_osd_unregister(void)
99 {
100 	osd_deregister(OSD_THREAD, osd_slot_id);
101 }
102 
103 struct nlpcb *
104 _nl_get_thread_nlp(struct thread *td)
105 {
106 	return (osd_get(OSD_THREAD, &td->td_osd, osd_slot_id));
107 }
108 
109 void
110 nl_set_thread_nlp(struct thread *td, struct nlpcb *nlp)
111 {
112 	NLP_LOG(LOG_DEBUG2, nlp, "Set thread %p nlp to %p (slot %u)", td, nlp, osd_slot_id);
113 	if (osd_set(OSD_THREAD, &td->td_osd, osd_slot_id, nlp) == 0)
114 		return;
115 	/* Failed, need to realloc */
116 	void **rsv = osd_reserve(osd_slot_id);
117 	osd_set_reserved(OSD_THREAD, &td->td_osd, osd_slot_id, rsv, nlp);
118 }
119 
120 /*
121  * Looks up a nlpcb struct based on the @portid. Need to claim nlsock_mtx.
122  * Returns nlpcb pointer if present else NULL
123  */
124 static struct nlpcb *
125 nl_port_lookup(uint32_t port_id)
126 {
127 	struct nlpcb *nlp;
128 
129 	CK_LIST_FOREACH(nlp, &V_nl_ctl->ctl_port_head, nl_port_next) {
130 		if (nlp->nl_port == port_id)
131 			return (nlp);
132 	}
133 	return (NULL);
134 }
135 
136 static void
137 nl_add_group_locked(struct nlpcb *nlp, unsigned int group_id)
138 {
139 	MPASS(group_id <= NLP_MAX_GROUPS);
140 	--group_id;
141 
142 	/* TODO: add family handler callback */
143 	if (!nlp_unconstrained_vnet(nlp))
144 		return;
145 
146 	nlp->nl_groups[group_id / 64] |= (uint64_t)1 << (group_id % 64);
147 }
148 
149 static void
150 nl_del_group_locked(struct nlpcb *nlp, unsigned int group_id)
151 {
152 	MPASS(group_id <= NLP_MAX_GROUPS);
153 	--group_id;
154 
155 	nlp->nl_groups[group_id / 64] &= ~((uint64_t)1 << (group_id % 64));
156 }
157 
158 static bool
159 nl_isset_group_locked(struct nlpcb *nlp, unsigned int group_id)
160 {
161 	MPASS(group_id <= NLP_MAX_GROUPS);
162 	--group_id;
163 
164 	return (nlp->nl_groups[group_id / 64] & ((uint64_t)1 << (group_id % 64)));
165 }
166 
167 static uint32_t
168 nl_get_groups_compat(struct nlpcb *nlp)
169 {
170 	uint32_t groups_mask = 0;
171 
172 	for (int i = 0; i < 32; i++) {
173 		if (nl_isset_group_locked(nlp, i + 1))
174 			groups_mask |= (1 << i);
175 	}
176 
177 	return (groups_mask);
178 }
179 
180 static void
181 nl_send_one_group(struct mbuf *m, struct nlpcb *nlp, int num_messages,
182     int io_flags)
183 {
184 	if (__predict_false(nlp->nl_flags & NLF_MSG_INFO))
185 		nl_add_msg_info(m);
186 	nl_send_one(m, nlp, num_messages, io_flags);
187 }
188 
189 /*
190  * Broadcasts message @m to the protocol @proto group specified by @group_id
191  */
192 void
193 nl_send_group(struct mbuf *m, int num_messages, int proto, int group_id)
194 {
195 	struct nlpcb *nlp_last = NULL;
196 	struct nlpcb *nlp;
197 	NLCTL_TRACKER;
198 
199 	IF_DEBUG_LEVEL(LOG_DEBUG2) {
200 		struct nlmsghdr *hdr = mtod(m, struct nlmsghdr *);
201 		NL_LOG(LOG_DEBUG2, "MCAST mbuf len %u msg type %d len %u to group %d/%d",
202 		    m->m_len, hdr->nlmsg_type, hdr->nlmsg_len, proto, group_id);
203 	}
204 
205 	struct nl_control *ctl = atomic_load_ptr(&V_nl_ctl);
206 	if (__predict_false(ctl == NULL)) {
207 		/*
208 		 * Can be the case when notification is sent within VNET
209 		 * which doesn't have any netlink sockets.
210 		 */
211 		m_freem(m);
212 		return;
213 	}
214 
215 	NLCTL_RLOCK(ctl);
216 
217 	int io_flags = NL_IOF_UNTRANSLATED;
218 
219 	CK_LIST_FOREACH(nlp, &ctl->ctl_pcb_head, nl_next) {
220 		if (nl_isset_group_locked(nlp, group_id) && nlp->nl_proto == proto) {
221 			if (nlp_last != NULL) {
222 				struct mbuf *m_copy;
223 				m_copy = m_copym(m, 0, M_COPYALL, M_NOWAIT);
224 				if (m_copy != NULL)
225 					nl_send_one_group(m_copy, nlp_last,
226 					    num_messages, io_flags);
227 				else {
228 					NLP_LOCK(nlp_last);
229 					if (nlp_last->nl_socket != NULL)
230 						sorwakeup(nlp_last->nl_socket);
231 					NLP_UNLOCK(nlp_last);
232 				}
233 			}
234 			nlp_last = nlp;
235 		}
236 	}
237 	if (nlp_last != NULL)
238 		nl_send_one_group(m, nlp_last, num_messages, io_flags);
239 	else
240 		m_freem(m);
241 
242 	NLCTL_RUNLOCK(ctl);
243 }
244 
245 bool
246 nl_has_listeners(int netlink_family, uint32_t groups_mask)
247 {
248 	return (V_nl_ctl != NULL);
249 }
250 
251 static uint32_t
252 nl_find_port(void)
253 {
254 	/*
255 	 * app can open multiple netlink sockets.
256 	 * Start with current pid, if already taken,
257 	 * try random numbers in 65k..256k+65k space,
258 	 * avoiding clash with pids.
259 	 */
260 	if (nl_port_lookup(curproc->p_pid) == NULL)
261 		return (curproc->p_pid);
262 	for (int i = 0; i < 16; i++) {
263 		uint32_t nl_port = (arc4random() % 65536) + 65536 * 4;
264 		if (nl_port_lookup(nl_port) == 0)
265 			return (nl_port);
266 		NL_LOG(LOG_DEBUG3, "tried %u\n", nl_port);
267 	}
268 	return (curproc->p_pid);
269 }
270 
271 static int
272 nl_bind_locked(struct nlpcb *nlp, struct sockaddr_nl *snl)
273 {
274 	if (nlp->nl_bound) {
275 		if (nlp->nl_port != snl->nl_pid) {
276 			NL_LOG(LOG_DEBUG,
277 			    "bind() failed: program pid %d "
278 			    "is different from provided pid %d",
279 			    nlp->nl_port, snl->nl_pid);
280 			return (EINVAL); // XXX: better error
281 		}
282 	} else {
283 		if (snl->nl_pid == 0)
284 			snl->nl_pid = nl_find_port();
285 		if (nl_port_lookup(snl->nl_pid) != NULL)
286 			return (EADDRINUSE);
287 		nlp->nl_port = snl->nl_pid;
288 		nlp->nl_bound = true;
289 		CK_LIST_INSERT_HEAD(&V_nl_ctl->ctl_port_head, nlp, nl_port_next);
290 	}
291 	for (int i = 0; i < 32; i++) {
292 		if (snl->nl_groups & ((uint32_t)1 << i))
293 			nl_add_group_locked(nlp, i + 1);
294 		else
295 			nl_del_group_locked(nlp, i + 1);
296 	}
297 
298 	return (0);
299 }
300 
301 static int
302 nl_pru_attach(struct socket *so, int proto, struct thread *td)
303 {
304 	struct nlpcb *nlp;
305 	int error;
306 
307 	if (__predict_false(netlink_unloading != 0))
308 		return (EAFNOSUPPORT);
309 
310 	error = nl_verify_proto(proto);
311 	if (error != 0)
312 		return (error);
313 
314 	bool is_linux = SV_PROC_ABI(td->td_proc) == SV_ABI_LINUX;
315 	NL_LOG(LOG_DEBUG2, "socket %p, %sPID %d: attaching socket to %s",
316 	    so, is_linux ? "(linux) " : "", curproc->p_pid,
317 	    nl_get_proto_name(proto));
318 
319 	/* Create per-VNET state on first socket init */
320 	struct nl_control *ctl = atomic_load_ptr(&V_nl_ctl);
321 	if (ctl == NULL)
322 		ctl = vnet_nl_ctl_init();
323 	KASSERT(V_nl_ctl != NULL, ("nl_attach: vnet_sock_init() failed"));
324 
325 	MPASS(sotonlpcb(so) == NULL);
326 
327 	nlp = malloc(sizeof(struct nlpcb), M_PCB, M_WAITOK | M_ZERO);
328 	error = soreserve(so, nl_sendspace, nl_recvspace);
329 	if (error != 0) {
330 		free(nlp, M_PCB);
331 		return (error);
332 	}
333 	so->so_pcb = nlp;
334 	nlp->nl_socket = so;
335 	/* Copy so_cred to avoid having socket_var.h in every header */
336 	nlp->nl_cred = so->so_cred;
337 	nlp->nl_proto = proto;
338 	nlp->nl_process_id = curproc->p_pid;
339 	nlp->nl_linux = is_linux;
340 	nlp->nl_active = true;
341 	nlp->nl_unconstrained_vnet = !jailed_without_vnet(so->so_cred);
342 	nlp->nl_need_thread_setup = true;
343 	NLP_LOCK_INIT(nlp);
344 	refcount_init(&nlp->nl_refcount, 1);
345 	nl_init_io(nlp);
346 
347 	nlp->nl_taskqueue = taskqueue_create("netlink_socket", M_WAITOK,
348 	    taskqueue_thread_enqueue, &nlp->nl_taskqueue);
349 	TASK_INIT(&nlp->nl_task, 0, nl_taskqueue_handler, nlp);
350 	taskqueue_start_threads(&nlp->nl_taskqueue, 1, PWAIT,
351 	    "netlink_socket (PID %u)", nlp->nl_process_id);
352 
353 	NLCTL_WLOCK(ctl);
354 	/* XXX: check ctl is still alive */
355 	CK_LIST_INSERT_HEAD(&ctl->ctl_pcb_head, nlp, nl_next);
356 	NLCTL_WUNLOCK(ctl);
357 
358 	soisconnected(so);
359 
360 	return (0);
361 }
362 
363 static int
364 nl_pru_bind(struct socket *so, struct sockaddr *sa, struct thread *td)
365 {
366 	struct nl_control *ctl = atomic_load_ptr(&V_nl_ctl);
367 	struct nlpcb *nlp = sotonlpcb(so);
368 	struct sockaddr_nl *snl = (struct sockaddr_nl *)sa;
369 	int error;
370 
371 	NL_LOG(LOG_DEBUG3, "socket %p, PID %d", so, curproc->p_pid);
372 	if (snl->nl_len != sizeof(*snl)) {
373 		NL_LOG(LOG_DEBUG, "socket %p, wrong sizeof(), ignoring bind()", so);
374 		return (EINVAL);
375 	}
376 
377 
378 	NLCTL_WLOCK(ctl);
379 	NLP_LOCK(nlp);
380 	error = nl_bind_locked(nlp, snl);
381 	NLP_UNLOCK(nlp);
382 	NLCTL_WUNLOCK(ctl);
383 	NL_LOG(LOG_DEBUG2, "socket %p, bind() to %u, groups %u, error %d", so,
384 	    snl->nl_pid, snl->nl_groups, error);
385 
386 	return (error);
387 }
388 
389 
390 static int
391 nl_assign_port(struct nlpcb *nlp, uint32_t port_id)
392 {
393 	struct nl_control *ctl = atomic_load_ptr(&V_nl_ctl);
394 	struct sockaddr_nl snl = {
395 		.nl_pid = port_id,
396 	};
397 	int error;
398 
399 	NLCTL_WLOCK(ctl);
400 	NLP_LOCK(nlp);
401 	snl.nl_groups = nl_get_groups_compat(nlp);
402 	error = nl_bind_locked(nlp, &snl);
403 	NLP_UNLOCK(nlp);
404 	NLCTL_WUNLOCK(ctl);
405 
406 	NL_LOG(LOG_DEBUG3, "socket %p, port assign: %d, error: %d", nlp->nl_socket, port_id, error);
407 	return (error);
408 }
409 
410 /*
411  * nl_autobind_port binds a unused portid to @nlp
412  * @nlp: pcb data for the netlink socket
413  * @candidate_id: first id to consider
414  */
415 static int
416 nl_autobind_port(struct nlpcb *nlp, uint32_t candidate_id)
417 {
418 	struct nl_control *ctl = atomic_load_ptr(&V_nl_ctl);
419 	uint32_t port_id = candidate_id;
420 	NLCTL_TRACKER;
421 	bool exist;
422 	int error = EADDRINUSE;
423 
424 	for (int i = 0; i < 10; i++) {
425 		NL_LOG(LOG_DEBUG3, "socket %p, trying to assign port %d", nlp->nl_socket, port_id);
426 		NLCTL_RLOCK(ctl);
427 		exist = nl_port_lookup(port_id) != 0;
428 		NLCTL_RUNLOCK(ctl);
429 		if (!exist) {
430 			error = nl_assign_port(nlp, port_id);
431 			if (error != EADDRINUSE)
432 				break;
433 		}
434 		port_id++;
435 	}
436 	NL_LOG(LOG_DEBUG3, "socket %p, autobind to %d, error: %d", nlp->nl_socket, port_id, error);
437 	return (error);
438 }
439 
440 static int
441 nl_pru_connect(struct socket *so, struct sockaddr *sa, struct thread *td)
442 {
443 	struct sockaddr_nl *snl = (struct sockaddr_nl *)sa;
444 	struct nlpcb *nlp;
445 
446 	NL_LOG(LOG_DEBUG3, "socket %p, PID %d", so, curproc->p_pid);
447 	if (snl->nl_len != sizeof(*snl)) {
448 		NL_LOG(LOG_DEBUG, "socket %p, wrong sizeof(), ignoring bind()", so);
449 		return (EINVAL);
450 	}
451 
452 	nlp = sotonlpcb(so);
453 	if (!nlp->nl_bound) {
454 		int error = nl_autobind_port(nlp, td->td_proc->p_pid);
455 		if (error != 0) {
456 			NL_LOG(LOG_DEBUG, "socket %p, nl_autobind() failed: %d", so, error);
457 			return (error);
458 		}
459 	}
460 	/* XXX: Handle socket flags & multicast */
461 	soisconnected(so);
462 
463 	NL_LOG(LOG_DEBUG2, "socket %p, connect to %u", so, snl->nl_pid);
464 
465 	return (0);
466 }
467 
468 static void
469 destroy_nlpcb(struct nlpcb *nlp)
470 {
471 	NLP_LOCK(nlp);
472 	nl_free_io(nlp);
473 	NLP_LOCK_DESTROY(nlp);
474 	free(nlp, M_PCB);
475 }
476 
477 static void
478 destroy_nlpcb_epoch(epoch_context_t ctx)
479 {
480 	struct nlpcb *nlp;
481 
482 	nlp = __containerof(ctx, struct nlpcb, nl_epoch_ctx);
483 
484 	destroy_nlpcb(nlp);
485 }
486 
487 
488 static void
489 nl_close(struct socket *so)
490 {
491 	struct nl_control *ctl = atomic_load_ptr(&V_nl_ctl);
492 	MPASS(sotonlpcb(so) != NULL);
493 	struct nlpcb *nlp;
494 
495 	NL_LOG(LOG_DEBUG2, "detaching socket %p, PID %d", so, curproc->p_pid);
496 	nlp = sotonlpcb(so);
497 
498 	/* Mark as inactive so no new work can be enqueued */
499 	NLP_LOCK(nlp);
500 	bool was_bound = nlp->nl_bound;
501 	nlp->nl_active = false;
502 	NLP_UNLOCK(nlp);
503 
504 	/* Wait till all scheduled work has been completed  */
505 	taskqueue_drain_all(nlp->nl_taskqueue);
506 	taskqueue_free(nlp->nl_taskqueue);
507 
508 	NLCTL_WLOCK(ctl);
509 	NLP_LOCK(nlp);
510 	if (was_bound) {
511 		CK_LIST_REMOVE(nlp, nl_port_next);
512 		NL_LOG(LOG_DEBUG3, "socket %p, unlinking bound pid %u", so, nlp->nl_port);
513 	}
514 	CK_LIST_REMOVE(nlp, nl_next);
515 	nlp->nl_socket = NULL;
516 	NLP_UNLOCK(nlp);
517 	NLCTL_WUNLOCK(ctl);
518 
519 	so->so_pcb = NULL;
520 
521 	NL_LOG(LOG_DEBUG3, "socket %p, detached", so);
522 
523 	/* XXX: is delayed free needed? */
524 	NET_EPOCH_CALL(destroy_nlpcb_epoch, &nlp->nl_epoch_ctx);
525 }
526 
527 static int
528 nl_pru_disconnect(struct socket *so)
529 {
530 	NL_LOG(LOG_DEBUG3, "socket %p, PID %d", so, curproc->p_pid);
531 	MPASS(sotonlpcb(so) != NULL);
532 	return (ENOTCONN);
533 }
534 
535 static int
536 nl_pru_shutdown(struct socket *so)
537 {
538 	NL_LOG(LOG_DEBUG3, "socket %p, PID %d", so, curproc->p_pid);
539 	MPASS(sotonlpcb(so) != NULL);
540 	socantsendmore(so);
541 	return (0);
542 }
543 
544 static int
545 nl_sockaddr(struct socket *so, struct sockaddr *sa)
546 {
547 
548 	*(struct sockaddr_nl *)sa = (struct sockaddr_nl ){
549 		/* TODO: set other fields */
550 		.nl_len = sizeof(struct sockaddr_nl),
551 		.nl_family = AF_NETLINK,
552 		.nl_pid = sotonlpcb(so)->nl_port,
553 	};
554 
555 	return (0);
556 }
557 
558 static int
559 nl_pru_output(struct mbuf *m, struct socket *so, ...)
560 {
561 
562 	if (__predict_false(m == NULL ||
563 	    ((m->m_len < sizeof(struct nlmsghdr)) &&
564 		(m = m_pullup(m, sizeof(struct nlmsghdr))) == NULL)))
565 		return (ENOBUFS);
566 	MPASS((m->m_flags & M_PKTHDR) != 0);
567 
568 	NL_LOG(LOG_DEBUG3, "sending message to kernel async processing");
569 	nl_receive_async(m, so);
570 	return (0);
571 }
572 
573 
574 static int
575 nl_pru_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *sa,
576     struct mbuf *control, struct thread *td)
577 {
578         NL_LOG(LOG_DEBUG2, "sending message to kernel");
579 
580 	if (__predict_false(control != NULL)) {
581 		if (control->m_len) {
582 			m_freem(control);
583 			return (EINVAL);
584 		}
585 		m_freem(control);
586 	}
587 
588 	return (nl_pru_output(m, so));
589 }
590 
591 static int
592 nl_pru_rcvd(struct socket *so, int flags)
593 {
594 	NL_LOG(LOG_DEBUG3, "socket %p, PID %d", so, curproc->p_pid);
595 	MPASS(sotonlpcb(so) != NULL);
596 
597 	nl_on_transmit(sotonlpcb(so));
598 
599 	return (0);
600 }
601 
602 static int
603 nl_getoptflag(int sopt_name)
604 {
605 	switch (sopt_name) {
606 	case NETLINK_CAP_ACK:
607 		return (NLF_CAP_ACK);
608 	case NETLINK_EXT_ACK:
609 		return (NLF_EXT_ACK);
610 	case NETLINK_GET_STRICT_CHK:
611 		return (NLF_STRICT);
612 	case NETLINK_MSG_INFO:
613 		return (NLF_MSG_INFO);
614 	}
615 
616 	return (0);
617 }
618 
619 static int
620 nl_ctloutput(struct socket *so, struct sockopt *sopt)
621 {
622 	struct nl_control *ctl = atomic_load_ptr(&V_nl_ctl);
623 	struct nlpcb *nlp = sotonlpcb(so);
624 	uint32_t flag;
625 	int optval, error = 0;
626 	NLCTL_TRACKER;
627 
628 	NL_LOG(LOG_DEBUG2, "%ssockopt(%p, %d)", (sopt->sopt_dir) ? "set" : "get",
629 	    so, sopt->sopt_name);
630 
631 	switch (sopt->sopt_dir) {
632 	case SOPT_SET:
633 		switch (sopt->sopt_name) {
634 		case NETLINK_ADD_MEMBERSHIP:
635 		case NETLINK_DROP_MEMBERSHIP:
636 			error = sooptcopyin(sopt, &optval, sizeof(optval), sizeof(optval));
637 			if (error != 0)
638 				break;
639 			if (optval <= 0 || optval >= NLP_MAX_GROUPS) {
640 				error = ERANGE;
641 				break;
642 			}
643 			NL_LOG(LOG_DEBUG2, "ADD/DEL group %d", (uint32_t)optval);
644 
645 			NLCTL_WLOCK(ctl);
646 			if (sopt->sopt_name == NETLINK_ADD_MEMBERSHIP)
647 				nl_add_group_locked(nlp, optval);
648 			else
649 				nl_del_group_locked(nlp, optval);
650 			NLCTL_WUNLOCK(ctl);
651 			break;
652 		case NETLINK_CAP_ACK:
653 		case NETLINK_EXT_ACK:
654 		case NETLINK_GET_STRICT_CHK:
655 		case NETLINK_MSG_INFO:
656 			error = sooptcopyin(sopt, &optval, sizeof(optval), sizeof(optval));
657 			if (error != 0)
658 				break;
659 
660 			flag = nl_getoptflag(sopt->sopt_name);
661 
662 			if ((flag == NLF_MSG_INFO) && nlp->nl_linux) {
663 				error = EINVAL;
664 				break;
665 			}
666 
667 			NLCTL_WLOCK(ctl);
668 			if (optval != 0)
669 				nlp->nl_flags |= flag;
670 			else
671 				nlp->nl_flags &= ~flag;
672 			NLCTL_WUNLOCK(ctl);
673 			break;
674 		default:
675 			error = ENOPROTOOPT;
676 		}
677 		break;
678 	case SOPT_GET:
679 		switch (sopt->sopt_name) {
680 		case NETLINK_LIST_MEMBERSHIPS:
681 			NLCTL_RLOCK(ctl);
682 			optval = nl_get_groups_compat(nlp);
683 			NLCTL_RUNLOCK(ctl);
684 			error = sooptcopyout(sopt, &optval, sizeof(optval));
685 			break;
686 		case NETLINK_CAP_ACK:
687 		case NETLINK_EXT_ACK:
688 		case NETLINK_GET_STRICT_CHK:
689 		case NETLINK_MSG_INFO:
690 			NLCTL_RLOCK(ctl);
691 			optval = (nlp->nl_flags & nl_getoptflag(sopt->sopt_name)) != 0;
692 			NLCTL_RUNLOCK(ctl);
693 			error = sooptcopyout(sopt, &optval, sizeof(optval));
694 			break;
695 		default:
696 			error = ENOPROTOOPT;
697 		}
698 		break;
699 	default:
700 		error = ENOPROTOOPT;
701 	}
702 
703 	return (error);
704 }
705 
706 static int
707 sysctl_handle_nl_maxsockbuf(SYSCTL_HANDLER_ARGS)
708 {
709 	int error = 0;
710 	u_long tmp_maxsockbuf = nl_maxsockbuf;
711 
712 	error = sysctl_handle_long(oidp, &tmp_maxsockbuf, arg2, req);
713 	if (error || !req->newptr)
714 		return (error);
715 	if (tmp_maxsockbuf < MSIZE + MCLBYTES)
716 		return (EINVAL);
717 	nl_maxsockbuf = tmp_maxsockbuf;
718 
719 	return (0);
720 }
721 
722 static int
723 nl_setsbopt(struct socket *so, struct sockopt *sopt)
724 {
725 	int error, optval;
726 	bool result;
727 
728 	if (sopt->sopt_name != SO_RCVBUF)
729 		return (sbsetopt(so, sopt));
730 
731 	/* Allow to override max buffer size in certain conditions */
732 
733 	error = sooptcopyin(sopt, &optval, sizeof optval, sizeof optval);
734 	if (error != 0)
735 		return (error);
736 	NL_LOG(LOG_DEBUG2, "socket %p, PID %d, SO_RCVBUF=%d", so, curproc->p_pid, optval);
737 	if (optval > sb_max_adj) {
738 		if (priv_check(curthread, PRIV_NET_ROUTE) != 0)
739 			return (EPERM);
740 	}
741 
742 	SOCK_RECVBUF_LOCK(so);
743 	result = sbreserve_locked_limit(so, SO_RCV, optval, nl_maxsockbuf, curthread);
744 	SOCK_RECVBUF_UNLOCK(so);
745 
746 	return (result ? 0 : ENOBUFS);
747 }
748 
749 #define	NETLINK_PROTOSW						\
750 	.pr_flags = PR_ATOMIC | PR_ADDR | PR_WANTRCVD,		\
751 	.pr_ctloutput = nl_ctloutput,				\
752 	.pr_setsbopt = nl_setsbopt,				\
753 	.pr_attach = nl_pru_attach,				\
754 	.pr_bind = nl_pru_bind,					\
755 	.pr_connect = nl_pru_connect,				\
756 	.pr_disconnect = nl_pru_disconnect,			\
757 	.pr_send = nl_pru_send,					\
758 	.pr_rcvd = nl_pru_rcvd,					\
759 	.pr_shutdown = nl_pru_shutdown,				\
760 	.pr_sockaddr = nl_sockaddr,				\
761 	.pr_close = nl_close
762 
763 static struct protosw netlink_raw_sw = {
764 	.pr_type = SOCK_RAW,
765 	NETLINK_PROTOSW
766 };
767 
768 static struct protosw netlink_dgram_sw = {
769 	.pr_type = SOCK_DGRAM,
770 	NETLINK_PROTOSW
771 };
772 
773 static struct domain netlinkdomain = {
774 	.dom_family = PF_NETLINK,
775 	.dom_name = "netlink",
776 	.dom_flags = DOMF_UNLOADABLE,
777 	.dom_nprotosw =		2,
778 	.dom_protosw =		{ &netlink_raw_sw, &netlink_dgram_sw },
779 };
780 
781 DOMAIN_SET(netlink);
782