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