• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * NETLINK      Kernel-user communication protocol.
3  *
4  * 		Authors:	Alan Cox <alan@lxorguk.ukuu.org.uk>
5  * 				Alexey Kuznetsov <kuznet@ms2.inr.ac.ru>
6  * 				Patrick McHardy <kaber@trash.net>
7  *
8  *		This program is free software; you can redistribute it and/or
9  *		modify it under the terms of the GNU General Public License
10  *		as published by the Free Software Foundation; either version
11  *		2 of the License, or (at your option) any later version.
12  *
13  * Tue Jun 26 14:36:48 MEST 2001 Herbert "herp" Rosmanith
14  *                               added netlink_proto_exit
15  * Tue Jan 22 18:32:44 BRST 2002 Arnaldo C. de Melo <acme@conectiva.com.br>
16  * 				 use nlk_sk, as sk->protinfo is on a diet 8)
17  * Fri Jul 22 19:51:12 MEST 2005 Harald Welte <laforge@gnumonks.org>
18  * 				 - inc module use count of module that owns
19  * 				   the kernel socket in case userspace opens
20  * 				   socket of same protocol
21  * 				 - remove all module support, since netlink is
22  * 				   mandatory if CONFIG_NET=y these days
23  */
24 
25 #include <linux/module.h>
26 
27 #include <linux/capability.h>
28 #include <linux/kernel.h>
29 #include <linux/init.h>
30 #include <linux/signal.h>
31 #include <linux/sched.h>
32 #include <linux/errno.h>
33 #include <linux/string.h>
34 #include <linux/stat.h>
35 #include <linux/socket.h>
36 #include <linux/un.h>
37 #include <linux/fcntl.h>
38 #include <linux/termios.h>
39 #include <linux/sockios.h>
40 #include <linux/net.h>
41 #include <linux/fs.h>
42 #include <linux/slab.h>
43 #include <asm/uaccess.h>
44 #include <linux/skbuff.h>
45 #include <linux/netdevice.h>
46 #include <linux/rtnetlink.h>
47 #include <linux/proc_fs.h>
48 #include <linux/seq_file.h>
49 #include <linux/notifier.h>
50 #include <linux/security.h>
51 #include <linux/jhash.h>
52 #include <linux/jiffies.h>
53 #include <linux/random.h>
54 #include <linux/bitops.h>
55 #include <linux/mm.h>
56 #include <linux/types.h>
57 #include <linux/audit.h>
58 #include <linux/mutex.h>
59 #include <linux/vmalloc.h>
60 #include <linux/if_arp.h>
61 #include <linux/rhashtable.h>
62 #include <asm/cacheflush.h>
63 #include <linux/hash.h>
64 #include <linux/genetlink.h>
65 #include <linux/nospec.h>
66 
67 #include <net/net_namespace.h>
68 #include <net/sock.h>
69 #include <net/scm.h>
70 #include <net/netlink.h>
71 
72 #include "af_netlink.h"
73 
74 struct listeners {
75 	struct rcu_head		rcu;
76 	unsigned long		masks[0];
77 };
78 
79 /* state bits */
80 #define NETLINK_S_CONGESTED		0x0
81 
82 /* flags */
83 #define NETLINK_F_KERNEL_SOCKET		0x1
84 #define NETLINK_F_RECV_PKTINFO		0x2
85 #define NETLINK_F_BROADCAST_SEND_ERROR	0x4
86 #define NETLINK_F_RECV_NO_ENOBUFS	0x8
87 #define NETLINK_F_LISTEN_ALL_NSID	0x10
88 #define NETLINK_F_CAP_ACK		0x20
89 
netlink_is_kernel(struct sock * sk)90 static inline int netlink_is_kernel(struct sock *sk)
91 {
92 	return nlk_sk(sk)->flags & NETLINK_F_KERNEL_SOCKET;
93 }
94 
95 struct netlink_table *nl_table __read_mostly;
96 EXPORT_SYMBOL_GPL(nl_table);
97 
98 static DECLARE_WAIT_QUEUE_HEAD(nl_table_wait);
99 
100 static struct lock_class_key nlk_cb_mutex_keys[MAX_LINKS];
101 
102 static const char *const nlk_cb_mutex_key_strings[MAX_LINKS + 1] = {
103 	"nlk_cb_mutex-ROUTE",
104 	"nlk_cb_mutex-1",
105 	"nlk_cb_mutex-USERSOCK",
106 	"nlk_cb_mutex-FIREWALL",
107 	"nlk_cb_mutex-SOCK_DIAG",
108 	"nlk_cb_mutex-NFLOG",
109 	"nlk_cb_mutex-XFRM",
110 	"nlk_cb_mutex-SELINUX",
111 	"nlk_cb_mutex-ISCSI",
112 	"nlk_cb_mutex-AUDIT",
113 	"nlk_cb_mutex-FIB_LOOKUP",
114 	"nlk_cb_mutex-CONNECTOR",
115 	"nlk_cb_mutex-NETFILTER",
116 	"nlk_cb_mutex-IP6_FW",
117 	"nlk_cb_mutex-DNRTMSG",
118 	"nlk_cb_mutex-KOBJECT_UEVENT",
119 	"nlk_cb_mutex-GENERIC",
120 	"nlk_cb_mutex-17",
121 	"nlk_cb_mutex-SCSITRANSPORT",
122 	"nlk_cb_mutex-ECRYPTFS",
123 	"nlk_cb_mutex-RDMA",
124 	"nlk_cb_mutex-CRYPTO",
125 	"nlk_cb_mutex-SMC",
126 	"nlk_cb_mutex-23",
127 	"nlk_cb_mutex-24",
128 	"nlk_cb_mutex-25",
129 	"nlk_cb_mutex-26",
130 	"nlk_cb_mutex-27",
131 	"nlk_cb_mutex-28",
132 	"nlk_cb_mutex-29",
133 	"nlk_cb_mutex-30",
134 	"nlk_cb_mutex-31",
135 	"nlk_cb_mutex-MAX_LINKS"
136 };
137 
138 static int netlink_dump(struct sock *sk);
139 static void netlink_skb_destructor(struct sk_buff *skb);
140 
141 /* nl_table locking explained:
142  * Lookup and traversal are protected with an RCU read-side lock. Insertion
143  * and removal are protected with per bucket lock while using RCU list
144  * modification primitives and may run in parallel to RCU protected lookups.
145  * Destruction of the Netlink socket may only occur *after* nl_table_lock has
146  * been acquired * either during or after the socket has been removed from
147  * the list and after an RCU grace period.
148  */
149 DEFINE_RWLOCK(nl_table_lock);
150 EXPORT_SYMBOL_GPL(nl_table_lock);
151 static atomic_t nl_table_users = ATOMIC_INIT(0);
152 
153 #define nl_deref_protected(X) rcu_dereference_protected(X, lockdep_is_held(&nl_table_lock));
154 
155 static ATOMIC_NOTIFIER_HEAD(netlink_chain);
156 
157 static DEFINE_SPINLOCK(netlink_tap_lock);
158 static struct list_head netlink_tap_all __read_mostly;
159 
160 static const struct rhashtable_params netlink_rhashtable_params;
161 
netlink_group_mask(u32 group)162 static inline u32 netlink_group_mask(u32 group)
163 {
164 	return group ? 1 << (group - 1) : 0;
165 }
166 
netlink_to_full_skb(const struct sk_buff * skb,gfp_t gfp_mask)167 static struct sk_buff *netlink_to_full_skb(const struct sk_buff *skb,
168 					   gfp_t gfp_mask)
169 {
170 	unsigned int len = skb_end_offset(skb);
171 	struct sk_buff *new;
172 
173 	new = alloc_skb(len, gfp_mask);
174 	if (new == NULL)
175 		return NULL;
176 
177 	NETLINK_CB(new).portid = NETLINK_CB(skb).portid;
178 	NETLINK_CB(new).dst_group = NETLINK_CB(skb).dst_group;
179 	NETLINK_CB(new).creds = NETLINK_CB(skb).creds;
180 
181 	memcpy(skb_put(new, len), skb->data, len);
182 	return new;
183 }
184 
netlink_add_tap(struct netlink_tap * nt)185 int netlink_add_tap(struct netlink_tap *nt)
186 {
187 	if (unlikely(nt->dev->type != ARPHRD_NETLINK))
188 		return -EINVAL;
189 
190 	spin_lock(&netlink_tap_lock);
191 	list_add_rcu(&nt->list, &netlink_tap_all);
192 	spin_unlock(&netlink_tap_lock);
193 
194 	__module_get(nt->module);
195 
196 	return 0;
197 }
198 EXPORT_SYMBOL_GPL(netlink_add_tap);
199 
__netlink_remove_tap(struct netlink_tap * nt)200 static int __netlink_remove_tap(struct netlink_tap *nt)
201 {
202 	bool found = false;
203 	struct netlink_tap *tmp;
204 
205 	spin_lock(&netlink_tap_lock);
206 
207 	list_for_each_entry(tmp, &netlink_tap_all, list) {
208 		if (nt == tmp) {
209 			list_del_rcu(&nt->list);
210 			found = true;
211 			goto out;
212 		}
213 	}
214 
215 	pr_warn("__netlink_remove_tap: %p not found\n", nt);
216 out:
217 	spin_unlock(&netlink_tap_lock);
218 
219 	if (found)
220 		module_put(nt->module);
221 
222 	return found ? 0 : -ENODEV;
223 }
224 
netlink_remove_tap(struct netlink_tap * nt)225 int netlink_remove_tap(struct netlink_tap *nt)
226 {
227 	int ret;
228 
229 	ret = __netlink_remove_tap(nt);
230 	synchronize_net();
231 
232 	return ret;
233 }
234 EXPORT_SYMBOL_GPL(netlink_remove_tap);
235 
netlink_filter_tap(const struct sk_buff * skb)236 static bool netlink_filter_tap(const struct sk_buff *skb)
237 {
238 	struct sock *sk = skb->sk;
239 
240 	/* We take the more conservative approach and
241 	 * whitelist socket protocols that may pass.
242 	 */
243 	switch (sk->sk_protocol) {
244 	case NETLINK_ROUTE:
245 	case NETLINK_USERSOCK:
246 	case NETLINK_SOCK_DIAG:
247 	case NETLINK_NFLOG:
248 	case NETLINK_XFRM:
249 	case NETLINK_FIB_LOOKUP:
250 	case NETLINK_NETFILTER:
251 	case NETLINK_GENERIC:
252 		return true;
253 	}
254 
255 	return false;
256 }
257 
__netlink_deliver_tap_skb(struct sk_buff * skb,struct net_device * dev)258 static int __netlink_deliver_tap_skb(struct sk_buff *skb,
259 				     struct net_device *dev)
260 {
261 	struct sk_buff *nskb;
262 	struct sock *sk = skb->sk;
263 	int ret = -ENOMEM;
264 
265 	if (!net_eq(dev_net(dev), sock_net(sk)))
266 		return 0;
267 
268 	dev_hold(dev);
269 
270 	if (is_vmalloc_addr(skb->head))
271 		nskb = netlink_to_full_skb(skb, GFP_ATOMIC);
272 	else
273 		nskb = skb_clone(skb, GFP_ATOMIC);
274 	if (nskb) {
275 		nskb->dev = dev;
276 		nskb->protocol = htons((u16) sk->sk_protocol);
277 		nskb->pkt_type = netlink_is_kernel(sk) ?
278 				 PACKET_KERNEL : PACKET_USER;
279 		skb_reset_network_header(nskb);
280 		ret = dev_queue_xmit(nskb);
281 		if (unlikely(ret > 0))
282 			ret = net_xmit_errno(ret);
283 	}
284 
285 	dev_put(dev);
286 	return ret;
287 }
288 
__netlink_deliver_tap(struct sk_buff * skb)289 static void __netlink_deliver_tap(struct sk_buff *skb)
290 {
291 	int ret;
292 	struct netlink_tap *tmp;
293 
294 	if (!netlink_filter_tap(skb))
295 		return;
296 
297 	list_for_each_entry_rcu(tmp, &netlink_tap_all, list) {
298 		ret = __netlink_deliver_tap_skb(skb, tmp->dev);
299 		if (unlikely(ret))
300 			break;
301 	}
302 }
303 
netlink_deliver_tap(struct sk_buff * skb)304 static void netlink_deliver_tap(struct sk_buff *skb)
305 {
306 	rcu_read_lock();
307 
308 	if (unlikely(!list_empty(&netlink_tap_all)))
309 		__netlink_deliver_tap(skb);
310 
311 	rcu_read_unlock();
312 }
313 
netlink_deliver_tap_kernel(struct sock * dst,struct sock * src,struct sk_buff * skb)314 static void netlink_deliver_tap_kernel(struct sock *dst, struct sock *src,
315 				       struct sk_buff *skb)
316 {
317 	if (!(netlink_is_kernel(dst) && netlink_is_kernel(src)))
318 		netlink_deliver_tap(skb);
319 }
320 
netlink_overrun(struct sock * sk)321 static void netlink_overrun(struct sock *sk)
322 {
323 	struct netlink_sock *nlk = nlk_sk(sk);
324 
325 	if (!(nlk->flags & NETLINK_F_RECV_NO_ENOBUFS)) {
326 		if (!test_and_set_bit(NETLINK_S_CONGESTED,
327 				      &nlk_sk(sk)->state)) {
328 			sk->sk_err = ENOBUFS;
329 			sk->sk_error_report(sk);
330 		}
331 	}
332 	atomic_inc(&sk->sk_drops);
333 }
334 
netlink_rcv_wake(struct sock * sk)335 static void netlink_rcv_wake(struct sock *sk)
336 {
337 	struct netlink_sock *nlk = nlk_sk(sk);
338 
339 	if (skb_queue_empty(&sk->sk_receive_queue))
340 		clear_bit(NETLINK_S_CONGESTED, &nlk->state);
341 	if (!test_bit(NETLINK_S_CONGESTED, &nlk->state))
342 		wake_up_interruptible(&nlk->wait);
343 }
344 
netlink_skb_destructor(struct sk_buff * skb)345 static void netlink_skb_destructor(struct sk_buff *skb)
346 {
347 	if (is_vmalloc_addr(skb->head)) {
348 		if (!skb->cloned ||
349 		    !atomic_dec_return(&(skb_shinfo(skb)->dataref)))
350 			vfree(skb->head);
351 
352 		skb->head = NULL;
353 	}
354 	if (skb->sk != NULL)
355 		sock_rfree(skb);
356 }
357 
netlink_skb_set_owner_r(struct sk_buff * skb,struct sock * sk)358 static void netlink_skb_set_owner_r(struct sk_buff *skb, struct sock *sk)
359 {
360 	WARN_ON(skb->sk != NULL);
361 	skb->sk = sk;
362 	skb->destructor = netlink_skb_destructor;
363 	atomic_add(skb->truesize, &sk->sk_rmem_alloc);
364 	sk_mem_charge(sk, skb->truesize);
365 }
366 
netlink_sock_destruct(struct sock * sk)367 static void netlink_sock_destruct(struct sock *sk)
368 {
369 	struct netlink_sock *nlk = nlk_sk(sk);
370 
371 	if (nlk->cb_running) {
372 		if (nlk->cb.done)
373 			nlk->cb.done(&nlk->cb);
374 		module_put(nlk->cb.module);
375 		kfree_skb(nlk->cb.skb);
376 	}
377 
378 	skb_queue_purge(&sk->sk_receive_queue);
379 
380 	if (!sock_flag(sk, SOCK_DEAD)) {
381 		printk(KERN_ERR "Freeing alive netlink socket %p\n", sk);
382 		return;
383 	}
384 
385 	WARN_ON(atomic_read(&sk->sk_rmem_alloc));
386 	WARN_ON(atomic_read(&sk->sk_wmem_alloc));
387 	WARN_ON(nlk_sk(sk)->groups);
388 }
389 
netlink_sock_destruct_work(struct work_struct * work)390 static void netlink_sock_destruct_work(struct work_struct *work)
391 {
392 	struct netlink_sock *nlk = container_of(work, struct netlink_sock,
393 						work);
394 
395 	sk_free(&nlk->sk);
396 }
397 
398 /* This lock without WQ_FLAG_EXCLUSIVE is good on UP and it is _very_ bad on
399  * SMP. Look, when several writers sleep and reader wakes them up, all but one
400  * immediately hit write lock and grab all the cpus. Exclusive sleep solves
401  * this, _but_ remember, it adds useless work on UP machines.
402  */
403 
netlink_table_grab(void)404 void netlink_table_grab(void)
405 	__acquires(nl_table_lock)
406 {
407 	might_sleep();
408 
409 	write_lock_irq(&nl_table_lock);
410 
411 	if (atomic_read(&nl_table_users)) {
412 		DECLARE_WAITQUEUE(wait, current);
413 
414 		add_wait_queue_exclusive(&nl_table_wait, &wait);
415 		for (;;) {
416 			set_current_state(TASK_UNINTERRUPTIBLE);
417 			if (atomic_read(&nl_table_users) == 0)
418 				break;
419 			write_unlock_irq(&nl_table_lock);
420 			schedule();
421 			write_lock_irq(&nl_table_lock);
422 		}
423 
424 		__set_current_state(TASK_RUNNING);
425 		remove_wait_queue(&nl_table_wait, &wait);
426 	}
427 }
428 
netlink_table_ungrab(void)429 void netlink_table_ungrab(void)
430 	__releases(nl_table_lock)
431 {
432 	write_unlock_irq(&nl_table_lock);
433 	wake_up(&nl_table_wait);
434 }
435 
436 static inline void
netlink_lock_table(void)437 netlink_lock_table(void)
438 {
439 	unsigned long flags;
440 
441 	/* read_lock() synchronizes us to netlink_table_grab */
442 
443 	read_lock_irqsave(&nl_table_lock, flags);
444 	atomic_inc(&nl_table_users);
445 	read_unlock_irqrestore(&nl_table_lock, flags);
446 }
447 
448 static inline void
netlink_unlock_table(void)449 netlink_unlock_table(void)
450 {
451 	if (atomic_dec_and_test(&nl_table_users))
452 		wake_up(&nl_table_wait);
453 }
454 
455 struct netlink_compare_arg
456 {
457 	possible_net_t pnet;
458 	u32 portid;
459 };
460 
461 /* Doing sizeof directly may yield 4 extra bytes on 64-bit. */
462 #define netlink_compare_arg_len \
463 	(offsetof(struct netlink_compare_arg, portid) + sizeof(u32))
464 
netlink_compare(struct rhashtable_compare_arg * arg,const void * ptr)465 static inline int netlink_compare(struct rhashtable_compare_arg *arg,
466 				  const void *ptr)
467 {
468 	const struct netlink_compare_arg *x = arg->key;
469 	const struct netlink_sock *nlk = ptr;
470 
471 	return nlk->portid != x->portid ||
472 	       !net_eq(sock_net(&nlk->sk), read_pnet(&x->pnet));
473 }
474 
netlink_compare_arg_init(struct netlink_compare_arg * arg,struct net * net,u32 portid)475 static void netlink_compare_arg_init(struct netlink_compare_arg *arg,
476 				     struct net *net, u32 portid)
477 {
478 	memset(arg, 0, sizeof(*arg));
479 	write_pnet(&arg->pnet, net);
480 	arg->portid = portid;
481 }
482 
__netlink_lookup(struct netlink_table * table,u32 portid,struct net * net)483 static struct sock *__netlink_lookup(struct netlink_table *table, u32 portid,
484 				     struct net *net)
485 {
486 	struct netlink_compare_arg arg;
487 
488 	netlink_compare_arg_init(&arg, net, portid);
489 	return rhashtable_lookup_fast(&table->hash, &arg,
490 				      netlink_rhashtable_params);
491 }
492 
__netlink_insert(struct netlink_table * table,struct sock * sk)493 static int __netlink_insert(struct netlink_table *table, struct sock *sk)
494 {
495 	struct netlink_compare_arg arg;
496 
497 	netlink_compare_arg_init(&arg, sock_net(sk), nlk_sk(sk)->portid);
498 	return rhashtable_lookup_insert_key(&table->hash, &arg,
499 					    &nlk_sk(sk)->node,
500 					    netlink_rhashtable_params);
501 }
502 
netlink_lookup(struct net * net,int protocol,u32 portid)503 static struct sock *netlink_lookup(struct net *net, int protocol, u32 portid)
504 {
505 	struct netlink_table *table = &nl_table[protocol];
506 	struct sock *sk;
507 
508 	rcu_read_lock();
509 	sk = __netlink_lookup(table, portid, net);
510 	if (sk)
511 		sock_hold(sk);
512 	rcu_read_unlock();
513 
514 	return sk;
515 }
516 
517 static const struct proto_ops netlink_ops;
518 
519 static void
netlink_update_listeners(struct sock * sk)520 netlink_update_listeners(struct sock *sk)
521 {
522 	struct netlink_table *tbl = &nl_table[sk->sk_protocol];
523 	unsigned long mask;
524 	unsigned int i;
525 	struct listeners *listeners;
526 
527 	listeners = nl_deref_protected(tbl->listeners);
528 	if (!listeners)
529 		return;
530 
531 	for (i = 0; i < NLGRPLONGS(tbl->groups); i++) {
532 		mask = 0;
533 		sk_for_each_bound(sk, &tbl->mc_list) {
534 			if (i < NLGRPLONGS(nlk_sk(sk)->ngroups))
535 				mask |= nlk_sk(sk)->groups[i];
536 		}
537 		listeners->masks[i] = mask;
538 	}
539 	/* this function is only called with the netlink table "grabbed", which
540 	 * makes sure updates are visible before bind or setsockopt return. */
541 }
542 
netlink_insert(struct sock * sk,u32 portid)543 static int netlink_insert(struct sock *sk, u32 portid)
544 {
545 	struct netlink_table *table = &nl_table[sk->sk_protocol];
546 	int err;
547 
548 	lock_sock(sk);
549 
550 	err = nlk_sk(sk)->portid == portid ? 0 : -EBUSY;
551 	if (nlk_sk(sk)->bound)
552 		goto err;
553 
554 	err = -ENOMEM;
555 	if (BITS_PER_LONG > 32 &&
556 	    unlikely(atomic_read(&table->hash.nelems) >= UINT_MAX))
557 		goto err;
558 
559 	nlk_sk(sk)->portid = portid;
560 	sock_hold(sk);
561 
562 	err = __netlink_insert(table, sk);
563 	if (err) {
564 		/* In case the hashtable backend returns with -EBUSY
565 		 * from here, it must not escape to the caller.
566 		 */
567 		if (unlikely(err == -EBUSY))
568 			err = -EOVERFLOW;
569 		if (err == -EEXIST)
570 			err = -EADDRINUSE;
571 		sock_put(sk);
572 		goto err;
573 	}
574 
575 	/* We need to ensure that the socket is hashed and visible. */
576 	smp_wmb();
577 	/* Paired with lockless reads from netlink_bind(),
578 	 * netlink_connect() and netlink_sendmsg().
579 	 */
580 	WRITE_ONCE(nlk_sk(sk)->bound, portid);
581 
582 err:
583 	release_sock(sk);
584 	return err;
585 }
586 
netlink_remove(struct sock * sk)587 static void netlink_remove(struct sock *sk)
588 {
589 	struct netlink_table *table;
590 
591 	table = &nl_table[sk->sk_protocol];
592 	if (!rhashtable_remove_fast(&table->hash, &nlk_sk(sk)->node,
593 				    netlink_rhashtable_params)) {
594 		WARN_ON(atomic_read(&sk->sk_refcnt) == 1);
595 		__sock_put(sk);
596 	}
597 
598 	netlink_table_grab();
599 	if (nlk_sk(sk)->subscriptions) {
600 		__sk_del_bind_node(sk);
601 		netlink_update_listeners(sk);
602 	}
603 	if (sk->sk_protocol == NETLINK_GENERIC)
604 		atomic_inc(&genl_sk_destructing_cnt);
605 	netlink_table_ungrab();
606 }
607 
608 static struct proto netlink_proto = {
609 	.name	  = "NETLINK",
610 	.owner	  = THIS_MODULE,
611 	.obj_size = sizeof(struct netlink_sock),
612 };
613 
__netlink_create(struct net * net,struct socket * sock,struct mutex * cb_mutex,int protocol,int kern)614 static int __netlink_create(struct net *net, struct socket *sock,
615 			    struct mutex *cb_mutex, int protocol,
616 			    int kern)
617 {
618 	struct sock *sk;
619 	struct netlink_sock *nlk;
620 
621 	sock->ops = &netlink_ops;
622 
623 	sk = sk_alloc(net, PF_NETLINK, GFP_KERNEL, &netlink_proto, kern);
624 	if (!sk)
625 		return -ENOMEM;
626 
627 	sock_init_data(sock, sk);
628 
629 	nlk = nlk_sk(sk);
630 	if (cb_mutex) {
631 		nlk->cb_mutex = cb_mutex;
632 	} else {
633 		nlk->cb_mutex = &nlk->cb_def_mutex;
634 		mutex_init(nlk->cb_mutex);
635 		lockdep_set_class_and_name(nlk->cb_mutex,
636 					   nlk_cb_mutex_keys + protocol,
637 					   nlk_cb_mutex_key_strings[protocol]);
638 	}
639 	init_waitqueue_head(&nlk->wait);
640 
641 	sk->sk_destruct = netlink_sock_destruct;
642 	sk->sk_protocol = protocol;
643 	return 0;
644 }
645 
netlink_create(struct net * net,struct socket * sock,int protocol,int kern)646 static int netlink_create(struct net *net, struct socket *sock, int protocol,
647 			  int kern)
648 {
649 	struct module *module = NULL;
650 	struct mutex *cb_mutex;
651 	struct netlink_sock *nlk;
652 	int (*bind)(struct net *net, int group);
653 	void (*unbind)(struct net *net, int group);
654 	int err = 0;
655 
656 	sock->state = SS_UNCONNECTED;
657 
658 	if (sock->type != SOCK_RAW && sock->type != SOCK_DGRAM)
659 		return -ESOCKTNOSUPPORT;
660 
661 	if (protocol < 0 || protocol >= MAX_LINKS)
662 		return -EPROTONOSUPPORT;
663 	protocol = array_index_nospec(protocol, MAX_LINKS);
664 
665 	netlink_lock_table();
666 #ifdef CONFIG_MODULES
667 	if (!nl_table[protocol].registered) {
668 		netlink_unlock_table();
669 		request_module("net-pf-%d-proto-%d", PF_NETLINK, protocol);
670 		netlink_lock_table();
671 	}
672 #endif
673 	if (nl_table[protocol].registered &&
674 	    try_module_get(nl_table[protocol].module))
675 		module = nl_table[protocol].module;
676 	else
677 		err = -EPROTONOSUPPORT;
678 	cb_mutex = nl_table[protocol].cb_mutex;
679 	bind = nl_table[protocol].bind;
680 	unbind = nl_table[protocol].unbind;
681 	netlink_unlock_table();
682 
683 	if (err < 0)
684 		goto out;
685 
686 	err = __netlink_create(net, sock, cb_mutex, protocol, kern);
687 	if (err < 0)
688 		goto out_module;
689 
690 	local_bh_disable();
691 	sock_prot_inuse_add(net, &netlink_proto, 1);
692 	local_bh_enable();
693 
694 	nlk = nlk_sk(sock->sk);
695 	nlk->module = module;
696 	nlk->netlink_bind = bind;
697 	nlk->netlink_unbind = unbind;
698 out:
699 	return err;
700 
701 out_module:
702 	module_put(module);
703 	goto out;
704 }
705 
deferred_put_nlk_sk(struct rcu_head * head)706 static void deferred_put_nlk_sk(struct rcu_head *head)
707 {
708 	struct netlink_sock *nlk = container_of(head, struct netlink_sock, rcu);
709 	struct sock *sk = &nlk->sk;
710 
711 	if (!atomic_dec_and_test(&sk->sk_refcnt))
712 		return;
713 
714 	if (nlk->cb_running && nlk->cb.done) {
715 		INIT_WORK(&nlk->work, netlink_sock_destruct_work);
716 		schedule_work(&nlk->work);
717 		return;
718 	}
719 
720 	sk_free(sk);
721 }
722 
netlink_release(struct socket * sock)723 static int netlink_release(struct socket *sock)
724 {
725 	struct sock *sk = sock->sk;
726 	struct netlink_sock *nlk;
727 
728 	if (!sk)
729 		return 0;
730 
731 	netlink_remove(sk);
732 	sock_orphan(sk);
733 	nlk = nlk_sk(sk);
734 
735 	/*
736 	 * OK. Socket is unlinked, any packets that arrive now
737 	 * will be purged.
738 	 */
739 
740 	/* must not acquire netlink_table_lock in any way again before unbind
741 	 * and notifying genetlink is done as otherwise it might deadlock
742 	 */
743 	if (nlk->netlink_unbind) {
744 		int i;
745 
746 		for (i = 0; i < nlk->ngroups; i++)
747 			if (test_bit(i, nlk->groups))
748 				nlk->netlink_unbind(sock_net(sk), i + 1);
749 	}
750 	if (sk->sk_protocol == NETLINK_GENERIC &&
751 	    atomic_dec_return(&genl_sk_destructing_cnt) == 0)
752 		wake_up(&genl_sk_destructing_waitq);
753 
754 	sock->sk = NULL;
755 	wake_up_interruptible_all(&nlk->wait);
756 
757 	skb_queue_purge(&sk->sk_write_queue);
758 
759 	if (nlk->portid && nlk->bound) {
760 		struct netlink_notify n = {
761 						.net = sock_net(sk),
762 						.protocol = sk->sk_protocol,
763 						.portid = nlk->portid,
764 					  };
765 		atomic_notifier_call_chain(&netlink_chain,
766 				NETLINK_URELEASE, &n);
767 	}
768 
769 	module_put(nlk->module);
770 
771 	if (netlink_is_kernel(sk)) {
772 		netlink_table_grab();
773 		BUG_ON(nl_table[sk->sk_protocol].registered == 0);
774 		if (--nl_table[sk->sk_protocol].registered == 0) {
775 			struct listeners *old;
776 
777 			old = nl_deref_protected(nl_table[sk->sk_protocol].listeners);
778 			RCU_INIT_POINTER(nl_table[sk->sk_protocol].listeners, NULL);
779 			kfree_rcu(old, rcu);
780 			nl_table[sk->sk_protocol].module = NULL;
781 			nl_table[sk->sk_protocol].bind = NULL;
782 			nl_table[sk->sk_protocol].unbind = NULL;
783 			nl_table[sk->sk_protocol].flags = 0;
784 			nl_table[sk->sk_protocol].registered = 0;
785 		}
786 		netlink_table_ungrab();
787 	}
788 
789 	kfree(nlk->groups);
790 	nlk->groups = NULL;
791 
792 	local_bh_disable();
793 	sock_prot_inuse_add(sock_net(sk), &netlink_proto, -1);
794 	local_bh_enable();
795 	call_rcu(&nlk->rcu, deferred_put_nlk_sk);
796 	return 0;
797 }
798 
netlink_autobind(struct socket * sock)799 static int netlink_autobind(struct socket *sock)
800 {
801 	struct sock *sk = sock->sk;
802 	struct net *net = sock_net(sk);
803 	struct netlink_table *table = &nl_table[sk->sk_protocol];
804 	s32 portid = task_tgid_vnr(current);
805 	int err;
806 	s32 rover = -4096;
807 	bool ok;
808 
809 retry:
810 	cond_resched();
811 	rcu_read_lock();
812 	ok = !__netlink_lookup(table, portid, net);
813 	rcu_read_unlock();
814 	if (!ok) {
815 		/* Bind collision, search negative portid values. */
816 		if (rover == -4096)
817 			/* rover will be in range [S32_MIN, -4097] */
818 			rover = S32_MIN + prandom_u32_max(-4096 - S32_MIN);
819 		else if (rover >= -4096)
820 			rover = -4097;
821 		portid = rover--;
822 		goto retry;
823 	}
824 
825 	err = netlink_insert(sk, portid);
826 	if (err == -EADDRINUSE)
827 		goto retry;
828 
829 	/* If 2 threads race to autobind, that is fine.  */
830 	if (err == -EBUSY)
831 		err = 0;
832 
833 	return err;
834 }
835 
836 /**
837  * __netlink_ns_capable - General netlink message capability test
838  * @nsp: NETLINK_CB of the socket buffer holding a netlink command from userspace.
839  * @user_ns: The user namespace of the capability to use
840  * @cap: The capability to use
841  *
842  * Test to see if the opener of the socket we received the message
843  * from had when the netlink socket was created and the sender of the
844  * message has has the capability @cap in the user namespace @user_ns.
845  */
__netlink_ns_capable(const struct netlink_skb_parms * nsp,struct user_namespace * user_ns,int cap)846 bool __netlink_ns_capable(const struct netlink_skb_parms *nsp,
847 			struct user_namespace *user_ns, int cap)
848 {
849 	return ((nsp->flags & NETLINK_SKB_DST) ||
850 		file_ns_capable(nsp->sk->sk_socket->file, user_ns, cap)) &&
851 		ns_capable(user_ns, cap);
852 }
853 EXPORT_SYMBOL(__netlink_ns_capable);
854 
855 /**
856  * netlink_ns_capable - General netlink message capability test
857  * @skb: socket buffer holding a netlink command from userspace
858  * @user_ns: The user namespace of the capability to use
859  * @cap: The capability to use
860  *
861  * Test to see if the opener of the socket we received the message
862  * from had when the netlink socket was created and the sender of the
863  * message has has the capability @cap in the user namespace @user_ns.
864  */
netlink_ns_capable(const struct sk_buff * skb,struct user_namespace * user_ns,int cap)865 bool netlink_ns_capable(const struct sk_buff *skb,
866 			struct user_namespace *user_ns, int cap)
867 {
868 	return __netlink_ns_capable(&NETLINK_CB(skb), user_ns, cap);
869 }
870 EXPORT_SYMBOL(netlink_ns_capable);
871 
872 /**
873  * netlink_capable - Netlink global message capability test
874  * @skb: socket buffer holding a netlink command from userspace
875  * @cap: The capability to use
876  *
877  * Test to see if the opener of the socket we received the message
878  * from had when the netlink socket was created and the sender of the
879  * message has has the capability @cap in all user namespaces.
880  */
netlink_capable(const struct sk_buff * skb,int cap)881 bool netlink_capable(const struct sk_buff *skb, int cap)
882 {
883 	return netlink_ns_capable(skb, &init_user_ns, cap);
884 }
885 EXPORT_SYMBOL(netlink_capable);
886 
887 /**
888  * netlink_net_capable - Netlink network namespace message capability test
889  * @skb: socket buffer holding a netlink command from userspace
890  * @cap: The capability to use
891  *
892  * Test to see if the opener of the socket we received the message
893  * from had when the netlink socket was created and the sender of the
894  * message has has the capability @cap over the network namespace of
895  * the socket we received the message from.
896  */
netlink_net_capable(const struct sk_buff * skb,int cap)897 bool netlink_net_capable(const struct sk_buff *skb, int cap)
898 {
899 	return netlink_ns_capable(skb, sock_net(skb->sk)->user_ns, cap);
900 }
901 EXPORT_SYMBOL(netlink_net_capable);
902 
netlink_allowed(const struct socket * sock,unsigned int flag)903 static inline int netlink_allowed(const struct socket *sock, unsigned int flag)
904 {
905 	return (nl_table[sock->sk->sk_protocol].flags & flag) ||
906 		ns_capable(sock_net(sock->sk)->user_ns, CAP_NET_ADMIN);
907 }
908 
909 static void
netlink_update_subscriptions(struct sock * sk,unsigned int subscriptions)910 netlink_update_subscriptions(struct sock *sk, unsigned int subscriptions)
911 {
912 	struct netlink_sock *nlk = nlk_sk(sk);
913 
914 	if (nlk->subscriptions && !subscriptions)
915 		__sk_del_bind_node(sk);
916 	else if (!nlk->subscriptions && subscriptions)
917 		sk_add_bind_node(sk, &nl_table[sk->sk_protocol].mc_list);
918 	nlk->subscriptions = subscriptions;
919 }
920 
netlink_realloc_groups(struct sock * sk)921 static int netlink_realloc_groups(struct sock *sk)
922 {
923 	struct netlink_sock *nlk = nlk_sk(sk);
924 	unsigned int groups;
925 	unsigned long *new_groups;
926 	int err = 0;
927 
928 	netlink_table_grab();
929 
930 	groups = nl_table[sk->sk_protocol].groups;
931 	if (!nl_table[sk->sk_protocol].registered) {
932 		err = -ENOENT;
933 		goto out_unlock;
934 	}
935 
936 	if (nlk->ngroups >= groups)
937 		goto out_unlock;
938 
939 	new_groups = krealloc(nlk->groups, NLGRPSZ(groups), GFP_ATOMIC);
940 	if (new_groups == NULL) {
941 		err = -ENOMEM;
942 		goto out_unlock;
943 	}
944 	memset((char *)new_groups + NLGRPSZ(nlk->ngroups), 0,
945 	       NLGRPSZ(groups) - NLGRPSZ(nlk->ngroups));
946 
947 	nlk->groups = new_groups;
948 	nlk->ngroups = groups;
949  out_unlock:
950 	netlink_table_ungrab();
951 	return err;
952 }
953 
netlink_undo_bind(int group,long unsigned int groups,struct sock * sk)954 static void netlink_undo_bind(int group, long unsigned int groups,
955 			      struct sock *sk)
956 {
957 	struct netlink_sock *nlk = nlk_sk(sk);
958 	int undo;
959 
960 	if (!nlk->netlink_unbind)
961 		return;
962 
963 	for (undo = 0; undo < group; undo++)
964 		if (test_bit(undo, &groups))
965 			nlk->netlink_unbind(sock_net(sk), undo + 1);
966 }
967 
netlink_bind(struct socket * sock,struct sockaddr * addr,int addr_len)968 static int netlink_bind(struct socket *sock, struct sockaddr *addr,
969 			int addr_len)
970 {
971 	struct sock *sk = sock->sk;
972 	struct net *net = sock_net(sk);
973 	struct netlink_sock *nlk = nlk_sk(sk);
974 	struct sockaddr_nl *nladdr = (struct sockaddr_nl *)addr;
975 	int err;
976 	long unsigned int groups = nladdr->nl_groups;
977 	bool bound;
978 
979 	if (addr_len < sizeof(struct sockaddr_nl))
980 		return -EINVAL;
981 
982 	if (nladdr->nl_family != AF_NETLINK)
983 		return -EINVAL;
984 
985 	/* Only superuser is allowed to listen multicasts */
986 	if (groups) {
987 		if (!netlink_allowed(sock, NL_CFG_F_NONROOT_RECV))
988 			return -EPERM;
989 		err = netlink_realloc_groups(sk);
990 		if (err)
991 			return err;
992 	}
993 
994 	if (nlk->ngroups == 0)
995 		groups = 0;
996 	else if (nlk->ngroups < 8*sizeof(groups))
997 		groups &= (1UL << nlk->ngroups) - 1;
998 
999 	/* Paired with WRITE_ONCE() in netlink_insert() */
1000 	bound = READ_ONCE(nlk->bound);
1001 	if (bound) {
1002 		/* Ensure nlk->portid is up-to-date. */
1003 		smp_rmb();
1004 
1005 		if (nladdr->nl_pid != nlk->portid)
1006 			return -EINVAL;
1007 	}
1008 
1009 	if (nlk->netlink_bind && groups) {
1010 		int group;
1011 
1012 		/* nl_groups is a u32, so cap the maximum groups we can bind */
1013 		for (group = 0; group < BITS_PER_TYPE(u32); group++) {
1014 			if (!test_bit(group, &groups))
1015 				continue;
1016 			err = nlk->netlink_bind(net, group + 1);
1017 			if (!err)
1018 				continue;
1019 			netlink_undo_bind(group, groups, sk);
1020 			return err;
1021 		}
1022 	}
1023 
1024 	/* No need for barriers here as we return to user-space without
1025 	 * using any of the bound attributes.
1026 	 */
1027 	if (!bound) {
1028 		err = nladdr->nl_pid ?
1029 			netlink_insert(sk, nladdr->nl_pid) :
1030 			netlink_autobind(sock);
1031 		if (err) {
1032 			netlink_undo_bind(BITS_PER_TYPE(u32), groups, sk);
1033 			return err;
1034 		}
1035 	}
1036 
1037 	if (!groups && (nlk->groups == NULL || !(u32)nlk->groups[0]))
1038 		return 0;
1039 
1040 	netlink_table_grab();
1041 	netlink_update_subscriptions(sk, nlk->subscriptions +
1042 					 hweight32(groups) -
1043 					 hweight32(nlk->groups[0]));
1044 	nlk->groups[0] = (nlk->groups[0] & ~0xffffffffUL) | groups;
1045 	netlink_update_listeners(sk);
1046 	netlink_table_ungrab();
1047 
1048 	return 0;
1049 }
1050 
netlink_connect(struct socket * sock,struct sockaddr * addr,int alen,int flags)1051 static int netlink_connect(struct socket *sock, struct sockaddr *addr,
1052 			   int alen, int flags)
1053 {
1054 	int err = 0;
1055 	struct sock *sk = sock->sk;
1056 	struct netlink_sock *nlk = nlk_sk(sk);
1057 	struct sockaddr_nl *nladdr = (struct sockaddr_nl *)addr;
1058 
1059 	if (alen < sizeof(addr->sa_family))
1060 		return -EINVAL;
1061 
1062 	if (addr->sa_family == AF_UNSPEC) {
1063 		sk->sk_state	= NETLINK_UNCONNECTED;
1064 		nlk->dst_portid	= 0;
1065 		nlk->dst_group  = 0;
1066 		return 0;
1067 	}
1068 	if (addr->sa_family != AF_NETLINK)
1069 		return -EINVAL;
1070 
1071 	if (alen < sizeof(struct sockaddr_nl))
1072 		return -EINVAL;
1073 
1074 	if ((nladdr->nl_groups || nladdr->nl_pid) &&
1075 	    !netlink_allowed(sock, NL_CFG_F_NONROOT_SEND))
1076 		return -EPERM;
1077 
1078 	/* No need for barriers here as we return to user-space without
1079 	 * using any of the bound attributes.
1080 	 * Paired with WRITE_ONCE() in netlink_insert().
1081 	 */
1082 	if (!READ_ONCE(nlk->bound))
1083 		err = netlink_autobind(sock);
1084 
1085 	if (err == 0) {
1086 		sk->sk_state	= NETLINK_CONNECTED;
1087 		nlk->dst_portid = nladdr->nl_pid;
1088 		nlk->dst_group  = ffs(nladdr->nl_groups);
1089 	}
1090 
1091 	return err;
1092 }
1093 
netlink_getname(struct socket * sock,struct sockaddr * addr,int * addr_len,int peer)1094 static int netlink_getname(struct socket *sock, struct sockaddr *addr,
1095 			   int *addr_len, int peer)
1096 {
1097 	struct sock *sk = sock->sk;
1098 	struct netlink_sock *nlk = nlk_sk(sk);
1099 	DECLARE_SOCKADDR(struct sockaddr_nl *, nladdr, addr);
1100 
1101 	nladdr->nl_family = AF_NETLINK;
1102 	nladdr->nl_pad = 0;
1103 	*addr_len = sizeof(*nladdr);
1104 
1105 	if (peer) {
1106 		nladdr->nl_pid = nlk->dst_portid;
1107 		nladdr->nl_groups = netlink_group_mask(nlk->dst_group);
1108 	} else {
1109 		nladdr->nl_pid = nlk->portid;
1110 		nladdr->nl_groups = nlk->groups ? nlk->groups[0] : 0;
1111 	}
1112 	return 0;
1113 }
1114 
netlink_getsockbyportid(struct sock * ssk,u32 portid)1115 static struct sock *netlink_getsockbyportid(struct sock *ssk, u32 portid)
1116 {
1117 	struct sock *sock;
1118 	struct netlink_sock *nlk;
1119 
1120 	sock = netlink_lookup(sock_net(ssk), ssk->sk_protocol, portid);
1121 	if (!sock)
1122 		return ERR_PTR(-ECONNREFUSED);
1123 
1124 	/* Don't bother queuing skb if kernel socket has no input function */
1125 	nlk = nlk_sk(sock);
1126 	if (sock->sk_state == NETLINK_CONNECTED &&
1127 	    nlk->dst_portid != nlk_sk(ssk)->portid) {
1128 		sock_put(sock);
1129 		return ERR_PTR(-ECONNREFUSED);
1130 	}
1131 	return sock;
1132 }
1133 
netlink_getsockbyfilp(struct file * filp)1134 struct sock *netlink_getsockbyfilp(struct file *filp)
1135 {
1136 	struct inode *inode = file_inode(filp);
1137 	struct sock *sock;
1138 
1139 	if (!S_ISSOCK(inode->i_mode))
1140 		return ERR_PTR(-ENOTSOCK);
1141 
1142 	sock = SOCKET_I(inode)->sk;
1143 	if (sock->sk_family != AF_NETLINK)
1144 		return ERR_PTR(-EINVAL);
1145 
1146 	sock_hold(sock);
1147 	return sock;
1148 }
1149 
netlink_alloc_large_skb(unsigned int size,int broadcast)1150 static struct sk_buff *netlink_alloc_large_skb(unsigned int size,
1151 					       int broadcast)
1152 {
1153 	struct sk_buff *skb;
1154 	void *data;
1155 
1156 	if (size <= NLMSG_GOODSIZE || broadcast)
1157 		return alloc_skb(size, GFP_KERNEL);
1158 
1159 	size = SKB_DATA_ALIGN(size) +
1160 	       SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
1161 
1162 	data = vmalloc(size);
1163 	if (data == NULL)
1164 		return NULL;
1165 
1166 	skb = __build_skb(data, size);
1167 	if (skb == NULL)
1168 		vfree(data);
1169 	else
1170 		skb->destructor = netlink_skb_destructor;
1171 
1172 	return skb;
1173 }
1174 
1175 /*
1176  * Attach a skb to a netlink socket.
1177  * The caller must hold a reference to the destination socket. On error, the
1178  * reference is dropped. The skb is not send to the destination, just all
1179  * all error checks are performed and memory in the queue is reserved.
1180  * Return values:
1181  * < 0: error. skb freed, reference to sock dropped.
1182  * 0: continue
1183  * 1: repeat lookup - reference dropped while waiting for socket memory.
1184  */
netlink_attachskb(struct sock * sk,struct sk_buff * skb,long * timeo,struct sock * ssk)1185 int netlink_attachskb(struct sock *sk, struct sk_buff *skb,
1186 		      long *timeo, struct sock *ssk)
1187 {
1188 	struct netlink_sock *nlk;
1189 
1190 	nlk = nlk_sk(sk);
1191 
1192 	if ((atomic_read(&sk->sk_rmem_alloc) > sk->sk_rcvbuf ||
1193 	     test_bit(NETLINK_S_CONGESTED, &nlk->state))) {
1194 		DECLARE_WAITQUEUE(wait, current);
1195 		if (!*timeo) {
1196 			if (!ssk || netlink_is_kernel(ssk))
1197 				netlink_overrun(sk);
1198 			sock_put(sk);
1199 			kfree_skb(skb);
1200 			return -EAGAIN;
1201 		}
1202 
1203 		__set_current_state(TASK_INTERRUPTIBLE);
1204 		add_wait_queue(&nlk->wait, &wait);
1205 
1206 		if ((atomic_read(&sk->sk_rmem_alloc) > sk->sk_rcvbuf ||
1207 		     test_bit(NETLINK_S_CONGESTED, &nlk->state)) &&
1208 		    !sock_flag(sk, SOCK_DEAD))
1209 			*timeo = schedule_timeout(*timeo);
1210 
1211 		__set_current_state(TASK_RUNNING);
1212 		remove_wait_queue(&nlk->wait, &wait);
1213 		sock_put(sk);
1214 
1215 		if (signal_pending(current)) {
1216 			kfree_skb(skb);
1217 			return sock_intr_errno(*timeo);
1218 		}
1219 		return 1;
1220 	}
1221 	netlink_skb_set_owner_r(skb, sk);
1222 	return 0;
1223 }
1224 
__netlink_sendskb(struct sock * sk,struct sk_buff * skb)1225 static int __netlink_sendskb(struct sock *sk, struct sk_buff *skb)
1226 {
1227 	int len = skb->len;
1228 
1229 	netlink_deliver_tap(skb);
1230 
1231 	skb_queue_tail(&sk->sk_receive_queue, skb);
1232 	sk->sk_data_ready(sk);
1233 	return len;
1234 }
1235 
netlink_sendskb(struct sock * sk,struct sk_buff * skb)1236 int netlink_sendskb(struct sock *sk, struct sk_buff *skb)
1237 {
1238 	int len = __netlink_sendskb(sk, skb);
1239 
1240 	sock_put(sk);
1241 	return len;
1242 }
1243 
netlink_detachskb(struct sock * sk,struct sk_buff * skb)1244 void netlink_detachskb(struct sock *sk, struct sk_buff *skb)
1245 {
1246 	kfree_skb(skb);
1247 	sock_put(sk);
1248 }
1249 
netlink_trim(struct sk_buff * skb,gfp_t allocation)1250 static struct sk_buff *netlink_trim(struct sk_buff *skb, gfp_t allocation)
1251 {
1252 	int delta;
1253 
1254 	WARN_ON(skb->sk != NULL);
1255 	delta = skb->end - skb->tail;
1256 	if (is_vmalloc_addr(skb->head) || delta * 2 < skb->truesize)
1257 		return skb;
1258 
1259 	if (skb_shared(skb)) {
1260 		struct sk_buff *nskb = skb_clone(skb, allocation);
1261 		if (!nskb)
1262 			return skb;
1263 		consume_skb(skb);
1264 		skb = nskb;
1265 	}
1266 
1267 	if (!pskb_expand_head(skb, 0, -delta, allocation))
1268 		skb->truesize -= delta;
1269 
1270 	return skb;
1271 }
1272 
netlink_unicast_kernel(struct sock * sk,struct sk_buff * skb,struct sock * ssk)1273 static int netlink_unicast_kernel(struct sock *sk, struct sk_buff *skb,
1274 				  struct sock *ssk)
1275 {
1276 	int ret;
1277 	struct netlink_sock *nlk = nlk_sk(sk);
1278 
1279 	ret = -ECONNREFUSED;
1280 	if (nlk->netlink_rcv != NULL) {
1281 		ret = skb->len;
1282 		netlink_skb_set_owner_r(skb, sk);
1283 		NETLINK_CB(skb).sk = ssk;
1284 		netlink_deliver_tap_kernel(sk, ssk, skb);
1285 		nlk->netlink_rcv(skb);
1286 		consume_skb(skb);
1287 	} else {
1288 		kfree_skb(skb);
1289 	}
1290 	sock_put(sk);
1291 	return ret;
1292 }
1293 
netlink_unicast(struct sock * ssk,struct sk_buff * skb,u32 portid,int nonblock)1294 int netlink_unicast(struct sock *ssk, struct sk_buff *skb,
1295 		    u32 portid, int nonblock)
1296 {
1297 	struct sock *sk;
1298 	int err;
1299 	long timeo;
1300 
1301 	skb = netlink_trim(skb, gfp_any());
1302 
1303 	timeo = sock_sndtimeo(ssk, nonblock);
1304 retry:
1305 	sk = netlink_getsockbyportid(ssk, portid);
1306 	if (IS_ERR(sk)) {
1307 		kfree_skb(skb);
1308 		return PTR_ERR(sk);
1309 	}
1310 	if (netlink_is_kernel(sk))
1311 		return netlink_unicast_kernel(sk, skb, ssk);
1312 
1313 	if (sk_filter(sk, skb)) {
1314 		err = skb->len;
1315 		kfree_skb(skb);
1316 		sock_put(sk);
1317 		return err;
1318 	}
1319 
1320 	err = netlink_attachskb(sk, skb, &timeo, ssk);
1321 	if (err == 1)
1322 		goto retry;
1323 	if (err)
1324 		return err;
1325 
1326 	return netlink_sendskb(sk, skb);
1327 }
1328 EXPORT_SYMBOL(netlink_unicast);
1329 
__netlink_alloc_skb(struct sock * ssk,unsigned int size,unsigned int ldiff,u32 dst_portid,gfp_t gfp_mask)1330 struct sk_buff *__netlink_alloc_skb(struct sock *ssk, unsigned int size,
1331 				    unsigned int ldiff, u32 dst_portid,
1332 				    gfp_t gfp_mask)
1333 {
1334 	return alloc_skb(size, gfp_mask);
1335 }
1336 EXPORT_SYMBOL_GPL(__netlink_alloc_skb);
1337 
netlink_has_listeners(struct sock * sk,unsigned int group)1338 int netlink_has_listeners(struct sock *sk, unsigned int group)
1339 {
1340 	int res = 0;
1341 	struct listeners *listeners;
1342 
1343 	BUG_ON(!netlink_is_kernel(sk));
1344 
1345 	rcu_read_lock();
1346 	listeners = rcu_dereference(nl_table[sk->sk_protocol].listeners);
1347 
1348 	if (listeners && group - 1 < nl_table[sk->sk_protocol].groups)
1349 		res = test_bit(group - 1, listeners->masks);
1350 
1351 	rcu_read_unlock();
1352 
1353 	return res;
1354 }
1355 EXPORT_SYMBOL_GPL(netlink_has_listeners);
1356 
netlink_broadcast_deliver(struct sock * sk,struct sk_buff * skb)1357 static int netlink_broadcast_deliver(struct sock *sk, struct sk_buff *skb)
1358 {
1359 	struct netlink_sock *nlk = nlk_sk(sk);
1360 
1361 	if (atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf &&
1362 	    !test_bit(NETLINK_S_CONGESTED, &nlk->state)) {
1363 		netlink_skb_set_owner_r(skb, sk);
1364 		__netlink_sendskb(sk, skb);
1365 		return atomic_read(&sk->sk_rmem_alloc) > (sk->sk_rcvbuf >> 1);
1366 	}
1367 	return -1;
1368 }
1369 
1370 struct netlink_broadcast_data {
1371 	struct sock *exclude_sk;
1372 	struct net *net;
1373 	u32 portid;
1374 	u32 group;
1375 	int failure;
1376 	int delivery_failure;
1377 	int congested;
1378 	int delivered;
1379 	gfp_t allocation;
1380 	struct sk_buff *skb, *skb2;
1381 	int (*tx_filter)(struct sock *dsk, struct sk_buff *skb, void *data);
1382 	void *tx_data;
1383 };
1384 
do_one_broadcast(struct sock * sk,struct netlink_broadcast_data * p)1385 static void do_one_broadcast(struct sock *sk,
1386 				    struct netlink_broadcast_data *p)
1387 {
1388 	struct netlink_sock *nlk = nlk_sk(sk);
1389 	int val;
1390 
1391 	if (p->exclude_sk == sk)
1392 		return;
1393 
1394 	if (nlk->portid == p->portid || p->group - 1 >= nlk->ngroups ||
1395 	    !test_bit(p->group - 1, nlk->groups))
1396 		return;
1397 
1398 	if (!net_eq(sock_net(sk), p->net)) {
1399 		if (!(nlk->flags & NETLINK_F_LISTEN_ALL_NSID))
1400 			return;
1401 
1402 		if (!peernet_has_id(sock_net(sk), p->net))
1403 			return;
1404 
1405 		if (!file_ns_capable(sk->sk_socket->file, p->net->user_ns,
1406 				     CAP_NET_BROADCAST))
1407 			return;
1408 	}
1409 
1410 	if (p->failure) {
1411 		netlink_overrun(sk);
1412 		return;
1413 	}
1414 
1415 	sock_hold(sk);
1416 	if (p->skb2 == NULL) {
1417 		if (skb_shared(p->skb)) {
1418 			p->skb2 = skb_clone(p->skb, p->allocation);
1419 		} else {
1420 			p->skb2 = skb_get(p->skb);
1421 			/*
1422 			 * skb ownership may have been set when
1423 			 * delivered to a previous socket.
1424 			 */
1425 			skb_orphan(p->skb2);
1426 		}
1427 	}
1428 	if (p->skb2 == NULL) {
1429 		netlink_overrun(sk);
1430 		/* Clone failed. Notify ALL listeners. */
1431 		p->failure = 1;
1432 		if (nlk->flags & NETLINK_F_BROADCAST_SEND_ERROR)
1433 			p->delivery_failure = 1;
1434 		goto out;
1435 	}
1436 	if (p->tx_filter && p->tx_filter(sk, p->skb2, p->tx_data)) {
1437 		kfree_skb(p->skb2);
1438 		p->skb2 = NULL;
1439 		goto out;
1440 	}
1441 	if (sk_filter(sk, p->skb2)) {
1442 		kfree_skb(p->skb2);
1443 		p->skb2 = NULL;
1444 		goto out;
1445 	}
1446 	NETLINK_CB(p->skb2).nsid = peernet2id(sock_net(sk), p->net);
1447 	NETLINK_CB(p->skb2).nsid_is_set = true;
1448 	val = netlink_broadcast_deliver(sk, p->skb2);
1449 	if (val < 0) {
1450 		netlink_overrun(sk);
1451 		if (nlk->flags & NETLINK_F_BROADCAST_SEND_ERROR)
1452 			p->delivery_failure = 1;
1453 	} else {
1454 		p->congested |= val;
1455 		p->delivered = 1;
1456 		p->skb2 = NULL;
1457 	}
1458 out:
1459 	sock_put(sk);
1460 }
1461 
netlink_broadcast_filtered(struct sock * ssk,struct sk_buff * skb,u32 portid,u32 group,gfp_t allocation,int (* filter)(struct sock * dsk,struct sk_buff * skb,void * data),void * filter_data)1462 int netlink_broadcast_filtered(struct sock *ssk, struct sk_buff *skb, u32 portid,
1463 	u32 group, gfp_t allocation,
1464 	int (*filter)(struct sock *dsk, struct sk_buff *skb, void *data),
1465 	void *filter_data)
1466 {
1467 	struct net *net = sock_net(ssk);
1468 	struct netlink_broadcast_data info;
1469 	struct sock *sk;
1470 
1471 	skb = netlink_trim(skb, allocation);
1472 
1473 	info.exclude_sk = ssk;
1474 	info.net = net;
1475 	info.portid = portid;
1476 	info.group = group;
1477 	info.failure = 0;
1478 	info.delivery_failure = 0;
1479 	info.congested = 0;
1480 	info.delivered = 0;
1481 	info.allocation = allocation;
1482 	info.skb = skb;
1483 	info.skb2 = NULL;
1484 	info.tx_filter = filter;
1485 	info.tx_data = filter_data;
1486 
1487 	/* While we sleep in clone, do not allow to change socket list */
1488 
1489 	netlink_lock_table();
1490 
1491 	sk_for_each_bound(sk, &nl_table[ssk->sk_protocol].mc_list)
1492 		do_one_broadcast(sk, &info);
1493 
1494 	consume_skb(skb);
1495 
1496 	netlink_unlock_table();
1497 
1498 	if (info.delivery_failure) {
1499 		kfree_skb(info.skb2);
1500 		return -ENOBUFS;
1501 	}
1502 	consume_skb(info.skb2);
1503 
1504 	if (info.delivered) {
1505 		if (info.congested && gfpflags_allow_blocking(allocation))
1506 			yield();
1507 		return 0;
1508 	}
1509 	return -ESRCH;
1510 }
1511 EXPORT_SYMBOL(netlink_broadcast_filtered);
1512 
netlink_broadcast(struct sock * ssk,struct sk_buff * skb,u32 portid,u32 group,gfp_t allocation)1513 int netlink_broadcast(struct sock *ssk, struct sk_buff *skb, u32 portid,
1514 		      u32 group, gfp_t allocation)
1515 {
1516 	return netlink_broadcast_filtered(ssk, skb, portid, group, allocation,
1517 		NULL, NULL);
1518 }
1519 EXPORT_SYMBOL(netlink_broadcast);
1520 
1521 struct netlink_set_err_data {
1522 	struct sock *exclude_sk;
1523 	u32 portid;
1524 	u32 group;
1525 	int code;
1526 };
1527 
do_one_set_err(struct sock * sk,struct netlink_set_err_data * p)1528 static int do_one_set_err(struct sock *sk, struct netlink_set_err_data *p)
1529 {
1530 	struct netlink_sock *nlk = nlk_sk(sk);
1531 	int ret = 0;
1532 
1533 	if (sk == p->exclude_sk)
1534 		goto out;
1535 
1536 	if (!net_eq(sock_net(sk), sock_net(p->exclude_sk)))
1537 		goto out;
1538 
1539 	if (nlk->portid == p->portid || p->group - 1 >= nlk->ngroups ||
1540 	    !test_bit(p->group - 1, nlk->groups))
1541 		goto out;
1542 
1543 	if (p->code == ENOBUFS && nlk->flags & NETLINK_F_RECV_NO_ENOBUFS) {
1544 		ret = 1;
1545 		goto out;
1546 	}
1547 
1548 	sk->sk_err = p->code;
1549 	sk->sk_error_report(sk);
1550 out:
1551 	return ret;
1552 }
1553 
1554 /**
1555  * netlink_set_err - report error to broadcast listeners
1556  * @ssk: the kernel netlink socket, as returned by netlink_kernel_create()
1557  * @portid: the PORTID of a process that we want to skip (if any)
1558  * @group: the broadcast group that will notice the error
1559  * @code: error code, must be negative (as usual in kernelspace)
1560  *
1561  * This function returns the number of broadcast listeners that have set the
1562  * NETLINK_NO_ENOBUFS socket option.
1563  */
netlink_set_err(struct sock * ssk,u32 portid,u32 group,int code)1564 int netlink_set_err(struct sock *ssk, u32 portid, u32 group, int code)
1565 {
1566 	struct netlink_set_err_data info;
1567 	struct sock *sk;
1568 	int ret = 0;
1569 
1570 	info.exclude_sk = ssk;
1571 	info.portid = portid;
1572 	info.group = group;
1573 	/* sk->sk_err wants a positive error value */
1574 	info.code = -code;
1575 
1576 	read_lock(&nl_table_lock);
1577 
1578 	sk_for_each_bound(sk, &nl_table[ssk->sk_protocol].mc_list)
1579 		ret += do_one_set_err(sk, &info);
1580 
1581 	read_unlock(&nl_table_lock);
1582 	return ret;
1583 }
1584 EXPORT_SYMBOL(netlink_set_err);
1585 
1586 /* must be called with netlink table grabbed */
netlink_update_socket_mc(struct netlink_sock * nlk,unsigned int group,int is_new)1587 static void netlink_update_socket_mc(struct netlink_sock *nlk,
1588 				     unsigned int group,
1589 				     int is_new)
1590 {
1591 	int old, new = !!is_new, subscriptions;
1592 
1593 	old = test_bit(group - 1, nlk->groups);
1594 	subscriptions = nlk->subscriptions - old + new;
1595 	if (new)
1596 		__set_bit(group - 1, nlk->groups);
1597 	else
1598 		__clear_bit(group - 1, nlk->groups);
1599 	netlink_update_subscriptions(&nlk->sk, subscriptions);
1600 	netlink_update_listeners(&nlk->sk);
1601 }
1602 
netlink_setsockopt(struct socket * sock,int level,int optname,char __user * optval,unsigned int optlen)1603 static int netlink_setsockopt(struct socket *sock, int level, int optname,
1604 			      char __user *optval, unsigned int optlen)
1605 {
1606 	struct sock *sk = sock->sk;
1607 	struct netlink_sock *nlk = nlk_sk(sk);
1608 	unsigned int val = 0;
1609 	int err;
1610 
1611 	if (level != SOL_NETLINK)
1612 		return -ENOPROTOOPT;
1613 
1614 	if (optlen >= sizeof(int) &&
1615 	    get_user(val, (unsigned int __user *)optval))
1616 		return -EFAULT;
1617 
1618 	switch (optname) {
1619 	case NETLINK_PKTINFO:
1620 		if (val)
1621 			nlk->flags |= NETLINK_F_RECV_PKTINFO;
1622 		else
1623 			nlk->flags &= ~NETLINK_F_RECV_PKTINFO;
1624 		err = 0;
1625 		break;
1626 	case NETLINK_ADD_MEMBERSHIP:
1627 	case NETLINK_DROP_MEMBERSHIP: {
1628 		if (!netlink_allowed(sock, NL_CFG_F_NONROOT_RECV))
1629 			return -EPERM;
1630 		err = netlink_realloc_groups(sk);
1631 		if (err)
1632 			return err;
1633 		if (!val || val - 1 >= nlk->ngroups)
1634 			return -EINVAL;
1635 		if (optname == NETLINK_ADD_MEMBERSHIP && nlk->netlink_bind) {
1636 			err = nlk->netlink_bind(sock_net(sk), val);
1637 			if (err)
1638 				return err;
1639 		}
1640 		netlink_table_grab();
1641 		netlink_update_socket_mc(nlk, val,
1642 					 optname == NETLINK_ADD_MEMBERSHIP);
1643 		netlink_table_ungrab();
1644 		if (optname == NETLINK_DROP_MEMBERSHIP && nlk->netlink_unbind)
1645 			nlk->netlink_unbind(sock_net(sk), val);
1646 
1647 		err = 0;
1648 		break;
1649 	}
1650 	case NETLINK_BROADCAST_ERROR:
1651 		if (val)
1652 			nlk->flags |= NETLINK_F_BROADCAST_SEND_ERROR;
1653 		else
1654 			nlk->flags &= ~NETLINK_F_BROADCAST_SEND_ERROR;
1655 		err = 0;
1656 		break;
1657 	case NETLINK_NO_ENOBUFS:
1658 		if (val) {
1659 			nlk->flags |= NETLINK_F_RECV_NO_ENOBUFS;
1660 			clear_bit(NETLINK_S_CONGESTED, &nlk->state);
1661 			wake_up_interruptible(&nlk->wait);
1662 		} else {
1663 			nlk->flags &= ~NETLINK_F_RECV_NO_ENOBUFS;
1664 		}
1665 		err = 0;
1666 		break;
1667 	case NETLINK_LISTEN_ALL_NSID:
1668 		if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_BROADCAST))
1669 			return -EPERM;
1670 
1671 		if (val)
1672 			nlk->flags |= NETLINK_F_LISTEN_ALL_NSID;
1673 		else
1674 			nlk->flags &= ~NETLINK_F_LISTEN_ALL_NSID;
1675 		err = 0;
1676 		break;
1677 	case NETLINK_CAP_ACK:
1678 		if (val)
1679 			nlk->flags |= NETLINK_F_CAP_ACK;
1680 		else
1681 			nlk->flags &= ~NETLINK_F_CAP_ACK;
1682 		err = 0;
1683 		break;
1684 	default:
1685 		err = -ENOPROTOOPT;
1686 	}
1687 	return err;
1688 }
1689 
netlink_getsockopt(struct socket * sock,int level,int optname,char __user * optval,int __user * optlen)1690 static int netlink_getsockopt(struct socket *sock, int level, int optname,
1691 			      char __user *optval, int __user *optlen)
1692 {
1693 	struct sock *sk = sock->sk;
1694 	struct netlink_sock *nlk = nlk_sk(sk);
1695 	int len, val, err;
1696 
1697 	if (level != SOL_NETLINK)
1698 		return -ENOPROTOOPT;
1699 
1700 	if (get_user(len, optlen))
1701 		return -EFAULT;
1702 	if (len < 0)
1703 		return -EINVAL;
1704 
1705 	switch (optname) {
1706 	case NETLINK_PKTINFO:
1707 		if (len < sizeof(int))
1708 			return -EINVAL;
1709 		len = sizeof(int);
1710 		val = nlk->flags & NETLINK_F_RECV_PKTINFO ? 1 : 0;
1711 		if (put_user(len, optlen) ||
1712 		    put_user(val, optval))
1713 			return -EFAULT;
1714 		err = 0;
1715 		break;
1716 	case NETLINK_BROADCAST_ERROR:
1717 		if (len < sizeof(int))
1718 			return -EINVAL;
1719 		len = sizeof(int);
1720 		val = nlk->flags & NETLINK_F_BROADCAST_SEND_ERROR ? 1 : 0;
1721 		if (put_user(len, optlen) ||
1722 		    put_user(val, optval))
1723 			return -EFAULT;
1724 		err = 0;
1725 		break;
1726 	case NETLINK_NO_ENOBUFS:
1727 		if (len < sizeof(int))
1728 			return -EINVAL;
1729 		len = sizeof(int);
1730 		val = nlk->flags & NETLINK_F_RECV_NO_ENOBUFS ? 1 : 0;
1731 		if (put_user(len, optlen) ||
1732 		    put_user(val, optval))
1733 			return -EFAULT;
1734 		err = 0;
1735 		break;
1736 	case NETLINK_LIST_MEMBERSHIPS: {
1737 		int pos, idx, shift;
1738 
1739 		err = 0;
1740 		netlink_lock_table();
1741 		for (pos = 0; pos * 8 < nlk->ngroups; pos += sizeof(u32)) {
1742 			if (len - pos < sizeof(u32))
1743 				break;
1744 
1745 			idx = pos / sizeof(unsigned long);
1746 			shift = (pos % sizeof(unsigned long)) * 8;
1747 			if (put_user((u32)(nlk->groups[idx] >> shift),
1748 				     (u32 __user *)(optval + pos))) {
1749 				err = -EFAULT;
1750 				break;
1751 			}
1752 		}
1753 		if (put_user(ALIGN(nlk->ngroups / 8, sizeof(u32)), optlen))
1754 			err = -EFAULT;
1755 		netlink_unlock_table();
1756 		break;
1757 	}
1758 	case NETLINK_CAP_ACK:
1759 		if (len < sizeof(int))
1760 			return -EINVAL;
1761 		len = sizeof(int);
1762 		val = nlk->flags & NETLINK_F_CAP_ACK ? 1 : 0;
1763 		if (put_user(len, optlen) ||
1764 		    put_user(val, optval))
1765 			return -EFAULT;
1766 		err = 0;
1767 		break;
1768 	default:
1769 		err = -ENOPROTOOPT;
1770 	}
1771 	return err;
1772 }
1773 
netlink_cmsg_recv_pktinfo(struct msghdr * msg,struct sk_buff * skb)1774 static void netlink_cmsg_recv_pktinfo(struct msghdr *msg, struct sk_buff *skb)
1775 {
1776 	struct nl_pktinfo info;
1777 
1778 	info.group = NETLINK_CB(skb).dst_group;
1779 	put_cmsg(msg, SOL_NETLINK, NETLINK_PKTINFO, sizeof(info), &info);
1780 }
1781 
netlink_cmsg_listen_all_nsid(struct sock * sk,struct msghdr * msg,struct sk_buff * skb)1782 static void netlink_cmsg_listen_all_nsid(struct sock *sk, struct msghdr *msg,
1783 					 struct sk_buff *skb)
1784 {
1785 	if (!NETLINK_CB(skb).nsid_is_set)
1786 		return;
1787 
1788 	put_cmsg(msg, SOL_NETLINK, NETLINK_LISTEN_ALL_NSID, sizeof(int),
1789 		 &NETLINK_CB(skb).nsid);
1790 }
1791 
netlink_sendmsg(struct socket * sock,struct msghdr * msg,size_t len)1792 static int netlink_sendmsg(struct socket *sock, struct msghdr *msg, size_t len)
1793 {
1794 	struct sock *sk = sock->sk;
1795 	struct netlink_sock *nlk = nlk_sk(sk);
1796 	DECLARE_SOCKADDR(struct sockaddr_nl *, addr, msg->msg_name);
1797 	u32 dst_portid;
1798 	u32 dst_group;
1799 	struct sk_buff *skb;
1800 	int err;
1801 	struct scm_cookie scm;
1802 	u32 netlink_skb_flags = 0;
1803 
1804 	if (msg->msg_flags&MSG_OOB)
1805 		return -EOPNOTSUPP;
1806 
1807 	if (len == 0) {
1808 		pr_warn_once("Zero length message leads to an empty skb\n");
1809 		return -ENODATA;
1810 	}
1811 
1812 	err = scm_send(sock, msg, &scm, true);
1813 	if (err < 0)
1814 		return err;
1815 
1816 	if (msg->msg_namelen) {
1817 		err = -EINVAL;
1818 		if (msg->msg_namelen < sizeof(struct sockaddr_nl))
1819 			goto out;
1820 		if (addr->nl_family != AF_NETLINK)
1821 			goto out;
1822 		dst_portid = addr->nl_pid;
1823 		dst_group = ffs(addr->nl_groups);
1824 		err =  -EPERM;
1825 		if ((dst_group || dst_portid) &&
1826 		    !netlink_allowed(sock, NL_CFG_F_NONROOT_SEND))
1827 			goto out;
1828 		netlink_skb_flags |= NETLINK_SKB_DST;
1829 	} else {
1830 		dst_portid = nlk->dst_portid;
1831 		dst_group = nlk->dst_group;
1832 	}
1833 
1834 	/* Paired with WRITE_ONCE() in netlink_insert() */
1835 	if (!READ_ONCE(nlk->bound)) {
1836 		err = netlink_autobind(sock);
1837 		if (err)
1838 			goto out;
1839 	} else {
1840 		/* Ensure nlk is hashed and visible. */
1841 		smp_rmb();
1842 	}
1843 
1844 	err = -EMSGSIZE;
1845 	if (len > sk->sk_sndbuf - 32)
1846 		goto out;
1847 	err = -ENOBUFS;
1848 	skb = netlink_alloc_large_skb(len, dst_group);
1849 	if (skb == NULL)
1850 		goto out;
1851 
1852 	NETLINK_CB(skb).portid	= nlk->portid;
1853 	NETLINK_CB(skb).dst_group = dst_group;
1854 	NETLINK_CB(skb).creds	= scm.creds;
1855 	NETLINK_CB(skb).flags	= netlink_skb_flags;
1856 
1857 	err = -EFAULT;
1858 	if (memcpy_from_msg(skb_put(skb, len), msg, len)) {
1859 		kfree_skb(skb);
1860 		goto out;
1861 	}
1862 
1863 	err = security_netlink_send(sk, skb);
1864 	if (err) {
1865 		kfree_skb(skb);
1866 		goto out;
1867 	}
1868 
1869 	if (dst_group) {
1870 		atomic_inc(&skb->users);
1871 		netlink_broadcast(sk, skb, dst_portid, dst_group, GFP_KERNEL);
1872 	}
1873 	err = netlink_unicast(sk, skb, dst_portid, msg->msg_flags&MSG_DONTWAIT);
1874 
1875 out:
1876 	scm_destroy(&scm);
1877 	return err;
1878 }
1879 
netlink_recvmsg(struct socket * sock,struct msghdr * msg,size_t len,int flags)1880 static int netlink_recvmsg(struct socket *sock, struct msghdr *msg, size_t len,
1881 			   int flags)
1882 {
1883 	struct scm_cookie scm;
1884 	struct sock *sk = sock->sk;
1885 	struct netlink_sock *nlk = nlk_sk(sk);
1886 	int noblock = flags&MSG_DONTWAIT;
1887 	size_t copied;
1888 	struct sk_buff *skb, *data_skb;
1889 	int err, ret;
1890 
1891 	if (flags&MSG_OOB)
1892 		return -EOPNOTSUPP;
1893 
1894 	copied = 0;
1895 
1896 	skb = skb_recv_datagram(sk, flags, noblock, &err);
1897 	if (skb == NULL)
1898 		goto out;
1899 
1900 	data_skb = skb;
1901 
1902 #ifdef CONFIG_COMPAT_NETLINK_MESSAGES
1903 	if (unlikely(skb_shinfo(skb)->frag_list)) {
1904 		/*
1905 		 * If this skb has a frag_list, then here that means that we
1906 		 * will have to use the frag_list skb's data for compat tasks
1907 		 * and the regular skb's data for normal (non-compat) tasks.
1908 		 *
1909 		 * If we need to send the compat skb, assign it to the
1910 		 * 'data_skb' variable so that it will be used below for data
1911 		 * copying. We keep 'skb' for everything else, including
1912 		 * freeing both later.
1913 		 */
1914 		if (flags & MSG_CMSG_COMPAT)
1915 			data_skb = skb_shinfo(skb)->frag_list;
1916 	}
1917 #endif
1918 
1919 	/* Record the max length of recvmsg() calls for future allocations */
1920 	nlk->max_recvmsg_len = max(nlk->max_recvmsg_len, len);
1921 	nlk->max_recvmsg_len = min_t(size_t, nlk->max_recvmsg_len,
1922 				     SKB_WITH_OVERHEAD(32768));
1923 
1924 	copied = data_skb->len;
1925 	if (len < copied) {
1926 		msg->msg_flags |= MSG_TRUNC;
1927 		copied = len;
1928 	}
1929 
1930 	skb_reset_transport_header(data_skb);
1931 	err = skb_copy_datagram_msg(data_skb, 0, msg, copied);
1932 
1933 	if (msg->msg_name) {
1934 		DECLARE_SOCKADDR(struct sockaddr_nl *, addr, msg->msg_name);
1935 		addr->nl_family = AF_NETLINK;
1936 		addr->nl_pad    = 0;
1937 		addr->nl_pid	= NETLINK_CB(skb).portid;
1938 		addr->nl_groups	= netlink_group_mask(NETLINK_CB(skb).dst_group);
1939 		msg->msg_namelen = sizeof(*addr);
1940 	}
1941 
1942 	if (nlk->flags & NETLINK_F_RECV_PKTINFO)
1943 		netlink_cmsg_recv_pktinfo(msg, skb);
1944 	if (nlk->flags & NETLINK_F_LISTEN_ALL_NSID)
1945 		netlink_cmsg_listen_all_nsid(sk, msg, skb);
1946 
1947 	memset(&scm, 0, sizeof(scm));
1948 	scm.creds = *NETLINK_CREDS(skb);
1949 	if (flags & MSG_TRUNC)
1950 		copied = data_skb->len;
1951 
1952 	skb_free_datagram(sk, skb);
1953 
1954 	if (nlk->cb_running &&
1955 	    atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf / 2) {
1956 		ret = netlink_dump(sk);
1957 		if (ret) {
1958 			sk->sk_err = -ret;
1959 			sk->sk_error_report(sk);
1960 		}
1961 	}
1962 
1963 	scm_recv(sock, msg, &scm, flags);
1964 out:
1965 	netlink_rcv_wake(sk);
1966 	return err ? : copied;
1967 }
1968 
netlink_data_ready(struct sock * sk)1969 static void netlink_data_ready(struct sock *sk)
1970 {
1971 	BUG();
1972 }
1973 
1974 /*
1975  *	We export these functions to other modules. They provide a
1976  *	complete set of kernel non-blocking support for message
1977  *	queueing.
1978  */
1979 
1980 struct sock *
__netlink_kernel_create(struct net * net,int unit,struct module * module,struct netlink_kernel_cfg * cfg)1981 __netlink_kernel_create(struct net *net, int unit, struct module *module,
1982 			struct netlink_kernel_cfg *cfg)
1983 {
1984 	struct socket *sock;
1985 	struct sock *sk;
1986 	struct netlink_sock *nlk;
1987 	struct listeners *listeners = NULL;
1988 	struct mutex *cb_mutex = cfg ? cfg->cb_mutex : NULL;
1989 	unsigned int groups;
1990 
1991 	BUG_ON(!nl_table);
1992 
1993 	if (unit < 0 || unit >= MAX_LINKS)
1994 		return NULL;
1995 
1996 	if (sock_create_lite(PF_NETLINK, SOCK_DGRAM, unit, &sock))
1997 		return NULL;
1998 
1999 	if (__netlink_create(net, sock, cb_mutex, unit, 1) < 0)
2000 		goto out_sock_release_nosk;
2001 
2002 	sk = sock->sk;
2003 
2004 	if (!cfg || cfg->groups < 32)
2005 		groups = 32;
2006 	else
2007 		groups = cfg->groups;
2008 
2009 	listeners = kzalloc(sizeof(*listeners) + NLGRPSZ(groups), GFP_KERNEL);
2010 	if (!listeners)
2011 		goto out_sock_release;
2012 
2013 	sk->sk_data_ready = netlink_data_ready;
2014 	if (cfg && cfg->input)
2015 		nlk_sk(sk)->netlink_rcv = cfg->input;
2016 
2017 	if (netlink_insert(sk, 0))
2018 		goto out_sock_release;
2019 
2020 	nlk = nlk_sk(sk);
2021 	nlk->flags |= NETLINK_F_KERNEL_SOCKET;
2022 
2023 	netlink_table_grab();
2024 	if (!nl_table[unit].registered) {
2025 		nl_table[unit].groups = groups;
2026 		rcu_assign_pointer(nl_table[unit].listeners, listeners);
2027 		nl_table[unit].cb_mutex = cb_mutex;
2028 		nl_table[unit].module = module;
2029 		if (cfg) {
2030 			nl_table[unit].bind = cfg->bind;
2031 			nl_table[unit].unbind = cfg->unbind;
2032 			nl_table[unit].flags = cfg->flags;
2033 			if (cfg->compare)
2034 				nl_table[unit].compare = cfg->compare;
2035 		}
2036 		nl_table[unit].registered = 1;
2037 	} else {
2038 		kfree(listeners);
2039 		nl_table[unit].registered++;
2040 	}
2041 	netlink_table_ungrab();
2042 	return sk;
2043 
2044 out_sock_release:
2045 	kfree(listeners);
2046 	netlink_kernel_release(sk);
2047 	return NULL;
2048 
2049 out_sock_release_nosk:
2050 	sock_release(sock);
2051 	return NULL;
2052 }
2053 EXPORT_SYMBOL(__netlink_kernel_create);
2054 
2055 void
netlink_kernel_release(struct sock * sk)2056 netlink_kernel_release(struct sock *sk)
2057 {
2058 	if (sk == NULL || sk->sk_socket == NULL)
2059 		return;
2060 
2061 	sock_release(sk->sk_socket);
2062 }
2063 EXPORT_SYMBOL(netlink_kernel_release);
2064 
__netlink_change_ngroups(struct sock * sk,unsigned int groups)2065 int __netlink_change_ngroups(struct sock *sk, unsigned int groups)
2066 {
2067 	struct listeners *new, *old;
2068 	struct netlink_table *tbl = &nl_table[sk->sk_protocol];
2069 
2070 	if (groups < 32)
2071 		groups = 32;
2072 
2073 	if (NLGRPSZ(tbl->groups) < NLGRPSZ(groups)) {
2074 		new = kzalloc(sizeof(*new) + NLGRPSZ(groups), GFP_ATOMIC);
2075 		if (!new)
2076 			return -ENOMEM;
2077 		old = nl_deref_protected(tbl->listeners);
2078 		memcpy(new->masks, old->masks, NLGRPSZ(tbl->groups));
2079 		rcu_assign_pointer(tbl->listeners, new);
2080 
2081 		kfree_rcu(old, rcu);
2082 	}
2083 	tbl->groups = groups;
2084 
2085 	return 0;
2086 }
2087 
2088 /**
2089  * netlink_change_ngroups - change number of multicast groups
2090  *
2091  * This changes the number of multicast groups that are available
2092  * on a certain netlink family. Note that it is not possible to
2093  * change the number of groups to below 32. Also note that it does
2094  * not implicitly call netlink_clear_multicast_users() when the
2095  * number of groups is reduced.
2096  *
2097  * @sk: The kernel netlink socket, as returned by netlink_kernel_create().
2098  * @groups: The new number of groups.
2099  */
netlink_change_ngroups(struct sock * sk,unsigned int groups)2100 int netlink_change_ngroups(struct sock *sk, unsigned int groups)
2101 {
2102 	int err;
2103 
2104 	netlink_table_grab();
2105 	err = __netlink_change_ngroups(sk, groups);
2106 	netlink_table_ungrab();
2107 
2108 	return err;
2109 }
2110 
__netlink_clear_multicast_users(struct sock * ksk,unsigned int group)2111 void __netlink_clear_multicast_users(struct sock *ksk, unsigned int group)
2112 {
2113 	struct sock *sk;
2114 	struct netlink_table *tbl = &nl_table[ksk->sk_protocol];
2115 
2116 	sk_for_each_bound(sk, &tbl->mc_list)
2117 		netlink_update_socket_mc(nlk_sk(sk), group, 0);
2118 }
2119 
2120 struct nlmsghdr *
__nlmsg_put(struct sk_buff * skb,u32 portid,u32 seq,int type,int len,int flags)2121 __nlmsg_put(struct sk_buff *skb, u32 portid, u32 seq, int type, int len, int flags)
2122 {
2123 	struct nlmsghdr *nlh;
2124 	int size = nlmsg_msg_size(len);
2125 
2126 	nlh = (struct nlmsghdr *)skb_put(skb, NLMSG_ALIGN(size));
2127 	nlh->nlmsg_type = type;
2128 	nlh->nlmsg_len = size;
2129 	nlh->nlmsg_flags = flags;
2130 	nlh->nlmsg_pid = portid;
2131 	nlh->nlmsg_seq = seq;
2132 	if (!__builtin_constant_p(size) || NLMSG_ALIGN(size) - size != 0)
2133 		memset(nlmsg_data(nlh) + len, 0, NLMSG_ALIGN(size) - size);
2134 	return nlh;
2135 }
2136 EXPORT_SYMBOL(__nlmsg_put);
2137 
2138 /*
2139  * It looks a bit ugly.
2140  * It would be better to create kernel thread.
2141  */
2142 
netlink_dump(struct sock * sk)2143 static int netlink_dump(struct sock *sk)
2144 {
2145 	struct netlink_sock *nlk = nlk_sk(sk);
2146 	struct netlink_callback *cb;
2147 	struct sk_buff *skb = NULL;
2148 	struct nlmsghdr *nlh;
2149 	struct module *module;
2150 	int err = -ENOBUFS;
2151 	int alloc_min_size;
2152 	int alloc_size;
2153 
2154 	mutex_lock(nlk->cb_mutex);
2155 	if (!nlk->cb_running) {
2156 		err = -EINVAL;
2157 		goto errout_skb;
2158 	}
2159 
2160 	if (atomic_read(&sk->sk_rmem_alloc) >= sk->sk_rcvbuf)
2161 		goto errout_skb;
2162 
2163 	/* NLMSG_GOODSIZE is small to avoid high order allocations being
2164 	 * required, but it makes sense to _attempt_ a 16K bytes allocation
2165 	 * to reduce number of system calls on dump operations, if user
2166 	 * ever provided a big enough buffer.
2167 	 */
2168 	cb = &nlk->cb;
2169 	alloc_min_size = max_t(int, cb->min_dump_alloc, NLMSG_GOODSIZE);
2170 
2171 	if (alloc_min_size < nlk->max_recvmsg_len) {
2172 		alloc_size = nlk->max_recvmsg_len;
2173 		skb = netlink_alloc_skb(sk, alloc_size, nlk->portid,
2174 					(GFP_KERNEL & ~__GFP_DIRECT_RECLAIM) |
2175 					__GFP_NOWARN | __GFP_NORETRY);
2176 	}
2177 	if (!skb) {
2178 		alloc_size = alloc_min_size;
2179 		skb = netlink_alloc_skb(sk, alloc_size, nlk->portid,
2180 					GFP_KERNEL);
2181 	}
2182 	if (!skb)
2183 		goto errout_skb;
2184 
2185 	/* Trim skb to allocated size. User is expected to provide buffer as
2186 	 * large as max(min_dump_alloc, 16KiB (mac_recvmsg_len capped at
2187 	 * netlink_recvmsg())). dump will pack as many smaller messages as
2188 	 * could fit within the allocated skb. skb is typically allocated
2189 	 * with larger space than required (could be as much as near 2x the
2190 	 * requested size with align to next power of 2 approach). Allowing
2191 	 * dump to use the excess space makes it difficult for a user to have a
2192 	 * reasonable static buffer based on the expected largest dump of a
2193 	 * single netdev. The outcome is MSG_TRUNC error.
2194 	 */
2195 	skb_reserve(skb, skb_tailroom(skb) - alloc_size);
2196 	netlink_skb_set_owner_r(skb, sk);
2197 
2198 	if (nlk->dump_done_errno > 0)
2199 		nlk->dump_done_errno = cb->dump(skb, cb);
2200 
2201 	if (nlk->dump_done_errno > 0 ||
2202 	    skb_tailroom(skb) < nlmsg_total_size(sizeof(nlk->dump_done_errno))) {
2203 		mutex_unlock(nlk->cb_mutex);
2204 
2205 		if (sk_filter(sk, skb))
2206 			kfree_skb(skb);
2207 		else
2208 			__netlink_sendskb(sk, skb);
2209 		return 0;
2210 	}
2211 
2212 	nlh = nlmsg_put_answer(skb, cb, NLMSG_DONE,
2213 			       sizeof(nlk->dump_done_errno), NLM_F_MULTI);
2214 	if (WARN_ON(!nlh))
2215 		goto errout_skb;
2216 
2217 	nl_dump_check_consistent(cb, nlh);
2218 
2219 	memcpy(nlmsg_data(nlh), &nlk->dump_done_errno,
2220 	       sizeof(nlk->dump_done_errno));
2221 
2222 	if (sk_filter(sk, skb))
2223 		kfree_skb(skb);
2224 	else
2225 		__netlink_sendskb(sk, skb);
2226 
2227 	if (cb->done)
2228 		cb->done(cb);
2229 
2230 	nlk->cb_running = false;
2231 	module = cb->module;
2232 	skb = cb->skb;
2233 	mutex_unlock(nlk->cb_mutex);
2234 	module_put(module);
2235 	consume_skb(skb);
2236 	return 0;
2237 
2238 errout_skb:
2239 	mutex_unlock(nlk->cb_mutex);
2240 	kfree_skb(skb);
2241 	return err;
2242 }
2243 
__netlink_dump_start(struct sock * ssk,struct sk_buff * skb,const struct nlmsghdr * nlh,struct netlink_dump_control * control)2244 int __netlink_dump_start(struct sock *ssk, struct sk_buff *skb,
2245 			 const struct nlmsghdr *nlh,
2246 			 struct netlink_dump_control *control)
2247 {
2248 	struct netlink_callback *cb;
2249 	struct sock *sk;
2250 	struct netlink_sock *nlk;
2251 	int ret;
2252 
2253 	atomic_inc(&skb->users);
2254 
2255 	sk = netlink_lookup(sock_net(ssk), ssk->sk_protocol, NETLINK_CB(skb).portid);
2256 	if (sk == NULL) {
2257 		ret = -ECONNREFUSED;
2258 		goto error_free;
2259 	}
2260 
2261 	nlk = nlk_sk(sk);
2262 	mutex_lock(nlk->cb_mutex);
2263 	/* A dump is in progress... */
2264 	if (nlk->cb_running) {
2265 		ret = -EBUSY;
2266 		goto error_unlock;
2267 	}
2268 	/* add reference of module which cb->dump belongs to */
2269 	if (!try_module_get(control->module)) {
2270 		ret = -EPROTONOSUPPORT;
2271 		goto error_unlock;
2272 	}
2273 
2274 	cb = &nlk->cb;
2275 	memset(cb, 0, sizeof(*cb));
2276 	cb->start = control->start;
2277 	cb->dump = control->dump;
2278 	cb->done = control->done;
2279 	cb->nlh = nlh;
2280 	cb->data = control->data;
2281 	cb->module = control->module;
2282 	cb->min_dump_alloc = control->min_dump_alloc;
2283 	cb->skb = skb;
2284 
2285 	nlk->cb_running = true;
2286 	nlk->dump_done_errno = INT_MAX;
2287 
2288 	mutex_unlock(nlk->cb_mutex);
2289 
2290 	if (cb->start)
2291 		cb->start(cb);
2292 
2293 	ret = netlink_dump(sk);
2294 	sock_put(sk);
2295 
2296 	if (ret)
2297 		return ret;
2298 
2299 	/* We successfully started a dump, by returning -EINTR we
2300 	 * signal not to send ACK even if it was requested.
2301 	 */
2302 	return -EINTR;
2303 
2304 error_unlock:
2305 	sock_put(sk);
2306 	mutex_unlock(nlk->cb_mutex);
2307 error_free:
2308 	kfree_skb(skb);
2309 	return ret;
2310 }
2311 EXPORT_SYMBOL(__netlink_dump_start);
2312 
netlink_ack(struct sk_buff * in_skb,struct nlmsghdr * nlh,int err)2313 void netlink_ack(struct sk_buff *in_skb, struct nlmsghdr *nlh, int err)
2314 {
2315 	struct sk_buff *skb;
2316 	struct nlmsghdr *rep;
2317 	struct nlmsgerr *errmsg;
2318 	size_t payload = sizeof(*errmsg);
2319 	struct netlink_sock *nlk = nlk_sk(NETLINK_CB(in_skb).sk);
2320 
2321 	/* Error messages get the original request appened, unless the user
2322 	 * requests to cap the error message.
2323 	 */
2324 	if (!(nlk->flags & NETLINK_F_CAP_ACK) && err)
2325 		payload += nlmsg_len(nlh);
2326 
2327 	skb = netlink_alloc_skb(in_skb->sk, nlmsg_total_size(payload),
2328 				NETLINK_CB(in_skb).portid, GFP_KERNEL);
2329 	if (!skb) {
2330 		struct sock *sk;
2331 
2332 		sk = netlink_lookup(sock_net(in_skb->sk),
2333 				    in_skb->sk->sk_protocol,
2334 				    NETLINK_CB(in_skb).portid);
2335 		if (sk) {
2336 			sk->sk_err = ENOBUFS;
2337 			sk->sk_error_report(sk);
2338 			sock_put(sk);
2339 		}
2340 		return;
2341 	}
2342 
2343 	rep = __nlmsg_put(skb, NETLINK_CB(in_skb).portid, nlh->nlmsg_seq,
2344 			  NLMSG_ERROR, payload, 0);
2345 	errmsg = nlmsg_data(rep);
2346 	errmsg->error = err;
2347 	memcpy(&errmsg->msg, nlh, payload > sizeof(*errmsg) ? nlh->nlmsg_len : sizeof(*nlh));
2348 	netlink_unicast(in_skb->sk, skb, NETLINK_CB(in_skb).portid, MSG_DONTWAIT);
2349 }
2350 EXPORT_SYMBOL(netlink_ack);
2351 
netlink_rcv_skb(struct sk_buff * skb,int (* cb)(struct sk_buff *,struct nlmsghdr *))2352 int netlink_rcv_skb(struct sk_buff *skb, int (*cb)(struct sk_buff *,
2353 						     struct nlmsghdr *))
2354 {
2355 	struct nlmsghdr *nlh;
2356 	int err;
2357 
2358 	while (skb->len >= nlmsg_total_size(0)) {
2359 		int msglen;
2360 
2361 		nlh = nlmsg_hdr(skb);
2362 		err = 0;
2363 
2364 		if (nlh->nlmsg_len < NLMSG_HDRLEN || skb->len < nlh->nlmsg_len)
2365 			return 0;
2366 
2367 		/* Only requests are handled by the kernel */
2368 		if (!(nlh->nlmsg_flags & NLM_F_REQUEST))
2369 			goto ack;
2370 
2371 		/* Skip control messages */
2372 		if (nlh->nlmsg_type < NLMSG_MIN_TYPE)
2373 			goto ack;
2374 
2375 		err = cb(skb, nlh);
2376 		if (err == -EINTR)
2377 			goto skip;
2378 
2379 ack:
2380 		if (nlh->nlmsg_flags & NLM_F_ACK || err)
2381 			netlink_ack(skb, nlh, err);
2382 
2383 skip:
2384 		msglen = NLMSG_ALIGN(nlh->nlmsg_len);
2385 		if (msglen > skb->len)
2386 			msglen = skb->len;
2387 		skb_pull(skb, msglen);
2388 	}
2389 
2390 	return 0;
2391 }
2392 EXPORT_SYMBOL(netlink_rcv_skb);
2393 
2394 /**
2395  * nlmsg_notify - send a notification netlink message
2396  * @sk: netlink socket to use
2397  * @skb: notification message
2398  * @portid: destination netlink portid for reports or 0
2399  * @group: destination multicast group or 0
2400  * @report: 1 to report back, 0 to disable
2401  * @flags: allocation flags
2402  */
nlmsg_notify(struct sock * sk,struct sk_buff * skb,u32 portid,unsigned int group,int report,gfp_t flags)2403 int nlmsg_notify(struct sock *sk, struct sk_buff *skb, u32 portid,
2404 		 unsigned int group, int report, gfp_t flags)
2405 {
2406 	int err = 0;
2407 
2408 	if (group) {
2409 		int exclude_portid = 0;
2410 
2411 		if (report) {
2412 			atomic_inc(&skb->users);
2413 			exclude_portid = portid;
2414 		}
2415 
2416 		/* errors reported via destination sk->sk_err, but propagate
2417 		 * delivery errors if NETLINK_BROADCAST_ERROR flag is set */
2418 		err = nlmsg_multicast(sk, skb, exclude_portid, group, flags);
2419 		if (err == -ESRCH)
2420 			err = 0;
2421 	}
2422 
2423 	if (report) {
2424 		int err2;
2425 
2426 		err2 = nlmsg_unicast(sk, skb, portid);
2427 		if (!err)
2428 			err = err2;
2429 	}
2430 
2431 	return err;
2432 }
2433 EXPORT_SYMBOL(nlmsg_notify);
2434 
2435 #ifdef CONFIG_PROC_FS
2436 struct nl_seq_iter {
2437 	struct seq_net_private p;
2438 	struct rhashtable_iter hti;
2439 	int link;
2440 };
2441 
netlink_walk_start(struct nl_seq_iter * iter)2442 static int netlink_walk_start(struct nl_seq_iter *iter)
2443 {
2444 	int err;
2445 
2446 	err = rhashtable_walk_init(&nl_table[iter->link].hash, &iter->hti);
2447 	if (err) {
2448 		iter->link = MAX_LINKS;
2449 		return err;
2450 	}
2451 
2452 	err = rhashtable_walk_start(&iter->hti);
2453 	return err == -EAGAIN ? 0 : err;
2454 }
2455 
netlink_walk_stop(struct nl_seq_iter * iter)2456 static void netlink_walk_stop(struct nl_seq_iter *iter)
2457 {
2458 	rhashtable_walk_stop(&iter->hti);
2459 	rhashtable_walk_exit(&iter->hti);
2460 }
2461 
__netlink_seq_next(struct seq_file * seq)2462 static void *__netlink_seq_next(struct seq_file *seq)
2463 {
2464 	struct nl_seq_iter *iter = seq->private;
2465 	struct netlink_sock *nlk;
2466 
2467 	do {
2468 		for (;;) {
2469 			int err;
2470 
2471 			nlk = rhashtable_walk_next(&iter->hti);
2472 
2473 			if (IS_ERR(nlk)) {
2474 				if (PTR_ERR(nlk) == -EAGAIN)
2475 					continue;
2476 
2477 				return nlk;
2478 			}
2479 
2480 			if (nlk)
2481 				break;
2482 
2483 			netlink_walk_stop(iter);
2484 			if (++iter->link >= MAX_LINKS)
2485 				return NULL;
2486 
2487 			err = netlink_walk_start(iter);
2488 			if (err)
2489 				return ERR_PTR(err);
2490 		}
2491 	} while (sock_net(&nlk->sk) != seq_file_net(seq));
2492 
2493 	return nlk;
2494 }
2495 
netlink_seq_start(struct seq_file * seq,loff_t * posp)2496 static void *netlink_seq_start(struct seq_file *seq, loff_t *posp)
2497 {
2498 	struct nl_seq_iter *iter = seq->private;
2499 	void *obj = SEQ_START_TOKEN;
2500 	loff_t pos;
2501 	int err;
2502 
2503 	iter->link = 0;
2504 
2505 	err = netlink_walk_start(iter);
2506 	if (err)
2507 		return ERR_PTR(err);
2508 
2509 	for (pos = *posp; pos && obj && !IS_ERR(obj); pos--)
2510 		obj = __netlink_seq_next(seq);
2511 
2512 	return obj;
2513 }
2514 
netlink_seq_next(struct seq_file * seq,void * v,loff_t * pos)2515 static void *netlink_seq_next(struct seq_file *seq, void *v, loff_t *pos)
2516 {
2517 	++*pos;
2518 	return __netlink_seq_next(seq);
2519 }
2520 
netlink_seq_stop(struct seq_file * seq,void * v)2521 static void netlink_seq_stop(struct seq_file *seq, void *v)
2522 {
2523 	struct nl_seq_iter *iter = seq->private;
2524 
2525 	if (iter->link >= MAX_LINKS)
2526 		return;
2527 
2528 	netlink_walk_stop(iter);
2529 }
2530 
2531 
netlink_seq_show(struct seq_file * seq,void * v)2532 static int netlink_seq_show(struct seq_file *seq, void *v)
2533 {
2534 	if (v == SEQ_START_TOKEN) {
2535 		seq_puts(seq,
2536 			 "sk       Eth Pid    Groups   "
2537 			 "Rmem     Wmem     Dump     Locks     Drops     Inode\n");
2538 	} else {
2539 		struct sock *s = v;
2540 		struct netlink_sock *nlk = nlk_sk(s);
2541 
2542 		seq_printf(seq, "%pK %-3d %-6u %08x %-8d %-8d %d %-8d %-8d %-8lu\n",
2543 			   s,
2544 			   s->sk_protocol,
2545 			   nlk->portid,
2546 			   nlk->groups ? (u32)nlk->groups[0] : 0,
2547 			   sk_rmem_alloc_get(s),
2548 			   sk_wmem_alloc_get(s),
2549 			   nlk->cb_running,
2550 			   atomic_read(&s->sk_refcnt),
2551 			   atomic_read(&s->sk_drops),
2552 			   sock_i_ino(s)
2553 			);
2554 
2555 	}
2556 	return 0;
2557 }
2558 
2559 static const struct seq_operations netlink_seq_ops = {
2560 	.start  = netlink_seq_start,
2561 	.next   = netlink_seq_next,
2562 	.stop   = netlink_seq_stop,
2563 	.show   = netlink_seq_show,
2564 };
2565 
2566 
netlink_seq_open(struct inode * inode,struct file * file)2567 static int netlink_seq_open(struct inode *inode, struct file *file)
2568 {
2569 	return seq_open_net(inode, file, &netlink_seq_ops,
2570 				sizeof(struct nl_seq_iter));
2571 }
2572 
2573 static const struct file_operations netlink_seq_fops = {
2574 	.owner		= THIS_MODULE,
2575 	.open		= netlink_seq_open,
2576 	.read		= seq_read,
2577 	.llseek		= seq_lseek,
2578 	.release	= seq_release_net,
2579 };
2580 
2581 #endif
2582 
netlink_register_notifier(struct notifier_block * nb)2583 int netlink_register_notifier(struct notifier_block *nb)
2584 {
2585 	return atomic_notifier_chain_register(&netlink_chain, nb);
2586 }
2587 EXPORT_SYMBOL(netlink_register_notifier);
2588 
netlink_unregister_notifier(struct notifier_block * nb)2589 int netlink_unregister_notifier(struct notifier_block *nb)
2590 {
2591 	return atomic_notifier_chain_unregister(&netlink_chain, nb);
2592 }
2593 EXPORT_SYMBOL(netlink_unregister_notifier);
2594 
2595 static const struct proto_ops netlink_ops = {
2596 	.family =	PF_NETLINK,
2597 	.owner =	THIS_MODULE,
2598 	.release =	netlink_release,
2599 	.bind =		netlink_bind,
2600 	.connect =	netlink_connect,
2601 	.socketpair =	sock_no_socketpair,
2602 	.accept =	sock_no_accept,
2603 	.getname =	netlink_getname,
2604 	.poll =		datagram_poll,
2605 	.ioctl =	sock_no_ioctl,
2606 	.listen =	sock_no_listen,
2607 	.shutdown =	sock_no_shutdown,
2608 	.setsockopt =	netlink_setsockopt,
2609 	.getsockopt =	netlink_getsockopt,
2610 	.sendmsg =	netlink_sendmsg,
2611 	.recvmsg =	netlink_recvmsg,
2612 	.mmap =		sock_no_mmap,
2613 	.sendpage =	sock_no_sendpage,
2614 };
2615 
2616 static const struct net_proto_family netlink_family_ops = {
2617 	.family = PF_NETLINK,
2618 	.create = netlink_create,
2619 	.owner	= THIS_MODULE,	/* for consistency 8) */
2620 };
2621 
netlink_net_init(struct net * net)2622 static int __net_init netlink_net_init(struct net *net)
2623 {
2624 #ifdef CONFIG_PROC_FS
2625 	if (!proc_create("netlink", 0, net->proc_net, &netlink_seq_fops))
2626 		return -ENOMEM;
2627 #endif
2628 	return 0;
2629 }
2630 
netlink_net_exit(struct net * net)2631 static void __net_exit netlink_net_exit(struct net *net)
2632 {
2633 #ifdef CONFIG_PROC_FS
2634 	remove_proc_entry("netlink", net->proc_net);
2635 #endif
2636 }
2637 
netlink_add_usersock_entry(void)2638 static void __init netlink_add_usersock_entry(void)
2639 {
2640 	struct listeners *listeners;
2641 	int groups = 32;
2642 
2643 	listeners = kzalloc(sizeof(*listeners) + NLGRPSZ(groups), GFP_KERNEL);
2644 	if (!listeners)
2645 		panic("netlink_add_usersock_entry: Cannot allocate listeners\n");
2646 
2647 	netlink_table_grab();
2648 
2649 	nl_table[NETLINK_USERSOCK].groups = groups;
2650 	rcu_assign_pointer(nl_table[NETLINK_USERSOCK].listeners, listeners);
2651 	nl_table[NETLINK_USERSOCK].module = THIS_MODULE;
2652 	nl_table[NETLINK_USERSOCK].registered = 1;
2653 	nl_table[NETLINK_USERSOCK].flags = NL_CFG_F_NONROOT_SEND;
2654 
2655 	netlink_table_ungrab();
2656 }
2657 
2658 static struct pernet_operations __net_initdata netlink_net_ops = {
2659 	.init = netlink_net_init,
2660 	.exit = netlink_net_exit,
2661 };
2662 
netlink_hash(const void * data,u32 len,u32 seed)2663 static inline u32 netlink_hash(const void *data, u32 len, u32 seed)
2664 {
2665 	const struct netlink_sock *nlk = data;
2666 	struct netlink_compare_arg arg;
2667 
2668 	netlink_compare_arg_init(&arg, sock_net(&nlk->sk), nlk->portid);
2669 	return jhash2((u32 *)&arg, netlink_compare_arg_len / sizeof(u32), seed);
2670 }
2671 
2672 static const struct rhashtable_params netlink_rhashtable_params = {
2673 	.head_offset = offsetof(struct netlink_sock, node),
2674 	.key_len = netlink_compare_arg_len,
2675 	.obj_hashfn = netlink_hash,
2676 	.obj_cmpfn = netlink_compare,
2677 	.automatic_shrinking = true,
2678 };
2679 
netlink_proto_init(void)2680 static int __init netlink_proto_init(void)
2681 {
2682 	int i;
2683 	int err = proto_register(&netlink_proto, 0);
2684 
2685 	if (err != 0)
2686 		goto out;
2687 
2688 	BUILD_BUG_ON(sizeof(struct netlink_skb_parms) > FIELD_SIZEOF(struct sk_buff, cb));
2689 
2690 	nl_table = kcalloc(MAX_LINKS, sizeof(*nl_table), GFP_KERNEL);
2691 	if (!nl_table)
2692 		goto panic;
2693 
2694 	for (i = 0; i < MAX_LINKS; i++) {
2695 		if (rhashtable_init(&nl_table[i].hash,
2696 				    &netlink_rhashtable_params) < 0) {
2697 			while (--i > 0)
2698 				rhashtable_destroy(&nl_table[i].hash);
2699 			kfree(nl_table);
2700 			goto panic;
2701 		}
2702 	}
2703 
2704 	INIT_LIST_HEAD(&netlink_tap_all);
2705 
2706 	netlink_add_usersock_entry();
2707 
2708 	sock_register(&netlink_family_ops);
2709 	register_pernet_subsys(&netlink_net_ops);
2710 	/* The netlink device handler may be needed early. */
2711 	rtnetlink_init();
2712 out:
2713 	return err;
2714 panic:
2715 	panic("netlink_init: Cannot allocate nl_table\n");
2716 }
2717 
2718 core_initcall(netlink_proto_init);
2719