2 * NETLINK Kernel-user communication protocol.
4 * Authors: Alan Cox <alan@lxorguk.ukuu.org.uk>
5 * Alexey Kuznetsov <kuznet@ms2.inr.ac.ru>
6 * Patrick McHardy <kaber@trash.net>
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.
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
25 #include <linux/module.h>
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>
37 #include <linux/fcntl.h>
38 #include <linux/termios.h>
39 #include <linux/sockios.h>
40 #include <linux/net.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>
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>
67 #include <net/net_namespace.h>
70 #include <net/netlink.h>
72 #include "af_netlink.h"
76 unsigned long masks[0];
80 #define NETLINK_S_CONGESTED 0x0
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
90 static inline int netlink_is_kernel(struct sock *sk)
92 return nlk_sk(sk)->flags & NETLINK_F_KERNEL_SOCKET;
95 struct netlink_table *nl_table __read_mostly;
96 EXPORT_SYMBOL_GPL(nl_table);
98 static DECLARE_WAIT_QUEUE_HEAD(nl_table_wait);
100 static struct lock_class_key nlk_cb_mutex_keys[MAX_LINKS];
102 static const char *const nlk_cb_mutex_key_strings[MAX_LINKS + 1] = {
103 "nlk_cb_mutex-ROUTE",
105 "nlk_cb_mutex-USERSOCK",
106 "nlk_cb_mutex-FIREWALL",
107 "nlk_cb_mutex-SOCK_DIAG",
108 "nlk_cb_mutex-NFLOG",
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",
121 "nlk_cb_mutex-SCSITRANSPORT",
122 "nlk_cb_mutex-ECRYPTFS",
124 "nlk_cb_mutex-CRYPTO",
135 "nlk_cb_mutex-MAX_LINKS"
138 static int netlink_dump(struct sock *sk);
139 static void netlink_skb_destructor(struct sk_buff *skb);
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.
149 DEFINE_RWLOCK(nl_table_lock);
150 EXPORT_SYMBOL_GPL(nl_table_lock);
151 static atomic_t nl_table_users = ATOMIC_INIT(0);
153 #define nl_deref_protected(X) rcu_dereference_protected(X, lockdep_is_held(&nl_table_lock));
155 static ATOMIC_NOTIFIER_HEAD(netlink_chain);
157 static DEFINE_SPINLOCK(netlink_tap_lock);
158 static struct list_head netlink_tap_all __read_mostly;
160 static const struct rhashtable_params netlink_rhashtable_params;
162 static inline u32 netlink_group_mask(u32 group)
164 return group ? 1 << (group - 1) : 0;
167 static struct sk_buff *netlink_to_full_skb(const struct sk_buff *skb,
170 unsigned int len = skb_end_offset(skb);
173 new = alloc_skb(len, gfp_mask);
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;
181 memcpy(skb_put(new, len), skb->data, len);
185 int netlink_add_tap(struct netlink_tap *nt)
187 if (unlikely(nt->dev->type != ARPHRD_NETLINK))
190 spin_lock(&netlink_tap_lock);
191 list_add_rcu(&nt->list, &netlink_tap_all);
192 spin_unlock(&netlink_tap_lock);
194 __module_get(nt->module);
198 EXPORT_SYMBOL_GPL(netlink_add_tap);
200 static int __netlink_remove_tap(struct netlink_tap *nt)
203 struct netlink_tap *tmp;
205 spin_lock(&netlink_tap_lock);
207 list_for_each_entry(tmp, &netlink_tap_all, list) {
209 list_del_rcu(&nt->list);
215 pr_warn("__netlink_remove_tap: %p not found\n", nt);
217 spin_unlock(&netlink_tap_lock);
220 module_put(nt->module);
222 return found ? 0 : -ENODEV;
225 int netlink_remove_tap(struct netlink_tap *nt)
229 ret = __netlink_remove_tap(nt);
234 EXPORT_SYMBOL_GPL(netlink_remove_tap);
236 static bool netlink_filter_tap(const struct sk_buff *skb)
238 struct sock *sk = skb->sk;
240 /* We take the more conservative approach and
241 * whitelist socket protocols that may pass.
243 switch (sk->sk_protocol) {
245 case NETLINK_USERSOCK:
246 case NETLINK_SOCK_DIAG:
249 case NETLINK_FIB_LOOKUP:
250 case NETLINK_NETFILTER:
251 case NETLINK_GENERIC:
258 static int __netlink_deliver_tap_skb(struct sk_buff *skb,
259 struct net_device *dev)
261 struct sk_buff *nskb;
262 struct sock *sk = skb->sk;
265 if (!net_eq(dev_net(dev), sock_net(sk)))
270 if (is_vmalloc_addr(skb->head))
271 nskb = netlink_to_full_skb(skb, GFP_ATOMIC);
273 nskb = skb_clone(skb, GFP_ATOMIC);
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);
289 static void __netlink_deliver_tap(struct sk_buff *skb)
292 struct netlink_tap *tmp;
294 if (!netlink_filter_tap(skb))
297 list_for_each_entry_rcu(tmp, &netlink_tap_all, list) {
298 ret = __netlink_deliver_tap_skb(skb, tmp->dev);
304 static void netlink_deliver_tap(struct sk_buff *skb)
308 if (unlikely(!list_empty(&netlink_tap_all)))
309 __netlink_deliver_tap(skb);
314 static void netlink_deliver_tap_kernel(struct sock *dst, struct sock *src,
317 if (!(netlink_is_kernel(dst) && netlink_is_kernel(src)))
318 netlink_deliver_tap(skb);
321 static void netlink_overrun(struct sock *sk)
323 struct netlink_sock *nlk = nlk_sk(sk);
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);
332 atomic_inc(&sk->sk_drops);
335 static void netlink_rcv_wake(struct sock *sk)
337 struct netlink_sock *nlk = nlk_sk(sk);
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);
345 static void netlink_skb_destructor(struct sk_buff *skb)
347 if (is_vmalloc_addr(skb->head)) {
349 !atomic_dec_return(&(skb_shinfo(skb)->dataref)))
358 static void netlink_skb_set_owner_r(struct sk_buff *skb, struct sock *sk)
360 WARN_ON(skb->sk != NULL);
362 skb->destructor = netlink_skb_destructor;
363 atomic_add(skb->truesize, &sk->sk_rmem_alloc);
364 sk_mem_charge(sk, skb->truesize);
367 static void netlink_sock_destruct(struct sock *sk)
369 struct netlink_sock *nlk = nlk_sk(sk);
371 if (nlk->cb_running) {
373 nlk->cb.done(&nlk->cb);
374 module_put(nlk->cb.module);
375 kfree_skb(nlk->cb.skb);
378 skb_queue_purge(&sk->sk_receive_queue);
380 if (!sock_flag(sk, SOCK_DEAD)) {
381 printk(KERN_ERR "Freeing alive netlink socket %p\n", sk);
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);
390 static void netlink_sock_destruct_work(struct work_struct *work)
392 struct netlink_sock *nlk = container_of(work, struct netlink_sock,
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.
404 void netlink_table_grab(void)
405 __acquires(nl_table_lock)
409 write_lock_irq(&nl_table_lock);
411 if (atomic_read(&nl_table_users)) {
412 DECLARE_WAITQUEUE(wait, current);
414 add_wait_queue_exclusive(&nl_table_wait, &wait);
416 set_current_state(TASK_UNINTERRUPTIBLE);
417 if (atomic_read(&nl_table_users) == 0)
419 write_unlock_irq(&nl_table_lock);
421 write_lock_irq(&nl_table_lock);
424 __set_current_state(TASK_RUNNING);
425 remove_wait_queue(&nl_table_wait, &wait);
429 void netlink_table_ungrab(void)
430 __releases(nl_table_lock)
432 write_unlock_irq(&nl_table_lock);
433 wake_up(&nl_table_wait);
437 netlink_lock_table(void)
439 /* read_lock() synchronizes us to netlink_table_grab */
441 read_lock(&nl_table_lock);
442 atomic_inc(&nl_table_users);
443 read_unlock(&nl_table_lock);
447 netlink_unlock_table(void)
449 if (atomic_dec_and_test(&nl_table_users))
450 wake_up(&nl_table_wait);
453 struct netlink_compare_arg
459 /* Doing sizeof directly may yield 4 extra bytes on 64-bit. */
460 #define netlink_compare_arg_len \
461 (offsetof(struct netlink_compare_arg, portid) + sizeof(u32))
463 static inline int netlink_compare(struct rhashtable_compare_arg *arg,
466 const struct netlink_compare_arg *x = arg->key;
467 const struct netlink_sock *nlk = ptr;
469 return nlk->portid != x->portid ||
470 !net_eq(sock_net(&nlk->sk), read_pnet(&x->pnet));
473 static void netlink_compare_arg_init(struct netlink_compare_arg *arg,
474 struct net *net, u32 portid)
476 memset(arg, 0, sizeof(*arg));
477 write_pnet(&arg->pnet, net);
478 arg->portid = portid;
481 static struct sock *__netlink_lookup(struct netlink_table *table, u32 portid,
484 struct netlink_compare_arg arg;
486 netlink_compare_arg_init(&arg, net, portid);
487 return rhashtable_lookup_fast(&table->hash, &arg,
488 netlink_rhashtable_params);
491 static int __netlink_insert(struct netlink_table *table, struct sock *sk)
493 struct netlink_compare_arg arg;
495 netlink_compare_arg_init(&arg, sock_net(sk), nlk_sk(sk)->portid);
496 return rhashtable_lookup_insert_key(&table->hash, &arg,
498 netlink_rhashtable_params);
501 static struct sock *netlink_lookup(struct net *net, int protocol, u32 portid)
503 struct netlink_table *table = &nl_table[protocol];
507 sk = __netlink_lookup(table, portid, net);
515 static const struct proto_ops netlink_ops;
518 netlink_update_listeners(struct sock *sk)
520 struct netlink_table *tbl = &nl_table[sk->sk_protocol];
523 struct listeners *listeners;
525 listeners = nl_deref_protected(tbl->listeners);
529 for (i = 0; i < NLGRPLONGS(tbl->groups); i++) {
531 sk_for_each_bound(sk, &tbl->mc_list) {
532 if (i < NLGRPLONGS(nlk_sk(sk)->ngroups))
533 mask |= nlk_sk(sk)->groups[i];
535 listeners->masks[i] = mask;
537 /* this function is only called with the netlink table "grabbed", which
538 * makes sure updates are visible before bind or setsockopt return. */
541 static int netlink_insert(struct sock *sk, u32 portid)
543 struct netlink_table *table = &nl_table[sk->sk_protocol];
548 err = nlk_sk(sk)->portid == portid ? 0 : -EBUSY;
549 if (nlk_sk(sk)->bound)
553 if (BITS_PER_LONG > 32 &&
554 unlikely(atomic_read(&table->hash.nelems) >= UINT_MAX))
557 nlk_sk(sk)->portid = portid;
560 err = __netlink_insert(table, sk);
562 /* In case the hashtable backend returns with -EBUSY
563 * from here, it must not escape to the caller.
565 if (unlikely(err == -EBUSY))
573 /* We need to ensure that the socket is hashed and visible. */
575 nlk_sk(sk)->bound = portid;
582 static void netlink_remove(struct sock *sk)
584 struct netlink_table *table;
586 table = &nl_table[sk->sk_protocol];
587 if (!rhashtable_remove_fast(&table->hash, &nlk_sk(sk)->node,
588 netlink_rhashtable_params)) {
589 WARN_ON(atomic_read(&sk->sk_refcnt) == 1);
593 netlink_table_grab();
594 if (nlk_sk(sk)->subscriptions) {
595 __sk_del_bind_node(sk);
596 netlink_update_listeners(sk);
598 if (sk->sk_protocol == NETLINK_GENERIC)
599 atomic_inc(&genl_sk_destructing_cnt);
600 netlink_table_ungrab();
603 static struct proto netlink_proto = {
605 .owner = THIS_MODULE,
606 .obj_size = sizeof(struct netlink_sock),
609 static int __netlink_create(struct net *net, struct socket *sock,
610 struct mutex *cb_mutex, int protocol,
614 struct netlink_sock *nlk;
616 sock->ops = &netlink_ops;
618 sk = sk_alloc(net, PF_NETLINK, GFP_KERNEL, &netlink_proto, kern);
622 sock_init_data(sock, sk);
626 nlk->cb_mutex = cb_mutex;
628 nlk->cb_mutex = &nlk->cb_def_mutex;
629 mutex_init(nlk->cb_mutex);
630 lockdep_set_class_and_name(nlk->cb_mutex,
631 nlk_cb_mutex_keys + protocol,
632 nlk_cb_mutex_key_strings[protocol]);
634 init_waitqueue_head(&nlk->wait);
636 sk->sk_destruct = netlink_sock_destruct;
637 sk->sk_protocol = protocol;
641 static int netlink_create(struct net *net, struct socket *sock, int protocol,
644 struct module *module = NULL;
645 struct mutex *cb_mutex;
646 struct netlink_sock *nlk;
647 int (*bind)(struct net *net, int group);
648 void (*unbind)(struct net *net, int group);
651 sock->state = SS_UNCONNECTED;
653 if (sock->type != SOCK_RAW && sock->type != SOCK_DGRAM)
654 return -ESOCKTNOSUPPORT;
656 if (protocol < 0 || protocol >= MAX_LINKS)
657 return -EPROTONOSUPPORT;
658 protocol = array_index_nospec(protocol, MAX_LINKS);
660 netlink_lock_table();
661 #ifdef CONFIG_MODULES
662 if (!nl_table[protocol].registered) {
663 netlink_unlock_table();
664 request_module("net-pf-%d-proto-%d", PF_NETLINK, protocol);
665 netlink_lock_table();
668 if (nl_table[protocol].registered &&
669 try_module_get(nl_table[protocol].module))
670 module = nl_table[protocol].module;
672 err = -EPROTONOSUPPORT;
673 cb_mutex = nl_table[protocol].cb_mutex;
674 bind = nl_table[protocol].bind;
675 unbind = nl_table[protocol].unbind;
676 netlink_unlock_table();
681 err = __netlink_create(net, sock, cb_mutex, protocol, kern);
686 sock_prot_inuse_add(net, &netlink_proto, 1);
689 nlk = nlk_sk(sock->sk);
690 nlk->module = module;
691 nlk->netlink_bind = bind;
692 nlk->netlink_unbind = unbind;
701 static void deferred_put_nlk_sk(struct rcu_head *head)
703 struct netlink_sock *nlk = container_of(head, struct netlink_sock, rcu);
704 struct sock *sk = &nlk->sk;
706 if (!atomic_dec_and_test(&sk->sk_refcnt))
709 if (nlk->cb_running && nlk->cb.done) {
710 INIT_WORK(&nlk->work, netlink_sock_destruct_work);
711 schedule_work(&nlk->work);
718 static int netlink_release(struct socket *sock)
720 struct sock *sk = sock->sk;
721 struct netlink_sock *nlk;
731 * OK. Socket is unlinked, any packets that arrive now
735 /* must not acquire netlink_table_lock in any way again before unbind
736 * and notifying genetlink is done as otherwise it might deadlock
738 if (nlk->netlink_unbind) {
741 for (i = 0; i < nlk->ngroups; i++)
742 if (test_bit(i, nlk->groups))
743 nlk->netlink_unbind(sock_net(sk), i + 1);
745 if (sk->sk_protocol == NETLINK_GENERIC &&
746 atomic_dec_return(&genl_sk_destructing_cnt) == 0)
747 wake_up(&genl_sk_destructing_waitq);
750 wake_up_interruptible_all(&nlk->wait);
752 skb_queue_purge(&sk->sk_write_queue);
754 if (nlk->portid && nlk->bound) {
755 struct netlink_notify n = {
757 .protocol = sk->sk_protocol,
758 .portid = nlk->portid,
760 atomic_notifier_call_chain(&netlink_chain,
761 NETLINK_URELEASE, &n);
764 module_put(nlk->module);
766 if (netlink_is_kernel(sk)) {
767 netlink_table_grab();
768 BUG_ON(nl_table[sk->sk_protocol].registered == 0);
769 if (--nl_table[sk->sk_protocol].registered == 0) {
770 struct listeners *old;
772 old = nl_deref_protected(nl_table[sk->sk_protocol].listeners);
773 RCU_INIT_POINTER(nl_table[sk->sk_protocol].listeners, NULL);
775 nl_table[sk->sk_protocol].module = NULL;
776 nl_table[sk->sk_protocol].bind = NULL;
777 nl_table[sk->sk_protocol].unbind = NULL;
778 nl_table[sk->sk_protocol].flags = 0;
779 nl_table[sk->sk_protocol].registered = 0;
781 netlink_table_ungrab();
788 sock_prot_inuse_add(sock_net(sk), &netlink_proto, -1);
790 call_rcu(&nlk->rcu, deferred_put_nlk_sk);
794 static int netlink_autobind(struct socket *sock)
796 struct sock *sk = sock->sk;
797 struct net *net = sock_net(sk);
798 struct netlink_table *table = &nl_table[sk->sk_protocol];
799 s32 portid = task_tgid_vnr(current);
807 ok = !__netlink_lookup(table, portid, net);
810 /* Bind collision, search negative portid values. */
812 /* rover will be in range [S32_MIN, -4097] */
813 rover = S32_MIN + prandom_u32_max(-4096 - S32_MIN);
814 else if (rover >= -4096)
820 err = netlink_insert(sk, portid);
821 if (err == -EADDRINUSE)
824 /* If 2 threads race to autobind, that is fine. */
832 * __netlink_ns_capable - General netlink message capability test
833 * @nsp: NETLINK_CB of the socket buffer holding a netlink command from userspace.
834 * @user_ns: The user namespace of the capability to use
835 * @cap: The capability to use
837 * Test to see if the opener of the socket we received the message
838 * from had when the netlink socket was created and the sender of the
839 * message has has the capability @cap in the user namespace @user_ns.
841 bool __netlink_ns_capable(const struct netlink_skb_parms *nsp,
842 struct user_namespace *user_ns, int cap)
844 return ((nsp->flags & NETLINK_SKB_DST) ||
845 file_ns_capable(nsp->sk->sk_socket->file, user_ns, cap)) &&
846 ns_capable(user_ns, cap);
848 EXPORT_SYMBOL(__netlink_ns_capable);
851 * netlink_ns_capable - General netlink message capability test
852 * @skb: socket buffer holding a netlink command from userspace
853 * @user_ns: The user namespace of the capability to use
854 * @cap: The capability to use
856 * Test to see if the opener of the socket we received the message
857 * from had when the netlink socket was created and the sender of the
858 * message has has the capability @cap in the user namespace @user_ns.
860 bool netlink_ns_capable(const struct sk_buff *skb,
861 struct user_namespace *user_ns, int cap)
863 return __netlink_ns_capable(&NETLINK_CB(skb), user_ns, cap);
865 EXPORT_SYMBOL(netlink_ns_capable);
868 * netlink_capable - Netlink global message capability test
869 * @skb: socket buffer holding a netlink command from userspace
870 * @cap: The capability to use
872 * Test to see if the opener of the socket we received the message
873 * from had when the netlink socket was created and the sender of the
874 * message has has the capability @cap in all user namespaces.
876 bool netlink_capable(const struct sk_buff *skb, int cap)
878 return netlink_ns_capable(skb, &init_user_ns, cap);
880 EXPORT_SYMBOL(netlink_capable);
883 * netlink_net_capable - Netlink network namespace message capability test
884 * @skb: socket buffer holding a netlink command from userspace
885 * @cap: The capability to use
887 * Test to see if the opener of the socket we received the message
888 * from had when the netlink socket was created and the sender of the
889 * message has has the capability @cap over the network namespace of
890 * the socket we received the message from.
892 bool netlink_net_capable(const struct sk_buff *skb, int cap)
894 return netlink_ns_capable(skb, sock_net(skb->sk)->user_ns, cap);
896 EXPORT_SYMBOL(netlink_net_capable);
898 static inline int netlink_allowed(const struct socket *sock, unsigned int flag)
900 return (nl_table[sock->sk->sk_protocol].flags & flag) ||
901 ns_capable(sock_net(sock->sk)->user_ns, CAP_NET_ADMIN);
905 netlink_update_subscriptions(struct sock *sk, unsigned int subscriptions)
907 struct netlink_sock *nlk = nlk_sk(sk);
909 if (nlk->subscriptions && !subscriptions)
910 __sk_del_bind_node(sk);
911 else if (!nlk->subscriptions && subscriptions)
912 sk_add_bind_node(sk, &nl_table[sk->sk_protocol].mc_list);
913 nlk->subscriptions = subscriptions;
916 static int netlink_realloc_groups(struct sock *sk)
918 struct netlink_sock *nlk = nlk_sk(sk);
920 unsigned long *new_groups;
923 netlink_table_grab();
925 groups = nl_table[sk->sk_protocol].groups;
926 if (!nl_table[sk->sk_protocol].registered) {
931 if (nlk->ngroups >= groups)
934 new_groups = krealloc(nlk->groups, NLGRPSZ(groups), GFP_ATOMIC);
935 if (new_groups == NULL) {
939 memset((char *)new_groups + NLGRPSZ(nlk->ngroups), 0,
940 NLGRPSZ(groups) - NLGRPSZ(nlk->ngroups));
942 nlk->groups = new_groups;
943 nlk->ngroups = groups;
945 netlink_table_ungrab();
949 static void netlink_undo_bind(int group, long unsigned int groups,
952 struct netlink_sock *nlk = nlk_sk(sk);
955 if (!nlk->netlink_unbind)
958 for (undo = 0; undo < group; undo++)
959 if (test_bit(undo, &groups))
960 nlk->netlink_unbind(sock_net(sk), undo + 1);
963 static int netlink_bind(struct socket *sock, struct sockaddr *addr,
966 struct sock *sk = sock->sk;
967 struct net *net = sock_net(sk);
968 struct netlink_sock *nlk = nlk_sk(sk);
969 struct sockaddr_nl *nladdr = (struct sockaddr_nl *)addr;
971 long unsigned int groups = nladdr->nl_groups;
974 if (addr_len < sizeof(struct sockaddr_nl))
977 if (nladdr->nl_family != AF_NETLINK)
980 /* Only superuser is allowed to listen multicasts */
982 if (!netlink_allowed(sock, NL_CFG_F_NONROOT_RECV))
984 err = netlink_realloc_groups(sk);
991 /* Ensure nlk->portid is up-to-date. */
994 if (nladdr->nl_pid != nlk->portid)
998 if (nlk->netlink_bind && groups) {
1001 for (group = 0; group < nlk->ngroups; group++) {
1002 if (!test_bit(group, &groups))
1004 err = nlk->netlink_bind(net, group + 1);
1007 netlink_undo_bind(group, groups, sk);
1012 /* No need for barriers here as we return to user-space without
1013 * using any of the bound attributes.
1016 err = nladdr->nl_pid ?
1017 netlink_insert(sk, nladdr->nl_pid) :
1018 netlink_autobind(sock);
1020 netlink_undo_bind(nlk->ngroups, groups, sk);
1025 if (!groups && (nlk->groups == NULL || !(u32)nlk->groups[0]))
1028 netlink_table_grab();
1029 netlink_update_subscriptions(sk, nlk->subscriptions +
1031 hweight32(nlk->groups[0]));
1032 nlk->groups[0] = (nlk->groups[0] & ~0xffffffffUL) | groups;
1033 netlink_update_listeners(sk);
1034 netlink_table_ungrab();
1039 static int netlink_connect(struct socket *sock, struct sockaddr *addr,
1040 int alen, int flags)
1043 struct sock *sk = sock->sk;
1044 struct netlink_sock *nlk = nlk_sk(sk);
1045 struct sockaddr_nl *nladdr = (struct sockaddr_nl *)addr;
1047 if (alen < sizeof(addr->sa_family))
1050 if (addr->sa_family == AF_UNSPEC) {
1051 sk->sk_state = NETLINK_UNCONNECTED;
1052 nlk->dst_portid = 0;
1056 if (addr->sa_family != AF_NETLINK)
1059 if (alen < sizeof(struct sockaddr_nl))
1062 if ((nladdr->nl_groups || nladdr->nl_pid) &&
1063 !netlink_allowed(sock, NL_CFG_F_NONROOT_SEND))
1066 /* No need for barriers here as we return to user-space without
1067 * using any of the bound attributes.
1070 err = netlink_autobind(sock);
1073 sk->sk_state = NETLINK_CONNECTED;
1074 nlk->dst_portid = nladdr->nl_pid;
1075 nlk->dst_group = ffs(nladdr->nl_groups);
1081 static int netlink_getname(struct socket *sock, struct sockaddr *addr,
1082 int *addr_len, int peer)
1084 struct sock *sk = sock->sk;
1085 struct netlink_sock *nlk = nlk_sk(sk);
1086 DECLARE_SOCKADDR(struct sockaddr_nl *, nladdr, addr);
1088 nladdr->nl_family = AF_NETLINK;
1090 *addr_len = sizeof(*nladdr);
1093 nladdr->nl_pid = nlk->dst_portid;
1094 nladdr->nl_groups = netlink_group_mask(nlk->dst_group);
1096 nladdr->nl_pid = nlk->portid;
1097 nladdr->nl_groups = nlk->groups ? nlk->groups[0] : 0;
1102 static struct sock *netlink_getsockbyportid(struct sock *ssk, u32 portid)
1105 struct netlink_sock *nlk;
1107 sock = netlink_lookup(sock_net(ssk), ssk->sk_protocol, portid);
1109 return ERR_PTR(-ECONNREFUSED);
1111 /* Don't bother queuing skb if kernel socket has no input function */
1113 if (sock->sk_state == NETLINK_CONNECTED &&
1114 nlk->dst_portid != nlk_sk(ssk)->portid) {
1116 return ERR_PTR(-ECONNREFUSED);
1121 struct sock *netlink_getsockbyfilp(struct file *filp)
1123 struct inode *inode = file_inode(filp);
1126 if (!S_ISSOCK(inode->i_mode))
1127 return ERR_PTR(-ENOTSOCK);
1129 sock = SOCKET_I(inode)->sk;
1130 if (sock->sk_family != AF_NETLINK)
1131 return ERR_PTR(-EINVAL);
1137 static struct sk_buff *netlink_alloc_large_skb(unsigned int size,
1140 struct sk_buff *skb;
1143 if (size <= NLMSG_GOODSIZE || broadcast)
1144 return alloc_skb(size, GFP_KERNEL);
1146 size = SKB_DATA_ALIGN(size) +
1147 SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
1149 data = vmalloc(size);
1153 skb = __build_skb(data, size);
1157 skb->destructor = netlink_skb_destructor;
1163 * Attach a skb to a netlink socket.
1164 * The caller must hold a reference to the destination socket. On error, the
1165 * reference is dropped. The skb is not send to the destination, just all
1166 * all error checks are performed and memory in the queue is reserved.
1168 * < 0: error. skb freed, reference to sock dropped.
1170 * 1: repeat lookup - reference dropped while waiting for socket memory.
1172 int netlink_attachskb(struct sock *sk, struct sk_buff *skb,
1173 long *timeo, struct sock *ssk)
1175 struct netlink_sock *nlk;
1179 if ((atomic_read(&sk->sk_rmem_alloc) > sk->sk_rcvbuf ||
1180 test_bit(NETLINK_S_CONGESTED, &nlk->state))) {
1181 DECLARE_WAITQUEUE(wait, current);
1183 if (!ssk || netlink_is_kernel(ssk))
1184 netlink_overrun(sk);
1190 __set_current_state(TASK_INTERRUPTIBLE);
1191 add_wait_queue(&nlk->wait, &wait);
1193 if ((atomic_read(&sk->sk_rmem_alloc) > sk->sk_rcvbuf ||
1194 test_bit(NETLINK_S_CONGESTED, &nlk->state)) &&
1195 !sock_flag(sk, SOCK_DEAD))
1196 *timeo = schedule_timeout(*timeo);
1198 __set_current_state(TASK_RUNNING);
1199 remove_wait_queue(&nlk->wait, &wait);
1202 if (signal_pending(current)) {
1204 return sock_intr_errno(*timeo);
1208 netlink_skb_set_owner_r(skb, sk);
1212 static int __netlink_sendskb(struct sock *sk, struct sk_buff *skb)
1216 netlink_deliver_tap(skb);
1218 skb_queue_tail(&sk->sk_receive_queue, skb);
1219 sk->sk_data_ready(sk);
1223 int netlink_sendskb(struct sock *sk, struct sk_buff *skb)
1225 int len = __netlink_sendskb(sk, skb);
1231 void netlink_detachskb(struct sock *sk, struct sk_buff *skb)
1237 static struct sk_buff *netlink_trim(struct sk_buff *skb, gfp_t allocation)
1241 WARN_ON(skb->sk != NULL);
1242 delta = skb->end - skb->tail;
1243 if (is_vmalloc_addr(skb->head) || delta * 2 < skb->truesize)
1246 if (skb_shared(skb)) {
1247 struct sk_buff *nskb = skb_clone(skb, allocation);
1254 if (!pskb_expand_head(skb, 0, -delta, allocation))
1255 skb->truesize -= delta;
1260 static int netlink_unicast_kernel(struct sock *sk, struct sk_buff *skb,
1264 struct netlink_sock *nlk = nlk_sk(sk);
1266 ret = -ECONNREFUSED;
1267 if (nlk->netlink_rcv != NULL) {
1269 netlink_skb_set_owner_r(skb, sk);
1270 NETLINK_CB(skb).sk = ssk;
1271 netlink_deliver_tap_kernel(sk, ssk, skb);
1272 nlk->netlink_rcv(skb);
1281 int netlink_unicast(struct sock *ssk, struct sk_buff *skb,
1282 u32 portid, int nonblock)
1288 skb = netlink_trim(skb, gfp_any());
1290 timeo = sock_sndtimeo(ssk, nonblock);
1292 sk = netlink_getsockbyportid(ssk, portid);
1297 if (netlink_is_kernel(sk))
1298 return netlink_unicast_kernel(sk, skb, ssk);
1300 if (sk_filter(sk, skb)) {
1307 err = netlink_attachskb(sk, skb, &timeo, ssk);
1313 return netlink_sendskb(sk, skb);
1315 EXPORT_SYMBOL(netlink_unicast);
1317 struct sk_buff *__netlink_alloc_skb(struct sock *ssk, unsigned int size,
1318 unsigned int ldiff, u32 dst_portid,
1321 return alloc_skb(size, gfp_mask);
1323 EXPORT_SYMBOL_GPL(__netlink_alloc_skb);
1325 int netlink_has_listeners(struct sock *sk, unsigned int group)
1328 struct listeners *listeners;
1330 BUG_ON(!netlink_is_kernel(sk));
1333 listeners = rcu_dereference(nl_table[sk->sk_protocol].listeners);
1335 if (listeners && group - 1 < nl_table[sk->sk_protocol].groups)
1336 res = test_bit(group - 1, listeners->masks);
1342 EXPORT_SYMBOL_GPL(netlink_has_listeners);
1344 static int netlink_broadcast_deliver(struct sock *sk, struct sk_buff *skb)
1346 struct netlink_sock *nlk = nlk_sk(sk);
1348 if (atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf &&
1349 !test_bit(NETLINK_S_CONGESTED, &nlk->state)) {
1350 netlink_skb_set_owner_r(skb, sk);
1351 __netlink_sendskb(sk, skb);
1352 return atomic_read(&sk->sk_rmem_alloc) > (sk->sk_rcvbuf >> 1);
1357 struct netlink_broadcast_data {
1358 struct sock *exclude_sk;
1363 int delivery_failure;
1367 struct sk_buff *skb, *skb2;
1368 int (*tx_filter)(struct sock *dsk, struct sk_buff *skb, void *data);
1372 static void do_one_broadcast(struct sock *sk,
1373 struct netlink_broadcast_data *p)
1375 struct netlink_sock *nlk = nlk_sk(sk);
1378 if (p->exclude_sk == sk)
1381 if (nlk->portid == p->portid || p->group - 1 >= nlk->ngroups ||
1382 !test_bit(p->group - 1, nlk->groups))
1385 if (!net_eq(sock_net(sk), p->net)) {
1386 if (!(nlk->flags & NETLINK_F_LISTEN_ALL_NSID))
1389 if (!peernet_has_id(sock_net(sk), p->net))
1392 if (!file_ns_capable(sk->sk_socket->file, p->net->user_ns,
1398 netlink_overrun(sk);
1403 if (p->skb2 == NULL) {
1404 if (skb_shared(p->skb)) {
1405 p->skb2 = skb_clone(p->skb, p->allocation);
1407 p->skb2 = skb_get(p->skb);
1409 * skb ownership may have been set when
1410 * delivered to a previous socket.
1412 skb_orphan(p->skb2);
1415 if (p->skb2 == NULL) {
1416 netlink_overrun(sk);
1417 /* Clone failed. Notify ALL listeners. */
1419 if (nlk->flags & NETLINK_F_BROADCAST_SEND_ERROR)
1420 p->delivery_failure = 1;
1423 if (p->tx_filter && p->tx_filter(sk, p->skb2, p->tx_data)) {
1428 if (sk_filter(sk, p->skb2)) {
1433 NETLINK_CB(p->skb2).nsid = peernet2id(sock_net(sk), p->net);
1434 NETLINK_CB(p->skb2).nsid_is_set = true;
1435 val = netlink_broadcast_deliver(sk, p->skb2);
1437 netlink_overrun(sk);
1438 if (nlk->flags & NETLINK_F_BROADCAST_SEND_ERROR)
1439 p->delivery_failure = 1;
1441 p->congested |= val;
1449 int netlink_broadcast_filtered(struct sock *ssk, struct sk_buff *skb, u32 portid,
1450 u32 group, gfp_t allocation,
1451 int (*filter)(struct sock *dsk, struct sk_buff *skb, void *data),
1454 struct net *net = sock_net(ssk);
1455 struct netlink_broadcast_data info;
1458 skb = netlink_trim(skb, allocation);
1460 info.exclude_sk = ssk;
1462 info.portid = portid;
1465 info.delivery_failure = 0;
1468 info.allocation = allocation;
1471 info.tx_filter = filter;
1472 info.tx_data = filter_data;
1474 /* While we sleep in clone, do not allow to change socket list */
1476 netlink_lock_table();
1478 sk_for_each_bound(sk, &nl_table[ssk->sk_protocol].mc_list)
1479 do_one_broadcast(sk, &info);
1483 netlink_unlock_table();
1485 if (info.delivery_failure) {
1486 kfree_skb(info.skb2);
1489 consume_skb(info.skb2);
1491 if (info.delivered) {
1492 if (info.congested && gfpflags_allow_blocking(allocation))
1498 EXPORT_SYMBOL(netlink_broadcast_filtered);
1500 int netlink_broadcast(struct sock *ssk, struct sk_buff *skb, u32 portid,
1501 u32 group, gfp_t allocation)
1503 return netlink_broadcast_filtered(ssk, skb, portid, group, allocation,
1506 EXPORT_SYMBOL(netlink_broadcast);
1508 struct netlink_set_err_data {
1509 struct sock *exclude_sk;
1515 static int do_one_set_err(struct sock *sk, struct netlink_set_err_data *p)
1517 struct netlink_sock *nlk = nlk_sk(sk);
1520 if (sk == p->exclude_sk)
1523 if (!net_eq(sock_net(sk), sock_net(p->exclude_sk)))
1526 if (nlk->portid == p->portid || p->group - 1 >= nlk->ngroups ||
1527 !test_bit(p->group - 1, nlk->groups))
1530 if (p->code == ENOBUFS && nlk->flags & NETLINK_F_RECV_NO_ENOBUFS) {
1535 sk->sk_err = p->code;
1536 sk->sk_error_report(sk);
1542 * netlink_set_err - report error to broadcast listeners
1543 * @ssk: the kernel netlink socket, as returned by netlink_kernel_create()
1544 * @portid: the PORTID of a process that we want to skip (if any)
1545 * @group: the broadcast group that will notice the error
1546 * @code: error code, must be negative (as usual in kernelspace)
1548 * This function returns the number of broadcast listeners that have set the
1549 * NETLINK_NO_ENOBUFS socket option.
1551 int netlink_set_err(struct sock *ssk, u32 portid, u32 group, int code)
1553 struct netlink_set_err_data info;
1557 info.exclude_sk = ssk;
1558 info.portid = portid;
1560 /* sk->sk_err wants a positive error value */
1563 read_lock(&nl_table_lock);
1565 sk_for_each_bound(sk, &nl_table[ssk->sk_protocol].mc_list)
1566 ret += do_one_set_err(sk, &info);
1568 read_unlock(&nl_table_lock);
1571 EXPORT_SYMBOL(netlink_set_err);
1573 /* must be called with netlink table grabbed */
1574 static void netlink_update_socket_mc(struct netlink_sock *nlk,
1578 int old, new = !!is_new, subscriptions;
1580 old = test_bit(group - 1, nlk->groups);
1581 subscriptions = nlk->subscriptions - old + new;
1583 __set_bit(group - 1, nlk->groups);
1585 __clear_bit(group - 1, nlk->groups);
1586 netlink_update_subscriptions(&nlk->sk, subscriptions);
1587 netlink_update_listeners(&nlk->sk);
1590 static int netlink_setsockopt(struct socket *sock, int level, int optname,
1591 char __user *optval, unsigned int optlen)
1593 struct sock *sk = sock->sk;
1594 struct netlink_sock *nlk = nlk_sk(sk);
1595 unsigned int val = 0;
1598 if (level != SOL_NETLINK)
1599 return -ENOPROTOOPT;
1601 if (optlen >= sizeof(int) &&
1602 get_user(val, (unsigned int __user *)optval))
1606 case NETLINK_PKTINFO:
1608 nlk->flags |= NETLINK_F_RECV_PKTINFO;
1610 nlk->flags &= ~NETLINK_F_RECV_PKTINFO;
1613 case NETLINK_ADD_MEMBERSHIP:
1614 case NETLINK_DROP_MEMBERSHIP: {
1615 if (!netlink_allowed(sock, NL_CFG_F_NONROOT_RECV))
1617 err = netlink_realloc_groups(sk);
1620 if (!val || val - 1 >= nlk->ngroups)
1622 if (optname == NETLINK_ADD_MEMBERSHIP && nlk->netlink_bind) {
1623 err = nlk->netlink_bind(sock_net(sk), val);
1627 netlink_table_grab();
1628 netlink_update_socket_mc(nlk, val,
1629 optname == NETLINK_ADD_MEMBERSHIP);
1630 netlink_table_ungrab();
1631 if (optname == NETLINK_DROP_MEMBERSHIP && nlk->netlink_unbind)
1632 nlk->netlink_unbind(sock_net(sk), val);
1637 case NETLINK_BROADCAST_ERROR:
1639 nlk->flags |= NETLINK_F_BROADCAST_SEND_ERROR;
1641 nlk->flags &= ~NETLINK_F_BROADCAST_SEND_ERROR;
1644 case NETLINK_NO_ENOBUFS:
1646 nlk->flags |= NETLINK_F_RECV_NO_ENOBUFS;
1647 clear_bit(NETLINK_S_CONGESTED, &nlk->state);
1648 wake_up_interruptible(&nlk->wait);
1650 nlk->flags &= ~NETLINK_F_RECV_NO_ENOBUFS;
1654 case NETLINK_LISTEN_ALL_NSID:
1655 if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_BROADCAST))
1659 nlk->flags |= NETLINK_F_LISTEN_ALL_NSID;
1661 nlk->flags &= ~NETLINK_F_LISTEN_ALL_NSID;
1664 case NETLINK_CAP_ACK:
1666 nlk->flags |= NETLINK_F_CAP_ACK;
1668 nlk->flags &= ~NETLINK_F_CAP_ACK;
1677 static int netlink_getsockopt(struct socket *sock, int level, int optname,
1678 char __user *optval, int __user *optlen)
1680 struct sock *sk = sock->sk;
1681 struct netlink_sock *nlk = nlk_sk(sk);
1684 if (level != SOL_NETLINK)
1685 return -ENOPROTOOPT;
1687 if (get_user(len, optlen))
1693 case NETLINK_PKTINFO:
1694 if (len < sizeof(int))
1697 val = nlk->flags & NETLINK_F_RECV_PKTINFO ? 1 : 0;
1698 if (put_user(len, optlen) ||
1699 put_user(val, optval))
1703 case NETLINK_BROADCAST_ERROR:
1704 if (len < sizeof(int))
1707 val = nlk->flags & NETLINK_F_BROADCAST_SEND_ERROR ? 1 : 0;
1708 if (put_user(len, optlen) ||
1709 put_user(val, optval))
1713 case NETLINK_NO_ENOBUFS:
1714 if (len < sizeof(int))
1717 val = nlk->flags & NETLINK_F_RECV_NO_ENOBUFS ? 1 : 0;
1718 if (put_user(len, optlen) ||
1719 put_user(val, optval))
1723 case NETLINK_LIST_MEMBERSHIPS: {
1724 int pos, idx, shift;
1727 netlink_lock_table();
1728 for (pos = 0; pos * 8 < nlk->ngroups; pos += sizeof(u32)) {
1729 if (len - pos < sizeof(u32))
1732 idx = pos / sizeof(unsigned long);
1733 shift = (pos % sizeof(unsigned long)) * 8;
1734 if (put_user((u32)(nlk->groups[idx] >> shift),
1735 (u32 __user *)(optval + pos))) {
1740 if (put_user(ALIGN(nlk->ngroups / 8, sizeof(u32)), optlen))
1742 netlink_unlock_table();
1745 case NETLINK_CAP_ACK:
1746 if (len < sizeof(int))
1749 val = nlk->flags & NETLINK_F_CAP_ACK ? 1 : 0;
1750 if (put_user(len, optlen) ||
1751 put_user(val, optval))
1761 static void netlink_cmsg_recv_pktinfo(struct msghdr *msg, struct sk_buff *skb)
1763 struct nl_pktinfo info;
1765 info.group = NETLINK_CB(skb).dst_group;
1766 put_cmsg(msg, SOL_NETLINK, NETLINK_PKTINFO, sizeof(info), &info);
1769 static void netlink_cmsg_listen_all_nsid(struct sock *sk, struct msghdr *msg,
1770 struct sk_buff *skb)
1772 if (!NETLINK_CB(skb).nsid_is_set)
1775 put_cmsg(msg, SOL_NETLINK, NETLINK_LISTEN_ALL_NSID, sizeof(int),
1776 &NETLINK_CB(skb).nsid);
1779 static int netlink_sendmsg(struct socket *sock, struct msghdr *msg, size_t len)
1781 struct sock *sk = sock->sk;
1782 struct netlink_sock *nlk = nlk_sk(sk);
1783 DECLARE_SOCKADDR(struct sockaddr_nl *, addr, msg->msg_name);
1786 struct sk_buff *skb;
1788 struct scm_cookie scm;
1789 u32 netlink_skb_flags = 0;
1791 if (msg->msg_flags&MSG_OOB)
1794 err = scm_send(sock, msg, &scm, true);
1798 if (msg->msg_namelen) {
1800 if (msg->msg_namelen < sizeof(struct sockaddr_nl))
1802 if (addr->nl_family != AF_NETLINK)
1804 dst_portid = addr->nl_pid;
1805 dst_group = ffs(addr->nl_groups);
1807 if ((dst_group || dst_portid) &&
1808 !netlink_allowed(sock, NL_CFG_F_NONROOT_SEND))
1810 netlink_skb_flags |= NETLINK_SKB_DST;
1812 dst_portid = nlk->dst_portid;
1813 dst_group = nlk->dst_group;
1817 err = netlink_autobind(sock);
1821 /* Ensure nlk is hashed and visible. */
1826 if (len > sk->sk_sndbuf - 32)
1829 skb = netlink_alloc_large_skb(len, dst_group);
1833 NETLINK_CB(skb).portid = nlk->portid;
1834 NETLINK_CB(skb).dst_group = dst_group;
1835 NETLINK_CB(skb).creds = scm.creds;
1836 NETLINK_CB(skb).flags = netlink_skb_flags;
1839 if (memcpy_from_msg(skb_put(skb, len), msg, len)) {
1844 err = security_netlink_send(sk, skb);
1851 atomic_inc(&skb->users);
1852 netlink_broadcast(sk, skb, dst_portid, dst_group, GFP_KERNEL);
1854 err = netlink_unicast(sk, skb, dst_portid, msg->msg_flags&MSG_DONTWAIT);
1861 static int netlink_recvmsg(struct socket *sock, struct msghdr *msg, size_t len,
1864 struct scm_cookie scm;
1865 struct sock *sk = sock->sk;
1866 struct netlink_sock *nlk = nlk_sk(sk);
1867 int noblock = flags&MSG_DONTWAIT;
1869 struct sk_buff *skb, *data_skb;
1877 skb = skb_recv_datagram(sk, flags, noblock, &err);
1883 #ifdef CONFIG_COMPAT_NETLINK_MESSAGES
1884 if (unlikely(skb_shinfo(skb)->frag_list)) {
1886 * If this skb has a frag_list, then here that means that we
1887 * will have to use the frag_list skb's data for compat tasks
1888 * and the regular skb's data for normal (non-compat) tasks.
1890 * If we need to send the compat skb, assign it to the
1891 * 'data_skb' variable so that it will be used below for data
1892 * copying. We keep 'skb' for everything else, including
1893 * freeing both later.
1895 if (flags & MSG_CMSG_COMPAT)
1896 data_skb = skb_shinfo(skb)->frag_list;
1900 /* Record the max length of recvmsg() calls for future allocations */
1901 nlk->max_recvmsg_len = max(nlk->max_recvmsg_len, len);
1902 nlk->max_recvmsg_len = min_t(size_t, nlk->max_recvmsg_len,
1903 SKB_WITH_OVERHEAD(32768));
1905 copied = data_skb->len;
1907 msg->msg_flags |= MSG_TRUNC;
1911 skb_reset_transport_header(data_skb);
1912 err = skb_copy_datagram_msg(data_skb, 0, msg, copied);
1914 if (msg->msg_name) {
1915 DECLARE_SOCKADDR(struct sockaddr_nl *, addr, msg->msg_name);
1916 addr->nl_family = AF_NETLINK;
1918 addr->nl_pid = NETLINK_CB(skb).portid;
1919 addr->nl_groups = netlink_group_mask(NETLINK_CB(skb).dst_group);
1920 msg->msg_namelen = sizeof(*addr);
1923 if (nlk->flags & NETLINK_F_RECV_PKTINFO)
1924 netlink_cmsg_recv_pktinfo(msg, skb);
1925 if (nlk->flags & NETLINK_F_LISTEN_ALL_NSID)
1926 netlink_cmsg_listen_all_nsid(sk, msg, skb);
1928 memset(&scm, 0, sizeof(scm));
1929 scm.creds = *NETLINK_CREDS(skb);
1930 if (flags & MSG_TRUNC)
1931 copied = data_skb->len;
1933 skb_free_datagram(sk, skb);
1935 if (nlk->cb_running &&
1936 atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf / 2) {
1937 ret = netlink_dump(sk);
1940 sk->sk_error_report(sk);
1944 scm_recv(sock, msg, &scm, flags);
1946 netlink_rcv_wake(sk);
1947 return err ? : copied;
1950 static void netlink_data_ready(struct sock *sk)
1956 * We export these functions to other modules. They provide a
1957 * complete set of kernel non-blocking support for message
1962 __netlink_kernel_create(struct net *net, int unit, struct module *module,
1963 struct netlink_kernel_cfg *cfg)
1965 struct socket *sock;
1967 struct netlink_sock *nlk;
1968 struct listeners *listeners = NULL;
1969 struct mutex *cb_mutex = cfg ? cfg->cb_mutex : NULL;
1970 unsigned int groups;
1974 if (unit < 0 || unit >= MAX_LINKS)
1977 if (sock_create_lite(PF_NETLINK, SOCK_DGRAM, unit, &sock))
1980 if (__netlink_create(net, sock, cb_mutex, unit, 1) < 0)
1981 goto out_sock_release_nosk;
1985 if (!cfg || cfg->groups < 32)
1988 groups = cfg->groups;
1990 listeners = kzalloc(sizeof(*listeners) + NLGRPSZ(groups), GFP_KERNEL);
1992 goto out_sock_release;
1994 sk->sk_data_ready = netlink_data_ready;
1995 if (cfg && cfg->input)
1996 nlk_sk(sk)->netlink_rcv = cfg->input;
1998 if (netlink_insert(sk, 0))
1999 goto out_sock_release;
2002 nlk->flags |= NETLINK_F_KERNEL_SOCKET;
2004 netlink_table_grab();
2005 if (!nl_table[unit].registered) {
2006 nl_table[unit].groups = groups;
2007 rcu_assign_pointer(nl_table[unit].listeners, listeners);
2008 nl_table[unit].cb_mutex = cb_mutex;
2009 nl_table[unit].module = module;
2011 nl_table[unit].bind = cfg->bind;
2012 nl_table[unit].unbind = cfg->unbind;
2013 nl_table[unit].flags = cfg->flags;
2015 nl_table[unit].compare = cfg->compare;
2017 nl_table[unit].registered = 1;
2020 nl_table[unit].registered++;
2022 netlink_table_ungrab();
2027 netlink_kernel_release(sk);
2030 out_sock_release_nosk:
2034 EXPORT_SYMBOL(__netlink_kernel_create);
2037 netlink_kernel_release(struct sock *sk)
2039 if (sk == NULL || sk->sk_socket == NULL)
2042 sock_release(sk->sk_socket);
2044 EXPORT_SYMBOL(netlink_kernel_release);
2046 int __netlink_change_ngroups(struct sock *sk, unsigned int groups)
2048 struct listeners *new, *old;
2049 struct netlink_table *tbl = &nl_table[sk->sk_protocol];
2054 if (NLGRPSZ(tbl->groups) < NLGRPSZ(groups)) {
2055 new = kzalloc(sizeof(*new) + NLGRPSZ(groups), GFP_ATOMIC);
2058 old = nl_deref_protected(tbl->listeners);
2059 memcpy(new->masks, old->masks, NLGRPSZ(tbl->groups));
2060 rcu_assign_pointer(tbl->listeners, new);
2062 kfree_rcu(old, rcu);
2064 tbl->groups = groups;
2070 * netlink_change_ngroups - change number of multicast groups
2072 * This changes the number of multicast groups that are available
2073 * on a certain netlink family. Note that it is not possible to
2074 * change the number of groups to below 32. Also note that it does
2075 * not implicitly call netlink_clear_multicast_users() when the
2076 * number of groups is reduced.
2078 * @sk: The kernel netlink socket, as returned by netlink_kernel_create().
2079 * @groups: The new number of groups.
2081 int netlink_change_ngroups(struct sock *sk, unsigned int groups)
2085 netlink_table_grab();
2086 err = __netlink_change_ngroups(sk, groups);
2087 netlink_table_ungrab();
2092 void __netlink_clear_multicast_users(struct sock *ksk, unsigned int group)
2095 struct netlink_table *tbl = &nl_table[ksk->sk_protocol];
2097 sk_for_each_bound(sk, &tbl->mc_list)
2098 netlink_update_socket_mc(nlk_sk(sk), group, 0);
2102 __nlmsg_put(struct sk_buff *skb, u32 portid, u32 seq, int type, int len, int flags)
2104 struct nlmsghdr *nlh;
2105 int size = nlmsg_msg_size(len);
2107 nlh = (struct nlmsghdr *)skb_put(skb, NLMSG_ALIGN(size));
2108 nlh->nlmsg_type = type;
2109 nlh->nlmsg_len = size;
2110 nlh->nlmsg_flags = flags;
2111 nlh->nlmsg_pid = portid;
2112 nlh->nlmsg_seq = seq;
2113 if (!__builtin_constant_p(size) || NLMSG_ALIGN(size) - size != 0)
2114 memset(nlmsg_data(nlh) + len, 0, NLMSG_ALIGN(size) - size);
2117 EXPORT_SYMBOL(__nlmsg_put);
2120 * It looks a bit ugly.
2121 * It would be better to create kernel thread.
2124 static int netlink_dump(struct sock *sk)
2126 struct netlink_sock *nlk = nlk_sk(sk);
2127 struct netlink_callback *cb;
2128 struct sk_buff *skb = NULL;
2129 struct nlmsghdr *nlh;
2130 struct module *module;
2135 mutex_lock(nlk->cb_mutex);
2136 if (!nlk->cb_running) {
2141 if (atomic_read(&sk->sk_rmem_alloc) >= sk->sk_rcvbuf)
2144 /* NLMSG_GOODSIZE is small to avoid high order allocations being
2145 * required, but it makes sense to _attempt_ a 16K bytes allocation
2146 * to reduce number of system calls on dump operations, if user
2147 * ever provided a big enough buffer.
2150 alloc_min_size = max_t(int, cb->min_dump_alloc, NLMSG_GOODSIZE);
2152 if (alloc_min_size < nlk->max_recvmsg_len) {
2153 alloc_size = nlk->max_recvmsg_len;
2154 skb = netlink_alloc_skb(sk, alloc_size, nlk->portid,
2155 (GFP_KERNEL & ~__GFP_DIRECT_RECLAIM) |
2156 __GFP_NOWARN | __GFP_NORETRY);
2159 alloc_size = alloc_min_size;
2160 skb = netlink_alloc_skb(sk, alloc_size, nlk->portid,
2166 /* Trim skb to allocated size. User is expected to provide buffer as
2167 * large as max(min_dump_alloc, 16KiB (mac_recvmsg_len capped at
2168 * netlink_recvmsg())). dump will pack as many smaller messages as
2169 * could fit within the allocated skb. skb is typically allocated
2170 * with larger space than required (could be as much as near 2x the
2171 * requested size with align to next power of 2 approach). Allowing
2172 * dump to use the excess space makes it difficult for a user to have a
2173 * reasonable static buffer based on the expected largest dump of a
2174 * single netdev. The outcome is MSG_TRUNC error.
2176 skb_reserve(skb, skb_tailroom(skb) - alloc_size);
2177 netlink_skb_set_owner_r(skb, sk);
2179 if (nlk->dump_done_errno > 0)
2180 nlk->dump_done_errno = cb->dump(skb, cb);
2182 if (nlk->dump_done_errno > 0 ||
2183 skb_tailroom(skb) < nlmsg_total_size(sizeof(nlk->dump_done_errno))) {
2184 mutex_unlock(nlk->cb_mutex);
2186 if (sk_filter(sk, skb))
2189 __netlink_sendskb(sk, skb);
2193 nlh = nlmsg_put_answer(skb, cb, NLMSG_DONE,
2194 sizeof(nlk->dump_done_errno), NLM_F_MULTI);
2198 nl_dump_check_consistent(cb, nlh);
2200 memcpy(nlmsg_data(nlh), &nlk->dump_done_errno,
2201 sizeof(nlk->dump_done_errno));
2203 if (sk_filter(sk, skb))
2206 __netlink_sendskb(sk, skb);
2211 nlk->cb_running = false;
2212 module = cb->module;
2214 mutex_unlock(nlk->cb_mutex);
2220 mutex_unlock(nlk->cb_mutex);
2225 int __netlink_dump_start(struct sock *ssk, struct sk_buff *skb,
2226 const struct nlmsghdr *nlh,
2227 struct netlink_dump_control *control)
2229 struct netlink_callback *cb;
2231 struct netlink_sock *nlk;
2234 atomic_inc(&skb->users);
2236 sk = netlink_lookup(sock_net(ssk), ssk->sk_protocol, NETLINK_CB(skb).portid);
2238 ret = -ECONNREFUSED;
2243 mutex_lock(nlk->cb_mutex);
2244 /* A dump is in progress... */
2245 if (nlk->cb_running) {
2249 /* add reference of module which cb->dump belongs to */
2250 if (!try_module_get(control->module)) {
2251 ret = -EPROTONOSUPPORT;
2256 memset(cb, 0, sizeof(*cb));
2257 cb->start = control->start;
2258 cb->dump = control->dump;
2259 cb->done = control->done;
2261 cb->data = control->data;
2262 cb->module = control->module;
2263 cb->min_dump_alloc = control->min_dump_alloc;
2266 nlk->cb_running = true;
2267 nlk->dump_done_errno = INT_MAX;
2269 mutex_unlock(nlk->cb_mutex);
2274 ret = netlink_dump(sk);
2280 /* We successfully started a dump, by returning -EINTR we
2281 * signal not to send ACK even if it was requested.
2287 mutex_unlock(nlk->cb_mutex);
2292 EXPORT_SYMBOL(__netlink_dump_start);
2294 void netlink_ack(struct sk_buff *in_skb, struct nlmsghdr *nlh, int err)
2296 struct sk_buff *skb;
2297 struct nlmsghdr *rep;
2298 struct nlmsgerr *errmsg;
2299 size_t payload = sizeof(*errmsg);
2300 struct netlink_sock *nlk = nlk_sk(NETLINK_CB(in_skb).sk);
2302 /* Error messages get the original request appened, unless the user
2303 * requests to cap the error message.
2305 if (!(nlk->flags & NETLINK_F_CAP_ACK) && err)
2306 payload += nlmsg_len(nlh);
2308 skb = netlink_alloc_skb(in_skb->sk, nlmsg_total_size(payload),
2309 NETLINK_CB(in_skb).portid, GFP_KERNEL);
2313 sk = netlink_lookup(sock_net(in_skb->sk),
2314 in_skb->sk->sk_protocol,
2315 NETLINK_CB(in_skb).portid);
2317 sk->sk_err = ENOBUFS;
2318 sk->sk_error_report(sk);
2324 rep = __nlmsg_put(skb, NETLINK_CB(in_skb).portid, nlh->nlmsg_seq,
2325 NLMSG_ERROR, payload, 0);
2326 errmsg = nlmsg_data(rep);
2327 errmsg->error = err;
2328 memcpy(&errmsg->msg, nlh, payload > sizeof(*errmsg) ? nlh->nlmsg_len : sizeof(*nlh));
2329 netlink_unicast(in_skb->sk, skb, NETLINK_CB(in_skb).portid, MSG_DONTWAIT);
2331 EXPORT_SYMBOL(netlink_ack);
2333 int netlink_rcv_skb(struct sk_buff *skb, int (*cb)(struct sk_buff *,
2336 struct nlmsghdr *nlh;
2339 while (skb->len >= nlmsg_total_size(0)) {
2342 nlh = nlmsg_hdr(skb);
2345 if (nlh->nlmsg_len < NLMSG_HDRLEN || skb->len < nlh->nlmsg_len)
2348 /* Only requests are handled by the kernel */
2349 if (!(nlh->nlmsg_flags & NLM_F_REQUEST))
2352 /* Skip control messages */
2353 if (nlh->nlmsg_type < NLMSG_MIN_TYPE)
2361 if (nlh->nlmsg_flags & NLM_F_ACK || err)
2362 netlink_ack(skb, nlh, err);
2365 msglen = NLMSG_ALIGN(nlh->nlmsg_len);
2366 if (msglen > skb->len)
2368 skb_pull(skb, msglen);
2373 EXPORT_SYMBOL(netlink_rcv_skb);
2376 * nlmsg_notify - send a notification netlink message
2377 * @sk: netlink socket to use
2378 * @skb: notification message
2379 * @portid: destination netlink portid for reports or 0
2380 * @group: destination multicast group or 0
2381 * @report: 1 to report back, 0 to disable
2382 * @flags: allocation flags
2384 int nlmsg_notify(struct sock *sk, struct sk_buff *skb, u32 portid,
2385 unsigned int group, int report, gfp_t flags)
2390 int exclude_portid = 0;
2393 atomic_inc(&skb->users);
2394 exclude_portid = portid;
2397 /* errors reported via destination sk->sk_err, but propagate
2398 * delivery errors if NETLINK_BROADCAST_ERROR flag is set */
2399 err = nlmsg_multicast(sk, skb, exclude_portid, group, flags);
2405 err2 = nlmsg_unicast(sk, skb, portid);
2406 if (!err || err == -ESRCH)
2412 EXPORT_SYMBOL(nlmsg_notify);
2414 #ifdef CONFIG_PROC_FS
2415 struct nl_seq_iter {
2416 struct seq_net_private p;
2417 struct rhashtable_iter hti;
2421 static int netlink_walk_start(struct nl_seq_iter *iter)
2425 err = rhashtable_walk_init(&nl_table[iter->link].hash, &iter->hti);
2427 iter->link = MAX_LINKS;
2431 err = rhashtable_walk_start(&iter->hti);
2432 return err == -EAGAIN ? 0 : err;
2435 static void netlink_walk_stop(struct nl_seq_iter *iter)
2437 rhashtable_walk_stop(&iter->hti);
2438 rhashtable_walk_exit(&iter->hti);
2441 static void *__netlink_seq_next(struct seq_file *seq)
2443 struct nl_seq_iter *iter = seq->private;
2444 struct netlink_sock *nlk;
2450 nlk = rhashtable_walk_next(&iter->hti);
2453 if (PTR_ERR(nlk) == -EAGAIN)
2462 netlink_walk_stop(iter);
2463 if (++iter->link >= MAX_LINKS)
2466 err = netlink_walk_start(iter);
2468 return ERR_PTR(err);
2470 } while (sock_net(&nlk->sk) != seq_file_net(seq));
2475 static void *netlink_seq_start(struct seq_file *seq, loff_t *posp)
2477 struct nl_seq_iter *iter = seq->private;
2478 void *obj = SEQ_START_TOKEN;
2484 err = netlink_walk_start(iter);
2486 return ERR_PTR(err);
2488 for (pos = *posp; pos && obj && !IS_ERR(obj); pos--)
2489 obj = __netlink_seq_next(seq);
2494 static void *netlink_seq_next(struct seq_file *seq, void *v, loff_t *pos)
2497 return __netlink_seq_next(seq);
2500 static void netlink_seq_stop(struct seq_file *seq, void *v)
2502 struct nl_seq_iter *iter = seq->private;
2504 if (iter->link >= MAX_LINKS)
2507 netlink_walk_stop(iter);
2511 static int netlink_seq_show(struct seq_file *seq, void *v)
2513 if (v == SEQ_START_TOKEN) {
2515 "sk Eth Pid Groups "
2516 "Rmem Wmem Dump Locks Drops Inode\n");
2519 struct netlink_sock *nlk = nlk_sk(s);
2521 seq_printf(seq, "%pK %-3d %-6u %08x %-8d %-8d %d %-8d %-8d %-8lu\n",
2525 nlk->groups ? (u32)nlk->groups[0] : 0,
2526 sk_rmem_alloc_get(s),
2527 sk_wmem_alloc_get(s),
2529 atomic_read(&s->sk_refcnt),
2530 atomic_read(&s->sk_drops),
2538 static const struct seq_operations netlink_seq_ops = {
2539 .start = netlink_seq_start,
2540 .next = netlink_seq_next,
2541 .stop = netlink_seq_stop,
2542 .show = netlink_seq_show,
2546 static int netlink_seq_open(struct inode *inode, struct file *file)
2548 return seq_open_net(inode, file, &netlink_seq_ops,
2549 sizeof(struct nl_seq_iter));
2552 static const struct file_operations netlink_seq_fops = {
2553 .owner = THIS_MODULE,
2554 .open = netlink_seq_open,
2556 .llseek = seq_lseek,
2557 .release = seq_release_net,
2562 int netlink_register_notifier(struct notifier_block *nb)
2564 return atomic_notifier_chain_register(&netlink_chain, nb);
2566 EXPORT_SYMBOL(netlink_register_notifier);
2568 int netlink_unregister_notifier(struct notifier_block *nb)
2570 return atomic_notifier_chain_unregister(&netlink_chain, nb);
2572 EXPORT_SYMBOL(netlink_unregister_notifier);
2574 static const struct proto_ops netlink_ops = {
2575 .family = PF_NETLINK,
2576 .owner = THIS_MODULE,
2577 .release = netlink_release,
2578 .bind = netlink_bind,
2579 .connect = netlink_connect,
2580 .socketpair = sock_no_socketpair,
2581 .accept = sock_no_accept,
2582 .getname = netlink_getname,
2583 .poll = datagram_poll,
2584 .ioctl = sock_no_ioctl,
2585 .listen = sock_no_listen,
2586 .shutdown = sock_no_shutdown,
2587 .setsockopt = netlink_setsockopt,
2588 .getsockopt = netlink_getsockopt,
2589 .sendmsg = netlink_sendmsg,
2590 .recvmsg = netlink_recvmsg,
2591 .mmap = sock_no_mmap,
2592 .sendpage = sock_no_sendpage,
2595 static const struct net_proto_family netlink_family_ops = {
2596 .family = PF_NETLINK,
2597 .create = netlink_create,
2598 .owner = THIS_MODULE, /* for consistency 8) */
2601 static int __net_init netlink_net_init(struct net *net)
2603 #ifdef CONFIG_PROC_FS
2604 if (!proc_create("netlink", 0, net->proc_net, &netlink_seq_fops))
2610 static void __net_exit netlink_net_exit(struct net *net)
2612 #ifdef CONFIG_PROC_FS
2613 remove_proc_entry("netlink", net->proc_net);
2617 static void __init netlink_add_usersock_entry(void)
2619 struct listeners *listeners;
2622 listeners = kzalloc(sizeof(*listeners) + NLGRPSZ(groups), GFP_KERNEL);
2624 panic("netlink_add_usersock_entry: Cannot allocate listeners\n");
2626 netlink_table_grab();
2628 nl_table[NETLINK_USERSOCK].groups = groups;
2629 rcu_assign_pointer(nl_table[NETLINK_USERSOCK].listeners, listeners);
2630 nl_table[NETLINK_USERSOCK].module = THIS_MODULE;
2631 nl_table[NETLINK_USERSOCK].registered = 1;
2632 nl_table[NETLINK_USERSOCK].flags = NL_CFG_F_NONROOT_SEND;
2634 netlink_table_ungrab();
2637 static struct pernet_operations __net_initdata netlink_net_ops = {
2638 .init = netlink_net_init,
2639 .exit = netlink_net_exit,
2642 static inline u32 netlink_hash(const void *data, u32 len, u32 seed)
2644 const struct netlink_sock *nlk = data;
2645 struct netlink_compare_arg arg;
2647 netlink_compare_arg_init(&arg, sock_net(&nlk->sk), nlk->portid);
2648 return jhash2((u32 *)&arg, netlink_compare_arg_len / sizeof(u32), seed);
2651 static const struct rhashtable_params netlink_rhashtable_params = {
2652 .head_offset = offsetof(struct netlink_sock, node),
2653 .key_len = netlink_compare_arg_len,
2654 .obj_hashfn = netlink_hash,
2655 .obj_cmpfn = netlink_compare,
2656 .automatic_shrinking = true,
2659 static int __init netlink_proto_init(void)
2662 int err = proto_register(&netlink_proto, 0);
2667 BUILD_BUG_ON(sizeof(struct netlink_skb_parms) > FIELD_SIZEOF(struct sk_buff, cb));
2669 nl_table = kcalloc(MAX_LINKS, sizeof(*nl_table), GFP_KERNEL);
2673 for (i = 0; i < MAX_LINKS; i++) {
2674 if (rhashtable_init(&nl_table[i].hash,
2675 &netlink_rhashtable_params) < 0) {
2677 rhashtable_destroy(&nl_table[i].hash);
2683 INIT_LIST_HEAD(&netlink_tap_all);
2685 netlink_add_usersock_entry();
2687 sock_register(&netlink_family_ops);
2688 register_pernet_subsys(&netlink_net_ops);
2689 /* The netlink device handler may be needed early. */
2694 panic("netlink_init: Cannot allocate nl_table\n");
2697 core_initcall(netlink_proto_init);