]> www.pilppa.org Git - linux-2.6-omap-h63xx.git/blob - net/netlink/af_netlink.c
3982f13dab17954db40368b37d6cf37ea19e2c96
[linux-2.6-omap-h63xx.git] / net / netlink / af_netlink.c
1 /*
2  * NETLINK      Kernel-user communication protocol.
3  *
4  *              Authors:        Alan Cox <alan@redhat.com>
5  *                              Alexey Kuznetsov <kuznet@ms2.inr.ac.ru>
6  *
7  *              This program is free software; you can redistribute it and/or
8  *              modify it under the terms of the GNU General Public License
9  *              as published by the Free Software Foundation; either version
10  *              2 of the License, or (at your option) any later version.
11  *
12  * Tue Jun 26 14:36:48 MEST 2001 Herbert "herp" Rosmanith
13  *                               added netlink_proto_exit
14  * Tue Jan 22 18:32:44 BRST 2002 Arnaldo C. de Melo <acme@conectiva.com.br>
15  *                               use nlk_sk, as sk->protinfo is on a diet 8)
16  * Fri Jul 22 19:51:12 MEST 2005 Harald Welte <laforge@gnumonks.org>
17  *                               - inc module use count of module that owns
18  *                                 the kernel socket in case userspace opens
19  *                                 socket of same protocol
20  *                               - remove all module support, since netlink is
21  *                                 mandatory if CONFIG_NET=y these days
22  */
23
24 #include <linux/module.h>
25
26 #include <linux/capability.h>
27 #include <linux/kernel.h>
28 #include <linux/init.h>
29 #include <linux/signal.h>
30 #include <linux/sched.h>
31 #include <linux/errno.h>
32 #include <linux/string.h>
33 #include <linux/stat.h>
34 #include <linux/socket.h>
35 #include <linux/un.h>
36 #include <linux/fcntl.h>
37 #include <linux/termios.h>
38 #include <linux/sockios.h>
39 #include <linux/net.h>
40 #include <linux/fs.h>
41 #include <linux/slab.h>
42 #include <asm/uaccess.h>
43 #include <linux/skbuff.h>
44 #include <linux/netdevice.h>
45 #include <linux/rtnetlink.h>
46 #include <linux/proc_fs.h>
47 #include <linux/seq_file.h>
48 #include <linux/notifier.h>
49 #include <linux/security.h>
50 #include <linux/jhash.h>
51 #include <linux/jiffies.h>
52 #include <linux/random.h>
53 #include <linux/bitops.h>
54 #include <linux/mm.h>
55 #include <linux/types.h>
56 #include <linux/audit.h>
57 #include <linux/selinux.h>
58 #include <linux/mutex.h>
59
60 #include <net/net_namespace.h>
61 #include <net/sock.h>
62 #include <net/scm.h>
63 #include <net/netlink.h>
64
65 #define NLGRPSZ(x)      (ALIGN(x, sizeof(unsigned long) * 8) / 8)
66 #define NLGRPLONGS(x)   (NLGRPSZ(x)/sizeof(unsigned long))
67
68 struct netlink_sock {
69         /* struct sock has to be the first member of netlink_sock */
70         struct sock             sk;
71         u32                     pid;
72         u32                     dst_pid;
73         u32                     dst_group;
74         u32                     flags;
75         u32                     subscriptions;
76         u32                     ngroups;
77         unsigned long           *groups;
78         unsigned long           state;
79         wait_queue_head_t       wait;
80         struct netlink_callback *cb;
81         struct mutex            *cb_mutex;
82         struct mutex            cb_def_mutex;
83         void                    (*data_ready)(struct sock *sk, int bytes);
84         struct module           *module;
85 };
86
87 #define NETLINK_KERNEL_SOCKET   0x1
88 #define NETLINK_RECV_PKTINFO    0x2
89
90 static inline struct netlink_sock *nlk_sk(struct sock *sk)
91 {
92         return container_of(sk, struct netlink_sock, sk);
93 }
94
95 struct nl_pid_hash {
96         struct hlist_head *table;
97         unsigned long rehash_time;
98
99         unsigned int mask;
100         unsigned int shift;
101
102         unsigned int entries;
103         unsigned int max_shift;
104
105         u32 rnd;
106 };
107
108 struct netlink_table {
109         struct nl_pid_hash hash;
110         struct hlist_head mc_list;
111         unsigned long *listeners;
112         unsigned int nl_nonroot;
113         unsigned int groups;
114         struct mutex *cb_mutex;
115         struct module *module;
116         int registered;
117 };
118
119 static struct netlink_table *nl_table;
120
121 static DECLARE_WAIT_QUEUE_HEAD(nl_table_wait);
122
123 static int netlink_dump(struct sock *sk);
124 static void netlink_destroy_callback(struct netlink_callback *cb);
125 static void netlink_queue_skip(struct nlmsghdr *nlh, struct sk_buff *skb);
126
127 static DEFINE_RWLOCK(nl_table_lock);
128 static atomic_t nl_table_users = ATOMIC_INIT(0);
129
130 static ATOMIC_NOTIFIER_HEAD(netlink_chain);
131
132 static u32 netlink_group_mask(u32 group)
133 {
134         return group ? 1 << (group - 1) : 0;
135 }
136
137 static struct hlist_head *nl_pid_hashfn(struct nl_pid_hash *hash, u32 pid)
138 {
139         return &hash->table[jhash_1word(pid, hash->rnd) & hash->mask];
140 }
141
142 static void netlink_sock_destruct(struct sock *sk)
143 {
144         struct netlink_sock *nlk = nlk_sk(sk);
145
146         if (nlk->cb) {
147                 if (nlk->cb->done)
148                         nlk->cb->done(nlk->cb);
149                 netlink_destroy_callback(nlk->cb);
150         }
151
152         skb_queue_purge(&sk->sk_receive_queue);
153
154         if (!sock_flag(sk, SOCK_DEAD)) {
155                 printk("Freeing alive netlink socket %p\n", sk);
156                 return;
157         }
158         BUG_TRAP(!atomic_read(&sk->sk_rmem_alloc));
159         BUG_TRAP(!atomic_read(&sk->sk_wmem_alloc));
160         BUG_TRAP(!nlk_sk(sk)->groups);
161 }
162
163 /* This lock without WQ_FLAG_EXCLUSIVE is good on UP and it is _very_ bad on SMP.
164  * Look, when several writers sleep and reader wakes them up, all but one
165  * immediately hit write lock and grab all the cpus. Exclusive sleep solves
166  * this, _but_ remember, it adds useless work on UP machines.
167  */
168
169 static void netlink_table_grab(void)
170 {
171         write_lock_irq(&nl_table_lock);
172
173         if (atomic_read(&nl_table_users)) {
174                 DECLARE_WAITQUEUE(wait, current);
175
176                 add_wait_queue_exclusive(&nl_table_wait, &wait);
177                 for(;;) {
178                         set_current_state(TASK_UNINTERRUPTIBLE);
179                         if (atomic_read(&nl_table_users) == 0)
180                                 break;
181                         write_unlock_irq(&nl_table_lock);
182                         schedule();
183                         write_lock_irq(&nl_table_lock);
184                 }
185
186                 __set_current_state(TASK_RUNNING);
187                 remove_wait_queue(&nl_table_wait, &wait);
188         }
189 }
190
191 static __inline__ void netlink_table_ungrab(void)
192 {
193         write_unlock_irq(&nl_table_lock);
194         wake_up(&nl_table_wait);
195 }
196
197 static __inline__ void
198 netlink_lock_table(void)
199 {
200         /* read_lock() synchronizes us to netlink_table_grab */
201
202         read_lock(&nl_table_lock);
203         atomic_inc(&nl_table_users);
204         read_unlock(&nl_table_lock);
205 }
206
207 static __inline__ void
208 netlink_unlock_table(void)
209 {
210         if (atomic_dec_and_test(&nl_table_users))
211                 wake_up(&nl_table_wait);
212 }
213
214 static __inline__ struct sock *netlink_lookup(int protocol, u32 pid)
215 {
216         struct nl_pid_hash *hash = &nl_table[protocol].hash;
217         struct hlist_head *head;
218         struct sock *sk;
219         struct hlist_node *node;
220
221         read_lock(&nl_table_lock);
222         head = nl_pid_hashfn(hash, pid);
223         sk_for_each(sk, node, head) {
224                 if (nlk_sk(sk)->pid == pid) {
225                         sock_hold(sk);
226                         goto found;
227                 }
228         }
229         sk = NULL;
230 found:
231         read_unlock(&nl_table_lock);
232         return sk;
233 }
234
235 static inline struct hlist_head *nl_pid_hash_alloc(size_t size)
236 {
237         if (size <= PAGE_SIZE)
238                 return kmalloc(size, GFP_ATOMIC);
239         else
240                 return (struct hlist_head *)
241                         __get_free_pages(GFP_ATOMIC, get_order(size));
242 }
243
244 static inline void nl_pid_hash_free(struct hlist_head *table, size_t size)
245 {
246         if (size <= PAGE_SIZE)
247                 kfree(table);
248         else
249                 free_pages((unsigned long)table, get_order(size));
250 }
251
252 static int nl_pid_hash_rehash(struct nl_pid_hash *hash, int grow)
253 {
254         unsigned int omask, mask, shift;
255         size_t osize, size;
256         struct hlist_head *otable, *table;
257         int i;
258
259         omask = mask = hash->mask;
260         osize = size = (mask + 1) * sizeof(*table);
261         shift = hash->shift;
262
263         if (grow) {
264                 if (++shift > hash->max_shift)
265                         return 0;
266                 mask = mask * 2 + 1;
267                 size *= 2;
268         }
269
270         table = nl_pid_hash_alloc(size);
271         if (!table)
272                 return 0;
273
274         memset(table, 0, size);
275         otable = hash->table;
276         hash->table = table;
277         hash->mask = mask;
278         hash->shift = shift;
279         get_random_bytes(&hash->rnd, sizeof(hash->rnd));
280
281         for (i = 0; i <= omask; i++) {
282                 struct sock *sk;
283                 struct hlist_node *node, *tmp;
284
285                 sk_for_each_safe(sk, node, tmp, &otable[i])
286                         __sk_add_node(sk, nl_pid_hashfn(hash, nlk_sk(sk)->pid));
287         }
288
289         nl_pid_hash_free(otable, osize);
290         hash->rehash_time = jiffies + 10 * 60 * HZ;
291         return 1;
292 }
293
294 static inline int nl_pid_hash_dilute(struct nl_pid_hash *hash, int len)
295 {
296         int avg = hash->entries >> hash->shift;
297
298         if (unlikely(avg > 1) && nl_pid_hash_rehash(hash, 1))
299                 return 1;
300
301         if (unlikely(len > avg) && time_after(jiffies, hash->rehash_time)) {
302                 nl_pid_hash_rehash(hash, 0);
303                 return 1;
304         }
305
306         return 0;
307 }
308
309 static const struct proto_ops netlink_ops;
310
311 static void
312 netlink_update_listeners(struct sock *sk)
313 {
314         struct netlink_table *tbl = &nl_table[sk->sk_protocol];
315         struct hlist_node *node;
316         unsigned long mask;
317         unsigned int i;
318
319         for (i = 0; i < NLGRPLONGS(tbl->groups); i++) {
320                 mask = 0;
321                 sk_for_each_bound(sk, node, &tbl->mc_list) {
322                         if (i < NLGRPLONGS(nlk_sk(sk)->ngroups))
323                                 mask |= nlk_sk(sk)->groups[i];
324                 }
325                 tbl->listeners[i] = mask;
326         }
327         /* this function is only called with the netlink table "grabbed", which
328          * makes sure updates are visible before bind or setsockopt return. */
329 }
330
331 static int netlink_insert(struct sock *sk, u32 pid)
332 {
333         struct nl_pid_hash *hash = &nl_table[sk->sk_protocol].hash;
334         struct hlist_head *head;
335         int err = -EADDRINUSE;
336         struct sock *osk;
337         struct hlist_node *node;
338         int len;
339
340         netlink_table_grab();
341         head = nl_pid_hashfn(hash, pid);
342         len = 0;
343         sk_for_each(osk, node, head) {
344                 if (nlk_sk(osk)->pid == pid)
345                         break;
346                 len++;
347         }
348         if (node)
349                 goto err;
350
351         err = -EBUSY;
352         if (nlk_sk(sk)->pid)
353                 goto err;
354
355         err = -ENOMEM;
356         if (BITS_PER_LONG > 32 && unlikely(hash->entries >= UINT_MAX))
357                 goto err;
358
359         if (len && nl_pid_hash_dilute(hash, len))
360                 head = nl_pid_hashfn(hash, pid);
361         hash->entries++;
362         nlk_sk(sk)->pid = pid;
363         sk_add_node(sk, head);
364         err = 0;
365
366 err:
367         netlink_table_ungrab();
368         return err;
369 }
370
371 static void netlink_remove(struct sock *sk)
372 {
373         netlink_table_grab();
374         if (sk_del_node_init(sk))
375                 nl_table[sk->sk_protocol].hash.entries--;
376         if (nlk_sk(sk)->subscriptions)
377                 __sk_del_bind_node(sk);
378         netlink_table_ungrab();
379 }
380
381 static struct proto netlink_proto = {
382         .name     = "NETLINK",
383         .owner    = THIS_MODULE,
384         .obj_size = sizeof(struct netlink_sock),
385 };
386
387 static int __netlink_create(struct socket *sock, struct mutex *cb_mutex,
388                             int protocol)
389 {
390         struct sock *sk;
391         struct netlink_sock *nlk;
392
393         sock->ops = &netlink_ops;
394
395         sk = sk_alloc(PF_NETLINK, GFP_KERNEL, &netlink_proto, 1);
396         if (!sk)
397                 return -ENOMEM;
398
399         sock_init_data(sock, sk);
400
401         nlk = nlk_sk(sk);
402         if (cb_mutex)
403                 nlk->cb_mutex = cb_mutex;
404         else {
405                 nlk->cb_mutex = &nlk->cb_def_mutex;
406                 mutex_init(nlk->cb_mutex);
407         }
408         init_waitqueue_head(&nlk->wait);
409
410         sk->sk_destruct = netlink_sock_destruct;
411         sk->sk_protocol = protocol;
412         return 0;
413 }
414
415 static int netlink_create(struct socket *sock, int protocol)
416 {
417         struct module *module = NULL;
418         struct mutex *cb_mutex;
419         struct netlink_sock *nlk;
420         int err = 0;
421
422         sock->state = SS_UNCONNECTED;
423
424         if (sock->type != SOCK_RAW && sock->type != SOCK_DGRAM)
425                 return -ESOCKTNOSUPPORT;
426
427         if (protocol<0 || protocol >= MAX_LINKS)
428                 return -EPROTONOSUPPORT;
429
430         netlink_lock_table();
431 #ifdef CONFIG_KMOD
432         if (!nl_table[protocol].registered) {
433                 netlink_unlock_table();
434                 request_module("net-pf-%d-proto-%d", PF_NETLINK, protocol);
435                 netlink_lock_table();
436         }
437 #endif
438         if (nl_table[protocol].registered &&
439             try_module_get(nl_table[protocol].module))
440                 module = nl_table[protocol].module;
441         cb_mutex = nl_table[protocol].cb_mutex;
442         netlink_unlock_table();
443
444         if ((err = __netlink_create(sock, cb_mutex, protocol)) < 0)
445                 goto out_module;
446
447         nlk = nlk_sk(sock->sk);
448         nlk->module = module;
449 out:
450         return err;
451
452 out_module:
453         module_put(module);
454         goto out;
455 }
456
457 static int netlink_release(struct socket *sock)
458 {
459         struct sock *sk = sock->sk;
460         struct netlink_sock *nlk;
461
462         if (!sk)
463                 return 0;
464
465         netlink_remove(sk);
466         sock_orphan(sk);
467         nlk = nlk_sk(sk);
468
469         /*
470          * OK. Socket is unlinked, any packets that arrive now
471          * will be purged.
472          */
473
474         sock->sk = NULL;
475         wake_up_interruptible_all(&nlk->wait);
476
477         skb_queue_purge(&sk->sk_write_queue);
478
479         if (nlk->pid && !nlk->subscriptions) {
480                 struct netlink_notify n = {
481                                                 .protocol = sk->sk_protocol,
482                                                 .pid = nlk->pid,
483                                           };
484                 atomic_notifier_call_chain(&netlink_chain,
485                                 NETLINK_URELEASE, &n);
486         }
487
488         module_put(nlk->module);
489
490         netlink_table_grab();
491         if (nlk->flags & NETLINK_KERNEL_SOCKET) {
492                 kfree(nl_table[sk->sk_protocol].listeners);
493                 nl_table[sk->sk_protocol].module = NULL;
494                 nl_table[sk->sk_protocol].registered = 0;
495         } else if (nlk->subscriptions)
496                 netlink_update_listeners(sk);
497         netlink_table_ungrab();
498
499         kfree(nlk->groups);
500         nlk->groups = NULL;
501
502         sock_put(sk);
503         return 0;
504 }
505
506 static int netlink_autobind(struct socket *sock)
507 {
508         struct sock *sk = sock->sk;
509         struct nl_pid_hash *hash = &nl_table[sk->sk_protocol].hash;
510         struct hlist_head *head;
511         struct sock *osk;
512         struct hlist_node *node;
513         s32 pid = current->tgid;
514         int err;
515         static s32 rover = -4097;
516
517 retry:
518         cond_resched();
519         netlink_table_grab();
520         head = nl_pid_hashfn(hash, pid);
521         sk_for_each(osk, node, head) {
522                 if (nlk_sk(osk)->pid == pid) {
523                         /* Bind collision, search negative pid values. */
524                         pid = rover--;
525                         if (rover > -4097)
526                                 rover = -4097;
527                         netlink_table_ungrab();
528                         goto retry;
529                 }
530         }
531         netlink_table_ungrab();
532
533         err = netlink_insert(sk, pid);
534         if (err == -EADDRINUSE)
535                 goto retry;
536
537         /* If 2 threads race to autobind, that is fine.  */
538         if (err == -EBUSY)
539                 err = 0;
540
541         return err;
542 }
543
544 static inline int netlink_capable(struct socket *sock, unsigned int flag)
545 {
546         return (nl_table[sock->sk->sk_protocol].nl_nonroot & flag) ||
547                capable(CAP_NET_ADMIN);
548 }
549
550 static void
551 netlink_update_subscriptions(struct sock *sk, unsigned int subscriptions)
552 {
553         struct netlink_sock *nlk = nlk_sk(sk);
554
555         if (nlk->subscriptions && !subscriptions)
556                 __sk_del_bind_node(sk);
557         else if (!nlk->subscriptions && subscriptions)
558                 sk_add_bind_node(sk, &nl_table[sk->sk_protocol].mc_list);
559         nlk->subscriptions = subscriptions;
560 }
561
562 static int netlink_realloc_groups(struct sock *sk)
563 {
564         struct netlink_sock *nlk = nlk_sk(sk);
565         unsigned int groups;
566         unsigned long *new_groups;
567         int err = 0;
568
569         netlink_table_grab();
570
571         groups = nl_table[sk->sk_protocol].groups;
572         if (!nl_table[sk->sk_protocol].registered) {
573                 err = -ENOENT;
574                 goto out_unlock;
575         }
576
577         if (nlk->ngroups >= groups)
578                 goto out_unlock;
579
580         new_groups = krealloc(nlk->groups, NLGRPSZ(groups), GFP_ATOMIC);
581         if (new_groups == NULL) {
582                 err = -ENOMEM;
583                 goto out_unlock;
584         }
585         memset((char*)new_groups + NLGRPSZ(nlk->ngroups), 0,
586                NLGRPSZ(groups) - NLGRPSZ(nlk->ngroups));
587
588         nlk->groups = new_groups;
589         nlk->ngroups = groups;
590  out_unlock:
591         netlink_table_ungrab();
592         return err;
593 }
594
595 static int netlink_bind(struct socket *sock, struct sockaddr *addr, int addr_len)
596 {
597         struct sock *sk = sock->sk;
598         struct netlink_sock *nlk = nlk_sk(sk);
599         struct sockaddr_nl *nladdr = (struct sockaddr_nl *)addr;
600         int err;
601
602         if (nladdr->nl_family != AF_NETLINK)
603                 return -EINVAL;
604
605         /* Only superuser is allowed to listen multicasts */
606         if (nladdr->nl_groups) {
607                 if (!netlink_capable(sock, NL_NONROOT_RECV))
608                         return -EPERM;
609                 err = netlink_realloc_groups(sk);
610                 if (err)
611                         return err;
612         }
613
614         if (nlk->pid) {
615                 if (nladdr->nl_pid != nlk->pid)
616                         return -EINVAL;
617         } else {
618                 err = nladdr->nl_pid ?
619                         netlink_insert(sk, nladdr->nl_pid) :
620                         netlink_autobind(sock);
621                 if (err)
622                         return err;
623         }
624
625         if (!nladdr->nl_groups && (nlk->groups == NULL || !(u32)nlk->groups[0]))
626                 return 0;
627
628         netlink_table_grab();
629         netlink_update_subscriptions(sk, nlk->subscriptions +
630                                          hweight32(nladdr->nl_groups) -
631                                          hweight32(nlk->groups[0]));
632         nlk->groups[0] = (nlk->groups[0] & ~0xffffffffUL) | nladdr->nl_groups;
633         netlink_update_listeners(sk);
634         netlink_table_ungrab();
635
636         return 0;
637 }
638
639 static int netlink_connect(struct socket *sock, struct sockaddr *addr,
640                            int alen, int flags)
641 {
642         int err = 0;
643         struct sock *sk = sock->sk;
644         struct netlink_sock *nlk = nlk_sk(sk);
645         struct sockaddr_nl *nladdr=(struct sockaddr_nl*)addr;
646
647         if (addr->sa_family == AF_UNSPEC) {
648                 sk->sk_state    = NETLINK_UNCONNECTED;
649                 nlk->dst_pid    = 0;
650                 nlk->dst_group  = 0;
651                 return 0;
652         }
653         if (addr->sa_family != AF_NETLINK)
654                 return -EINVAL;
655
656         /* Only superuser is allowed to send multicasts */
657         if (nladdr->nl_groups && !netlink_capable(sock, NL_NONROOT_SEND))
658                 return -EPERM;
659
660         if (!nlk->pid)
661                 err = netlink_autobind(sock);
662
663         if (err == 0) {
664                 sk->sk_state    = NETLINK_CONNECTED;
665                 nlk->dst_pid    = nladdr->nl_pid;
666                 nlk->dst_group  = ffs(nladdr->nl_groups);
667         }
668
669         return err;
670 }
671
672 static int netlink_getname(struct socket *sock, struct sockaddr *addr, int *addr_len, int peer)
673 {
674         struct sock *sk = sock->sk;
675         struct netlink_sock *nlk = nlk_sk(sk);
676         struct sockaddr_nl *nladdr=(struct sockaddr_nl *)addr;
677
678         nladdr->nl_family = AF_NETLINK;
679         nladdr->nl_pad = 0;
680         *addr_len = sizeof(*nladdr);
681
682         if (peer) {
683                 nladdr->nl_pid = nlk->dst_pid;
684                 nladdr->nl_groups = netlink_group_mask(nlk->dst_group);
685         } else {
686                 nladdr->nl_pid = nlk->pid;
687                 nladdr->nl_groups = nlk->groups ? nlk->groups[0] : 0;
688         }
689         return 0;
690 }
691
692 static void netlink_overrun(struct sock *sk)
693 {
694         if (!test_and_set_bit(0, &nlk_sk(sk)->state)) {
695                 sk->sk_err = ENOBUFS;
696                 sk->sk_error_report(sk);
697         }
698 }
699
700 static struct sock *netlink_getsockbypid(struct sock *ssk, u32 pid)
701 {
702         int protocol = ssk->sk_protocol;
703         struct sock *sock;
704         struct netlink_sock *nlk;
705
706         sock = netlink_lookup(protocol, pid);
707         if (!sock)
708                 return ERR_PTR(-ECONNREFUSED);
709
710         /* Don't bother queuing skb if kernel socket has no input function */
711         nlk = nlk_sk(sock);
712         if ((nlk->pid == 0 && !nlk->data_ready) ||
713             (sock->sk_state == NETLINK_CONNECTED &&
714              nlk->dst_pid != nlk_sk(ssk)->pid)) {
715                 sock_put(sock);
716                 return ERR_PTR(-ECONNREFUSED);
717         }
718         return sock;
719 }
720
721 struct sock *netlink_getsockbyfilp(struct file *filp)
722 {
723         struct inode *inode = filp->f_path.dentry->d_inode;
724         struct sock *sock;
725
726         if (!S_ISSOCK(inode->i_mode))
727                 return ERR_PTR(-ENOTSOCK);
728
729         sock = SOCKET_I(inode)->sk;
730         if (sock->sk_family != AF_NETLINK)
731                 return ERR_PTR(-EINVAL);
732
733         sock_hold(sock);
734         return sock;
735 }
736
737 /*
738  * Attach a skb to a netlink socket.
739  * The caller must hold a reference to the destination socket. On error, the
740  * reference is dropped. The skb is not send to the destination, just all
741  * all error checks are performed and memory in the queue is reserved.
742  * Return values:
743  * < 0: error. skb freed, reference to sock dropped.
744  * 0: continue
745  * 1: repeat lookup - reference dropped while waiting for socket memory.
746  */
747 int netlink_attachskb(struct sock *sk, struct sk_buff *skb, int nonblock,
748                 long timeo, struct sock *ssk)
749 {
750         struct netlink_sock *nlk;
751
752         nlk = nlk_sk(sk);
753
754         if (atomic_read(&sk->sk_rmem_alloc) > sk->sk_rcvbuf ||
755             test_bit(0, &nlk->state)) {
756                 DECLARE_WAITQUEUE(wait, current);
757                 if (!timeo) {
758                         if (!ssk || nlk_sk(ssk)->pid == 0)
759                                 netlink_overrun(sk);
760                         sock_put(sk);
761                         kfree_skb(skb);
762                         return -EAGAIN;
763                 }
764
765                 __set_current_state(TASK_INTERRUPTIBLE);
766                 add_wait_queue(&nlk->wait, &wait);
767
768                 if ((atomic_read(&sk->sk_rmem_alloc) > sk->sk_rcvbuf ||
769                      test_bit(0, &nlk->state)) &&
770                     !sock_flag(sk, SOCK_DEAD))
771                         timeo = schedule_timeout(timeo);
772
773                 __set_current_state(TASK_RUNNING);
774                 remove_wait_queue(&nlk->wait, &wait);
775                 sock_put(sk);
776
777                 if (signal_pending(current)) {
778                         kfree_skb(skb);
779                         return sock_intr_errno(timeo);
780                 }
781                 return 1;
782         }
783         skb_set_owner_r(skb, sk);
784         return 0;
785 }
786
787 int netlink_sendskb(struct sock *sk, struct sk_buff *skb, int protocol)
788 {
789         int len = skb->len;
790
791         skb_queue_tail(&sk->sk_receive_queue, skb);
792         sk->sk_data_ready(sk, len);
793         sock_put(sk);
794         return len;
795 }
796
797 void netlink_detachskb(struct sock *sk, struct sk_buff *skb)
798 {
799         kfree_skb(skb);
800         sock_put(sk);
801 }
802
803 static inline struct sk_buff *netlink_trim(struct sk_buff *skb,
804                                            gfp_t allocation)
805 {
806         int delta;
807
808         skb_orphan(skb);
809
810         delta = skb->end - skb->tail;
811         if (delta * 2 < skb->truesize)
812                 return skb;
813
814         if (skb_shared(skb)) {
815                 struct sk_buff *nskb = skb_clone(skb, allocation);
816                 if (!nskb)
817                         return skb;
818                 kfree_skb(skb);
819                 skb = nskb;
820         }
821
822         if (!pskb_expand_head(skb, 0, -delta, allocation))
823                 skb->truesize -= delta;
824
825         return skb;
826 }
827
828 int netlink_unicast(struct sock *ssk, struct sk_buff *skb, u32 pid, int nonblock)
829 {
830         struct sock *sk;
831         int err;
832         long timeo;
833
834         skb = netlink_trim(skb, gfp_any());
835
836         timeo = sock_sndtimeo(ssk, nonblock);
837 retry:
838         sk = netlink_getsockbypid(ssk, pid);
839         if (IS_ERR(sk)) {
840                 kfree_skb(skb);
841                 return PTR_ERR(sk);
842         }
843         err = netlink_attachskb(sk, skb, nonblock, timeo, ssk);
844         if (err == 1)
845                 goto retry;
846         if (err)
847                 return err;
848
849         return netlink_sendskb(sk, skb, ssk->sk_protocol);
850 }
851
852 int netlink_has_listeners(struct sock *sk, unsigned int group)
853 {
854         int res = 0;
855         unsigned long *listeners;
856
857         BUG_ON(!(nlk_sk(sk)->flags & NETLINK_KERNEL_SOCKET));
858
859         rcu_read_lock();
860         listeners = rcu_dereference(nl_table[sk->sk_protocol].listeners);
861
862         if (group - 1 < nl_table[sk->sk_protocol].groups)
863                 res = test_bit(group - 1, listeners);
864
865         rcu_read_unlock();
866
867         return res;
868 }
869 EXPORT_SYMBOL_GPL(netlink_has_listeners);
870
871 static __inline__ int netlink_broadcast_deliver(struct sock *sk, struct sk_buff *skb)
872 {
873         struct netlink_sock *nlk = nlk_sk(sk);
874
875         if (atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf &&
876             !test_bit(0, &nlk->state)) {
877                 skb_set_owner_r(skb, sk);
878                 skb_queue_tail(&sk->sk_receive_queue, skb);
879                 sk->sk_data_ready(sk, skb->len);
880                 return atomic_read(&sk->sk_rmem_alloc) > sk->sk_rcvbuf;
881         }
882         return -1;
883 }
884
885 struct netlink_broadcast_data {
886         struct sock *exclude_sk;
887         u32 pid;
888         u32 group;
889         int failure;
890         int congested;
891         int delivered;
892         gfp_t allocation;
893         struct sk_buff *skb, *skb2;
894 };
895
896 static inline int do_one_broadcast(struct sock *sk,
897                                    struct netlink_broadcast_data *p)
898 {
899         struct netlink_sock *nlk = nlk_sk(sk);
900         int val;
901
902         if (p->exclude_sk == sk)
903                 goto out;
904
905         if (nlk->pid == p->pid || p->group - 1 >= nlk->ngroups ||
906             !test_bit(p->group - 1, nlk->groups))
907                 goto out;
908
909         if (p->failure) {
910                 netlink_overrun(sk);
911                 goto out;
912         }
913
914         sock_hold(sk);
915         if (p->skb2 == NULL) {
916                 if (skb_shared(p->skb)) {
917                         p->skb2 = skb_clone(p->skb, p->allocation);
918                 } else {
919                         p->skb2 = skb_get(p->skb);
920                         /*
921                          * skb ownership may have been set when
922                          * delivered to a previous socket.
923                          */
924                         skb_orphan(p->skb2);
925                 }
926         }
927         if (p->skb2 == NULL) {
928                 netlink_overrun(sk);
929                 /* Clone failed. Notify ALL listeners. */
930                 p->failure = 1;
931         } else if ((val = netlink_broadcast_deliver(sk, p->skb2)) < 0) {
932                 netlink_overrun(sk);
933         } else {
934                 p->congested |= val;
935                 p->delivered = 1;
936                 p->skb2 = NULL;
937         }
938         sock_put(sk);
939
940 out:
941         return 0;
942 }
943
944 int netlink_broadcast(struct sock *ssk, struct sk_buff *skb, u32 pid,
945                       u32 group, gfp_t allocation)
946 {
947         struct netlink_broadcast_data info;
948         struct hlist_node *node;
949         struct sock *sk;
950
951         skb = netlink_trim(skb, allocation);
952
953         info.exclude_sk = ssk;
954         info.pid = pid;
955         info.group = group;
956         info.failure = 0;
957         info.congested = 0;
958         info.delivered = 0;
959         info.allocation = allocation;
960         info.skb = skb;
961         info.skb2 = NULL;
962
963         /* While we sleep in clone, do not allow to change socket list */
964
965         netlink_lock_table();
966
967         sk_for_each_bound(sk, node, &nl_table[ssk->sk_protocol].mc_list)
968                 do_one_broadcast(sk, &info);
969
970         kfree_skb(skb);
971
972         netlink_unlock_table();
973
974         if (info.skb2)
975                 kfree_skb(info.skb2);
976
977         if (info.delivered) {
978                 if (info.congested && (allocation & __GFP_WAIT))
979                         yield();
980                 return 0;
981         }
982         if (info.failure)
983                 return -ENOBUFS;
984         return -ESRCH;
985 }
986
987 struct netlink_set_err_data {
988         struct sock *exclude_sk;
989         u32 pid;
990         u32 group;
991         int code;
992 };
993
994 static inline int do_one_set_err(struct sock *sk,
995                                  struct netlink_set_err_data *p)
996 {
997         struct netlink_sock *nlk = nlk_sk(sk);
998
999         if (sk == p->exclude_sk)
1000                 goto out;
1001
1002         if (nlk->pid == p->pid || p->group - 1 >= nlk->ngroups ||
1003             !test_bit(p->group - 1, nlk->groups))
1004                 goto out;
1005
1006         sk->sk_err = p->code;
1007         sk->sk_error_report(sk);
1008 out:
1009         return 0;
1010 }
1011
1012 void netlink_set_err(struct sock *ssk, u32 pid, u32 group, int code)
1013 {
1014         struct netlink_set_err_data info;
1015         struct hlist_node *node;
1016         struct sock *sk;
1017
1018         info.exclude_sk = ssk;
1019         info.pid = pid;
1020         info.group = group;
1021         info.code = code;
1022
1023         read_lock(&nl_table_lock);
1024
1025         sk_for_each_bound(sk, node, &nl_table[ssk->sk_protocol].mc_list)
1026                 do_one_set_err(sk, &info);
1027
1028         read_unlock(&nl_table_lock);
1029 }
1030
1031 /* must be called with netlink table grabbed */
1032 static void netlink_update_socket_mc(struct netlink_sock *nlk,
1033                                      unsigned int group,
1034                                      int is_new)
1035 {
1036         int old, new = !!is_new, subscriptions;
1037
1038         old = test_bit(group - 1, nlk->groups);
1039         subscriptions = nlk->subscriptions - old + new;
1040         if (new)
1041                 __set_bit(group - 1, nlk->groups);
1042         else
1043                 __clear_bit(group - 1, nlk->groups);
1044         netlink_update_subscriptions(&nlk->sk, subscriptions);
1045         netlink_update_listeners(&nlk->sk);
1046 }
1047
1048 static int netlink_setsockopt(struct socket *sock, int level, int optname,
1049                               char __user *optval, int optlen)
1050 {
1051         struct sock *sk = sock->sk;
1052         struct netlink_sock *nlk = nlk_sk(sk);
1053         unsigned int val = 0;
1054         int err;
1055
1056         if (level != SOL_NETLINK)
1057                 return -ENOPROTOOPT;
1058
1059         if (optlen >= sizeof(int) &&
1060             get_user(val, (unsigned int __user *)optval))
1061                 return -EFAULT;
1062
1063         switch (optname) {
1064         case NETLINK_PKTINFO:
1065                 if (val)
1066                         nlk->flags |= NETLINK_RECV_PKTINFO;
1067                 else
1068                         nlk->flags &= ~NETLINK_RECV_PKTINFO;
1069                 err = 0;
1070                 break;
1071         case NETLINK_ADD_MEMBERSHIP:
1072         case NETLINK_DROP_MEMBERSHIP: {
1073                 if (!netlink_capable(sock, NL_NONROOT_RECV))
1074                         return -EPERM;
1075                 err = netlink_realloc_groups(sk);
1076                 if (err)
1077                         return err;
1078                 if (!val || val - 1 >= nlk->ngroups)
1079                         return -EINVAL;
1080                 netlink_table_grab();
1081                 netlink_update_socket_mc(nlk, val,
1082                                          optname == NETLINK_ADD_MEMBERSHIP);
1083                 netlink_table_ungrab();
1084                 err = 0;
1085                 break;
1086         }
1087         default:
1088                 err = -ENOPROTOOPT;
1089         }
1090         return err;
1091 }
1092
1093 static int netlink_getsockopt(struct socket *sock, int level, int optname,
1094                               char __user *optval, int __user *optlen)
1095 {
1096         struct sock *sk = sock->sk;
1097         struct netlink_sock *nlk = nlk_sk(sk);
1098         int len, val, err;
1099
1100         if (level != SOL_NETLINK)
1101                 return -ENOPROTOOPT;
1102
1103         if (get_user(len, optlen))
1104                 return -EFAULT;
1105         if (len < 0)
1106                 return -EINVAL;
1107
1108         switch (optname) {
1109         case NETLINK_PKTINFO:
1110                 if (len < sizeof(int))
1111                         return -EINVAL;
1112                 len = sizeof(int);
1113                 val = nlk->flags & NETLINK_RECV_PKTINFO ? 1 : 0;
1114                 if (put_user(len, optlen) ||
1115                     put_user(val, optval))
1116                         return -EFAULT;
1117                 err = 0;
1118                 break;
1119         default:
1120                 err = -ENOPROTOOPT;
1121         }
1122         return err;
1123 }
1124
1125 static void netlink_cmsg_recv_pktinfo(struct msghdr *msg, struct sk_buff *skb)
1126 {
1127         struct nl_pktinfo info;
1128
1129         info.group = NETLINK_CB(skb).dst_group;
1130         put_cmsg(msg, SOL_NETLINK, NETLINK_PKTINFO, sizeof(info), &info);
1131 }
1132
1133 static inline void netlink_rcv_wake(struct sock *sk)
1134 {
1135         struct netlink_sock *nlk = nlk_sk(sk);
1136
1137         if (skb_queue_empty(&sk->sk_receive_queue))
1138                 clear_bit(0, &nlk->state);
1139         if (!test_bit(0, &nlk->state))
1140                 wake_up_interruptible(&nlk->wait);
1141 }
1142
1143 static int netlink_sendmsg(struct kiocb *kiocb, struct socket *sock,
1144                            struct msghdr *msg, size_t len)
1145 {
1146         struct sock_iocb *siocb = kiocb_to_siocb(kiocb);
1147         struct sock *sk = sock->sk;
1148         struct netlink_sock *nlk = nlk_sk(sk);
1149         struct sockaddr_nl *addr=msg->msg_name;
1150         u32 dst_pid;
1151         u32 dst_group;
1152         struct sk_buff *skb;
1153         int err;
1154         struct scm_cookie scm;
1155
1156         if (msg->msg_flags&MSG_OOB)
1157                 return -EOPNOTSUPP;
1158
1159         if (NULL == siocb->scm)
1160                 siocb->scm = &scm;
1161         err = scm_send(sock, msg, siocb->scm);
1162         if (err < 0)
1163                 return err;
1164
1165         if (msg->msg_namelen) {
1166                 if (addr->nl_family != AF_NETLINK)
1167                         return -EINVAL;
1168                 dst_pid = addr->nl_pid;
1169                 dst_group = ffs(addr->nl_groups);
1170                 if (dst_group && !netlink_capable(sock, NL_NONROOT_SEND))
1171                         return -EPERM;
1172         } else {
1173                 dst_pid = nlk->dst_pid;
1174                 dst_group = nlk->dst_group;
1175         }
1176
1177         if (!nlk->pid) {
1178                 err = netlink_autobind(sock);
1179                 if (err)
1180                         goto out;
1181         }
1182
1183         err = -EMSGSIZE;
1184         if (len > sk->sk_sndbuf - 32)
1185                 goto out;
1186         err = -ENOBUFS;
1187         skb = alloc_skb(len, GFP_KERNEL);
1188         if (skb==NULL)
1189                 goto out;
1190
1191         NETLINK_CB(skb).pid     = nlk->pid;
1192         NETLINK_CB(skb).dst_group = dst_group;
1193         NETLINK_CB(skb).loginuid = audit_get_loginuid(current->audit_context);
1194         selinux_get_task_sid(current, &(NETLINK_CB(skb).sid));
1195         memcpy(NETLINK_CREDS(skb), &siocb->scm->creds, sizeof(struct ucred));
1196
1197         /* What can I do? Netlink is asynchronous, so that
1198            we will have to save current capabilities to
1199            check them, when this message will be delivered
1200            to corresponding kernel module.   --ANK (980802)
1201          */
1202
1203         err = -EFAULT;
1204         if (memcpy_fromiovec(skb_put(skb,len), msg->msg_iov, len)) {
1205                 kfree_skb(skb);
1206                 goto out;
1207         }
1208
1209         err = security_netlink_send(sk, skb);
1210         if (err) {
1211                 kfree_skb(skb);
1212                 goto out;
1213         }
1214
1215         if (dst_group) {
1216                 atomic_inc(&skb->users);
1217                 netlink_broadcast(sk, skb, dst_pid, dst_group, GFP_KERNEL);
1218         }
1219         err = netlink_unicast(sk, skb, dst_pid, msg->msg_flags&MSG_DONTWAIT);
1220
1221 out:
1222         return err;
1223 }
1224
1225 static int netlink_recvmsg(struct kiocb *kiocb, struct socket *sock,
1226                            struct msghdr *msg, size_t len,
1227                            int flags)
1228 {
1229         struct sock_iocb *siocb = kiocb_to_siocb(kiocb);
1230         struct scm_cookie scm;
1231         struct sock *sk = sock->sk;
1232         struct netlink_sock *nlk = nlk_sk(sk);
1233         int noblock = flags&MSG_DONTWAIT;
1234         size_t copied;
1235         struct sk_buff *skb;
1236         int err;
1237
1238         if (flags&MSG_OOB)
1239                 return -EOPNOTSUPP;
1240
1241         copied = 0;
1242
1243         skb = skb_recv_datagram(sk,flags,noblock,&err);
1244         if (skb==NULL)
1245                 goto out;
1246
1247         msg->msg_namelen = 0;
1248
1249         copied = skb->len;
1250         if (len < copied) {
1251                 msg->msg_flags |= MSG_TRUNC;
1252                 copied = len;
1253         }
1254
1255         skb_reset_transport_header(skb);
1256         err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
1257
1258         if (msg->msg_name) {
1259                 struct sockaddr_nl *addr = (struct sockaddr_nl*)msg->msg_name;
1260                 addr->nl_family = AF_NETLINK;
1261                 addr->nl_pad    = 0;
1262                 addr->nl_pid    = NETLINK_CB(skb).pid;
1263                 addr->nl_groups = netlink_group_mask(NETLINK_CB(skb).dst_group);
1264                 msg->msg_namelen = sizeof(*addr);
1265         }
1266
1267         if (nlk->flags & NETLINK_RECV_PKTINFO)
1268                 netlink_cmsg_recv_pktinfo(msg, skb);
1269
1270         if (NULL == siocb->scm) {
1271                 memset(&scm, 0, sizeof(scm));
1272                 siocb->scm = &scm;
1273         }
1274         siocb->scm->creds = *NETLINK_CREDS(skb);
1275         if (flags & MSG_TRUNC)
1276                 copied = skb->len;
1277         skb_free_datagram(sk, skb);
1278
1279         if (nlk->cb && atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf / 2)
1280                 netlink_dump(sk);
1281
1282         scm_recv(sock, msg, siocb->scm, flags);
1283 out:
1284         netlink_rcv_wake(sk);
1285         return err ? : copied;
1286 }
1287
1288 static void netlink_data_ready(struct sock *sk, int len)
1289 {
1290         struct netlink_sock *nlk = nlk_sk(sk);
1291
1292         if (nlk->data_ready)
1293                 nlk->data_ready(sk, len);
1294         netlink_rcv_wake(sk);
1295 }
1296
1297 /*
1298  *      We export these functions to other modules. They provide a
1299  *      complete set of kernel non-blocking support for message
1300  *      queueing.
1301  */
1302
1303 struct sock *
1304 netlink_kernel_create(int unit, unsigned int groups,
1305                       void (*input)(struct sock *sk, int len),
1306                       struct mutex *cb_mutex, struct module *module)
1307 {
1308         struct socket *sock;
1309         struct sock *sk;
1310         struct netlink_sock *nlk;
1311         unsigned long *listeners = NULL;
1312
1313         BUG_ON(!nl_table);
1314
1315         if (unit<0 || unit>=MAX_LINKS)
1316                 return NULL;
1317
1318         if (sock_create_lite(PF_NETLINK, SOCK_DGRAM, unit, &sock))
1319                 return NULL;
1320
1321         if (__netlink_create(sock, cb_mutex, unit) < 0)
1322                 goto out_sock_release;
1323
1324         if (groups < 32)
1325                 groups = 32;
1326
1327         listeners = kzalloc(NLGRPSZ(groups), GFP_KERNEL);
1328         if (!listeners)
1329                 goto out_sock_release;
1330
1331         sk = sock->sk;
1332         sk->sk_data_ready = netlink_data_ready;
1333         if (input)
1334                 nlk_sk(sk)->data_ready = input;
1335
1336         if (netlink_insert(sk, 0))
1337                 goto out_sock_release;
1338
1339         nlk = nlk_sk(sk);
1340         nlk->flags |= NETLINK_KERNEL_SOCKET;
1341
1342         netlink_table_grab();
1343         nl_table[unit].groups = groups;
1344         nl_table[unit].listeners = listeners;
1345         nl_table[unit].cb_mutex = cb_mutex;
1346         nl_table[unit].module = module;
1347         nl_table[unit].registered = 1;
1348         netlink_table_ungrab();
1349
1350         return sk;
1351
1352 out_sock_release:
1353         kfree(listeners);
1354         sock_release(sock);
1355         return NULL;
1356 }
1357
1358 /**
1359  * netlink_change_ngroups - change number of multicast groups
1360  *
1361  * This changes the number of multicast groups that are available
1362  * on a certain netlink family. Note that it is not possible to
1363  * change the number of groups to below 32. Also note that it does
1364  * not implicitly call netlink_clear_multicast_users() when the
1365  * number of groups is reduced.
1366  *
1367  * @sk: The kernel netlink socket, as returned by netlink_kernel_create().
1368  * @groups: The new number of groups.
1369  */
1370 int netlink_change_ngroups(struct sock *sk, unsigned int groups)
1371 {
1372         unsigned long *listeners, *old = NULL;
1373         struct netlink_table *tbl = &nl_table[sk->sk_protocol];
1374         int err = 0;
1375
1376         if (groups < 32)
1377                 groups = 32;
1378
1379         netlink_table_grab();
1380         if (NLGRPSZ(tbl->groups) < NLGRPSZ(groups)) {
1381                 listeners = kzalloc(NLGRPSZ(groups), GFP_ATOMIC);
1382                 if (!listeners) {
1383                         err = -ENOMEM;
1384                         goto out_ungrab;
1385                 }
1386                 old = tbl->listeners;
1387                 memcpy(listeners, old, NLGRPSZ(tbl->groups));
1388                 rcu_assign_pointer(tbl->listeners, listeners);
1389         }
1390         tbl->groups = groups;
1391
1392  out_ungrab:
1393         netlink_table_ungrab();
1394         synchronize_rcu();
1395         kfree(old);
1396         return err;
1397 }
1398 EXPORT_SYMBOL(netlink_change_ngroups);
1399
1400 /**
1401  * netlink_clear_multicast_users - kick off multicast listeners
1402  *
1403  * This function removes all listeners from the given group.
1404  * @ksk: The kernel netlink socket, as returned by
1405  *      netlink_kernel_create().
1406  * @group: The multicast group to clear.
1407  */
1408 void netlink_clear_multicast_users(struct sock *ksk, unsigned int group)
1409 {
1410         struct sock *sk;
1411         struct hlist_node *node;
1412         struct netlink_table *tbl = &nl_table[ksk->sk_protocol];
1413
1414         netlink_table_grab();
1415
1416         sk_for_each_bound(sk, node, &tbl->mc_list)
1417                 netlink_update_socket_mc(nlk_sk(sk), group, 0);
1418
1419         netlink_table_ungrab();
1420 }
1421 EXPORT_SYMBOL(netlink_clear_multicast_users);
1422
1423 void netlink_set_nonroot(int protocol, unsigned int flags)
1424 {
1425         if ((unsigned int)protocol < MAX_LINKS)
1426                 nl_table[protocol].nl_nonroot = flags;
1427 }
1428
1429 static void netlink_destroy_callback(struct netlink_callback *cb)
1430 {
1431         if (cb->skb)
1432                 kfree_skb(cb->skb);
1433         kfree(cb);
1434 }
1435
1436 /*
1437  * It looks a bit ugly.
1438  * It would be better to create kernel thread.
1439  */
1440
1441 static int netlink_dump(struct sock *sk)
1442 {
1443         struct netlink_sock *nlk = nlk_sk(sk);
1444         struct netlink_callback *cb;
1445         struct sk_buff *skb;
1446         struct nlmsghdr *nlh;
1447         int len, err = -ENOBUFS;
1448
1449         skb = sock_rmalloc(sk, NLMSG_GOODSIZE, 0, GFP_KERNEL);
1450         if (!skb)
1451                 goto errout;
1452
1453         mutex_lock(nlk->cb_mutex);
1454
1455         cb = nlk->cb;
1456         if (cb == NULL) {
1457                 err = -EINVAL;
1458                 goto errout_skb;
1459         }
1460
1461         len = cb->dump(skb, cb);
1462
1463         if (len > 0) {
1464                 mutex_unlock(nlk->cb_mutex);
1465                 skb_queue_tail(&sk->sk_receive_queue, skb);
1466                 sk->sk_data_ready(sk, len);
1467                 return 0;
1468         }
1469
1470         nlh = nlmsg_put_answer(skb, cb, NLMSG_DONE, sizeof(len), NLM_F_MULTI);
1471         if (!nlh)
1472                 goto errout_skb;
1473
1474         memcpy(nlmsg_data(nlh), &len, sizeof(len));
1475
1476         skb_queue_tail(&sk->sk_receive_queue, skb);
1477         sk->sk_data_ready(sk, skb->len);
1478
1479         if (cb->done)
1480                 cb->done(cb);
1481         nlk->cb = NULL;
1482         mutex_unlock(nlk->cb_mutex);
1483
1484         netlink_destroy_callback(cb);
1485         return 0;
1486
1487 errout_skb:
1488         mutex_unlock(nlk->cb_mutex);
1489         kfree_skb(skb);
1490 errout:
1491         return err;
1492 }
1493
1494 int netlink_dump_start(struct sock *ssk, struct sk_buff *skb,
1495                        struct nlmsghdr *nlh,
1496                        int (*dump)(struct sk_buff *skb, struct netlink_callback*),
1497                        int (*done)(struct netlink_callback*))
1498 {
1499         struct netlink_callback *cb;
1500         struct sock *sk;
1501         struct netlink_sock *nlk;
1502
1503         cb = kzalloc(sizeof(*cb), GFP_KERNEL);
1504         if (cb == NULL)
1505                 return -ENOBUFS;
1506
1507         cb->dump = dump;
1508         cb->done = done;
1509         cb->nlh = nlh;
1510         atomic_inc(&skb->users);
1511         cb->skb = skb;
1512
1513         sk = netlink_lookup(ssk->sk_protocol, NETLINK_CB(skb).pid);
1514         if (sk == NULL) {
1515                 netlink_destroy_callback(cb);
1516                 return -ECONNREFUSED;
1517         }
1518         nlk = nlk_sk(sk);
1519         /* A dump is in progress... */
1520         mutex_lock(nlk->cb_mutex);
1521         if (nlk->cb) {
1522                 mutex_unlock(nlk->cb_mutex);
1523                 netlink_destroy_callback(cb);
1524                 sock_put(sk);
1525                 return -EBUSY;
1526         }
1527         nlk->cb = cb;
1528         mutex_unlock(nlk->cb_mutex);
1529
1530         netlink_dump(sk);
1531         sock_put(sk);
1532
1533         /* We successfully started a dump, by returning -EINTR we
1534          * signal the queue mangement to interrupt processing of
1535          * any netlink messages so userspace gets a chance to read
1536          * the results. */
1537         return -EINTR;
1538 }
1539
1540 void netlink_ack(struct sk_buff *in_skb, struct nlmsghdr *nlh, int err)
1541 {
1542         struct sk_buff *skb;
1543         struct nlmsghdr *rep;
1544         struct nlmsgerr *errmsg;
1545         size_t payload = sizeof(*errmsg);
1546
1547         /* error messages get the original request appened */
1548         if (err)
1549                 payload += nlmsg_len(nlh);
1550
1551         skb = nlmsg_new(payload, GFP_KERNEL);
1552         if (!skb) {
1553                 struct sock *sk;
1554
1555                 sk = netlink_lookup(in_skb->sk->sk_protocol,
1556                                     NETLINK_CB(in_skb).pid);
1557                 if (sk) {
1558                         sk->sk_err = ENOBUFS;
1559                         sk->sk_error_report(sk);
1560                         sock_put(sk);
1561                 }
1562                 return;
1563         }
1564
1565         rep = __nlmsg_put(skb, NETLINK_CB(in_skb).pid, nlh->nlmsg_seq,
1566                           NLMSG_ERROR, sizeof(struct nlmsgerr), 0);
1567         errmsg = nlmsg_data(rep);
1568         errmsg->error = err;
1569         memcpy(&errmsg->msg, nlh, err ? nlh->nlmsg_len : sizeof(*nlh));
1570         netlink_unicast(in_skb->sk, skb, NETLINK_CB(in_skb).pid, MSG_DONTWAIT);
1571 }
1572
1573 static int netlink_rcv_skb(struct sk_buff *skb, int (*cb)(struct sk_buff *,
1574                                                      struct nlmsghdr *))
1575 {
1576         struct nlmsghdr *nlh;
1577         int err;
1578
1579         while (skb->len >= nlmsg_total_size(0)) {
1580                 nlh = nlmsg_hdr(skb);
1581                 err = 0;
1582
1583                 if (nlh->nlmsg_len < NLMSG_HDRLEN || skb->len < nlh->nlmsg_len)
1584                         return 0;
1585
1586                 /* Only requests are handled by the kernel */
1587                 if (!(nlh->nlmsg_flags & NLM_F_REQUEST))
1588                         goto skip;
1589
1590                 /* Skip control messages */
1591                 if (nlh->nlmsg_type < NLMSG_MIN_TYPE)
1592                         goto skip;
1593
1594                 err = cb(skb, nlh);
1595                 if (err == -EINTR) {
1596                         /* Not an error, but we interrupt processing */
1597                         netlink_queue_skip(nlh, skb);
1598                         return err;
1599                 }
1600 skip:
1601                 if (nlh->nlmsg_flags & NLM_F_ACK || err)
1602                         netlink_ack(skb, nlh, err);
1603
1604                 netlink_queue_skip(nlh, skb);
1605         }
1606
1607         return 0;
1608 }
1609
1610 /**
1611  * nelink_run_queue - Process netlink receive queue.
1612  * @sk: Netlink socket containing the queue
1613  * @qlen: Place to store queue length upon entry
1614  * @cb: Callback function invoked for each netlink message found
1615  *
1616  * Processes as much as there was in the queue upon entry and invokes
1617  * a callback function for each netlink message found. The callback
1618  * function may refuse a message by returning a negative error code
1619  * but setting the error pointer to 0 in which case this function
1620  * returns with a qlen != 0.
1621  *
1622  * qlen must be initialized to 0 before the initial entry, afterwards
1623  * the function may be called repeatedly until qlen reaches 0.
1624  *
1625  * The callback function may return -EINTR to signal that processing
1626  * of netlink messages shall be interrupted. In this case the message
1627  * currently being processed will NOT be requeued onto the receive
1628  * queue.
1629  */
1630 void netlink_run_queue(struct sock *sk, unsigned int *qlen,
1631                        int (*cb)(struct sk_buff *, struct nlmsghdr *))
1632 {
1633         struct sk_buff *skb;
1634
1635         if (!*qlen || *qlen > skb_queue_len(&sk->sk_receive_queue))
1636                 *qlen = skb_queue_len(&sk->sk_receive_queue);
1637
1638         for (; *qlen; (*qlen)--) {
1639                 skb = skb_dequeue(&sk->sk_receive_queue);
1640                 if (netlink_rcv_skb(skb, cb)) {
1641                         if (skb->len)
1642                                 skb_queue_head(&sk->sk_receive_queue, skb);
1643                         else {
1644                                 kfree_skb(skb);
1645                                 (*qlen)--;
1646                         }
1647                         break;
1648                 }
1649
1650                 kfree_skb(skb);
1651         }
1652 }
1653
1654 /**
1655  * netlink_queue_skip - Skip netlink message while processing queue.
1656  * @nlh: Netlink message to be skipped
1657  * @skb: Socket buffer containing the netlink messages.
1658  *
1659  * Pulls the given netlink message off the socket buffer so the next
1660  * call to netlink_queue_run() will not reconsider the message.
1661  */
1662 static void netlink_queue_skip(struct nlmsghdr *nlh, struct sk_buff *skb)
1663 {
1664         int msglen = NLMSG_ALIGN(nlh->nlmsg_len);
1665
1666         if (msglen > skb->len)
1667                 msglen = skb->len;
1668
1669         skb_pull(skb, msglen);
1670 }
1671
1672 /**
1673  * nlmsg_notify - send a notification netlink message
1674  * @sk: netlink socket to use
1675  * @skb: notification message
1676  * @pid: destination netlink pid for reports or 0
1677  * @group: destination multicast group or 0
1678  * @report: 1 to report back, 0 to disable
1679  * @flags: allocation flags
1680  */
1681 int nlmsg_notify(struct sock *sk, struct sk_buff *skb, u32 pid,
1682                  unsigned int group, int report, gfp_t flags)
1683 {
1684         int err = 0;
1685
1686         if (group) {
1687                 int exclude_pid = 0;
1688
1689                 if (report) {
1690                         atomic_inc(&skb->users);
1691                         exclude_pid = pid;
1692                 }
1693
1694                 /* errors reported via destination sk->sk_err */
1695                 nlmsg_multicast(sk, skb, exclude_pid, group, flags);
1696         }
1697
1698         if (report)
1699                 err = nlmsg_unicast(sk, skb, pid);
1700
1701         return err;
1702 }
1703
1704 #ifdef CONFIG_PROC_FS
1705 struct nl_seq_iter {
1706         int link;
1707         int hash_idx;
1708 };
1709
1710 static struct sock *netlink_seq_socket_idx(struct seq_file *seq, loff_t pos)
1711 {
1712         struct nl_seq_iter *iter = seq->private;
1713         int i, j;
1714         struct sock *s;
1715         struct hlist_node *node;
1716         loff_t off = 0;
1717
1718         for (i=0; i<MAX_LINKS; i++) {
1719                 struct nl_pid_hash *hash = &nl_table[i].hash;
1720
1721                 for (j = 0; j <= hash->mask; j++) {
1722                         sk_for_each(s, node, &hash->table[j]) {
1723                                 if (off == pos) {
1724                                         iter->link = i;
1725                                         iter->hash_idx = j;
1726                                         return s;
1727                                 }
1728                                 ++off;
1729                         }
1730                 }
1731         }
1732         return NULL;
1733 }
1734
1735 static void *netlink_seq_start(struct seq_file *seq, loff_t *pos)
1736 {
1737         read_lock(&nl_table_lock);
1738         return *pos ? netlink_seq_socket_idx(seq, *pos - 1) : SEQ_START_TOKEN;
1739 }
1740
1741 static void *netlink_seq_next(struct seq_file *seq, void *v, loff_t *pos)
1742 {
1743         struct sock *s;
1744         struct nl_seq_iter *iter;
1745         int i, j;
1746
1747         ++*pos;
1748
1749         if (v == SEQ_START_TOKEN)
1750                 return netlink_seq_socket_idx(seq, 0);
1751
1752         s = sk_next(v);
1753         if (s)
1754                 return s;
1755
1756         iter = seq->private;
1757         i = iter->link;
1758         j = iter->hash_idx + 1;
1759
1760         do {
1761                 struct nl_pid_hash *hash = &nl_table[i].hash;
1762
1763                 for (; j <= hash->mask; j++) {
1764                         s = sk_head(&hash->table[j]);
1765                         if (s) {
1766                                 iter->link = i;
1767                                 iter->hash_idx = j;
1768                                 return s;
1769                         }
1770                 }
1771
1772                 j = 0;
1773         } while (++i < MAX_LINKS);
1774
1775         return NULL;
1776 }
1777
1778 static void netlink_seq_stop(struct seq_file *seq, void *v)
1779 {
1780         read_unlock(&nl_table_lock);
1781 }
1782
1783
1784 static int netlink_seq_show(struct seq_file *seq, void *v)
1785 {
1786         if (v == SEQ_START_TOKEN)
1787                 seq_puts(seq,
1788                          "sk       Eth Pid    Groups   "
1789                          "Rmem     Wmem     Dump     Locks\n");
1790         else {
1791                 struct sock *s = v;
1792                 struct netlink_sock *nlk = nlk_sk(s);
1793
1794                 seq_printf(seq, "%p %-3d %-6d %08x %-8d %-8d %p %d\n",
1795                            s,
1796                            s->sk_protocol,
1797                            nlk->pid,
1798                            nlk->groups ? (u32)nlk->groups[0] : 0,
1799                            atomic_read(&s->sk_rmem_alloc),
1800                            atomic_read(&s->sk_wmem_alloc),
1801                            nlk->cb,
1802                            atomic_read(&s->sk_refcnt)
1803                         );
1804
1805         }
1806         return 0;
1807 }
1808
1809 static const struct seq_operations netlink_seq_ops = {
1810         .start  = netlink_seq_start,
1811         .next   = netlink_seq_next,
1812         .stop   = netlink_seq_stop,
1813         .show   = netlink_seq_show,
1814 };
1815
1816
1817 static int netlink_seq_open(struct inode *inode, struct file *file)
1818 {
1819         struct seq_file *seq;
1820         struct nl_seq_iter *iter;
1821         int err;
1822
1823         iter = kzalloc(sizeof(*iter), GFP_KERNEL);
1824         if (!iter)
1825                 return -ENOMEM;
1826
1827         err = seq_open(file, &netlink_seq_ops);
1828         if (err) {
1829                 kfree(iter);
1830                 return err;
1831         }
1832
1833         seq = file->private_data;
1834         seq->private = iter;
1835         return 0;
1836 }
1837
1838 static const struct file_operations netlink_seq_fops = {
1839         .owner          = THIS_MODULE,
1840         .open           = netlink_seq_open,
1841         .read           = seq_read,
1842         .llseek         = seq_lseek,
1843         .release        = seq_release_private,
1844 };
1845
1846 #endif
1847
1848 int netlink_register_notifier(struct notifier_block *nb)
1849 {
1850         return atomic_notifier_chain_register(&netlink_chain, nb);
1851 }
1852
1853 int netlink_unregister_notifier(struct notifier_block *nb)
1854 {
1855         return atomic_notifier_chain_unregister(&netlink_chain, nb);
1856 }
1857
1858 static const struct proto_ops netlink_ops = {
1859         .family =       PF_NETLINK,
1860         .owner =        THIS_MODULE,
1861         .release =      netlink_release,
1862         .bind =         netlink_bind,
1863         .connect =      netlink_connect,
1864         .socketpair =   sock_no_socketpair,
1865         .accept =       sock_no_accept,
1866         .getname =      netlink_getname,
1867         .poll =         datagram_poll,
1868         .ioctl =        sock_no_ioctl,
1869         .listen =       sock_no_listen,
1870         .shutdown =     sock_no_shutdown,
1871         .setsockopt =   netlink_setsockopt,
1872         .getsockopt =   netlink_getsockopt,
1873         .sendmsg =      netlink_sendmsg,
1874         .recvmsg =      netlink_recvmsg,
1875         .mmap =         sock_no_mmap,
1876         .sendpage =     sock_no_sendpage,
1877 };
1878
1879 static struct net_proto_family netlink_family_ops = {
1880         .family = PF_NETLINK,
1881         .create = netlink_create,
1882         .owner  = THIS_MODULE,  /* for consistency 8) */
1883 };
1884
1885 static int __init netlink_proto_init(void)
1886 {
1887         struct sk_buff *dummy_skb;
1888         int i;
1889         unsigned long max;
1890         unsigned int order;
1891         int err = proto_register(&netlink_proto, 0);
1892
1893         if (err != 0)
1894                 goto out;
1895
1896         BUILD_BUG_ON(sizeof(struct netlink_skb_parms) > sizeof(dummy_skb->cb));
1897
1898         nl_table = kcalloc(MAX_LINKS, sizeof(*nl_table), GFP_KERNEL);
1899         if (!nl_table)
1900                 goto panic;
1901
1902         if (num_physpages >= (128 * 1024))
1903                 max = num_physpages >> (21 - PAGE_SHIFT);
1904         else
1905                 max = num_physpages >> (23 - PAGE_SHIFT);
1906
1907         order = get_bitmask_order(max) - 1 + PAGE_SHIFT;
1908         max = (1UL << order) / sizeof(struct hlist_head);
1909         order = get_bitmask_order(max > UINT_MAX ? UINT_MAX : max) - 1;
1910
1911         for (i = 0; i < MAX_LINKS; i++) {
1912                 struct nl_pid_hash *hash = &nl_table[i].hash;
1913
1914                 hash->table = nl_pid_hash_alloc(1 * sizeof(*hash->table));
1915                 if (!hash->table) {
1916                         while (i-- > 0)
1917                                 nl_pid_hash_free(nl_table[i].hash.table,
1918                                                  1 * sizeof(*hash->table));
1919                         kfree(nl_table);
1920                         goto panic;
1921                 }
1922                 memset(hash->table, 0, 1 * sizeof(*hash->table));
1923                 hash->max_shift = order;
1924                 hash->shift = 0;
1925                 hash->mask = 0;
1926                 hash->rehash_time = jiffies;
1927         }
1928
1929         sock_register(&netlink_family_ops);
1930 #ifdef CONFIG_PROC_FS
1931         proc_net_fops_create(&init_net, "netlink", 0, &netlink_seq_fops);
1932 #endif
1933         /* The netlink device handler may be needed early. */
1934         rtnetlink_init();
1935 out:
1936         return err;
1937 panic:
1938         panic("netlink_init: Cannot allocate nl_table\n");
1939 }
1940
1941 core_initcall(netlink_proto_init);
1942
1943 EXPORT_SYMBOL(netlink_ack);
1944 EXPORT_SYMBOL(netlink_run_queue);
1945 EXPORT_SYMBOL(netlink_broadcast);
1946 EXPORT_SYMBOL(netlink_dump_start);
1947 EXPORT_SYMBOL(netlink_kernel_create);
1948 EXPORT_SYMBOL(netlink_register_notifier);
1949 EXPORT_SYMBOL(netlink_set_nonroot);
1950 EXPORT_SYMBOL(netlink_unicast);
1951 EXPORT_SYMBOL(netlink_unregister_notifier);
1952 EXPORT_SYMBOL(nlmsg_notify);