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