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)
166 return group ? 1 << (group - 1) : 0;
169 static struct sk_buff *netlink_to_full_skb(const struct sk_buff *skb,
172 unsigned int len = skb_end_offset(skb);
175 new = alloc_skb(len, gfp_mask);
179 NETLINK_CB(new).portid = NETLINK_CB(skb).portid;
180 NETLINK_CB(new).dst_group = NETLINK_CB(skb).dst_group;
181 NETLINK_CB(new).creds = NETLINK_CB(skb).creds;
183 memcpy(skb_put(new, len), skb->data, len);
187 int netlink_add_tap(struct netlink_tap *nt)
189 if (unlikely(nt->dev->type != ARPHRD_NETLINK))
192 spin_lock(&netlink_tap_lock);
193 list_add_rcu(&nt->list, &netlink_tap_all);
194 spin_unlock(&netlink_tap_lock);
196 __module_get(nt->module);
200 EXPORT_SYMBOL_GPL(netlink_add_tap);
202 static int __netlink_remove_tap(struct netlink_tap *nt)
205 struct netlink_tap *tmp;
207 spin_lock(&netlink_tap_lock);
209 list_for_each_entry(tmp, &netlink_tap_all, list) {
211 list_del_rcu(&nt->list);
217 pr_warn("__netlink_remove_tap: %p not found\n", nt);
219 spin_unlock(&netlink_tap_lock);
222 module_put(nt->module);
224 return found ? 0 : -ENODEV;
227 int netlink_remove_tap(struct netlink_tap *nt)
231 ret = __netlink_remove_tap(nt);
236 EXPORT_SYMBOL_GPL(netlink_remove_tap);
238 static bool netlink_filter_tap(const struct sk_buff *skb)
240 struct sock *sk = skb->sk;
242 /* We take the more conservative approach and
243 * whitelist socket protocols that may pass.
245 switch (sk->sk_protocol) {
247 case NETLINK_USERSOCK:
248 case NETLINK_SOCK_DIAG:
251 case NETLINK_FIB_LOOKUP:
252 case NETLINK_NETFILTER:
253 case NETLINK_GENERIC:
260 static int __netlink_deliver_tap_skb(struct sk_buff *skb,
261 struct net_device *dev)
263 struct sk_buff *nskb;
264 struct sock *sk = skb->sk;
267 if (!net_eq(dev_net(dev), sock_net(sk)))
272 if (is_vmalloc_addr(skb->head))
273 nskb = netlink_to_full_skb(skb, GFP_ATOMIC);
275 nskb = skb_clone(skb, GFP_ATOMIC);
278 nskb->protocol = htons((u16) sk->sk_protocol);
279 nskb->pkt_type = netlink_is_kernel(sk) ?
280 PACKET_KERNEL : PACKET_USER;
281 skb_reset_network_header(nskb);
282 ret = dev_queue_xmit(nskb);
283 if (unlikely(ret > 0))
284 ret = net_xmit_errno(ret);
291 static void __netlink_deliver_tap(struct sk_buff *skb)
294 struct netlink_tap *tmp;
296 if (!netlink_filter_tap(skb))
299 list_for_each_entry_rcu(tmp, &netlink_tap_all, list) {
300 ret = __netlink_deliver_tap_skb(skb, tmp->dev);
306 static void netlink_deliver_tap(struct sk_buff *skb)
310 if (unlikely(!list_empty(&netlink_tap_all)))
311 __netlink_deliver_tap(skb);
316 static void netlink_deliver_tap_kernel(struct sock *dst, struct sock *src,
319 if (!(netlink_is_kernel(dst) && netlink_is_kernel(src)))
320 netlink_deliver_tap(skb);
323 static void netlink_overrun(struct sock *sk)
325 struct netlink_sock *nlk = nlk_sk(sk);
327 if (!(nlk->flags & NETLINK_F_RECV_NO_ENOBUFS)) {
328 if (!test_and_set_bit(NETLINK_S_CONGESTED,
329 &nlk_sk(sk)->state)) {
330 sk->sk_err = ENOBUFS;
331 sk->sk_error_report(sk);
334 atomic_inc(&sk->sk_drops);
337 static void netlink_rcv_wake(struct sock *sk)
339 struct netlink_sock *nlk = nlk_sk(sk);
341 if (skb_queue_empty(&sk->sk_receive_queue))
342 clear_bit(NETLINK_S_CONGESTED, &nlk->state);
343 if (!test_bit(NETLINK_S_CONGESTED, &nlk->state))
344 wake_up_interruptible(&nlk->wait);
347 static void netlink_skb_destructor(struct sk_buff *skb)
349 if (is_vmalloc_addr(skb->head)) {
351 !atomic_dec_return(&(skb_shinfo(skb)->dataref)))
360 static void netlink_skb_set_owner_r(struct sk_buff *skb, struct sock *sk)
362 WARN_ON(skb->sk != NULL);
364 skb->destructor = netlink_skb_destructor;
365 atomic_add(skb->truesize, &sk->sk_rmem_alloc);
366 sk_mem_charge(sk, skb->truesize);
369 static void netlink_sock_destruct(struct sock *sk)
371 struct netlink_sock *nlk = nlk_sk(sk);
373 if (nlk->cb_running) {
375 nlk->cb.done(&nlk->cb);
376 module_put(nlk->cb.module);
377 kfree_skb(nlk->cb.skb);
380 skb_queue_purge(&sk->sk_receive_queue);
382 if (!sock_flag(sk, SOCK_DEAD)) {
383 printk(KERN_ERR "Freeing alive netlink socket %p\n", sk);
387 WARN_ON(atomic_read(&sk->sk_rmem_alloc));
388 WARN_ON(atomic_read(&sk->sk_wmem_alloc));
389 WARN_ON(nlk_sk(sk)->groups);
392 static void netlink_sock_destruct_work(struct work_struct *work)
394 struct netlink_sock *nlk = container_of(work, struct netlink_sock,
400 /* This lock without WQ_FLAG_EXCLUSIVE is good on UP and it is _very_ bad on
401 * SMP. Look, when several writers sleep and reader wakes them up, all but one
402 * immediately hit write lock and grab all the cpus. Exclusive sleep solves
403 * this, _but_ remember, it adds useless work on UP machines.
406 void netlink_table_grab(void)
407 __acquires(nl_table_lock)
411 write_lock_irq(&nl_table_lock);
413 if (atomic_read(&nl_table_users)) {
414 DECLARE_WAITQUEUE(wait, current);
416 add_wait_queue_exclusive(&nl_table_wait, &wait);
418 set_current_state(TASK_UNINTERRUPTIBLE);
419 if (atomic_read(&nl_table_users) == 0)
421 write_unlock_irq(&nl_table_lock);
423 write_lock_irq(&nl_table_lock);
426 __set_current_state(TASK_RUNNING);
427 remove_wait_queue(&nl_table_wait, &wait);
431 void netlink_table_ungrab(void)
432 __releases(nl_table_lock)
434 write_unlock_irq(&nl_table_lock);
435 wake_up(&nl_table_wait);
439 netlink_lock_table(void)
443 /* read_lock() synchronizes us to netlink_table_grab */
445 read_lock_irqsave(&nl_table_lock, flags);
446 atomic_inc(&nl_table_users);
447 read_unlock_irqrestore(&nl_table_lock, flags);
451 netlink_unlock_table(void)
453 if (atomic_dec_and_test(&nl_table_users))
454 wake_up(&nl_table_wait);
457 struct netlink_compare_arg
463 /* Doing sizeof directly may yield 4 extra bytes on 64-bit. */
464 #define netlink_compare_arg_len \
465 (offsetof(struct netlink_compare_arg, portid) + sizeof(u32))
467 static inline int netlink_compare(struct rhashtable_compare_arg *arg,
470 const struct netlink_compare_arg *x = arg->key;
471 const struct netlink_sock *nlk = ptr;
473 return nlk->portid != x->portid ||
474 !net_eq(sock_net(&nlk->sk), read_pnet(&x->pnet));
477 static void netlink_compare_arg_init(struct netlink_compare_arg *arg,
478 struct net *net, u32 portid)
480 memset(arg, 0, sizeof(*arg));
481 write_pnet(&arg->pnet, net);
482 arg->portid = portid;
485 static struct sock *__netlink_lookup(struct netlink_table *table, u32 portid,
488 struct netlink_compare_arg arg;
490 netlink_compare_arg_init(&arg, net, portid);
491 return rhashtable_lookup_fast(&table->hash, &arg,
492 netlink_rhashtable_params);
495 static int __netlink_insert(struct netlink_table *table, struct sock *sk)
497 struct netlink_compare_arg arg;
499 netlink_compare_arg_init(&arg, sock_net(sk), nlk_sk(sk)->portid);
500 return rhashtable_lookup_insert_key(&table->hash, &arg,
502 netlink_rhashtable_params);
505 static struct sock *netlink_lookup(struct net *net, int protocol, u32 portid)
507 struct netlink_table *table = &nl_table[protocol];
511 sk = __netlink_lookup(table, portid, net);
519 static const struct proto_ops netlink_ops;
522 netlink_update_listeners(struct sock *sk)
524 struct netlink_table *tbl = &nl_table[sk->sk_protocol];
527 struct listeners *listeners;
529 listeners = nl_deref_protected(tbl->listeners);
533 for (i = 0; i < NLGRPLONGS(tbl->groups); i++) {
535 sk_for_each_bound(sk, &tbl->mc_list) {
536 if (i < NLGRPLONGS(nlk_sk(sk)->ngroups))
537 mask |= nlk_sk(sk)->groups[i];
539 listeners->masks[i] = mask;
541 /* this function is only called with the netlink table "grabbed", which
542 * makes sure updates are visible before bind or setsockopt return. */
545 static int netlink_insert(struct sock *sk, u32 portid)
547 struct netlink_table *table = &nl_table[sk->sk_protocol];
552 err = nlk_sk(sk)->portid == portid ? 0 : -EBUSY;
553 if (nlk_sk(sk)->bound)
557 if (BITS_PER_LONG > 32 &&
558 unlikely(atomic_read(&table->hash.nelems) >= UINT_MAX))
561 nlk_sk(sk)->portid = portid;
564 err = __netlink_insert(table, sk);
566 /* In case the hashtable backend returns with -EBUSY
567 * from here, it must not escape to the caller.
569 if (unlikely(err == -EBUSY))
577 /* We need to ensure that the socket is hashed and visible. */
579 /* Paired with lockless reads from netlink_bind(),
580 * netlink_connect() and netlink_sendmsg().
582 WRITE_ONCE(nlk_sk(sk)->bound, portid);
589 static void netlink_remove(struct sock *sk)
591 struct netlink_table *table;
593 table = &nl_table[sk->sk_protocol];
594 if (!rhashtable_remove_fast(&table->hash, &nlk_sk(sk)->node,
595 netlink_rhashtable_params)) {
596 WARN_ON(atomic_read(&sk->sk_refcnt) == 1);
600 netlink_table_grab();
601 if (nlk_sk(sk)->subscriptions) {
602 __sk_del_bind_node(sk);
603 netlink_update_listeners(sk);
605 if (sk->sk_protocol == NETLINK_GENERIC)
606 atomic_inc(&genl_sk_destructing_cnt);
607 netlink_table_ungrab();
610 static struct proto netlink_proto = {
612 .owner = THIS_MODULE,
613 .obj_size = sizeof(struct netlink_sock),
616 static int __netlink_create(struct net *net, struct socket *sock,
617 struct mutex *cb_mutex, int protocol,
621 struct netlink_sock *nlk;
623 sock->ops = &netlink_ops;
625 sk = sk_alloc(net, PF_NETLINK, GFP_KERNEL, &netlink_proto, kern);
629 sock_init_data(sock, sk);
633 nlk->cb_mutex = cb_mutex;
635 nlk->cb_mutex = &nlk->cb_def_mutex;
636 mutex_init(nlk->cb_mutex);
637 lockdep_set_class_and_name(nlk->cb_mutex,
638 nlk_cb_mutex_keys + protocol,
639 nlk_cb_mutex_key_strings[protocol]);
641 init_waitqueue_head(&nlk->wait);
643 sk->sk_destruct = netlink_sock_destruct;
644 sk->sk_protocol = protocol;
648 static int netlink_create(struct net *net, struct socket *sock, int protocol,
651 struct module *module = NULL;
652 struct mutex *cb_mutex;
653 struct netlink_sock *nlk;
654 int (*bind)(struct net *net, int group);
655 void (*unbind)(struct net *net, int group);
658 sock->state = SS_UNCONNECTED;
660 if (sock->type != SOCK_RAW && sock->type != SOCK_DGRAM)
661 return -ESOCKTNOSUPPORT;
663 if (protocol < 0 || protocol >= MAX_LINKS)
664 return -EPROTONOSUPPORT;
665 protocol = array_index_nospec(protocol, MAX_LINKS);
667 netlink_lock_table();
668 #ifdef CONFIG_MODULES
669 if (!nl_table[protocol].registered) {
670 netlink_unlock_table();
671 request_module("net-pf-%d-proto-%d", PF_NETLINK, protocol);
672 netlink_lock_table();
675 if (nl_table[protocol].registered &&
676 try_module_get(nl_table[protocol].module))
677 module = nl_table[protocol].module;
679 err = -EPROTONOSUPPORT;
680 cb_mutex = nl_table[protocol].cb_mutex;
681 bind = nl_table[protocol].bind;
682 unbind = nl_table[protocol].unbind;
683 netlink_unlock_table();
688 err = __netlink_create(net, sock, cb_mutex, protocol, kern);
693 sock_prot_inuse_add(net, &netlink_proto, 1);
696 nlk = nlk_sk(sock->sk);
697 nlk->module = module;
698 nlk->netlink_bind = bind;
699 nlk->netlink_unbind = unbind;
708 static void deferred_put_nlk_sk(struct rcu_head *head)
710 struct netlink_sock *nlk = container_of(head, struct netlink_sock, rcu);
711 struct sock *sk = &nlk->sk;
713 if (!atomic_dec_and_test(&sk->sk_refcnt))
716 if (nlk->cb_running && nlk->cb.done) {
717 INIT_WORK(&nlk->work, netlink_sock_destruct_work);
718 schedule_work(&nlk->work);
725 static int netlink_release(struct socket *sock)
727 struct sock *sk = sock->sk;
728 struct netlink_sock *nlk;
738 * OK. Socket is unlinked, any packets that arrive now
742 /* must not acquire netlink_table_lock in any way again before unbind
743 * and notifying genetlink is done as otherwise it might deadlock
745 if (nlk->netlink_unbind) {
748 for (i = 0; i < nlk->ngroups; i++)
749 if (test_bit(i, nlk->groups))
750 nlk->netlink_unbind(sock_net(sk), i + 1);
752 if (sk->sk_protocol == NETLINK_GENERIC &&
753 atomic_dec_return(&genl_sk_destructing_cnt) == 0)
754 wake_up(&genl_sk_destructing_waitq);
757 wake_up_interruptible_all(&nlk->wait);
759 skb_queue_purge(&sk->sk_write_queue);
761 if (nlk->portid && nlk->bound) {
762 struct netlink_notify n = {
764 .protocol = sk->sk_protocol,
765 .portid = nlk->portid,
767 atomic_notifier_call_chain(&netlink_chain,
768 NETLINK_URELEASE, &n);
771 module_put(nlk->module);
773 if (netlink_is_kernel(sk)) {
774 netlink_table_grab();
775 BUG_ON(nl_table[sk->sk_protocol].registered == 0);
776 if (--nl_table[sk->sk_protocol].registered == 0) {
777 struct listeners *old;
779 old = nl_deref_protected(nl_table[sk->sk_protocol].listeners);
780 RCU_INIT_POINTER(nl_table[sk->sk_protocol].listeners, NULL);
782 nl_table[sk->sk_protocol].module = NULL;
783 nl_table[sk->sk_protocol].bind = NULL;
784 nl_table[sk->sk_protocol].unbind = NULL;
785 nl_table[sk->sk_protocol].flags = 0;
786 nl_table[sk->sk_protocol].registered = 0;
788 netlink_table_ungrab();
795 sock_prot_inuse_add(sock_net(sk), &netlink_proto, -1);
797 call_rcu(&nlk->rcu, deferred_put_nlk_sk);
801 static int netlink_autobind(struct socket *sock)
803 struct sock *sk = sock->sk;
804 struct net *net = sock_net(sk);
805 struct netlink_table *table = &nl_table[sk->sk_protocol];
806 s32 portid = task_tgid_vnr(current);
814 ok = !__netlink_lookup(table, portid, net);
817 /* Bind collision, search negative portid values. */
819 /* rover will be in range [S32_MIN, -4097] */
820 rover = S32_MIN + prandom_u32_max(-4096 - S32_MIN);
821 else if (rover >= -4096)
827 err = netlink_insert(sk, portid);
828 if (err == -EADDRINUSE)
831 /* If 2 threads race to autobind, that is fine. */
839 * __netlink_ns_capable - General netlink message capability test
840 * @nsp: NETLINK_CB of the socket buffer holding a netlink command from userspace.
841 * @user_ns: The user namespace of the capability to use
842 * @cap: The capability to use
844 * Test to see if the opener of the socket we received the message
845 * from had when the netlink socket was created and the sender of the
846 * message has has the capability @cap in the user namespace @user_ns.
848 bool __netlink_ns_capable(const struct netlink_skb_parms *nsp,
849 struct user_namespace *user_ns, int cap)
851 return ((nsp->flags & NETLINK_SKB_DST) ||
852 file_ns_capable(nsp->sk->sk_socket->file, user_ns, cap)) &&
853 ns_capable(user_ns, cap);
855 EXPORT_SYMBOL(__netlink_ns_capable);
858 * netlink_ns_capable - General netlink message capability test
859 * @skb: socket buffer holding a netlink command from userspace
860 * @user_ns: The user namespace of the capability to use
861 * @cap: The capability to use
863 * Test to see if the opener of the socket we received the message
864 * from had when the netlink socket was created and the sender of the
865 * message has has the capability @cap in the user namespace @user_ns.
867 bool netlink_ns_capable(const struct sk_buff *skb,
868 struct user_namespace *user_ns, int cap)
870 return __netlink_ns_capable(&NETLINK_CB(skb), user_ns, cap);
872 EXPORT_SYMBOL(netlink_ns_capable);
875 * netlink_capable - Netlink global message capability test
876 * @skb: socket buffer holding a netlink command from userspace
877 * @cap: The capability to use
879 * Test to see if the opener of the socket we received the message
880 * from had when the netlink socket was created and the sender of the
881 * message has has the capability @cap in all user namespaces.
883 bool netlink_capable(const struct sk_buff *skb, int cap)
885 return netlink_ns_capable(skb, &init_user_ns, cap);
887 EXPORT_SYMBOL(netlink_capable);
890 * netlink_net_capable - Netlink network namespace message capability test
891 * @skb: socket buffer holding a netlink command from userspace
892 * @cap: The capability to use
894 * Test to see if the opener of the socket we received the message
895 * from had when the netlink socket was created and the sender of the
896 * message has has the capability @cap over the network namespace of
897 * the socket we received the message from.
899 bool netlink_net_capable(const struct sk_buff *skb, int cap)
901 return netlink_ns_capable(skb, sock_net(skb->sk)->user_ns, cap);
903 EXPORT_SYMBOL(netlink_net_capable);
905 static inline int netlink_allowed(const struct socket *sock, unsigned int flag)
907 return (nl_table[sock->sk->sk_protocol].flags & flag) ||
908 ns_capable(sock_net(sock->sk)->user_ns, CAP_NET_ADMIN);
912 netlink_update_subscriptions(struct sock *sk, unsigned int subscriptions)
914 struct netlink_sock *nlk = nlk_sk(sk);
916 if (nlk->subscriptions && !subscriptions)
917 __sk_del_bind_node(sk);
918 else if (!nlk->subscriptions && subscriptions)
919 sk_add_bind_node(sk, &nl_table[sk->sk_protocol].mc_list);
920 nlk->subscriptions = subscriptions;
923 static int netlink_realloc_groups(struct sock *sk)
925 struct netlink_sock *nlk = nlk_sk(sk);
927 unsigned long *new_groups;
930 netlink_table_grab();
932 groups = nl_table[sk->sk_protocol].groups;
933 if (!nl_table[sk->sk_protocol].registered) {
938 if (nlk->ngroups >= groups)
941 new_groups = krealloc(nlk->groups, NLGRPSZ(groups), GFP_ATOMIC);
942 if (new_groups == NULL) {
946 memset((char *)new_groups + NLGRPSZ(nlk->ngroups), 0,
947 NLGRPSZ(groups) - NLGRPSZ(nlk->ngroups));
949 nlk->groups = new_groups;
950 nlk->ngroups = groups;
952 netlink_table_ungrab();
956 static void netlink_undo_bind(int group, long unsigned int groups,
959 struct netlink_sock *nlk = nlk_sk(sk);
962 if (!nlk->netlink_unbind)
965 for (undo = 0; undo < group; undo++)
966 if (test_bit(undo, &groups))
967 nlk->netlink_unbind(sock_net(sk), undo + 1);
970 static int netlink_bind(struct socket *sock, struct sockaddr *addr,
973 struct sock *sk = sock->sk;
974 struct net *net = sock_net(sk);
975 struct netlink_sock *nlk = nlk_sk(sk);
976 struct sockaddr_nl *nladdr = (struct sockaddr_nl *)addr;
978 long unsigned int groups = nladdr->nl_groups;
981 if (addr_len < sizeof(struct sockaddr_nl))
984 if (nladdr->nl_family != AF_NETLINK)
987 /* Only superuser is allowed to listen multicasts */
989 if (!netlink_allowed(sock, NL_CFG_F_NONROOT_RECV))
991 err = netlink_realloc_groups(sk);
996 if (nlk->ngroups == 0)
998 else if (nlk->ngroups < 8*sizeof(groups))
999 groups &= (1UL << nlk->ngroups) - 1;
1001 /* Paired with WRITE_ONCE() in netlink_insert() */
1002 bound = READ_ONCE(nlk->bound);
1004 /* Ensure nlk->portid is up-to-date. */
1007 if (nladdr->nl_pid != nlk->portid)
1011 if (nlk->netlink_bind && groups) {
1014 /* nl_groups is a u32, so cap the maximum groups we can bind */
1015 for (group = 0; group < BITS_PER_TYPE(u32); group++) {
1016 if (!test_bit(group, &groups))
1018 err = nlk->netlink_bind(net, group + 1);
1021 netlink_undo_bind(group, groups, sk);
1026 /* No need for barriers here as we return to user-space without
1027 * using any of the bound attributes.
1030 err = nladdr->nl_pid ?
1031 netlink_insert(sk, nladdr->nl_pid) :
1032 netlink_autobind(sock);
1034 netlink_undo_bind(BITS_PER_TYPE(u32), groups, sk);
1039 if (!groups && (nlk->groups == NULL || !(u32)nlk->groups[0]))
1042 netlink_table_grab();
1043 netlink_update_subscriptions(sk, nlk->subscriptions +
1045 hweight32(nlk->groups[0]));
1046 nlk->groups[0] = (nlk->groups[0] & ~0xffffffffUL) | groups;
1047 netlink_update_listeners(sk);
1048 netlink_table_ungrab();
1053 static int netlink_connect(struct socket *sock, struct sockaddr *addr,
1054 int alen, int flags)
1057 struct sock *sk = sock->sk;
1058 struct netlink_sock *nlk = nlk_sk(sk);
1059 struct sockaddr_nl *nladdr = (struct sockaddr_nl *)addr;
1061 if (alen < sizeof(addr->sa_family))
1064 if (addr->sa_family == AF_UNSPEC) {
1065 sk->sk_state = NETLINK_UNCONNECTED;
1066 nlk->dst_portid = 0;
1070 if (addr->sa_family != AF_NETLINK)
1073 if (alen < sizeof(struct sockaddr_nl))
1076 if ((nladdr->nl_groups || nladdr->nl_pid) &&
1077 !netlink_allowed(sock, NL_CFG_F_NONROOT_SEND))
1080 /* No need for barriers here as we return to user-space without
1081 * using any of the bound attributes.
1082 * Paired with WRITE_ONCE() in netlink_insert().
1084 if (!READ_ONCE(nlk->bound))
1085 err = netlink_autobind(sock);
1088 sk->sk_state = NETLINK_CONNECTED;
1089 nlk->dst_portid = nladdr->nl_pid;
1090 nlk->dst_group = ffs(nladdr->nl_groups);
1096 static int netlink_getname(struct socket *sock, struct sockaddr *addr,
1097 int *addr_len, int peer)
1099 struct sock *sk = sock->sk;
1100 struct netlink_sock *nlk = nlk_sk(sk);
1101 DECLARE_SOCKADDR(struct sockaddr_nl *, nladdr, addr);
1103 nladdr->nl_family = AF_NETLINK;
1105 *addr_len = sizeof(*nladdr);
1108 nladdr->nl_pid = nlk->dst_portid;
1109 nladdr->nl_groups = netlink_group_mask(nlk->dst_group);
1111 nladdr->nl_pid = nlk->portid;
1112 nladdr->nl_groups = nlk->groups ? nlk->groups[0] : 0;
1117 static int netlink_ioctl(struct socket *sock, unsigned int cmd,
1120 /* try to hand this ioctl down to the NIC drivers.
1122 return -ENOIOCTLCMD;
1125 static struct sock *netlink_getsockbyportid(struct sock *ssk, u32 portid)
1128 struct netlink_sock *nlk;
1130 sock = netlink_lookup(sock_net(ssk), ssk->sk_protocol, portid);
1132 return ERR_PTR(-ECONNREFUSED);
1134 /* Don't bother queuing skb if kernel socket has no input function */
1136 if (sock->sk_state == NETLINK_CONNECTED &&
1137 nlk->dst_portid != nlk_sk(ssk)->portid) {
1139 return ERR_PTR(-ECONNREFUSED);
1144 struct sock *netlink_getsockbyfilp(struct file *filp)
1146 struct inode *inode = file_inode(filp);
1149 if (!S_ISSOCK(inode->i_mode))
1150 return ERR_PTR(-ENOTSOCK);
1152 sock = SOCKET_I(inode)->sk;
1153 if (sock->sk_family != AF_NETLINK)
1154 return ERR_PTR(-EINVAL);
1160 static struct sk_buff *netlink_alloc_large_skb(unsigned int size,
1163 struct sk_buff *skb;
1166 if (size <= NLMSG_GOODSIZE || broadcast)
1167 return alloc_skb(size, GFP_KERNEL);
1169 size = SKB_DATA_ALIGN(size) +
1170 SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
1172 data = vmalloc(size);
1176 skb = __build_skb(data, size);
1180 skb->destructor = netlink_skb_destructor;
1186 * Attach a skb to a netlink socket.
1187 * The caller must hold a reference to the destination socket. On error, the
1188 * reference is dropped. The skb is not send to the destination, just all
1189 * all error checks are performed and memory in the queue is reserved.
1191 * < 0: error. skb freed, reference to sock dropped.
1193 * 1: repeat lookup - reference dropped while waiting for socket memory.
1195 int netlink_attachskb(struct sock *sk, struct sk_buff *skb,
1196 long *timeo, struct sock *ssk)
1198 struct netlink_sock *nlk;
1202 if ((atomic_read(&sk->sk_rmem_alloc) > sk->sk_rcvbuf ||
1203 test_bit(NETLINK_S_CONGESTED, &nlk->state))) {
1204 DECLARE_WAITQUEUE(wait, current);
1206 if (!ssk || netlink_is_kernel(ssk))
1207 netlink_overrun(sk);
1213 __set_current_state(TASK_INTERRUPTIBLE);
1214 add_wait_queue(&nlk->wait, &wait);
1216 if ((atomic_read(&sk->sk_rmem_alloc) > sk->sk_rcvbuf ||
1217 test_bit(NETLINK_S_CONGESTED, &nlk->state)) &&
1218 !sock_flag(sk, SOCK_DEAD))
1219 *timeo = schedule_timeout(*timeo);
1221 __set_current_state(TASK_RUNNING);
1222 remove_wait_queue(&nlk->wait, &wait);
1225 if (signal_pending(current)) {
1227 return sock_intr_errno(*timeo);
1231 netlink_skb_set_owner_r(skb, sk);
1235 static int __netlink_sendskb(struct sock *sk, struct sk_buff *skb)
1239 netlink_deliver_tap(skb);
1241 skb_queue_tail(&sk->sk_receive_queue, skb);
1242 sk->sk_data_ready(sk);
1246 int netlink_sendskb(struct sock *sk, struct sk_buff *skb)
1248 int len = __netlink_sendskb(sk, skb);
1254 void netlink_detachskb(struct sock *sk, struct sk_buff *skb)
1260 static struct sk_buff *netlink_trim(struct sk_buff *skb, gfp_t allocation)
1264 WARN_ON(skb->sk != NULL);
1265 delta = skb->end - skb->tail;
1266 if (is_vmalloc_addr(skb->head) || delta * 2 < skb->truesize)
1269 if (skb_shared(skb)) {
1270 struct sk_buff *nskb = skb_clone(skb, allocation);
1277 if (!pskb_expand_head(skb, 0, -delta, allocation))
1278 skb->truesize -= delta;
1283 static int netlink_unicast_kernel(struct sock *sk, struct sk_buff *skb,
1287 struct netlink_sock *nlk = nlk_sk(sk);
1289 ret = -ECONNREFUSED;
1290 if (nlk->netlink_rcv != NULL) {
1292 netlink_skb_set_owner_r(skb, sk);
1293 NETLINK_CB(skb).sk = ssk;
1294 netlink_deliver_tap_kernel(sk, ssk, skb);
1295 nlk->netlink_rcv(skb);
1304 int netlink_unicast(struct sock *ssk, struct sk_buff *skb,
1305 u32 portid, int nonblock)
1311 skb = netlink_trim(skb, gfp_any());
1313 timeo = sock_sndtimeo(ssk, nonblock);
1315 sk = netlink_getsockbyportid(ssk, portid);
1320 if (netlink_is_kernel(sk))
1321 return netlink_unicast_kernel(sk, skb, ssk);
1323 if (sk_filter(sk, skb)) {
1330 err = netlink_attachskb(sk, skb, &timeo, ssk);
1336 return netlink_sendskb(sk, skb);
1338 EXPORT_SYMBOL(netlink_unicast);
1340 int netlink_has_listeners(struct sock *sk, unsigned int group)
1343 struct listeners *listeners;
1345 BUG_ON(!netlink_is_kernel(sk));
1348 listeners = rcu_dereference(nl_table[sk->sk_protocol].listeners);
1350 if (listeners && group - 1 < nl_table[sk->sk_protocol].groups)
1351 res = test_bit(group - 1, listeners->masks);
1357 EXPORT_SYMBOL_GPL(netlink_has_listeners);
1359 static int netlink_broadcast_deliver(struct sock *sk, struct sk_buff *skb)
1361 struct netlink_sock *nlk = nlk_sk(sk);
1363 if (atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf &&
1364 !test_bit(NETLINK_S_CONGESTED, &nlk->state)) {
1365 netlink_skb_set_owner_r(skb, sk);
1366 __netlink_sendskb(sk, skb);
1367 return atomic_read(&sk->sk_rmem_alloc) > (sk->sk_rcvbuf >> 1);
1372 struct netlink_broadcast_data {
1373 struct sock *exclude_sk;
1378 int delivery_failure;
1382 struct sk_buff *skb, *skb2;
1383 int (*tx_filter)(struct sock *dsk, struct sk_buff *skb, void *data);
1387 static void do_one_broadcast(struct sock *sk,
1388 struct netlink_broadcast_data *p)
1390 struct netlink_sock *nlk = nlk_sk(sk);
1393 if (p->exclude_sk == sk)
1396 if (nlk->portid == p->portid || p->group - 1 >= nlk->ngroups ||
1397 !test_bit(p->group - 1, nlk->groups))
1400 if (!net_eq(sock_net(sk), p->net)) {
1401 if (!(nlk->flags & NETLINK_F_LISTEN_ALL_NSID))
1404 if (!peernet_has_id(sock_net(sk), p->net))
1407 if (!file_ns_capable(sk->sk_socket->file, p->net->user_ns,
1413 netlink_overrun(sk);
1418 if (p->skb2 == NULL) {
1419 if (skb_shared(p->skb)) {
1420 p->skb2 = skb_clone(p->skb, p->allocation);
1422 p->skb2 = skb_get(p->skb);
1424 * skb ownership may have been set when
1425 * delivered to a previous socket.
1427 skb_orphan(p->skb2);
1430 if (p->skb2 == NULL) {
1431 netlink_overrun(sk);
1432 /* Clone failed. Notify ALL listeners. */
1434 if (nlk->flags & NETLINK_F_BROADCAST_SEND_ERROR)
1435 p->delivery_failure = 1;
1438 if (p->tx_filter && p->tx_filter(sk, p->skb2, p->tx_data)) {
1443 if (sk_filter(sk, p->skb2)) {
1448 NETLINK_CB(p->skb2).nsid = peernet2id(sock_net(sk), p->net);
1449 NETLINK_CB(p->skb2).nsid_is_set = true;
1450 val = netlink_broadcast_deliver(sk, p->skb2);
1452 netlink_overrun(sk);
1453 if (nlk->flags & NETLINK_F_BROADCAST_SEND_ERROR)
1454 p->delivery_failure = 1;
1456 p->congested |= val;
1464 int netlink_broadcast_filtered(struct sock *ssk, struct sk_buff *skb, u32 portid,
1465 u32 group, gfp_t allocation,
1466 int (*filter)(struct sock *dsk, struct sk_buff *skb, void *data),
1469 struct net *net = sock_net(ssk);
1470 struct netlink_broadcast_data info;
1473 skb = netlink_trim(skb, allocation);
1475 info.exclude_sk = ssk;
1477 info.portid = portid;
1480 info.delivery_failure = 0;
1483 info.allocation = allocation;
1486 info.tx_filter = filter;
1487 info.tx_data = filter_data;
1489 /* While we sleep in clone, do not allow to change socket list */
1491 netlink_lock_table();
1493 sk_for_each_bound(sk, &nl_table[ssk->sk_protocol].mc_list)
1494 do_one_broadcast(sk, &info);
1498 netlink_unlock_table();
1500 if (info.delivery_failure) {
1501 kfree_skb(info.skb2);
1504 consume_skb(info.skb2);
1506 if (info.delivered) {
1507 if (info.congested && gfpflags_allow_blocking(allocation))
1513 EXPORT_SYMBOL(netlink_broadcast_filtered);
1515 int netlink_broadcast(struct sock *ssk, struct sk_buff *skb, u32 portid,
1516 u32 group, gfp_t allocation)
1518 return netlink_broadcast_filtered(ssk, skb, portid, group, allocation,
1521 EXPORT_SYMBOL(netlink_broadcast);
1523 struct netlink_set_err_data {
1524 struct sock *exclude_sk;
1530 static int do_one_set_err(struct sock *sk, struct netlink_set_err_data *p)
1532 struct netlink_sock *nlk = nlk_sk(sk);
1535 if (sk == p->exclude_sk)
1538 if (!net_eq(sock_net(sk), sock_net(p->exclude_sk)))
1541 if (nlk->portid == p->portid || p->group - 1 >= nlk->ngroups ||
1542 !test_bit(p->group - 1, nlk->groups))
1545 if (p->code == ENOBUFS && nlk->flags & NETLINK_F_RECV_NO_ENOBUFS) {
1550 sk->sk_err = p->code;
1551 sk->sk_error_report(sk);
1557 * netlink_set_err - report error to broadcast listeners
1558 * @ssk: the kernel netlink socket, as returned by netlink_kernel_create()
1559 * @portid: the PORTID of a process that we want to skip (if any)
1560 * @group: the broadcast group that will notice the error
1561 * @code: error code, must be negative (as usual in kernelspace)
1563 * This function returns the number of broadcast listeners that have set the
1564 * NETLINK_NO_ENOBUFS socket option.
1566 int netlink_set_err(struct sock *ssk, u32 portid, u32 group, int code)
1568 struct netlink_set_err_data info;
1572 info.exclude_sk = ssk;
1573 info.portid = portid;
1575 /* sk->sk_err wants a positive error value */
1578 read_lock(&nl_table_lock);
1580 sk_for_each_bound(sk, &nl_table[ssk->sk_protocol].mc_list)
1581 ret += do_one_set_err(sk, &info);
1583 read_unlock(&nl_table_lock);
1586 EXPORT_SYMBOL(netlink_set_err);
1588 /* must be called with netlink table grabbed */
1589 static void netlink_update_socket_mc(struct netlink_sock *nlk,
1593 int old, new = !!is_new, subscriptions;
1595 old = test_bit(group - 1, nlk->groups);
1596 subscriptions = nlk->subscriptions - old + new;
1598 __set_bit(group - 1, nlk->groups);
1600 __clear_bit(group - 1, nlk->groups);
1601 netlink_update_subscriptions(&nlk->sk, subscriptions);
1602 netlink_update_listeners(&nlk->sk);
1605 static int netlink_setsockopt(struct socket *sock, int level, int optname,
1606 char __user *optval, unsigned int optlen)
1608 struct sock *sk = sock->sk;
1609 struct netlink_sock *nlk = nlk_sk(sk);
1610 unsigned int val = 0;
1613 if (level != SOL_NETLINK)
1614 return -ENOPROTOOPT;
1616 if (optlen >= sizeof(int) &&
1617 get_user(val, (unsigned int __user *)optval))
1621 case NETLINK_PKTINFO:
1623 nlk->flags |= NETLINK_F_RECV_PKTINFO;
1625 nlk->flags &= ~NETLINK_F_RECV_PKTINFO;
1628 case NETLINK_ADD_MEMBERSHIP:
1629 case NETLINK_DROP_MEMBERSHIP: {
1630 if (!netlink_allowed(sock, NL_CFG_F_NONROOT_RECV))
1632 err = netlink_realloc_groups(sk);
1635 if (!val || val - 1 >= nlk->ngroups)
1637 if (optname == NETLINK_ADD_MEMBERSHIP && nlk->netlink_bind) {
1638 err = nlk->netlink_bind(sock_net(sk), val);
1642 netlink_table_grab();
1643 netlink_update_socket_mc(nlk, val,
1644 optname == NETLINK_ADD_MEMBERSHIP);
1645 netlink_table_ungrab();
1646 if (optname == NETLINK_DROP_MEMBERSHIP && nlk->netlink_unbind)
1647 nlk->netlink_unbind(sock_net(sk), val);
1652 case NETLINK_BROADCAST_ERROR:
1654 nlk->flags |= NETLINK_F_BROADCAST_SEND_ERROR;
1656 nlk->flags &= ~NETLINK_F_BROADCAST_SEND_ERROR;
1659 case NETLINK_NO_ENOBUFS:
1661 nlk->flags |= NETLINK_F_RECV_NO_ENOBUFS;
1662 clear_bit(NETLINK_S_CONGESTED, &nlk->state);
1663 wake_up_interruptible(&nlk->wait);
1665 nlk->flags &= ~NETLINK_F_RECV_NO_ENOBUFS;
1669 case NETLINK_LISTEN_ALL_NSID:
1670 if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_BROADCAST))
1674 nlk->flags |= NETLINK_F_LISTEN_ALL_NSID;
1676 nlk->flags &= ~NETLINK_F_LISTEN_ALL_NSID;
1679 case NETLINK_CAP_ACK:
1681 nlk->flags |= NETLINK_F_CAP_ACK;
1683 nlk->flags &= ~NETLINK_F_CAP_ACK;
1692 static int netlink_getsockopt(struct socket *sock, int level, int optname,
1693 char __user *optval, int __user *optlen)
1695 struct sock *sk = sock->sk;
1696 struct netlink_sock *nlk = nlk_sk(sk);
1699 if (level != SOL_NETLINK)
1700 return -ENOPROTOOPT;
1702 if (get_user(len, optlen))
1708 case NETLINK_PKTINFO:
1709 if (len < sizeof(int))
1712 val = nlk->flags & NETLINK_F_RECV_PKTINFO ? 1 : 0;
1713 if (put_user(len, optlen) ||
1714 put_user(val, optval))
1718 case NETLINK_BROADCAST_ERROR:
1719 if (len < sizeof(int))
1722 val = nlk->flags & NETLINK_F_BROADCAST_SEND_ERROR ? 1 : 0;
1723 if (put_user(len, optlen) ||
1724 put_user(val, optval))
1728 case NETLINK_NO_ENOBUFS:
1729 if (len < sizeof(int))
1732 val = nlk->flags & NETLINK_F_RECV_NO_ENOBUFS ? 1 : 0;
1733 if (put_user(len, optlen) ||
1734 put_user(val, optval))
1738 case NETLINK_LIST_MEMBERSHIPS: {
1739 int pos, idx, shift;
1742 netlink_lock_table();
1743 for (pos = 0; pos * 8 < nlk->ngroups; pos += sizeof(u32)) {
1744 if (len - pos < sizeof(u32))
1747 idx = pos / sizeof(unsigned long);
1748 shift = (pos % sizeof(unsigned long)) * 8;
1749 if (put_user((u32)(nlk->groups[idx] >> shift),
1750 (u32 __user *)(optval + pos))) {
1755 if (put_user(ALIGN(nlk->ngroups / 8, sizeof(u32)), optlen))
1757 netlink_unlock_table();
1760 case NETLINK_CAP_ACK:
1761 if (len < sizeof(int))
1764 val = nlk->flags & NETLINK_F_CAP_ACK ? 1 : 0;
1765 if (put_user(len, optlen) ||
1766 put_user(val, optval))
1776 static void netlink_cmsg_recv_pktinfo(struct msghdr *msg, struct sk_buff *skb)
1778 struct nl_pktinfo info;
1780 info.group = NETLINK_CB(skb).dst_group;
1781 put_cmsg(msg, SOL_NETLINK, NETLINK_PKTINFO, sizeof(info), &info);
1784 static void netlink_cmsg_listen_all_nsid(struct sock *sk, struct msghdr *msg,
1785 struct sk_buff *skb)
1787 if (!NETLINK_CB(skb).nsid_is_set)
1790 put_cmsg(msg, SOL_NETLINK, NETLINK_LISTEN_ALL_NSID, sizeof(int),
1791 &NETLINK_CB(skb).nsid);
1794 static int netlink_sendmsg(struct socket *sock, struct msghdr *msg, size_t len)
1796 struct sock *sk = sock->sk;
1797 struct netlink_sock *nlk = nlk_sk(sk);
1798 DECLARE_SOCKADDR(struct sockaddr_nl *, addr, msg->msg_name);
1801 struct sk_buff *skb;
1803 struct scm_cookie scm;
1804 u32 netlink_skb_flags = 0;
1806 if (msg->msg_flags&MSG_OOB)
1810 pr_warn_once("Zero length message leads to an empty skb\n");
1814 err = scm_send(sock, msg, &scm, true);
1818 if (msg->msg_namelen) {
1820 if (msg->msg_namelen < sizeof(struct sockaddr_nl))
1822 if (addr->nl_family != AF_NETLINK)
1824 dst_portid = addr->nl_pid;
1825 dst_group = ffs(addr->nl_groups);
1827 if ((dst_group || dst_portid) &&
1828 !netlink_allowed(sock, NL_CFG_F_NONROOT_SEND))
1830 netlink_skb_flags |= NETLINK_SKB_DST;
1832 dst_portid = nlk->dst_portid;
1833 dst_group = nlk->dst_group;
1836 /* Paired with WRITE_ONCE() in netlink_insert() */
1837 if (!READ_ONCE(nlk->bound)) {
1838 err = netlink_autobind(sock);
1842 /* Ensure nlk is hashed and visible. */
1847 if (len > sk->sk_sndbuf - 32)
1850 skb = netlink_alloc_large_skb(len, dst_group);
1854 NETLINK_CB(skb).portid = nlk->portid;
1855 NETLINK_CB(skb).dst_group = dst_group;
1856 NETLINK_CB(skb).creds = scm.creds;
1857 NETLINK_CB(skb).flags = netlink_skb_flags;
1860 if (memcpy_from_msg(skb_put(skb, len), msg, len)) {
1865 err = security_netlink_send(sk, skb);
1872 atomic_inc(&skb->users);
1873 netlink_broadcast(sk, skb, dst_portid, dst_group, GFP_KERNEL);
1875 err = netlink_unicast(sk, skb, dst_portid, msg->msg_flags&MSG_DONTWAIT);
1882 static int netlink_recvmsg(struct socket *sock, struct msghdr *msg, size_t len,
1885 struct scm_cookie scm;
1886 struct sock *sk = sock->sk;
1887 struct netlink_sock *nlk = nlk_sk(sk);
1888 int noblock = flags&MSG_DONTWAIT;
1890 struct sk_buff *skb, *data_skb;
1898 skb = skb_recv_datagram(sk, flags, noblock, &err);
1904 #ifdef CONFIG_COMPAT_NETLINK_MESSAGES
1905 if (unlikely(skb_shinfo(skb)->frag_list)) {
1907 * If this skb has a frag_list, then here that means that we
1908 * will have to use the frag_list skb's data for compat tasks
1909 * and the regular skb's data for normal (non-compat) tasks.
1911 * If we need to send the compat skb, assign it to the
1912 * 'data_skb' variable so that it will be used below for data
1913 * copying. We keep 'skb' for everything else, including
1914 * freeing both later.
1916 if (flags & MSG_CMSG_COMPAT)
1917 data_skb = skb_shinfo(skb)->frag_list;
1921 /* Record the max length of recvmsg() calls for future allocations */
1922 nlk->max_recvmsg_len = max(nlk->max_recvmsg_len, len);
1923 nlk->max_recvmsg_len = min_t(size_t, nlk->max_recvmsg_len,
1924 SKB_WITH_OVERHEAD(32768));
1926 copied = data_skb->len;
1928 msg->msg_flags |= MSG_TRUNC;
1932 err = skb_copy_datagram_msg(data_skb, 0, msg, copied);
1934 if (msg->msg_name) {
1935 DECLARE_SOCKADDR(struct sockaddr_nl *, addr, msg->msg_name);
1936 addr->nl_family = AF_NETLINK;
1938 addr->nl_pid = NETLINK_CB(skb).portid;
1939 addr->nl_groups = netlink_group_mask(NETLINK_CB(skb).dst_group);
1940 msg->msg_namelen = sizeof(*addr);
1943 if (nlk->flags & NETLINK_F_RECV_PKTINFO)
1944 netlink_cmsg_recv_pktinfo(msg, skb);
1945 if (nlk->flags & NETLINK_F_LISTEN_ALL_NSID)
1946 netlink_cmsg_listen_all_nsid(sk, msg, skb);
1948 memset(&scm, 0, sizeof(scm));
1949 scm.creds = *NETLINK_CREDS(skb);
1950 if (flags & MSG_TRUNC)
1951 copied = data_skb->len;
1953 skb_free_datagram(sk, skb);
1955 if (nlk->cb_running &&
1956 atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf / 2) {
1957 ret = netlink_dump(sk);
1960 sk->sk_error_report(sk);
1964 scm_recv(sock, msg, &scm, flags);
1966 netlink_rcv_wake(sk);
1967 return err ? : copied;
1970 static void netlink_data_ready(struct sock *sk)
1976 * We export these functions to other modules. They provide a
1977 * complete set of kernel non-blocking support for message
1982 __netlink_kernel_create(struct net *net, int unit, struct module *module,
1983 struct netlink_kernel_cfg *cfg)
1985 struct socket *sock;
1987 struct netlink_sock *nlk;
1988 struct listeners *listeners = NULL;
1989 struct mutex *cb_mutex = cfg ? cfg->cb_mutex : NULL;
1990 unsigned int groups;
1994 if (unit < 0 || unit >= MAX_LINKS)
1997 if (sock_create_lite(PF_NETLINK, SOCK_DGRAM, unit, &sock))
2000 if (__netlink_create(net, sock, cb_mutex, unit, 1) < 0)
2001 goto out_sock_release_nosk;
2005 if (!cfg || cfg->groups < 32)
2008 groups = cfg->groups;
2010 listeners = kzalloc(sizeof(*listeners) + NLGRPSZ(groups), GFP_KERNEL);
2012 goto out_sock_release;
2014 sk->sk_data_ready = netlink_data_ready;
2015 if (cfg && cfg->input)
2016 nlk_sk(sk)->netlink_rcv = cfg->input;
2018 if (netlink_insert(sk, 0))
2019 goto out_sock_release;
2022 nlk->flags |= NETLINK_F_KERNEL_SOCKET;
2024 netlink_table_grab();
2025 if (!nl_table[unit].registered) {
2026 nl_table[unit].groups = groups;
2027 rcu_assign_pointer(nl_table[unit].listeners, listeners);
2028 nl_table[unit].cb_mutex = cb_mutex;
2029 nl_table[unit].module = module;
2031 nl_table[unit].bind = cfg->bind;
2032 nl_table[unit].unbind = cfg->unbind;
2033 nl_table[unit].flags = cfg->flags;
2035 nl_table[unit].compare = cfg->compare;
2037 nl_table[unit].registered = 1;
2040 nl_table[unit].registered++;
2042 netlink_table_ungrab();
2047 netlink_kernel_release(sk);
2050 out_sock_release_nosk:
2054 EXPORT_SYMBOL(__netlink_kernel_create);
2057 netlink_kernel_release(struct sock *sk)
2059 if (sk == NULL || sk->sk_socket == NULL)
2062 sock_release(sk->sk_socket);
2064 EXPORT_SYMBOL(netlink_kernel_release);
2066 int __netlink_change_ngroups(struct sock *sk, unsigned int groups)
2068 struct listeners *new, *old;
2069 struct netlink_table *tbl = &nl_table[sk->sk_protocol];
2074 if (NLGRPSZ(tbl->groups) < NLGRPSZ(groups)) {
2075 new = kzalloc(sizeof(*new) + NLGRPSZ(groups), GFP_ATOMIC);
2078 old = nl_deref_protected(tbl->listeners);
2079 memcpy(new->masks, old->masks, NLGRPSZ(tbl->groups));
2080 rcu_assign_pointer(tbl->listeners, new);
2082 kfree_rcu(old, rcu);
2084 tbl->groups = groups;
2090 * netlink_change_ngroups - change number of multicast groups
2092 * This changes the number of multicast groups that are available
2093 * on a certain netlink family. Note that it is not possible to
2094 * change the number of groups to below 32. Also note that it does
2095 * not implicitly call netlink_clear_multicast_users() when the
2096 * number of groups is reduced.
2098 * @sk: The kernel netlink socket, as returned by netlink_kernel_create().
2099 * @groups: The new number of groups.
2101 int netlink_change_ngroups(struct sock *sk, unsigned int groups)
2105 netlink_table_grab();
2106 err = __netlink_change_ngroups(sk, groups);
2107 netlink_table_ungrab();
2112 void __netlink_clear_multicast_users(struct sock *ksk, unsigned int group)
2115 struct netlink_table *tbl = &nl_table[ksk->sk_protocol];
2117 sk_for_each_bound(sk, &tbl->mc_list)
2118 netlink_update_socket_mc(nlk_sk(sk), group, 0);
2122 __nlmsg_put(struct sk_buff *skb, u32 portid, u32 seq, int type, int len, int flags)
2124 struct nlmsghdr *nlh;
2125 int size = nlmsg_msg_size(len);
2127 nlh = (struct nlmsghdr *)skb_put(skb, NLMSG_ALIGN(size));
2128 nlh->nlmsg_type = type;
2129 nlh->nlmsg_len = size;
2130 nlh->nlmsg_flags = flags;
2131 nlh->nlmsg_pid = portid;
2132 nlh->nlmsg_seq = seq;
2133 if (!__builtin_constant_p(size) || NLMSG_ALIGN(size) - size != 0)
2134 memset(nlmsg_data(nlh) + len, 0, NLMSG_ALIGN(size) - size);
2137 EXPORT_SYMBOL(__nlmsg_put);
2140 * It looks a bit ugly.
2141 * It would be better to create kernel thread.
2144 static int netlink_dump(struct sock *sk)
2146 struct netlink_sock *nlk = nlk_sk(sk);
2147 struct netlink_callback *cb;
2148 struct sk_buff *skb = NULL;
2149 struct nlmsghdr *nlh;
2150 struct module *module;
2155 mutex_lock(nlk->cb_mutex);
2156 if (!nlk->cb_running) {
2161 if (atomic_read(&sk->sk_rmem_alloc) >= sk->sk_rcvbuf)
2164 /* NLMSG_GOODSIZE is small to avoid high order allocations being
2165 * required, but it makes sense to _attempt_ a 16K bytes allocation
2166 * to reduce number of system calls on dump operations, if user
2167 * ever provided a big enough buffer.
2170 alloc_min_size = max_t(int, cb->min_dump_alloc, NLMSG_GOODSIZE);
2172 if (alloc_min_size < nlk->max_recvmsg_len) {
2173 alloc_size = nlk->max_recvmsg_len;
2174 skb = alloc_skb(alloc_size,
2175 (GFP_KERNEL & ~__GFP_DIRECT_RECLAIM) |
2176 __GFP_NOWARN | __GFP_NORETRY);
2179 alloc_size = alloc_min_size;
2180 skb = alloc_skb(alloc_size, GFP_KERNEL);
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.
2195 skb_reserve(skb, skb_tailroom(skb) - alloc_size);
2197 /* Make sure malicious BPF programs can not read unitialized memory
2198 * from skb->head -> skb->data
2200 skb_reset_network_header(skb);
2201 skb_reset_mac_header(skb);
2203 netlink_skb_set_owner_r(skb, sk);
2205 if (nlk->dump_done_errno > 0)
2206 nlk->dump_done_errno = cb->dump(skb, cb);
2208 if (nlk->dump_done_errno > 0 ||
2209 skb_tailroom(skb) < nlmsg_total_size(sizeof(nlk->dump_done_errno))) {
2210 mutex_unlock(nlk->cb_mutex);
2212 if (sk_filter(sk, skb))
2215 __netlink_sendskb(sk, skb);
2219 nlh = nlmsg_put_answer(skb, cb, NLMSG_DONE,
2220 sizeof(nlk->dump_done_errno), NLM_F_MULTI);
2224 nl_dump_check_consistent(cb, nlh);
2226 memcpy(nlmsg_data(nlh), &nlk->dump_done_errno,
2227 sizeof(nlk->dump_done_errno));
2229 if (sk_filter(sk, skb))
2232 __netlink_sendskb(sk, skb);
2237 nlk->cb_running = false;
2238 module = cb->module;
2240 mutex_unlock(nlk->cb_mutex);
2246 mutex_unlock(nlk->cb_mutex);
2251 int __netlink_dump_start(struct sock *ssk, struct sk_buff *skb,
2252 const struct nlmsghdr *nlh,
2253 struct netlink_dump_control *control)
2255 struct netlink_callback *cb;
2257 struct netlink_sock *nlk;
2260 atomic_inc(&skb->users);
2262 sk = netlink_lookup(sock_net(ssk), ssk->sk_protocol, NETLINK_CB(skb).portid);
2264 ret = -ECONNREFUSED;
2269 mutex_lock(nlk->cb_mutex);
2270 /* A dump is in progress... */
2271 if (nlk->cb_running) {
2275 /* add reference of module which cb->dump belongs to */
2276 if (!try_module_get(control->module)) {
2277 ret = -EPROTONOSUPPORT;
2282 memset(cb, 0, sizeof(*cb));
2283 cb->start = control->start;
2284 cb->dump = control->dump;
2285 cb->done = control->done;
2287 cb->data = control->data;
2288 cb->module = control->module;
2289 cb->min_dump_alloc = control->min_dump_alloc;
2293 ret = cb->start(cb);
2298 nlk->cb_running = true;
2299 nlk->dump_done_errno = INT_MAX;
2301 mutex_unlock(nlk->cb_mutex);
2303 ret = netlink_dump(sk);
2310 /* We successfully started a dump, by returning -EINTR we
2311 * signal not to send ACK even if it was requested.
2316 module_put(control->module);
2319 mutex_unlock(nlk->cb_mutex);
2324 EXPORT_SYMBOL(__netlink_dump_start);
2326 void netlink_ack(struct sk_buff *in_skb, struct nlmsghdr *nlh, int err)
2328 struct sk_buff *skb;
2329 struct nlmsghdr *rep;
2330 struct nlmsgerr *errmsg;
2331 size_t payload = sizeof(*errmsg);
2332 struct netlink_sock *nlk = nlk_sk(NETLINK_CB(in_skb).sk);
2334 /* Error messages get the original request appened, unless the user
2335 * requests to cap the error message.
2337 if (!(nlk->flags & NETLINK_F_CAP_ACK) && err)
2338 payload += nlmsg_len(nlh);
2340 skb = nlmsg_new(payload, GFP_KERNEL);
2344 sk = netlink_lookup(sock_net(in_skb->sk),
2345 in_skb->sk->sk_protocol,
2346 NETLINK_CB(in_skb).portid);
2348 sk->sk_err = ENOBUFS;
2349 sk->sk_error_report(sk);
2355 rep = __nlmsg_put(skb, NETLINK_CB(in_skb).portid, nlh->nlmsg_seq,
2356 NLMSG_ERROR, payload, 0);
2357 errmsg = nlmsg_data(rep);
2358 errmsg->error = err;
2359 memcpy(&errmsg->msg, nlh, payload > sizeof(*errmsg) ? nlh->nlmsg_len : sizeof(*nlh));
2360 netlink_unicast(in_skb->sk, skb, NETLINK_CB(in_skb).portid, MSG_DONTWAIT);
2362 EXPORT_SYMBOL(netlink_ack);
2364 int netlink_rcv_skb(struct sk_buff *skb, int (*cb)(struct sk_buff *,
2367 struct nlmsghdr *nlh;
2370 while (skb->len >= nlmsg_total_size(0)) {
2373 nlh = nlmsg_hdr(skb);
2376 if (nlh->nlmsg_len < NLMSG_HDRLEN || skb->len < nlh->nlmsg_len)
2379 /* Only requests are handled by the kernel */
2380 if (!(nlh->nlmsg_flags & NLM_F_REQUEST))
2383 /* Skip control messages */
2384 if (nlh->nlmsg_type < NLMSG_MIN_TYPE)
2392 if (nlh->nlmsg_flags & NLM_F_ACK || err)
2393 netlink_ack(skb, nlh, err);
2396 msglen = NLMSG_ALIGN(nlh->nlmsg_len);
2397 if (msglen > skb->len)
2399 skb_pull(skb, msglen);
2404 EXPORT_SYMBOL(netlink_rcv_skb);
2407 * nlmsg_notify - send a notification netlink message
2408 * @sk: netlink socket to use
2409 * @skb: notification message
2410 * @portid: destination netlink portid for reports or 0
2411 * @group: destination multicast group or 0
2412 * @report: 1 to report back, 0 to disable
2413 * @flags: allocation flags
2415 int nlmsg_notify(struct sock *sk, struct sk_buff *skb, u32 portid,
2416 unsigned int group, int report, gfp_t flags)
2421 int exclude_portid = 0;
2424 atomic_inc(&skb->users);
2425 exclude_portid = portid;
2428 /* errors reported via destination sk->sk_err, but propagate
2429 * delivery errors if NETLINK_BROADCAST_ERROR flag is set */
2430 err = nlmsg_multicast(sk, skb, exclude_portid, group, flags);
2438 err2 = nlmsg_unicast(sk, skb, portid);
2445 EXPORT_SYMBOL(nlmsg_notify);
2447 #ifdef CONFIG_PROC_FS
2448 struct nl_seq_iter {
2449 struct seq_net_private p;
2450 struct rhashtable_iter hti;
2454 static int netlink_walk_start(struct nl_seq_iter *iter)
2458 err = rhashtable_walk_init(&nl_table[iter->link].hash, &iter->hti,
2461 iter->link = MAX_LINKS;
2465 err = rhashtable_walk_start(&iter->hti);
2466 return err == -EAGAIN ? 0 : err;
2469 static void netlink_walk_stop(struct nl_seq_iter *iter)
2471 rhashtable_walk_stop(&iter->hti);
2472 rhashtable_walk_exit(&iter->hti);
2475 static void *__netlink_seq_next(struct seq_file *seq)
2477 struct nl_seq_iter *iter = seq->private;
2478 struct netlink_sock *nlk;
2484 nlk = rhashtable_walk_next(&iter->hti);
2487 if (PTR_ERR(nlk) == -EAGAIN)
2496 netlink_walk_stop(iter);
2497 if (++iter->link >= MAX_LINKS)
2500 err = netlink_walk_start(iter);
2502 return ERR_PTR(err);
2504 } while (sock_net(&nlk->sk) != seq_file_net(seq));
2509 static void *netlink_seq_start(struct seq_file *seq, loff_t *posp)
2511 struct nl_seq_iter *iter = seq->private;
2512 void *obj = SEQ_START_TOKEN;
2518 err = netlink_walk_start(iter);
2520 return ERR_PTR(err);
2522 for (pos = *posp; pos && obj && !IS_ERR(obj); pos--)
2523 obj = __netlink_seq_next(seq);
2528 static void *netlink_seq_next(struct seq_file *seq, void *v, loff_t *pos)
2531 return __netlink_seq_next(seq);
2534 static void netlink_seq_stop(struct seq_file *seq, void *v)
2536 struct nl_seq_iter *iter = seq->private;
2538 if (iter->link >= MAX_LINKS)
2541 netlink_walk_stop(iter);
2545 static int netlink_seq_show(struct seq_file *seq, void *v)
2547 if (v == SEQ_START_TOKEN) {
2549 "sk Eth Pid Groups "
2550 "Rmem Wmem Dump Locks Drops Inode\n");
2553 struct netlink_sock *nlk = nlk_sk(s);
2555 seq_printf(seq, "%pK %-3d %-6u %08x %-8d %-8d %d %-8d %-8d %-8lu\n",
2559 nlk->groups ? (u32)nlk->groups[0] : 0,
2560 sk_rmem_alloc_get(s),
2561 sk_wmem_alloc_get(s),
2563 atomic_read(&s->sk_refcnt),
2564 atomic_read(&s->sk_drops),
2572 static const struct seq_operations netlink_seq_ops = {
2573 .start = netlink_seq_start,
2574 .next = netlink_seq_next,
2575 .stop = netlink_seq_stop,
2576 .show = netlink_seq_show,
2580 static int netlink_seq_open(struct inode *inode, struct file *file)
2582 return seq_open_net(inode, file, &netlink_seq_ops,
2583 sizeof(struct nl_seq_iter));
2586 static const struct file_operations netlink_seq_fops = {
2587 .owner = THIS_MODULE,
2588 .open = netlink_seq_open,
2590 .llseek = seq_lseek,
2591 .release = seq_release_net,
2596 int netlink_register_notifier(struct notifier_block *nb)
2598 return atomic_notifier_chain_register(&netlink_chain, nb);
2600 EXPORT_SYMBOL(netlink_register_notifier);
2602 int netlink_unregister_notifier(struct notifier_block *nb)
2604 return atomic_notifier_chain_unregister(&netlink_chain, nb);
2606 EXPORT_SYMBOL(netlink_unregister_notifier);
2608 static const struct proto_ops netlink_ops = {
2609 .family = PF_NETLINK,
2610 .owner = THIS_MODULE,
2611 .release = netlink_release,
2612 .bind = netlink_bind,
2613 .connect = netlink_connect,
2614 .socketpair = sock_no_socketpair,
2615 .accept = sock_no_accept,
2616 .getname = netlink_getname,
2617 .poll = datagram_poll,
2618 .ioctl = netlink_ioctl,
2619 .listen = sock_no_listen,
2620 .shutdown = sock_no_shutdown,
2621 .setsockopt = netlink_setsockopt,
2622 .getsockopt = netlink_getsockopt,
2623 .sendmsg = netlink_sendmsg,
2624 .recvmsg = netlink_recvmsg,
2625 .mmap = sock_no_mmap,
2626 .sendpage = sock_no_sendpage,
2629 static const struct net_proto_family netlink_family_ops = {
2630 .family = PF_NETLINK,
2631 .create = netlink_create,
2632 .owner = THIS_MODULE, /* for consistency 8) */
2635 static int __net_init netlink_net_init(struct net *net)
2637 #ifdef CONFIG_PROC_FS
2638 if (!proc_create("netlink", 0, net->proc_net, &netlink_seq_fops))
2644 static void __net_exit netlink_net_exit(struct net *net)
2646 #ifdef CONFIG_PROC_FS
2647 remove_proc_entry("netlink", net->proc_net);
2651 static void __init netlink_add_usersock_entry(void)
2653 struct listeners *listeners;
2656 listeners = kzalloc(sizeof(*listeners) + NLGRPSZ(groups), GFP_KERNEL);
2658 panic("netlink_add_usersock_entry: Cannot allocate listeners\n");
2660 netlink_table_grab();
2662 nl_table[NETLINK_USERSOCK].groups = groups;
2663 rcu_assign_pointer(nl_table[NETLINK_USERSOCK].listeners, listeners);
2664 nl_table[NETLINK_USERSOCK].module = THIS_MODULE;
2665 nl_table[NETLINK_USERSOCK].registered = 1;
2666 nl_table[NETLINK_USERSOCK].flags = NL_CFG_F_NONROOT_SEND;
2668 netlink_table_ungrab();
2671 static struct pernet_operations __net_initdata netlink_net_ops = {
2672 .init = netlink_net_init,
2673 .exit = netlink_net_exit,
2676 static inline u32 netlink_hash(const void *data, u32 len, u32 seed)
2678 const struct netlink_sock *nlk = data;
2679 struct netlink_compare_arg arg;
2681 netlink_compare_arg_init(&arg, sock_net(&nlk->sk), nlk->portid);
2682 return jhash2((u32 *)&arg, netlink_compare_arg_len / sizeof(u32), seed);
2685 static const struct rhashtable_params netlink_rhashtable_params = {
2686 .head_offset = offsetof(struct netlink_sock, node),
2687 .key_len = netlink_compare_arg_len,
2688 .obj_hashfn = netlink_hash,
2689 .obj_cmpfn = netlink_compare,
2690 .automatic_shrinking = true,
2693 static int __init netlink_proto_init(void)
2696 int err = proto_register(&netlink_proto, 0);
2701 BUILD_BUG_ON(sizeof(struct netlink_skb_parms) > FIELD_SIZEOF(struct sk_buff, cb));
2703 nl_table = kcalloc(MAX_LINKS, sizeof(*nl_table), GFP_KERNEL);
2707 for (i = 0; i < MAX_LINKS; i++) {
2708 if (rhashtable_init(&nl_table[i].hash,
2709 &netlink_rhashtable_params) < 0) {
2711 rhashtable_destroy(&nl_table[i].hash);
2717 INIT_LIST_HEAD(&netlink_tap_all);
2719 netlink_add_usersock_entry();
2721 sock_register(&netlink_family_ops);
2722 register_pernet_subsys(&netlink_net_ops);
2723 /* The netlink device handler may be needed early. */
2728 panic("netlink_init: Cannot allocate nl_table\n");
2731 core_initcall(netlink_proto_init);