vserver 1.9.5.x5
[linux-2.6.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  *
17  */
18
19 #include <linux/config.h>
20 #include <linux/module.h>
21
22 #include <linux/kernel.h>
23 #include <linux/init.h>
24 #include <linux/major.h>
25 #include <linux/signal.h>
26 #include <linux/sched.h>
27 #include <linux/errno.h>
28 #include <linux/string.h>
29 #include <linux/stat.h>
30 #include <linux/socket.h>
31 #include <linux/un.h>
32 #include <linux/fcntl.h>
33 #include <linux/termios.h>
34 #include <linux/sockios.h>
35 #include <linux/net.h>
36 #include <linux/fs.h>
37 #include <linux/slab.h>
38 #include <asm/uaccess.h>
39 #include <linux/skbuff.h>
40 #include <linux/netdevice.h>
41 #include <linux/rtnetlink.h>
42 #include <linux/proc_fs.h>
43 #include <linux/seq_file.h>
44 #include <linux/smp_lock.h>
45 #include <linux/notifier.h>
46 #include <linux/security.h>
47 #include <linux/jhash.h>
48 #include <linux/jiffies.h>
49 #include <linux/random.h>
50 #include <linux/bitops.h>
51 #include <linux/mm.h>
52 #include <linux/types.h>
53 #include <linux/vs_context.h>
54 #include <linux/vs_network.h>
55 #include <linux/vs_limit.h>
56 #include <net/sock.h>
57 #include <net/scm.h>
58
59 #define Nprintk(a...)
60
61 #if defined(CONFIG_NETLINK_DEV) || defined(CONFIG_NETLINK_DEV_MODULE)
62 #define NL_EMULATE_DEV
63 #endif
64
65 struct netlink_opt
66 {
67         u32                     pid;
68         unsigned int            groups;
69         u32                     dst_pid;
70         unsigned int            dst_groups;
71         unsigned long           state;
72         int                     (*handler)(int unit, struct sk_buff *skb);
73         wait_queue_head_t       wait;
74         struct netlink_callback *cb;
75         spinlock_t              cb_lock;
76         void                    (*data_ready)(struct sock *sk, int bytes);
77 };
78
79 #define nlk_sk(__sk) ((struct netlink_opt *)(__sk)->sk_protinfo)
80
81 struct nl_pid_hash {
82         struct hlist_head *table;
83         unsigned long rehash_time;
84
85         unsigned int mask;
86         unsigned int shift;
87
88         unsigned int entries;
89         unsigned int max_shift;
90
91         u32 rnd;
92 };
93
94 struct netlink_table {
95         struct nl_pid_hash hash;
96         struct hlist_head mc_list;
97         unsigned int nl_nonroot;
98 };
99
100 static struct netlink_table *nl_table;
101
102 static DECLARE_WAIT_QUEUE_HEAD(nl_table_wait);
103
104 static int netlink_dump(struct sock *sk);
105 static void netlink_destroy_callback(struct netlink_callback *cb);
106
107 static DEFINE_RWLOCK(nl_table_lock);
108 static atomic_t nl_table_users = ATOMIC_INIT(0);
109
110 static struct notifier_block *netlink_chain;
111
112 static struct hlist_head *nl_pid_hashfn(struct nl_pid_hash *hash, u32 pid)
113 {
114         return &hash->table[jhash_1word(pid, hash->rnd) & hash->mask];
115 }
116
117 static void netlink_sock_destruct(struct sock *sk)
118 {
119         skb_queue_purge(&sk->sk_receive_queue);
120
121         if (!sock_flag(sk, SOCK_DEAD)) {
122                 printk("Freeing alive netlink socket %p\n", sk);
123                 return;
124         }
125         BUG_TRAP(!atomic_read(&sk->sk_rmem_alloc));
126         BUG_TRAP(!atomic_read(&sk->sk_wmem_alloc));
127         BUG_TRAP(!nlk_sk(sk)->cb);
128
129         kfree(nlk_sk(sk));
130 }
131
132 /* This lock without WQ_FLAG_EXCLUSIVE is good on UP and it is _very_ bad on SMP.
133  * Look, when several writers sleep and reader wakes them up, all but one
134  * immediately hit write lock and grab all the cpus. Exclusive sleep solves
135  * this, _but_ remember, it adds useless work on UP machines.
136  */
137
138 static void netlink_table_grab(void)
139 {
140         write_lock_bh(&nl_table_lock);
141
142         if (atomic_read(&nl_table_users)) {
143                 DECLARE_WAITQUEUE(wait, current);
144
145                 add_wait_queue_exclusive(&nl_table_wait, &wait);
146                 for(;;) {
147                         set_current_state(TASK_UNINTERRUPTIBLE);
148                         if (atomic_read(&nl_table_users) == 0)
149                                 break;
150                         write_unlock_bh(&nl_table_lock);
151                         schedule();
152                         write_lock_bh(&nl_table_lock);
153                 }
154
155                 __set_current_state(TASK_RUNNING);
156                 remove_wait_queue(&nl_table_wait, &wait);
157         }
158 }
159
160 static __inline__ void netlink_table_ungrab(void)
161 {
162         write_unlock_bh(&nl_table_lock);
163         wake_up(&nl_table_wait);
164 }
165
166 static __inline__ void
167 netlink_lock_table(void)
168 {
169         /* read_lock() synchronizes us to netlink_table_grab */
170
171         read_lock(&nl_table_lock);
172         atomic_inc(&nl_table_users);
173         read_unlock(&nl_table_lock);
174 }
175
176 static __inline__ void
177 netlink_unlock_table(void)
178 {
179         if (atomic_dec_and_test(&nl_table_users))
180                 wake_up(&nl_table_wait);
181 }
182
183 static __inline__ struct sock *netlink_lookup(int protocol, u32 pid)
184 {
185         struct nl_pid_hash *hash = &nl_table[protocol].hash;
186         struct hlist_head *head;
187         struct sock *sk;
188         struct hlist_node *node;
189
190         read_lock(&nl_table_lock);
191         head = nl_pid_hashfn(hash, pid);
192         sk_for_each(sk, node, head) {
193                 if (nlk_sk(sk)->pid == pid) {
194                         sock_hold(sk);
195                         goto found;
196                 }
197         }
198         sk = NULL;
199 found:
200         read_unlock(&nl_table_lock);
201         return sk;
202 }
203
204 static inline struct hlist_head *nl_pid_hash_alloc(size_t size)
205 {
206         if (size <= PAGE_SIZE)
207                 return kmalloc(size, GFP_ATOMIC);
208         else
209                 return (struct hlist_head *)
210                         __get_free_pages(GFP_ATOMIC, get_order(size));
211 }
212
213 static inline void nl_pid_hash_free(struct hlist_head *table, size_t size)
214 {
215         if (size <= PAGE_SIZE)
216                 kfree(table);
217         else
218                 free_pages((unsigned long)table, get_order(size));
219 }
220
221 static int nl_pid_hash_rehash(struct nl_pid_hash *hash, int grow)
222 {
223         unsigned int omask, mask, shift;
224         size_t osize, size;
225         struct hlist_head *otable, *table;
226         int i;
227
228         omask = mask = hash->mask;
229         osize = size = (mask + 1) * sizeof(*table);
230         shift = hash->shift;
231
232         if (grow) {
233                 if (++shift > hash->max_shift)
234                         return 0;
235                 mask = mask * 2 + 1;
236                 size *= 2;
237         }
238
239         table = nl_pid_hash_alloc(size);
240         if (!table)
241                 return 0;
242
243         memset(table, 0, size);
244         otable = hash->table;
245         hash->table = table;
246         hash->mask = mask;
247         hash->shift = shift;
248         get_random_bytes(&hash->rnd, sizeof(hash->rnd));
249
250         for (i = 0; i <= omask; i++) {
251                 struct sock *sk;
252                 struct hlist_node *node, *tmp;
253
254                 sk_for_each_safe(sk, node, tmp, &otable[i])
255                         __sk_add_node(sk, nl_pid_hashfn(hash, nlk_sk(sk)->pid));
256         }
257
258         nl_pid_hash_free(otable, osize);
259         hash->rehash_time = jiffies + 10 * 60 * HZ;
260         return 1;
261 }
262
263 static inline int nl_pid_hash_dilute(struct nl_pid_hash *hash, int len)
264 {
265         int avg = hash->entries >> hash->shift;
266
267         if (unlikely(avg > 1) && nl_pid_hash_rehash(hash, 1))
268                 return 1;
269
270         if (unlikely(len > avg) && time_after(jiffies, hash->rehash_time)) {
271                 nl_pid_hash_rehash(hash, 0);
272                 return 1;
273         }
274
275         return 0;
276 }
277
278 static struct proto_ops netlink_ops;
279
280 static int netlink_insert(struct sock *sk, u32 pid)
281 {
282         struct nl_pid_hash *hash = &nl_table[sk->sk_protocol].hash;
283         struct hlist_head *head;
284         int err = -EADDRINUSE;
285         struct sock *osk;
286         struct hlist_node *node;
287         int len;
288
289         netlink_table_grab();
290         head = nl_pid_hashfn(hash, pid);
291         len = 0;
292         sk_for_each(osk, node, head) {
293                 if (nlk_sk(osk)->pid == pid)
294                         break;
295                 len++;
296         }
297         if (node)
298                 goto err;
299
300         err = -EBUSY;
301         if (nlk_sk(sk)->pid)
302                 goto err;
303
304         err = -ENOMEM;
305         if (BITS_PER_LONG > 32 && unlikely(hash->entries >= UINT_MAX))
306                 goto err;
307
308         if (len && nl_pid_hash_dilute(hash, len))
309                 head = nl_pid_hashfn(hash, pid);
310         hash->entries++;
311         nlk_sk(sk)->pid = pid;
312         sk_add_node(sk, head);
313         err = 0;
314
315 err:
316         netlink_table_ungrab();
317         return err;
318 }
319
320 static void netlink_remove(struct sock *sk)
321 {
322         netlink_table_grab();
323         nl_table[sk->sk_protocol].hash.entries--;
324         sk_del_node_init(sk);
325         if (nlk_sk(sk)->groups)
326                 __sk_del_bind_node(sk);
327         netlink_table_ungrab();
328 }
329
330 static int netlink_create(struct socket *sock, int protocol)
331 {
332         struct sock *sk;
333         struct netlink_opt *nlk;
334
335         sock->state = SS_UNCONNECTED;
336
337         if (sock->type != SOCK_RAW && sock->type != SOCK_DGRAM)
338                 return -ESOCKTNOSUPPORT;
339
340         if (protocol<0 || protocol >= MAX_LINKS)
341                 return -EPROTONOSUPPORT;
342
343         sock->ops = &netlink_ops;
344
345         sk = sk_alloc(PF_NETLINK, GFP_KERNEL, 1, NULL);
346         if (!sk)
347                 return -ENOMEM;
348
349         sock_init_data(sock,sk);
350         sk_set_owner(sk, THIS_MODULE);
351
352         nlk = sk->sk_protinfo = kmalloc(sizeof(*nlk), GFP_KERNEL);
353         if (!nlk) {
354                 sk_free(sk);
355                 return -ENOMEM;
356         }
357         memset(nlk, 0, sizeof(*nlk));
358
359         spin_lock_init(&nlk->cb_lock);
360         init_waitqueue_head(&nlk->wait);
361         sk->sk_destruct = netlink_sock_destruct;
362
363         sk->sk_protocol = protocol;
364         return 0;
365 }
366
367 static int netlink_release(struct socket *sock)
368 {
369         struct sock *sk = sock->sk;
370         struct netlink_opt *nlk;
371
372         if (!sk)
373                 return 0;
374
375         netlink_remove(sk);
376         nlk = nlk_sk(sk);
377
378         spin_lock(&nlk->cb_lock);
379         if (nlk->cb) {
380                 nlk->cb->done(nlk->cb);
381                 netlink_destroy_callback(nlk->cb);
382                 nlk->cb = NULL;
383                 __sock_put(sk);
384         }
385         spin_unlock(&nlk->cb_lock);
386
387         /* OK. Socket is unlinked, and, therefore,
388            no new packets will arrive */
389
390         sock_orphan(sk);
391         sock->sk = NULL;
392         wake_up_interruptible_all(&nlk->wait);
393
394         skb_queue_purge(&sk->sk_write_queue);
395
396         if (nlk->pid && !nlk->groups) {
397                 struct netlink_notify n = {
398                                                 .protocol = sk->sk_protocol,
399                                                 .pid = nlk->pid,
400                                           };
401                 notifier_call_chain(&netlink_chain, NETLINK_URELEASE, &n);
402         }       
403         
404         sock_put(sk);
405         return 0;
406 }
407
408 static int netlink_autobind(struct socket *sock)
409 {
410         struct sock *sk = sock->sk;
411         struct nl_pid_hash *hash = &nl_table[sk->sk_protocol].hash;
412         struct hlist_head *head;
413         struct sock *osk;
414         struct hlist_node *node;
415         s32 pid = current->pid;
416         int err;
417         static s32 rover = -4097;
418
419 retry:
420         cond_resched();
421         netlink_table_grab();
422         head = nl_pid_hashfn(hash, pid);
423         sk_for_each(osk, node, head) {
424                 if (nlk_sk(osk)->pid == pid) {
425                         /* Bind collision, search negative pid values. */
426                         pid = rover--;
427                         if (rover > -4097)
428                                 rover = -4097;
429                         netlink_table_ungrab();
430                         goto retry;
431                 }
432         }
433         netlink_table_ungrab();
434
435         err = netlink_insert(sk, pid);
436         if (err == -EADDRINUSE)
437                 goto retry;
438         nlk_sk(sk)->groups = 0;
439         return 0;
440 }
441
442 static inline int netlink_capable(struct socket *sock, unsigned int flag) 
443
444         return (nl_table[sock->sk->sk_protocol].nl_nonroot & flag) ||
445                capable(CAP_NET_ADMIN);
446
447
448 static int netlink_bind(struct socket *sock, struct sockaddr *addr, int addr_len)
449 {
450         struct sock *sk = sock->sk;
451         struct netlink_opt *nlk = nlk_sk(sk);
452         struct sockaddr_nl *nladdr = (struct sockaddr_nl *)addr;
453         int err;
454         
455         if (nladdr->nl_family != AF_NETLINK)
456                 return -EINVAL;
457
458         /* Only superuser is allowed to listen multicasts */
459         if (nladdr->nl_groups && !netlink_capable(sock, NL_NONROOT_RECV))
460                 return -EPERM;
461
462         if (nlk->pid) {
463                 if (nladdr->nl_pid != nlk->pid)
464                         return -EINVAL;
465         } else {
466                 err = nladdr->nl_pid ?
467                         netlink_insert(sk, nladdr->nl_pid) :
468                         netlink_autobind(sock);
469                 if (err)
470                         return err;
471         }
472
473         if (!nladdr->nl_groups && !nlk->groups)
474                 return 0;
475
476         netlink_table_grab();
477         if (nlk->groups && !nladdr->nl_groups)
478                 __sk_del_bind_node(sk);
479         else if (!nlk->groups && nladdr->nl_groups)
480                 sk_add_bind_node(sk, &nl_table[sk->sk_protocol].mc_list);
481         nlk->groups = nladdr->nl_groups;
482         netlink_table_ungrab();
483
484         return 0;
485 }
486
487 static int netlink_connect(struct socket *sock, struct sockaddr *addr,
488                            int alen, int flags)
489 {
490         int err = 0;
491         struct sock *sk = sock->sk;
492         struct netlink_opt *nlk = nlk_sk(sk);
493         struct sockaddr_nl *nladdr=(struct sockaddr_nl*)addr;
494
495         if (addr->sa_family == AF_UNSPEC) {
496                 sk->sk_state    = NETLINK_UNCONNECTED;
497                 nlk->dst_pid    = 0;
498                 nlk->dst_groups = 0;
499                 return 0;
500         }
501         if (addr->sa_family != AF_NETLINK)
502                 return -EINVAL;
503
504         /* Only superuser is allowed to send multicasts */
505         if (nladdr->nl_groups && !netlink_capable(sock, NL_NONROOT_SEND))
506                 return -EPERM;
507
508         if (!nlk->pid)
509                 err = netlink_autobind(sock);
510
511         if (err == 0) {
512                 sk->sk_state    = NETLINK_CONNECTED;
513                 nlk->dst_pid    = nladdr->nl_pid;
514                 nlk->dst_groups = nladdr->nl_groups;
515         }
516
517         return err;
518 }
519
520 static int netlink_getname(struct socket *sock, struct sockaddr *addr, int *addr_len, int peer)
521 {
522         struct sock *sk = sock->sk;
523         struct netlink_opt *nlk = nlk_sk(sk);
524         struct sockaddr_nl *nladdr=(struct sockaddr_nl *)addr;
525         
526         nladdr->nl_family = AF_NETLINK;
527         nladdr->nl_pad = 0;
528         *addr_len = sizeof(*nladdr);
529
530         if (peer) {
531                 nladdr->nl_pid = nlk->dst_pid;
532                 nladdr->nl_groups = nlk->dst_groups;
533         } else {
534                 nladdr->nl_pid = nlk->pid;
535                 nladdr->nl_groups = nlk->groups;
536         }
537         return 0;
538 }
539
540 static void netlink_overrun(struct sock *sk)
541 {
542         if (!test_and_set_bit(0, &nlk_sk(sk)->state)) {
543                 sk->sk_err = ENOBUFS;
544                 sk->sk_error_report(sk);
545         }
546 }
547
548 static struct sock *netlink_getsockbypid(struct sock *ssk, u32 pid)
549 {
550         int protocol = ssk->sk_protocol;
551         struct sock *sock;
552         struct netlink_opt *nlk;
553
554         sock = netlink_lookup(protocol, pid);
555         if (!sock)
556                 return ERR_PTR(-ECONNREFUSED);
557
558         /* Don't bother queuing skb if kernel socket has no input function */
559         nlk = nlk_sk(sock);
560         if ((nlk->pid == 0 && !nlk->data_ready) ||
561             (sock->sk_state == NETLINK_CONNECTED &&
562              nlk->dst_pid != nlk_sk(ssk)->pid)) {
563                 sock_put(sock);
564                 return ERR_PTR(-ECONNREFUSED);
565         }
566         return sock;
567 }
568
569 struct sock *netlink_getsockbyfilp(struct file *filp)
570 {
571         struct inode *inode = filp->f_dentry->d_inode;
572         struct socket *socket;
573         struct sock *sock;
574
575         if (!inode->i_sock || !(socket = SOCKET_I(inode)))
576                 return ERR_PTR(-ENOTSOCK);
577
578         sock = socket->sk;
579         if (sock->sk_family != AF_NETLINK)
580                 return ERR_PTR(-EINVAL);
581
582         sock_hold(sock);
583         return sock;
584 }
585
586 /*
587  * Attach a skb to a netlink socket.
588  * The caller must hold a reference to the destination socket. On error, the
589  * reference is dropped. The skb is not send to the destination, just all
590  * all error checks are performed and memory in the queue is reserved.
591  * Return values:
592  * < 0: error. skb freed, reference to sock dropped.
593  * 0: continue
594  * 1: repeat lookup - reference dropped while waiting for socket memory.
595  */
596 int netlink_attachskb(struct sock *sk, struct sk_buff *skb, int nonblock, long timeo)
597 {
598         struct netlink_opt *nlk;
599
600         nlk = nlk_sk(sk);
601
602 #ifdef NL_EMULATE_DEV
603         if (nlk->handler)
604                 return 0;
605 #endif
606         if (atomic_read(&sk->sk_rmem_alloc) > sk->sk_rcvbuf ||
607             test_bit(0, &nlk->state)) {
608                 DECLARE_WAITQUEUE(wait, current);
609                 if (!timeo) {
610                         if (!nlk->pid)
611                                 netlink_overrun(sk);
612                         sock_put(sk);
613                         kfree_skb(skb);
614                         return -EAGAIN;
615                 }
616
617                 __set_current_state(TASK_INTERRUPTIBLE);
618                 add_wait_queue(&nlk->wait, &wait);
619
620                 if ((atomic_read(&sk->sk_rmem_alloc) > sk->sk_rcvbuf ||
621                      test_bit(0, &nlk->state)) &&
622                     !sock_flag(sk, SOCK_DEAD))
623                         timeo = schedule_timeout(timeo);
624
625                 __set_current_state(TASK_RUNNING);
626                 remove_wait_queue(&nlk->wait, &wait);
627                 sock_put(sk);
628
629                 if (signal_pending(current)) {
630                         kfree_skb(skb);
631                         return sock_intr_errno(timeo);
632                 }
633                 return 1;
634         }
635         skb_set_owner_r(skb, sk);
636         return 0;
637 }
638
639 int netlink_sendskb(struct sock *sk, struct sk_buff *skb, int protocol)
640 {
641         struct netlink_opt *nlk;
642         int len = skb->len;
643
644         nlk = nlk_sk(sk);
645 #ifdef NL_EMULATE_DEV
646         if (nlk->handler) {
647                 skb_orphan(skb);
648                 len = nlk->handler(protocol, skb);
649                 sock_put(sk);
650                 return len;
651         }
652 #endif
653
654         skb_queue_tail(&sk->sk_receive_queue, skb);
655         sk->sk_data_ready(sk, len);
656         sock_put(sk);
657         return len;
658 }
659
660 void netlink_detachskb(struct sock *sk, struct sk_buff *skb)
661 {
662         kfree_skb(skb);
663         sock_put(sk);
664 }
665
666 static inline struct sk_buff *netlink_trim(struct sk_buff *skb, int allocation)
667 {
668         int delta;
669
670         skb_orphan(skb);
671
672         delta = skb->end - skb->tail;
673         if (delta * 2 < skb->truesize)
674                 return skb;
675
676         if (skb_shared(skb)) {
677                 struct sk_buff *nskb = skb_clone(skb, allocation);
678                 if (!nskb)
679                         return skb;
680                 kfree_skb(skb);
681                 skb = nskb;
682         }
683
684         if (!pskb_expand_head(skb, 0, -delta, allocation))
685                 skb->truesize -= delta;
686
687         return skb;
688 }
689
690 int netlink_unicast(struct sock *ssk, struct sk_buff *skb, u32 pid, int nonblock)
691 {
692         struct sock *sk;
693         int err;
694         long timeo;
695
696         skb = netlink_trim(skb, gfp_any());
697
698         timeo = sock_sndtimeo(ssk, nonblock);
699 retry:
700         sk = netlink_getsockbypid(ssk, pid);
701         if (IS_ERR(sk)) {
702                 kfree_skb(skb);
703                 return PTR_ERR(sk);
704         }
705         err = netlink_attachskb(sk, skb, nonblock, timeo);
706         if (err == 1)
707                 goto retry;
708         if (err)
709                 return err;
710
711         return netlink_sendskb(sk, skb, ssk->sk_protocol);
712 }
713
714 static __inline__ int netlink_broadcast_deliver(struct sock *sk, struct sk_buff *skb)
715 {
716         struct netlink_opt *nlk = nlk_sk(sk);
717 #ifdef NL_EMULATE_DEV
718         if (nlk->handler) {
719                 nlk->handler(sk->sk_protocol, skb);
720                 return 0;
721         } else
722 #endif
723         if (atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf &&
724             !test_bit(0, &nlk->state)) {
725                 skb_set_owner_r(skb, sk);
726                 skb_queue_tail(&sk->sk_receive_queue, skb);
727                 sk->sk_data_ready(sk, skb->len);
728                 return atomic_read(&sk->sk_rmem_alloc) > sk->sk_rcvbuf;
729         }
730         return -1;
731 }
732
733 struct netlink_broadcast_data {
734         struct sock *exclude_sk;
735         u32 pid;
736         u32 group;
737         int failure;
738         int congested;
739         int delivered;
740         int allocation;
741         struct sk_buff *skb, *skb2;
742 };
743
744 static inline int do_one_broadcast(struct sock *sk,
745                                    struct netlink_broadcast_data *p)
746 {
747         struct netlink_opt *nlk = nlk_sk(sk);
748         int val;
749
750         if (p->exclude_sk == sk)
751                 goto out;
752
753         if (nlk->pid == p->pid || !(nlk->groups & p->group))
754                 goto out;
755
756         if (p->failure) {
757                 netlink_overrun(sk);
758                 goto out;
759         }
760
761         sock_hold(sk);
762         if (p->skb2 == NULL) {
763                 if (atomic_read(&p->skb->users) != 1) {
764                         p->skb2 = skb_clone(p->skb, p->allocation);
765                 } else {
766                         p->skb2 = p->skb;
767                         atomic_inc(&p->skb->users);
768                 }
769         }
770         if (p->skb2 == NULL) {
771                 netlink_overrun(sk);
772                 /* Clone failed. Notify ALL listeners. */
773                 p->failure = 1;
774         } else if ((val = netlink_broadcast_deliver(sk, p->skb2)) < 0) {
775                 netlink_overrun(sk);
776         } else {
777                 p->congested |= val;
778                 p->delivered = 1;
779                 p->skb2 = NULL;
780         }
781         sock_put(sk);
782
783 out:
784         return 0;
785 }
786
787 int netlink_broadcast(struct sock *ssk, struct sk_buff *skb, u32 pid,
788                       u32 group, int allocation)
789 {
790         struct netlink_broadcast_data info;
791         struct hlist_node *node;
792         struct sock *sk;
793
794         skb = netlink_trim(skb, allocation);
795
796         info.exclude_sk = ssk;
797         info.pid = pid;
798         info.group = group;
799         info.failure = 0;
800         info.congested = 0;
801         info.delivered = 0;
802         info.allocation = allocation;
803         info.skb = skb;
804         info.skb2 = NULL;
805
806         /* While we sleep in clone, do not allow to change socket list */
807
808         netlink_lock_table();
809
810         sk_for_each_bound(sk, node, &nl_table[ssk->sk_protocol].mc_list)
811                 do_one_broadcast(sk, &info);
812
813         netlink_unlock_table();
814
815         if (info.skb2)
816                 kfree_skb(info.skb2);
817         kfree_skb(skb);
818
819         if (info.delivered) {
820                 if (info.congested && (allocation & __GFP_WAIT))
821                         yield();
822                 return 0;
823         }
824         if (info.failure)
825                 return -ENOBUFS;
826         return -ESRCH;
827 }
828
829 struct netlink_set_err_data {
830         struct sock *exclude_sk;
831         u32 pid;
832         u32 group;
833         int code;
834 };
835
836 static inline int do_one_set_err(struct sock *sk,
837                                  struct netlink_set_err_data *p)
838 {
839         struct netlink_opt *nlk = nlk_sk(sk);
840
841         if (sk == p->exclude_sk)
842                 goto out;
843
844         if (nlk->pid == p->pid || !(nlk->groups & p->group))
845                 goto out;
846
847         sk->sk_err = p->code;
848         sk->sk_error_report(sk);
849 out:
850         return 0;
851 }
852
853 void netlink_set_err(struct sock *ssk, u32 pid, u32 group, int code)
854 {
855         struct netlink_set_err_data info;
856         struct hlist_node *node;
857         struct sock *sk;
858
859         info.exclude_sk = ssk;
860         info.pid = pid;
861         info.group = group;
862         info.code = code;
863
864         read_lock(&nl_table_lock);
865
866         sk_for_each_bound(sk, node, &nl_table[ssk->sk_protocol].mc_list)
867                 do_one_set_err(sk, &info);
868
869         read_unlock(&nl_table_lock);
870 }
871
872 static inline void netlink_rcv_wake(struct sock *sk)
873 {
874         struct netlink_opt *nlk = nlk_sk(sk);
875
876         if (!skb_queue_len(&sk->sk_receive_queue))
877                 clear_bit(0, &nlk->state);
878         if (!test_bit(0, &nlk->state))
879                 wake_up_interruptible(&nlk->wait);
880 }
881
882 static int netlink_sendmsg(struct kiocb *kiocb, struct socket *sock,
883                            struct msghdr *msg, size_t len)
884 {
885         struct sock_iocb *siocb = kiocb_to_siocb(kiocb);
886         struct sock *sk = sock->sk;
887         struct netlink_opt *nlk = nlk_sk(sk);
888         struct sockaddr_nl *addr=msg->msg_name;
889         u32 dst_pid;
890         u32 dst_groups;
891         struct sk_buff *skb;
892         int err;
893         struct scm_cookie scm;
894
895         if (msg->msg_flags&MSG_OOB)
896                 return -EOPNOTSUPP;
897
898         if (NULL == siocb->scm)
899                 siocb->scm = &scm;
900         err = scm_send(sock, msg, siocb->scm);
901         if (err < 0)
902                 return err;
903
904         if (msg->msg_namelen) {
905                 if (addr->nl_family != AF_NETLINK)
906                         return -EINVAL;
907                 dst_pid = addr->nl_pid;
908                 dst_groups = addr->nl_groups;
909                 if (dst_groups && !netlink_capable(sock, NL_NONROOT_SEND))
910                         return -EPERM;
911         } else {
912                 dst_pid = nlk->dst_pid;
913                 dst_groups = nlk->dst_groups;
914         }
915
916         if (!nlk->pid) {
917                 err = netlink_autobind(sock);
918                 if (err)
919                         goto out;
920         }
921
922         err = -EMSGSIZE;
923         if (len > sk->sk_sndbuf - 32)
924                 goto out;
925         err = -ENOBUFS;
926         skb = alloc_skb(len, GFP_KERNEL);
927         if (skb==NULL)
928                 goto out;
929
930         NETLINK_CB(skb).pid     = nlk->pid;
931         NETLINK_CB(skb).groups  = nlk->groups;
932         NETLINK_CB(skb).dst_pid = dst_pid;
933         NETLINK_CB(skb).dst_groups = dst_groups;
934         memcpy(NETLINK_CREDS(skb), &siocb->scm->creds, sizeof(struct ucred));
935
936         /* What can I do? Netlink is asynchronous, so that
937            we will have to save current capabilities to
938            check them, when this message will be delivered
939            to corresponding kernel module.   --ANK (980802)
940          */
941
942         err = -EFAULT;
943         if (memcpy_fromiovec(skb_put(skb,len), msg->msg_iov, len)) {
944                 kfree_skb(skb);
945                 goto out;
946         }
947
948         err = security_netlink_send(sk, skb);
949         if (err) {
950                 kfree_skb(skb);
951                 goto out;
952         }
953
954         if (dst_groups) {
955                 atomic_inc(&skb->users);
956                 netlink_broadcast(sk, skb, dst_pid, dst_groups, GFP_KERNEL);
957         }
958         err = netlink_unicast(sk, skb, dst_pid, msg->msg_flags&MSG_DONTWAIT);
959
960 out:
961         return err;
962 }
963
964 static int netlink_recvmsg(struct kiocb *kiocb, struct socket *sock,
965                            struct msghdr *msg, size_t len,
966                            int flags)
967 {
968         struct sock_iocb *siocb = kiocb_to_siocb(kiocb);
969         struct scm_cookie scm;
970         struct sock *sk = sock->sk;
971         struct netlink_opt *nlk = nlk_sk(sk);
972         int noblock = flags&MSG_DONTWAIT;
973         size_t copied;
974         struct sk_buff *skb;
975         int err;
976
977         if (flags&MSG_OOB)
978                 return -EOPNOTSUPP;
979
980         copied = 0;
981
982         skb = skb_recv_datagram(sk,flags,noblock,&err);
983         if (skb==NULL)
984                 goto out;
985
986         msg->msg_namelen = 0;
987
988         copied = skb->len;
989         if (len < copied) {
990                 msg->msg_flags |= MSG_TRUNC;
991                 copied = len;
992         }
993
994         skb->h.raw = skb->data;
995         err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
996
997         if (msg->msg_name) {
998                 struct sockaddr_nl *addr = (struct sockaddr_nl*)msg->msg_name;
999                 addr->nl_family = AF_NETLINK;
1000                 addr->nl_pad    = 0;
1001                 addr->nl_pid    = NETLINK_CB(skb).pid;
1002                 addr->nl_groups = NETLINK_CB(skb).dst_groups;
1003                 msg->msg_namelen = sizeof(*addr);
1004         }
1005
1006         if (NULL == siocb->scm) {
1007                 memset(&scm, 0, sizeof(scm));
1008                 siocb->scm = &scm;
1009         }
1010         siocb->scm->creds = *NETLINK_CREDS(skb);
1011         skb_free_datagram(sk, skb);
1012
1013         if (nlk->cb && atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf / 2)
1014                 netlink_dump(sk);
1015
1016         scm_recv(sock, msg, siocb->scm, flags);
1017
1018 out:
1019         netlink_rcv_wake(sk);
1020         return err ? : copied;
1021 }
1022
1023 static void netlink_data_ready(struct sock *sk, int len)
1024 {
1025         struct netlink_opt *nlk = nlk_sk(sk);
1026
1027         if (nlk->data_ready)
1028                 nlk->data_ready(sk, len);
1029         netlink_rcv_wake(sk);
1030 }
1031
1032 /*
1033  *      We export these functions to other modules. They provide a 
1034  *      complete set of kernel non-blocking support for message
1035  *      queueing.
1036  */
1037
1038 struct sock *
1039 netlink_kernel_create(int unit, void (*input)(struct sock *sk, int len))
1040 {
1041         struct socket *sock;
1042         struct sock *sk;
1043
1044         if (!nl_table)
1045                 return NULL;
1046
1047         if (unit<0 || unit>=MAX_LINKS)
1048                 return NULL;
1049
1050         if (sock_create_lite(PF_NETLINK, SOCK_DGRAM, unit, &sock))
1051                 return NULL;
1052
1053         if (netlink_create(sock, unit) < 0) {
1054                 sock_release(sock);
1055                 return NULL;
1056         }
1057         sk = sock->sk;
1058         sk->sk_data_ready = netlink_data_ready;
1059         if (input)
1060                 nlk_sk(sk)->data_ready = input;
1061
1062         if (netlink_insert(sk, 0)) {
1063                 sock_release(sock);
1064                 return NULL;
1065         }
1066         return sk;
1067 }
1068
1069 void netlink_set_nonroot(int protocol, unsigned int flags)
1070
1071         if ((unsigned int)protocol < MAX_LINKS) 
1072                 nl_table[protocol].nl_nonroot = flags;
1073
1074
1075 static void netlink_destroy_callback(struct netlink_callback *cb)
1076 {
1077         if (cb->skb)
1078                 kfree_skb(cb->skb);
1079         kfree(cb);
1080 }
1081
1082 /*
1083  * It looks a bit ugly.
1084  * It would be better to create kernel thread.
1085  */
1086
1087 static int netlink_dump(struct sock *sk)
1088 {
1089         struct netlink_opt *nlk = nlk_sk(sk);
1090         struct netlink_callback *cb;
1091         struct sk_buff *skb;
1092         struct nlmsghdr *nlh;
1093         int len;
1094         
1095         skb = sock_rmalloc(sk, NLMSG_GOODSIZE, 0, GFP_KERNEL);
1096         if (!skb)
1097                 return -ENOBUFS;
1098
1099         spin_lock(&nlk->cb_lock);
1100
1101         cb = nlk->cb;
1102         if (cb == NULL) {
1103                 spin_unlock(&nlk->cb_lock);
1104                 kfree_skb(skb);
1105                 return -EINVAL;
1106         }
1107
1108         len = cb->dump(skb, cb);
1109
1110         if (len > 0) {
1111                 spin_unlock(&nlk->cb_lock);
1112                 skb_queue_tail(&sk->sk_receive_queue, skb);
1113                 sk->sk_data_ready(sk, len);
1114                 return 0;
1115         }
1116
1117         nlh = __nlmsg_put(skb, NETLINK_CB(cb->skb).pid, cb->nlh->nlmsg_seq, NLMSG_DONE, sizeof(int));
1118         nlh->nlmsg_flags |= NLM_F_MULTI;
1119         memcpy(NLMSG_DATA(nlh), &len, sizeof(len));
1120         skb_queue_tail(&sk->sk_receive_queue, skb);
1121         sk->sk_data_ready(sk, skb->len);
1122
1123         cb->done(cb);
1124         nlk->cb = NULL;
1125         spin_unlock(&nlk->cb_lock);
1126
1127         netlink_destroy_callback(cb);
1128         sock_put(sk);
1129         return 0;
1130 }
1131
1132 int netlink_dump_start(struct sock *ssk, struct sk_buff *skb,
1133                        struct nlmsghdr *nlh,
1134                        int (*dump)(struct sk_buff *skb, struct netlink_callback*),
1135                        int (*done)(struct netlink_callback*))
1136 {
1137         struct netlink_callback *cb;
1138         struct sock *sk;
1139         struct netlink_opt *nlk;
1140
1141         cb = kmalloc(sizeof(*cb), GFP_KERNEL);
1142         if (cb == NULL)
1143                 return -ENOBUFS;
1144
1145         memset(cb, 0, sizeof(*cb));
1146         cb->dump = dump;
1147         cb->done = done;
1148         cb->nlh = nlh;
1149         atomic_inc(&skb->users);
1150         cb->skb = skb;
1151
1152         sk = netlink_lookup(ssk->sk_protocol, NETLINK_CB(skb).pid);
1153         if (sk == NULL) {
1154                 netlink_destroy_callback(cb);
1155                 return -ECONNREFUSED;
1156         }
1157         nlk = nlk_sk(sk);
1158         /* A dump is in progress... */
1159         spin_lock(&nlk->cb_lock);
1160         if (nlk->cb) {
1161                 spin_unlock(&nlk->cb_lock);
1162                 netlink_destroy_callback(cb);
1163                 sock_put(sk);
1164                 return -EBUSY;
1165         }
1166         nlk->cb = cb;
1167         spin_unlock(&nlk->cb_lock);
1168
1169         netlink_dump(sk);
1170         return 0;
1171 }
1172
1173 void netlink_ack(struct sk_buff *in_skb, struct nlmsghdr *nlh, int err)
1174 {
1175         struct sk_buff *skb;
1176         struct nlmsghdr *rep;
1177         struct nlmsgerr *errmsg;
1178         int size;
1179
1180         if (err == 0)
1181                 size = NLMSG_SPACE(sizeof(struct nlmsgerr));
1182         else
1183                 size = NLMSG_SPACE(4 + NLMSG_ALIGN(nlh->nlmsg_len));
1184
1185         skb = alloc_skb(size, GFP_KERNEL);
1186         if (!skb) {
1187                 struct sock *sk;
1188
1189                 sk = netlink_lookup(in_skb->sk->sk_protocol,
1190                                     NETLINK_CB(in_skb).pid);
1191                 if (sk) {
1192                         sk->sk_err = ENOBUFS;
1193                         sk->sk_error_report(sk);
1194                         sock_put(sk);
1195                 }
1196                 return;
1197         }
1198
1199         rep = __nlmsg_put(skb, NETLINK_CB(in_skb).pid, nlh->nlmsg_seq,
1200                           NLMSG_ERROR, sizeof(struct nlmsgerr));
1201         errmsg = NLMSG_DATA(rep);
1202         errmsg->error = err;
1203         memcpy(&errmsg->msg, nlh, err ? nlh->nlmsg_len : sizeof(struct nlmsghdr));
1204         netlink_unicast(in_skb->sk, skb, NETLINK_CB(in_skb).pid, MSG_DONTWAIT);
1205 }
1206
1207
1208 #ifdef CONFIG_PROC_FS
1209 struct nl_seq_iter {
1210         int link;
1211         int hash_idx;
1212 };
1213
1214 static struct sock *netlink_seq_socket_idx(struct seq_file *seq, loff_t pos)
1215 {
1216         struct nl_seq_iter *iter = seq->private;
1217         int i, j;
1218         struct sock *s;
1219         struct hlist_node *node;
1220         loff_t off = 0;
1221
1222         for (i=0; i<MAX_LINKS; i++) {
1223                 struct nl_pid_hash *hash = &nl_table[i].hash;
1224
1225                 for (j = 0; j <= hash->mask; j++) {
1226                         sk_for_each(s, node, &hash->table[j]) {
1227                                 if (off == pos) {
1228                                         iter->link = i;
1229                                         iter->hash_idx = j;
1230                                         return s;
1231                                 }
1232                                 ++off;
1233                         }
1234                 }
1235         }
1236         return NULL;
1237 }
1238
1239 static void *netlink_seq_start(struct seq_file *seq, loff_t *pos)
1240 {
1241         read_lock(&nl_table_lock);
1242         return *pos ? netlink_seq_socket_idx(seq, *pos - 1) : SEQ_START_TOKEN;
1243 }
1244
1245 static void *netlink_seq_next(struct seq_file *seq, void *v, loff_t *pos)
1246 {
1247         struct sock *s;
1248         struct nl_seq_iter *iter;
1249         int i, j;
1250
1251         ++*pos;
1252
1253         if (v == SEQ_START_TOKEN)
1254                 return netlink_seq_socket_idx(seq, 0);
1255                 
1256         s = sk_next(v);
1257         if (s)
1258                 return s;
1259
1260         iter = seq->private;
1261         i = iter->link;
1262         j = iter->hash_idx + 1;
1263
1264         do {
1265                 struct nl_pid_hash *hash = &nl_table[i].hash;
1266
1267                 for (; j <= hash->mask; j++) {
1268                         s = sk_head(&hash->table[j]);
1269                         if (s) {
1270                                 iter->link = i;
1271                                 iter->hash_idx = j;
1272                                 return s;
1273                         }
1274                 }
1275
1276                 j = 0;
1277         } while (++i < MAX_LINKS);
1278
1279         return NULL;
1280 }
1281
1282 static void netlink_seq_stop(struct seq_file *seq, void *v)
1283 {
1284         read_unlock(&nl_table_lock);
1285 }
1286
1287
1288 static int netlink_seq_show(struct seq_file *seq, void *v)
1289 {
1290         if (v == SEQ_START_TOKEN)
1291                 seq_puts(seq,
1292                          "sk       Eth Pid    Groups   "
1293                          "Rmem     Wmem     Dump     Locks\n");
1294         else {
1295                 struct sock *s = v;
1296                 struct netlink_opt *nlk = nlk_sk(s);
1297
1298                 seq_printf(seq, "%p %-3d %-6d %08x %-8d %-8d %p %d\n",
1299                            s,
1300                            s->sk_protocol,
1301                            nlk->pid,
1302                            nlk->groups,
1303                            atomic_read(&s->sk_rmem_alloc),
1304                            atomic_read(&s->sk_wmem_alloc),
1305                            nlk->cb,
1306                            atomic_read(&s->sk_refcnt)
1307                         );
1308
1309         }
1310         return 0;
1311 }
1312
1313 static struct seq_operations netlink_seq_ops = {
1314         .start  = netlink_seq_start,
1315         .next   = netlink_seq_next,
1316         .stop   = netlink_seq_stop,
1317         .show   = netlink_seq_show,
1318 };
1319
1320
1321 static int netlink_seq_open(struct inode *inode, struct file *file)
1322 {
1323         struct seq_file *seq;
1324         struct nl_seq_iter *iter;
1325         int err;
1326
1327         iter = kmalloc(sizeof(*iter), GFP_KERNEL);
1328         if (!iter)
1329                 return -ENOMEM;
1330
1331         err = seq_open(file, &netlink_seq_ops);
1332         if (err) {
1333                 kfree(iter);
1334                 return err;
1335         }
1336
1337         memset(iter, 0, sizeof(*iter));
1338         seq = file->private_data;
1339         seq->private = iter;
1340         return 0;
1341 }
1342
1343 static struct file_operations netlink_seq_fops = {
1344         .owner          = THIS_MODULE,
1345         .open           = netlink_seq_open,
1346         .read           = seq_read,
1347         .llseek         = seq_lseek,
1348         .release        = seq_release_private,
1349 };
1350
1351 #endif
1352
1353 int netlink_register_notifier(struct notifier_block *nb)
1354 {
1355         return notifier_chain_register(&netlink_chain, nb);
1356 }
1357
1358 int netlink_unregister_notifier(struct notifier_block *nb)
1359 {
1360         return notifier_chain_unregister(&netlink_chain, nb);
1361 }
1362                 
1363 static struct proto_ops netlink_ops = {
1364         .family =       PF_NETLINK,
1365         .owner =        THIS_MODULE,
1366         .release =      netlink_release,
1367         .bind =         netlink_bind,
1368         .connect =      netlink_connect,
1369         .socketpair =   sock_no_socketpair,
1370         .accept =       sock_no_accept,
1371         .getname =      netlink_getname,
1372         .poll =         datagram_poll,
1373         .ioctl =        sock_no_ioctl,
1374         .listen =       sock_no_listen,
1375         .shutdown =     sock_no_shutdown,
1376         .setsockopt =   sock_no_setsockopt,
1377         .getsockopt =   sock_no_getsockopt,
1378         .sendmsg =      netlink_sendmsg,
1379         .recvmsg =      netlink_recvmsg,
1380         .mmap =         sock_no_mmap,
1381         .sendpage =     sock_no_sendpage,
1382 };
1383
1384 static struct net_proto_family netlink_family_ops = {
1385         .family = PF_NETLINK,
1386         .create = netlink_create,
1387         .owner  = THIS_MODULE,  /* for consistency 8) */
1388 };
1389
1390 extern void netlink_skb_parms_too_large(void);
1391
1392 static int __init netlink_proto_init(void)
1393 {
1394         struct sk_buff *dummy_skb;
1395         int i;
1396         unsigned long max;
1397         unsigned int order;
1398
1399         if (sizeof(struct netlink_skb_parms) > sizeof(dummy_skb->cb))
1400                 netlink_skb_parms_too_large();
1401
1402         nl_table = kmalloc(sizeof(*nl_table) * MAX_LINKS, GFP_KERNEL);
1403         if (!nl_table) {
1404 enomem:
1405                 printk(KERN_CRIT "netlink_init: Cannot allocate nl_table\n");
1406                 return -ENOMEM;
1407         }
1408
1409         memset(nl_table, 0, sizeof(*nl_table) * MAX_LINKS);
1410
1411         if (num_physpages >= (128 * 1024))
1412                 max = num_physpages >> (21 - PAGE_SHIFT);
1413         else
1414                 max = num_physpages >> (23 - PAGE_SHIFT);
1415
1416         order = get_bitmask_order(max) - 1 + PAGE_SHIFT;
1417         max = (1UL << order) / sizeof(struct hlist_head);
1418         order = get_bitmask_order(max > UINT_MAX ? UINT_MAX : max) - 1;
1419
1420         for (i = 0; i < MAX_LINKS; i++) {
1421                 struct nl_pid_hash *hash = &nl_table[i].hash;
1422
1423                 hash->table = nl_pid_hash_alloc(1 * sizeof(*hash->table));
1424                 if (!hash->table) {
1425                         while (i-- > 0)
1426                                 nl_pid_hash_free(nl_table[i].hash.table,
1427                                                  1 * sizeof(*hash->table));
1428                         kfree(nl_table);
1429                         goto enomem;
1430                 }
1431                 memset(hash->table, 0, 1 * sizeof(*hash->table));
1432                 hash->max_shift = order;
1433                 hash->shift = 0;
1434                 hash->mask = 0;
1435                 hash->rehash_time = jiffies;
1436         }
1437
1438         sock_register(&netlink_family_ops);
1439 #ifdef CONFIG_PROC_FS
1440         proc_net_fops_create("netlink", 0, &netlink_seq_fops);
1441 #endif
1442         /* The netlink device handler may be needed early. */ 
1443         rtnetlink_init();
1444         return 0;
1445 }
1446
1447 static void __exit netlink_proto_exit(void)
1448 {
1449        sock_unregister(PF_NETLINK);
1450        proc_net_remove("netlink");
1451        kfree(nl_table);
1452        nl_table = NULL;
1453 }
1454
1455 core_initcall(netlink_proto_init);
1456 module_exit(netlink_proto_exit);
1457
1458 MODULE_LICENSE("GPL");
1459
1460 MODULE_ALIAS_NETPROTO(PF_NETLINK);
1461
1462 EXPORT_SYMBOL(netlink_ack);
1463 EXPORT_SYMBOL(netlink_broadcast);
1464 EXPORT_SYMBOL(netlink_dump_start);
1465 EXPORT_SYMBOL(netlink_kernel_create);
1466 EXPORT_SYMBOL(netlink_register_notifier);
1467 EXPORT_SYMBOL(netlink_set_err);
1468 EXPORT_SYMBOL(netlink_set_nonroot);
1469 EXPORT_SYMBOL(netlink_unicast);
1470 EXPORT_SYMBOL(netlink_unregister_notifier);
1471