Merge branch 'x86/unify-cpu-detect' into x86-v28-for-linus-phase4-D
[linux-2.6] / net / key / af_key.c
1 /*
2  * net/key/af_key.c     An implementation of PF_KEYv2 sockets.
3  *
4  *              This program is free software; you can redistribute it and/or
5  *              modify it under the terms of the GNU General Public License
6  *              as published by the Free Software Foundation; either version
7  *              2 of the License, or (at your option) any later version.
8  *
9  * Authors:     Maxim Giryaev   <gem@asplinux.ru>
10  *              David S. Miller <davem@redhat.com>
11  *              Alexey Kuznetsov <kuznet@ms2.inr.ac.ru>
12  *              Kunihiro Ishiguro <kunihiro@ipinfusion.com>
13  *              Kazunori MIYAZAWA / USAGI Project <miyazawa@linux-ipv6.org>
14  *              Derek Atkins <derek@ihtfp.com>
15  */
16
17 #include <linux/capability.h>
18 #include <linux/module.h>
19 #include <linux/kernel.h>
20 #include <linux/socket.h>
21 #include <linux/pfkeyv2.h>
22 #include <linux/ipsec.h>
23 #include <linux/skbuff.h>
24 #include <linux/rtnetlink.h>
25 #include <linux/in.h>
26 #include <linux/in6.h>
27 #include <linux/proc_fs.h>
28 #include <linux/init.h>
29 #include <net/net_namespace.h>
30 #include <net/xfrm.h>
31
32 #include <net/sock.h>
33
34 #define _X2KEY(x) ((x) == XFRM_INF ? 0 : (x))
35 #define _KEY2X(x) ((x) == 0 ? XFRM_INF : (x))
36
37
38 /* List of all pfkey sockets. */
39 static HLIST_HEAD(pfkey_table);
40 static DECLARE_WAIT_QUEUE_HEAD(pfkey_table_wait);
41 static DEFINE_RWLOCK(pfkey_table_lock);
42 static atomic_t pfkey_table_users = ATOMIC_INIT(0);
43
44 static atomic_t pfkey_socks_nr = ATOMIC_INIT(0);
45
46 struct pfkey_sock {
47         /* struct sock must be the first member of struct pfkey_sock */
48         struct sock     sk;
49         int             registered;
50         int             promisc;
51
52         struct {
53                 uint8_t         msg_version;
54                 uint32_t        msg_pid;
55                 int             (*dump)(struct pfkey_sock *sk);
56                 void            (*done)(struct pfkey_sock *sk);
57                 union {
58                         struct xfrm_policy_walk policy;
59                         struct xfrm_state_walk  state;
60                 } u;
61         } dump;
62 };
63
64 static inline struct pfkey_sock *pfkey_sk(struct sock *sk)
65 {
66         return (struct pfkey_sock *)sk;
67 }
68
69 static int pfkey_can_dump(struct sock *sk)
70 {
71         if (3 * atomic_read(&sk->sk_rmem_alloc) <= 2 * sk->sk_rcvbuf)
72                 return 1;
73         return 0;
74 }
75
76 static void pfkey_terminate_dump(struct pfkey_sock *pfk)
77 {
78         if (pfk->dump.dump) {
79                 pfk->dump.done(pfk);
80                 pfk->dump.dump = NULL;
81                 pfk->dump.done = NULL;
82         }
83 }
84
85 static void pfkey_sock_destruct(struct sock *sk)
86 {
87         pfkey_terminate_dump(pfkey_sk(sk));
88         skb_queue_purge(&sk->sk_receive_queue);
89
90         if (!sock_flag(sk, SOCK_DEAD)) {
91                 printk("Attempt to release alive pfkey socket: %p\n", sk);
92                 return;
93         }
94
95         WARN_ON(atomic_read(&sk->sk_rmem_alloc));
96         WARN_ON(atomic_read(&sk->sk_wmem_alloc));
97
98         atomic_dec(&pfkey_socks_nr);
99 }
100
101 static void pfkey_table_grab(void)
102 {
103         write_lock_bh(&pfkey_table_lock);
104
105         if (atomic_read(&pfkey_table_users)) {
106                 DECLARE_WAITQUEUE(wait, current);
107
108                 add_wait_queue_exclusive(&pfkey_table_wait, &wait);
109                 for(;;) {
110                         set_current_state(TASK_UNINTERRUPTIBLE);
111                         if (atomic_read(&pfkey_table_users) == 0)
112                                 break;
113                         write_unlock_bh(&pfkey_table_lock);
114                         schedule();
115                         write_lock_bh(&pfkey_table_lock);
116                 }
117
118                 __set_current_state(TASK_RUNNING);
119                 remove_wait_queue(&pfkey_table_wait, &wait);
120         }
121 }
122
123 static __inline__ void pfkey_table_ungrab(void)
124 {
125         write_unlock_bh(&pfkey_table_lock);
126         wake_up(&pfkey_table_wait);
127 }
128
129 static __inline__ void pfkey_lock_table(void)
130 {
131         /* read_lock() synchronizes us to pfkey_table_grab */
132
133         read_lock(&pfkey_table_lock);
134         atomic_inc(&pfkey_table_users);
135         read_unlock(&pfkey_table_lock);
136 }
137
138 static __inline__ void pfkey_unlock_table(void)
139 {
140         if (atomic_dec_and_test(&pfkey_table_users))
141                 wake_up(&pfkey_table_wait);
142 }
143
144
145 static const struct proto_ops pfkey_ops;
146
147 static void pfkey_insert(struct sock *sk)
148 {
149         pfkey_table_grab();
150         sk_add_node(sk, &pfkey_table);
151         pfkey_table_ungrab();
152 }
153
154 static void pfkey_remove(struct sock *sk)
155 {
156         pfkey_table_grab();
157         sk_del_node_init(sk);
158         pfkey_table_ungrab();
159 }
160
161 static struct proto key_proto = {
162         .name     = "KEY",
163         .owner    = THIS_MODULE,
164         .obj_size = sizeof(struct pfkey_sock),
165 };
166
167 static int pfkey_create(struct net *net, struct socket *sock, int protocol)
168 {
169         struct sock *sk;
170         int err;
171
172         if (net != &init_net)
173                 return -EAFNOSUPPORT;
174
175         if (!capable(CAP_NET_ADMIN))
176                 return -EPERM;
177         if (sock->type != SOCK_RAW)
178                 return -ESOCKTNOSUPPORT;
179         if (protocol != PF_KEY_V2)
180                 return -EPROTONOSUPPORT;
181
182         err = -ENOMEM;
183         sk = sk_alloc(net, PF_KEY, GFP_KERNEL, &key_proto);
184         if (sk == NULL)
185                 goto out;
186
187         sock->ops = &pfkey_ops;
188         sock_init_data(sock, sk);
189
190         sk->sk_family = PF_KEY;
191         sk->sk_destruct = pfkey_sock_destruct;
192
193         atomic_inc(&pfkey_socks_nr);
194
195         pfkey_insert(sk);
196
197         return 0;
198 out:
199         return err;
200 }
201
202 static int pfkey_release(struct socket *sock)
203 {
204         struct sock *sk = sock->sk;
205
206         if (!sk)
207                 return 0;
208
209         pfkey_remove(sk);
210
211         sock_orphan(sk);
212         sock->sk = NULL;
213         skb_queue_purge(&sk->sk_write_queue);
214         sock_put(sk);
215
216         return 0;
217 }
218
219 static int pfkey_broadcast_one(struct sk_buff *skb, struct sk_buff **skb2,
220                                gfp_t allocation, struct sock *sk)
221 {
222         int err = -ENOBUFS;
223
224         sock_hold(sk);
225         if (*skb2 == NULL) {
226                 if (atomic_read(&skb->users) != 1) {
227                         *skb2 = skb_clone(skb, allocation);
228                 } else {
229                         *skb2 = skb;
230                         atomic_inc(&skb->users);
231                 }
232         }
233         if (*skb2 != NULL) {
234                 if (atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf) {
235                         skb_orphan(*skb2);
236                         skb_set_owner_r(*skb2, sk);
237                         skb_queue_tail(&sk->sk_receive_queue, *skb2);
238                         sk->sk_data_ready(sk, (*skb2)->len);
239                         *skb2 = NULL;
240                         err = 0;
241                 }
242         }
243         sock_put(sk);
244         return err;
245 }
246
247 /* Send SKB to all pfkey sockets matching selected criteria.  */
248 #define BROADCAST_ALL           0
249 #define BROADCAST_ONE           1
250 #define BROADCAST_REGISTERED    2
251 #define BROADCAST_PROMISC_ONLY  4
252 static int pfkey_broadcast(struct sk_buff *skb, gfp_t allocation,
253                            int broadcast_flags, struct sock *one_sk)
254 {
255         struct sock *sk;
256         struct hlist_node *node;
257         struct sk_buff *skb2 = NULL;
258         int err = -ESRCH;
259
260         /* XXX Do we need something like netlink_overrun?  I think
261          * XXX PF_KEY socket apps will not mind current behavior.
262          */
263         if (!skb)
264                 return -ENOMEM;
265
266         pfkey_lock_table();
267         sk_for_each(sk, node, &pfkey_table) {
268                 struct pfkey_sock *pfk = pfkey_sk(sk);
269                 int err2;
270
271                 /* Yes, it means that if you are meant to receive this
272                  * pfkey message you receive it twice as promiscuous
273                  * socket.
274                  */
275                 if (pfk->promisc)
276                         pfkey_broadcast_one(skb, &skb2, allocation, sk);
277
278                 /* the exact target will be processed later */
279                 if (sk == one_sk)
280                         continue;
281                 if (broadcast_flags != BROADCAST_ALL) {
282                         if (broadcast_flags & BROADCAST_PROMISC_ONLY)
283                                 continue;
284                         if ((broadcast_flags & BROADCAST_REGISTERED) &&
285                             !pfk->registered)
286                                 continue;
287                         if (broadcast_flags & BROADCAST_ONE)
288                                 continue;
289                 }
290
291                 err2 = pfkey_broadcast_one(skb, &skb2, allocation, sk);
292
293                 /* Error is cleare after succecful sending to at least one
294                  * registered KM */
295                 if ((broadcast_flags & BROADCAST_REGISTERED) && err)
296                         err = err2;
297         }
298         pfkey_unlock_table();
299
300         if (one_sk != NULL)
301                 err = pfkey_broadcast_one(skb, &skb2, allocation, one_sk);
302
303         if (skb2)
304                 kfree_skb(skb2);
305         kfree_skb(skb);
306         return err;
307 }
308
309 static int pfkey_do_dump(struct pfkey_sock *pfk)
310 {
311         int rc;
312
313         rc = pfk->dump.dump(pfk);
314         if (rc == -ENOBUFS)
315                 return 0;
316
317         pfkey_terminate_dump(pfk);
318         return rc;
319 }
320
321 static inline void pfkey_hdr_dup(struct sadb_msg *new, struct sadb_msg *orig)
322 {
323         *new = *orig;
324 }
325
326 static int pfkey_error(struct sadb_msg *orig, int err, struct sock *sk)
327 {
328         struct sk_buff *skb = alloc_skb(sizeof(struct sadb_msg) + 16, GFP_KERNEL);
329         struct sadb_msg *hdr;
330
331         if (!skb)
332                 return -ENOBUFS;
333
334         /* Woe be to the platform trying to support PFKEY yet
335          * having normal errnos outside the 1-255 range, inclusive.
336          */
337         err = -err;
338         if (err == ERESTARTSYS ||
339             err == ERESTARTNOHAND ||
340             err == ERESTARTNOINTR)
341                 err = EINTR;
342         if (err >= 512)
343                 err = EINVAL;
344         BUG_ON(err <= 0 || err >= 256);
345
346         hdr = (struct sadb_msg *) skb_put(skb, sizeof(struct sadb_msg));
347         pfkey_hdr_dup(hdr, orig);
348         hdr->sadb_msg_errno = (uint8_t) err;
349         hdr->sadb_msg_len = (sizeof(struct sadb_msg) /
350                              sizeof(uint64_t));
351
352         pfkey_broadcast(skb, GFP_KERNEL, BROADCAST_ONE, sk);
353
354         return 0;
355 }
356
357 static u8 sadb_ext_min_len[] = {
358         [SADB_EXT_RESERVED]             = (u8) 0,
359         [SADB_EXT_SA]                   = (u8) sizeof(struct sadb_sa),
360         [SADB_EXT_LIFETIME_CURRENT]     = (u8) sizeof(struct sadb_lifetime),
361         [SADB_EXT_LIFETIME_HARD]        = (u8) sizeof(struct sadb_lifetime),
362         [SADB_EXT_LIFETIME_SOFT]        = (u8) sizeof(struct sadb_lifetime),
363         [SADB_EXT_ADDRESS_SRC]          = (u8) sizeof(struct sadb_address),
364         [SADB_EXT_ADDRESS_DST]          = (u8) sizeof(struct sadb_address),
365         [SADB_EXT_ADDRESS_PROXY]        = (u8) sizeof(struct sadb_address),
366         [SADB_EXT_KEY_AUTH]             = (u8) sizeof(struct sadb_key),
367         [SADB_EXT_KEY_ENCRYPT]          = (u8) sizeof(struct sadb_key),
368         [SADB_EXT_IDENTITY_SRC]         = (u8) sizeof(struct sadb_ident),
369         [SADB_EXT_IDENTITY_DST]         = (u8) sizeof(struct sadb_ident),
370         [SADB_EXT_SENSITIVITY]          = (u8) sizeof(struct sadb_sens),
371         [SADB_EXT_PROPOSAL]             = (u8) sizeof(struct sadb_prop),
372         [SADB_EXT_SUPPORTED_AUTH]       = (u8) sizeof(struct sadb_supported),
373         [SADB_EXT_SUPPORTED_ENCRYPT]    = (u8) sizeof(struct sadb_supported),
374         [SADB_EXT_SPIRANGE]             = (u8) sizeof(struct sadb_spirange),
375         [SADB_X_EXT_KMPRIVATE]          = (u8) sizeof(struct sadb_x_kmprivate),
376         [SADB_X_EXT_POLICY]             = (u8) sizeof(struct sadb_x_policy),
377         [SADB_X_EXT_SA2]                = (u8) sizeof(struct sadb_x_sa2),
378         [SADB_X_EXT_NAT_T_TYPE]         = (u8) sizeof(struct sadb_x_nat_t_type),
379         [SADB_X_EXT_NAT_T_SPORT]        = (u8) sizeof(struct sadb_x_nat_t_port),
380         [SADB_X_EXT_NAT_T_DPORT]        = (u8) sizeof(struct sadb_x_nat_t_port),
381         [SADB_X_EXT_NAT_T_OA]           = (u8) sizeof(struct sadb_address),
382         [SADB_X_EXT_SEC_CTX]            = (u8) sizeof(struct sadb_x_sec_ctx),
383 };
384
385 /* Verify sadb_address_{len,prefixlen} against sa_family.  */
386 static int verify_address_len(void *p)
387 {
388         struct sadb_address *sp = p;
389         struct sockaddr *addr = (struct sockaddr *)(sp + 1);
390         struct sockaddr_in *sin;
391 #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
392         struct sockaddr_in6 *sin6;
393 #endif
394         int len;
395
396         switch (addr->sa_family) {
397         case AF_INET:
398                 len = DIV_ROUND_UP(sizeof(*sp) + sizeof(*sin), sizeof(uint64_t));
399                 if (sp->sadb_address_len != len ||
400                     sp->sadb_address_prefixlen > 32)
401                         return -EINVAL;
402                 break;
403 #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
404         case AF_INET6:
405                 len = DIV_ROUND_UP(sizeof(*sp) + sizeof(*sin6), sizeof(uint64_t));
406                 if (sp->sadb_address_len != len ||
407                     sp->sadb_address_prefixlen > 128)
408                         return -EINVAL;
409                 break;
410 #endif
411         default:
412                 /* It is user using kernel to keep track of security
413                  * associations for another protocol, such as
414                  * OSPF/RSVP/RIPV2/MIP.  It is user's job to verify
415                  * lengths.
416                  *
417                  * XXX Actually, association/policy database is not yet
418                  * XXX able to cope with arbitrary sockaddr families.
419                  * XXX When it can, remove this -EINVAL.  -DaveM
420                  */
421                 return -EINVAL;
422                 break;
423         }
424
425         return 0;
426 }
427
428 static inline int pfkey_sec_ctx_len(struct sadb_x_sec_ctx *sec_ctx)
429 {
430         return DIV_ROUND_UP(sizeof(struct sadb_x_sec_ctx) +
431                             sec_ctx->sadb_x_ctx_len,
432                             sizeof(uint64_t));
433 }
434
435 static inline int verify_sec_ctx_len(void *p)
436 {
437         struct sadb_x_sec_ctx *sec_ctx = (struct sadb_x_sec_ctx *)p;
438         int len = sec_ctx->sadb_x_ctx_len;
439
440         if (len > PAGE_SIZE)
441                 return -EINVAL;
442
443         len = pfkey_sec_ctx_len(sec_ctx);
444
445         if (sec_ctx->sadb_x_sec_len != len)
446                 return -EINVAL;
447
448         return 0;
449 }
450
451 static inline struct xfrm_user_sec_ctx *pfkey_sadb2xfrm_user_sec_ctx(struct sadb_x_sec_ctx *sec_ctx)
452 {
453         struct xfrm_user_sec_ctx *uctx = NULL;
454         int ctx_size = sec_ctx->sadb_x_ctx_len;
455
456         uctx = kmalloc((sizeof(*uctx)+ctx_size), GFP_KERNEL);
457
458         if (!uctx)
459                 return NULL;
460
461         uctx->len = pfkey_sec_ctx_len(sec_ctx);
462         uctx->exttype = sec_ctx->sadb_x_sec_exttype;
463         uctx->ctx_doi = sec_ctx->sadb_x_ctx_doi;
464         uctx->ctx_alg = sec_ctx->sadb_x_ctx_alg;
465         uctx->ctx_len = sec_ctx->sadb_x_ctx_len;
466         memcpy(uctx + 1, sec_ctx + 1,
467                uctx->ctx_len);
468
469         return uctx;
470 }
471
472 static int present_and_same_family(struct sadb_address *src,
473                                    struct sadb_address *dst)
474 {
475         struct sockaddr *s_addr, *d_addr;
476
477         if (!src || !dst)
478                 return 0;
479
480         s_addr = (struct sockaddr *)(src + 1);
481         d_addr = (struct sockaddr *)(dst + 1);
482         if (s_addr->sa_family != d_addr->sa_family)
483                 return 0;
484         if (s_addr->sa_family != AF_INET
485 #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
486             && s_addr->sa_family != AF_INET6
487 #endif
488                 )
489                 return 0;
490
491         return 1;
492 }
493
494 static int parse_exthdrs(struct sk_buff *skb, struct sadb_msg *hdr, void **ext_hdrs)
495 {
496         char *p = (char *) hdr;
497         int len = skb->len;
498
499         len -= sizeof(*hdr);
500         p += sizeof(*hdr);
501         while (len > 0) {
502                 struct sadb_ext *ehdr = (struct sadb_ext *) p;
503                 uint16_t ext_type;
504                 int ext_len;
505
506                 ext_len  = ehdr->sadb_ext_len;
507                 ext_len *= sizeof(uint64_t);
508                 ext_type = ehdr->sadb_ext_type;
509                 if (ext_len < sizeof(uint64_t) ||
510                     ext_len > len ||
511                     ext_type == SADB_EXT_RESERVED)
512                         return -EINVAL;
513
514                 if (ext_type <= SADB_EXT_MAX) {
515                         int min = (int) sadb_ext_min_len[ext_type];
516                         if (ext_len < min)
517                                 return -EINVAL;
518                         if (ext_hdrs[ext_type-1] != NULL)
519                                 return -EINVAL;
520                         if (ext_type == SADB_EXT_ADDRESS_SRC ||
521                             ext_type == SADB_EXT_ADDRESS_DST ||
522                             ext_type == SADB_EXT_ADDRESS_PROXY ||
523                             ext_type == SADB_X_EXT_NAT_T_OA) {
524                                 if (verify_address_len(p))
525                                         return -EINVAL;
526                         }
527                         if (ext_type == SADB_X_EXT_SEC_CTX) {
528                                 if (verify_sec_ctx_len(p))
529                                         return -EINVAL;
530                         }
531                         ext_hdrs[ext_type-1] = p;
532                 }
533                 p   += ext_len;
534                 len -= ext_len;
535         }
536
537         return 0;
538 }
539
540 static uint16_t
541 pfkey_satype2proto(uint8_t satype)
542 {
543         switch (satype) {
544         case SADB_SATYPE_UNSPEC:
545                 return IPSEC_PROTO_ANY;
546         case SADB_SATYPE_AH:
547                 return IPPROTO_AH;
548         case SADB_SATYPE_ESP:
549                 return IPPROTO_ESP;
550         case SADB_X_SATYPE_IPCOMP:
551                 return IPPROTO_COMP;
552                 break;
553         default:
554                 return 0;
555         }
556         /* NOTREACHED */
557 }
558
559 static uint8_t
560 pfkey_proto2satype(uint16_t proto)
561 {
562         switch (proto) {
563         case IPPROTO_AH:
564                 return SADB_SATYPE_AH;
565         case IPPROTO_ESP:
566                 return SADB_SATYPE_ESP;
567         case IPPROTO_COMP:
568                 return SADB_X_SATYPE_IPCOMP;
569                 break;
570         default:
571                 return 0;
572         }
573         /* NOTREACHED */
574 }
575
576 /* BTW, this scheme means that there is no way with PFKEY2 sockets to
577  * say specifically 'just raw sockets' as we encode them as 255.
578  */
579
580 static uint8_t pfkey_proto_to_xfrm(uint8_t proto)
581 {
582         return (proto == IPSEC_PROTO_ANY ? 0 : proto);
583 }
584
585 static uint8_t pfkey_proto_from_xfrm(uint8_t proto)
586 {
587         return (proto ? proto : IPSEC_PROTO_ANY);
588 }
589
590 static inline int pfkey_sockaddr_len(sa_family_t family)
591 {
592         switch (family) {
593         case AF_INET:
594                 return sizeof(struct sockaddr_in);
595 #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
596         case AF_INET6:
597                 return sizeof(struct sockaddr_in6);
598 #endif
599         }
600         return 0;
601 }
602
603 static
604 int pfkey_sockaddr_extract(const struct sockaddr *sa, xfrm_address_t *xaddr)
605 {
606         switch (sa->sa_family) {
607         case AF_INET:
608                 xaddr->a4 =
609                         ((struct sockaddr_in *)sa)->sin_addr.s_addr;
610                 return AF_INET;
611 #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
612         case AF_INET6:
613                 memcpy(xaddr->a6,
614                        &((struct sockaddr_in6 *)sa)->sin6_addr,
615                        sizeof(struct in6_addr));
616                 return AF_INET6;
617 #endif
618         }
619         return 0;
620 }
621
622 static
623 int pfkey_sadb_addr2xfrm_addr(struct sadb_address *addr, xfrm_address_t *xaddr)
624 {
625         return pfkey_sockaddr_extract((struct sockaddr *)(addr + 1),
626                                       xaddr);
627 }
628
629 static struct  xfrm_state *pfkey_xfrm_state_lookup(struct sadb_msg *hdr, void **ext_hdrs)
630 {
631         struct sadb_sa *sa;
632         struct sadb_address *addr;
633         uint16_t proto;
634         unsigned short family;
635         xfrm_address_t *xaddr;
636
637         sa = (struct sadb_sa *) ext_hdrs[SADB_EXT_SA-1];
638         if (sa == NULL)
639                 return NULL;
640
641         proto = pfkey_satype2proto(hdr->sadb_msg_satype);
642         if (proto == 0)
643                 return NULL;
644
645         /* sadb_address_len should be checked by caller */
646         addr = (struct sadb_address *) ext_hdrs[SADB_EXT_ADDRESS_DST-1];
647         if (addr == NULL)
648                 return NULL;
649
650         family = ((struct sockaddr *)(addr + 1))->sa_family;
651         switch (family) {
652         case AF_INET:
653                 xaddr = (xfrm_address_t *)&((struct sockaddr_in *)(addr + 1))->sin_addr;
654                 break;
655 #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
656         case AF_INET6:
657                 xaddr = (xfrm_address_t *)&((struct sockaddr_in6 *)(addr + 1))->sin6_addr;
658                 break;
659 #endif
660         default:
661                 xaddr = NULL;
662         }
663
664         if (!xaddr)
665                 return NULL;
666
667         return xfrm_state_lookup(xaddr, sa->sadb_sa_spi, proto, family);
668 }
669
670 #define PFKEY_ALIGN8(a) (1 + (((a) - 1) | (8 - 1)))
671
672 static int
673 pfkey_sockaddr_size(sa_family_t family)
674 {
675         return PFKEY_ALIGN8(pfkey_sockaddr_len(family));
676 }
677
678 static inline int pfkey_mode_from_xfrm(int mode)
679 {
680         switch(mode) {
681         case XFRM_MODE_TRANSPORT:
682                 return IPSEC_MODE_TRANSPORT;
683         case XFRM_MODE_TUNNEL:
684                 return IPSEC_MODE_TUNNEL;
685         case XFRM_MODE_BEET:
686                 return IPSEC_MODE_BEET;
687         default:
688                 return -1;
689         }
690 }
691
692 static inline int pfkey_mode_to_xfrm(int mode)
693 {
694         switch(mode) {
695         case IPSEC_MODE_ANY:    /*XXX*/
696         case IPSEC_MODE_TRANSPORT:
697                 return XFRM_MODE_TRANSPORT;
698         case IPSEC_MODE_TUNNEL:
699                 return XFRM_MODE_TUNNEL;
700         case IPSEC_MODE_BEET:
701                 return XFRM_MODE_BEET;
702         default:
703                 return -1;
704         }
705 }
706
707 static unsigned int pfkey_sockaddr_fill(xfrm_address_t *xaddr, __be16 port,
708                                        struct sockaddr *sa,
709                                        unsigned short family)
710 {
711         switch (family) {
712         case AF_INET:
713             {
714                 struct sockaddr_in *sin = (struct sockaddr_in *)sa;
715                 sin->sin_family = AF_INET;
716                 sin->sin_port = port;
717                 sin->sin_addr.s_addr = xaddr->a4;
718                 memset(sin->sin_zero, 0, sizeof(sin->sin_zero));
719                 return 32;
720             }
721 #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
722         case AF_INET6:
723             {
724                 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)sa;
725                 sin6->sin6_family = AF_INET6;
726                 sin6->sin6_port = port;
727                 sin6->sin6_flowinfo = 0;
728                 ipv6_addr_copy(&sin6->sin6_addr, (struct in6_addr *)xaddr->a6);
729                 sin6->sin6_scope_id = 0;
730                 return 128;
731             }
732 #endif
733         }
734         return 0;
735 }
736
737 static struct sk_buff *__pfkey_xfrm_state2msg(struct xfrm_state *x,
738                                               int add_keys, int hsc)
739 {
740         struct sk_buff *skb;
741         struct sadb_msg *hdr;
742         struct sadb_sa *sa;
743         struct sadb_lifetime *lifetime;
744         struct sadb_address *addr;
745         struct sadb_key *key;
746         struct sadb_x_sa2 *sa2;
747         struct sadb_x_sec_ctx *sec_ctx;
748         struct xfrm_sec_ctx *xfrm_ctx;
749         int ctx_size = 0;
750         int size;
751         int auth_key_size = 0;
752         int encrypt_key_size = 0;
753         int sockaddr_size;
754         struct xfrm_encap_tmpl *natt = NULL;
755         int mode;
756
757         /* address family check */
758         sockaddr_size = pfkey_sockaddr_size(x->props.family);
759         if (!sockaddr_size)
760                 return ERR_PTR(-EINVAL);
761
762         /* base, SA, (lifetime (HSC),) address(SD), (address(P),)
763            key(AE), (identity(SD),) (sensitivity)> */
764         size = sizeof(struct sadb_msg) +sizeof(struct sadb_sa) +
765                 sizeof(struct sadb_lifetime) +
766                 ((hsc & 1) ? sizeof(struct sadb_lifetime) : 0) +
767                 ((hsc & 2) ? sizeof(struct sadb_lifetime) : 0) +
768                         sizeof(struct sadb_address)*2 +
769                                 sockaddr_size*2 +
770                                         sizeof(struct sadb_x_sa2);
771
772         if ((xfrm_ctx = x->security)) {
773                 ctx_size = PFKEY_ALIGN8(xfrm_ctx->ctx_len);
774                 size += sizeof(struct sadb_x_sec_ctx) + ctx_size;
775         }
776
777         /* identity & sensitivity */
778         if (xfrm_addr_cmp(&x->sel.saddr, &x->props.saddr, x->props.family))
779                 size += sizeof(struct sadb_address) + sockaddr_size;
780
781         if (add_keys) {
782                 if (x->aalg && x->aalg->alg_key_len) {
783                         auth_key_size =
784                                 PFKEY_ALIGN8((x->aalg->alg_key_len + 7) / 8);
785                         size += sizeof(struct sadb_key) + auth_key_size;
786                 }
787                 if (x->ealg && x->ealg->alg_key_len) {
788                         encrypt_key_size =
789                                 PFKEY_ALIGN8((x->ealg->alg_key_len+7) / 8);
790                         size += sizeof(struct sadb_key) + encrypt_key_size;
791                 }
792         }
793         if (x->encap)
794                 natt = x->encap;
795
796         if (natt && natt->encap_type) {
797                 size += sizeof(struct sadb_x_nat_t_type);
798                 size += sizeof(struct sadb_x_nat_t_port);
799                 size += sizeof(struct sadb_x_nat_t_port);
800         }
801
802         skb =  alloc_skb(size + 16, GFP_ATOMIC);
803         if (skb == NULL)
804                 return ERR_PTR(-ENOBUFS);
805
806         /* call should fill header later */
807         hdr = (struct sadb_msg *) skb_put(skb, sizeof(struct sadb_msg));
808         memset(hdr, 0, size);   /* XXX do we need this ? */
809         hdr->sadb_msg_len = size / sizeof(uint64_t);
810
811         /* sa */
812         sa = (struct sadb_sa *)  skb_put(skb, sizeof(struct sadb_sa));
813         sa->sadb_sa_len = sizeof(struct sadb_sa)/sizeof(uint64_t);
814         sa->sadb_sa_exttype = SADB_EXT_SA;
815         sa->sadb_sa_spi = x->id.spi;
816         sa->sadb_sa_replay = x->props.replay_window;
817         switch (x->km.state) {
818         case XFRM_STATE_VALID:
819                 sa->sadb_sa_state = x->km.dying ?
820                         SADB_SASTATE_DYING : SADB_SASTATE_MATURE;
821                 break;
822         case XFRM_STATE_ACQ:
823                 sa->sadb_sa_state = SADB_SASTATE_LARVAL;
824                 break;
825         default:
826                 sa->sadb_sa_state = SADB_SASTATE_DEAD;
827                 break;
828         }
829         sa->sadb_sa_auth = 0;
830         if (x->aalg) {
831                 struct xfrm_algo_desc *a = xfrm_aalg_get_byname(x->aalg->alg_name, 0);
832                 sa->sadb_sa_auth = a ? a->desc.sadb_alg_id : 0;
833         }
834         sa->sadb_sa_encrypt = 0;
835         BUG_ON(x->ealg && x->calg);
836         if (x->ealg) {
837                 struct xfrm_algo_desc *a = xfrm_ealg_get_byname(x->ealg->alg_name, 0);
838                 sa->sadb_sa_encrypt = a ? a->desc.sadb_alg_id : 0;
839         }
840         /* KAME compatible: sadb_sa_encrypt is overloaded with calg id */
841         if (x->calg) {
842                 struct xfrm_algo_desc *a = xfrm_calg_get_byname(x->calg->alg_name, 0);
843                 sa->sadb_sa_encrypt = a ? a->desc.sadb_alg_id : 0;
844         }
845
846         sa->sadb_sa_flags = 0;
847         if (x->props.flags & XFRM_STATE_NOECN)
848                 sa->sadb_sa_flags |= SADB_SAFLAGS_NOECN;
849         if (x->props.flags & XFRM_STATE_DECAP_DSCP)
850                 sa->sadb_sa_flags |= SADB_SAFLAGS_DECAP_DSCP;
851         if (x->props.flags & XFRM_STATE_NOPMTUDISC)
852                 sa->sadb_sa_flags |= SADB_SAFLAGS_NOPMTUDISC;
853
854         /* hard time */
855         if (hsc & 2) {
856                 lifetime = (struct sadb_lifetime *)  skb_put(skb,
857                                                              sizeof(struct sadb_lifetime));
858                 lifetime->sadb_lifetime_len =
859                         sizeof(struct sadb_lifetime)/sizeof(uint64_t);
860                 lifetime->sadb_lifetime_exttype = SADB_EXT_LIFETIME_HARD;
861                 lifetime->sadb_lifetime_allocations =  _X2KEY(x->lft.hard_packet_limit);
862                 lifetime->sadb_lifetime_bytes = _X2KEY(x->lft.hard_byte_limit);
863                 lifetime->sadb_lifetime_addtime = x->lft.hard_add_expires_seconds;
864                 lifetime->sadb_lifetime_usetime = x->lft.hard_use_expires_seconds;
865         }
866         /* soft time */
867         if (hsc & 1) {
868                 lifetime = (struct sadb_lifetime *)  skb_put(skb,
869                                                              sizeof(struct sadb_lifetime));
870                 lifetime->sadb_lifetime_len =
871                         sizeof(struct sadb_lifetime)/sizeof(uint64_t);
872                 lifetime->sadb_lifetime_exttype = SADB_EXT_LIFETIME_SOFT;
873                 lifetime->sadb_lifetime_allocations =  _X2KEY(x->lft.soft_packet_limit);
874                 lifetime->sadb_lifetime_bytes = _X2KEY(x->lft.soft_byte_limit);
875                 lifetime->sadb_lifetime_addtime = x->lft.soft_add_expires_seconds;
876                 lifetime->sadb_lifetime_usetime = x->lft.soft_use_expires_seconds;
877         }
878         /* current time */
879         lifetime = (struct sadb_lifetime *)  skb_put(skb,
880                                                      sizeof(struct sadb_lifetime));
881         lifetime->sadb_lifetime_len =
882                 sizeof(struct sadb_lifetime)/sizeof(uint64_t);
883         lifetime->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
884         lifetime->sadb_lifetime_allocations = x->curlft.packets;
885         lifetime->sadb_lifetime_bytes = x->curlft.bytes;
886         lifetime->sadb_lifetime_addtime = x->curlft.add_time;
887         lifetime->sadb_lifetime_usetime = x->curlft.use_time;
888         /* src address */
889         addr = (struct sadb_address*) skb_put(skb,
890                                               sizeof(struct sadb_address)+sockaddr_size);
891         addr->sadb_address_len =
892                 (sizeof(struct sadb_address)+sockaddr_size)/
893                         sizeof(uint64_t);
894         addr->sadb_address_exttype = SADB_EXT_ADDRESS_SRC;
895         /* "if the ports are non-zero, then the sadb_address_proto field,
896            normally zero, MUST be filled in with the transport
897            protocol's number." - RFC2367 */
898         addr->sadb_address_proto = 0;
899         addr->sadb_address_reserved = 0;
900
901         addr->sadb_address_prefixlen =
902                 pfkey_sockaddr_fill(&x->props.saddr, 0,
903                                     (struct sockaddr *) (addr + 1),
904                                     x->props.family);
905         if (!addr->sadb_address_prefixlen)
906                 BUG();
907
908         /* dst address */
909         addr = (struct sadb_address*) skb_put(skb,
910                                               sizeof(struct sadb_address)+sockaddr_size);
911         addr->sadb_address_len =
912                 (sizeof(struct sadb_address)+sockaddr_size)/
913                         sizeof(uint64_t);
914         addr->sadb_address_exttype = SADB_EXT_ADDRESS_DST;
915         addr->sadb_address_proto = 0;
916         addr->sadb_address_reserved = 0;
917
918         addr->sadb_address_prefixlen =
919                 pfkey_sockaddr_fill(&x->id.daddr, 0,
920                                     (struct sockaddr *) (addr + 1),
921                                     x->props.family);
922         if (!addr->sadb_address_prefixlen)
923                 BUG();
924
925         if (xfrm_addr_cmp(&x->sel.saddr, &x->props.saddr,
926                           x->props.family)) {
927                 addr = (struct sadb_address*) skb_put(skb,
928                         sizeof(struct sadb_address)+sockaddr_size);
929                 addr->sadb_address_len =
930                         (sizeof(struct sadb_address)+sockaddr_size)/
931                         sizeof(uint64_t);
932                 addr->sadb_address_exttype = SADB_EXT_ADDRESS_PROXY;
933                 addr->sadb_address_proto =
934                         pfkey_proto_from_xfrm(x->sel.proto);
935                 addr->sadb_address_prefixlen = x->sel.prefixlen_s;
936                 addr->sadb_address_reserved = 0;
937
938                 pfkey_sockaddr_fill(&x->sel.saddr, x->sel.sport,
939                                     (struct sockaddr *) (addr + 1),
940                                     x->props.family);
941         }
942
943         /* auth key */
944         if (add_keys && auth_key_size) {
945                 key = (struct sadb_key *) skb_put(skb,
946                                                   sizeof(struct sadb_key)+auth_key_size);
947                 key->sadb_key_len = (sizeof(struct sadb_key) + auth_key_size) /
948                         sizeof(uint64_t);
949                 key->sadb_key_exttype = SADB_EXT_KEY_AUTH;
950                 key->sadb_key_bits = x->aalg->alg_key_len;
951                 key->sadb_key_reserved = 0;
952                 memcpy(key + 1, x->aalg->alg_key, (x->aalg->alg_key_len+7)/8);
953         }
954         /* encrypt key */
955         if (add_keys && encrypt_key_size) {
956                 key = (struct sadb_key *) skb_put(skb,
957                                                   sizeof(struct sadb_key)+encrypt_key_size);
958                 key->sadb_key_len = (sizeof(struct sadb_key) +
959                                      encrypt_key_size) / sizeof(uint64_t);
960                 key->sadb_key_exttype = SADB_EXT_KEY_ENCRYPT;
961                 key->sadb_key_bits = x->ealg->alg_key_len;
962                 key->sadb_key_reserved = 0;
963                 memcpy(key + 1, x->ealg->alg_key,
964                        (x->ealg->alg_key_len+7)/8);
965         }
966
967         /* sa */
968         sa2 = (struct sadb_x_sa2 *)  skb_put(skb, sizeof(struct sadb_x_sa2));
969         sa2->sadb_x_sa2_len = sizeof(struct sadb_x_sa2)/sizeof(uint64_t);
970         sa2->sadb_x_sa2_exttype = SADB_X_EXT_SA2;
971         if ((mode = pfkey_mode_from_xfrm(x->props.mode)) < 0) {
972                 kfree_skb(skb);
973                 return ERR_PTR(-EINVAL);
974         }
975         sa2->sadb_x_sa2_mode = mode;
976         sa2->sadb_x_sa2_reserved1 = 0;
977         sa2->sadb_x_sa2_reserved2 = 0;
978         sa2->sadb_x_sa2_sequence = 0;
979         sa2->sadb_x_sa2_reqid = x->props.reqid;
980
981         if (natt && natt->encap_type) {
982                 struct sadb_x_nat_t_type *n_type;
983                 struct sadb_x_nat_t_port *n_port;
984
985                 /* type */
986                 n_type = (struct sadb_x_nat_t_type*) skb_put(skb, sizeof(*n_type));
987                 n_type->sadb_x_nat_t_type_len = sizeof(*n_type)/sizeof(uint64_t);
988                 n_type->sadb_x_nat_t_type_exttype = SADB_X_EXT_NAT_T_TYPE;
989                 n_type->sadb_x_nat_t_type_type = natt->encap_type;
990                 n_type->sadb_x_nat_t_type_reserved[0] = 0;
991                 n_type->sadb_x_nat_t_type_reserved[1] = 0;
992                 n_type->sadb_x_nat_t_type_reserved[2] = 0;
993
994                 /* source port */
995                 n_port = (struct sadb_x_nat_t_port*) skb_put(skb, sizeof (*n_port));
996                 n_port->sadb_x_nat_t_port_len = sizeof(*n_port)/sizeof(uint64_t);
997                 n_port->sadb_x_nat_t_port_exttype = SADB_X_EXT_NAT_T_SPORT;
998                 n_port->sadb_x_nat_t_port_port = natt->encap_sport;
999                 n_port->sadb_x_nat_t_port_reserved = 0;
1000
1001                 /* dest port */
1002                 n_port = (struct sadb_x_nat_t_port*) skb_put(skb, sizeof (*n_port));
1003                 n_port->sadb_x_nat_t_port_len = sizeof(*n_port)/sizeof(uint64_t);
1004                 n_port->sadb_x_nat_t_port_exttype = SADB_X_EXT_NAT_T_DPORT;
1005                 n_port->sadb_x_nat_t_port_port = natt->encap_dport;
1006                 n_port->sadb_x_nat_t_port_reserved = 0;
1007         }
1008
1009         /* security context */
1010         if (xfrm_ctx) {
1011                 sec_ctx = (struct sadb_x_sec_ctx *) skb_put(skb,
1012                                 sizeof(struct sadb_x_sec_ctx) + ctx_size);
1013                 sec_ctx->sadb_x_sec_len =
1014                   (sizeof(struct sadb_x_sec_ctx) + ctx_size) / sizeof(uint64_t);
1015                 sec_ctx->sadb_x_sec_exttype = SADB_X_EXT_SEC_CTX;
1016                 sec_ctx->sadb_x_ctx_doi = xfrm_ctx->ctx_doi;
1017                 sec_ctx->sadb_x_ctx_alg = xfrm_ctx->ctx_alg;
1018                 sec_ctx->sadb_x_ctx_len = xfrm_ctx->ctx_len;
1019                 memcpy(sec_ctx + 1, xfrm_ctx->ctx_str,
1020                        xfrm_ctx->ctx_len);
1021         }
1022
1023         return skb;
1024 }
1025
1026
1027 static inline struct sk_buff *pfkey_xfrm_state2msg(struct xfrm_state *x)
1028 {
1029         struct sk_buff *skb;
1030
1031         skb = __pfkey_xfrm_state2msg(x, 1, 3);
1032
1033         return skb;
1034 }
1035
1036 static inline struct sk_buff *pfkey_xfrm_state2msg_expire(struct xfrm_state *x,
1037                                                           int hsc)
1038 {
1039         return __pfkey_xfrm_state2msg(x, 0, hsc);
1040 }
1041
1042 static struct xfrm_state * pfkey_msg2xfrm_state(struct sadb_msg *hdr,
1043                                                 void **ext_hdrs)
1044 {
1045         struct xfrm_state *x;
1046         struct sadb_lifetime *lifetime;
1047         struct sadb_sa *sa;
1048         struct sadb_key *key;
1049         struct sadb_x_sec_ctx *sec_ctx;
1050         uint16_t proto;
1051         int err;
1052
1053
1054         sa = (struct sadb_sa *) ext_hdrs[SADB_EXT_SA-1];
1055         if (!sa ||
1056             !present_and_same_family(ext_hdrs[SADB_EXT_ADDRESS_SRC-1],
1057                                      ext_hdrs[SADB_EXT_ADDRESS_DST-1]))
1058                 return ERR_PTR(-EINVAL);
1059         if (hdr->sadb_msg_satype == SADB_SATYPE_ESP &&
1060             !ext_hdrs[SADB_EXT_KEY_ENCRYPT-1])
1061                 return ERR_PTR(-EINVAL);
1062         if (hdr->sadb_msg_satype == SADB_SATYPE_AH &&
1063             !ext_hdrs[SADB_EXT_KEY_AUTH-1])
1064                 return ERR_PTR(-EINVAL);
1065         if (!!ext_hdrs[SADB_EXT_LIFETIME_HARD-1] !=
1066             !!ext_hdrs[SADB_EXT_LIFETIME_SOFT-1])
1067                 return ERR_PTR(-EINVAL);
1068
1069         proto = pfkey_satype2proto(hdr->sadb_msg_satype);
1070         if (proto == 0)
1071                 return ERR_PTR(-EINVAL);
1072
1073         /* default error is no buffer space */
1074         err = -ENOBUFS;
1075
1076         /* RFC2367:
1077
1078    Only SADB_SASTATE_MATURE SAs may be submitted in an SADB_ADD message.
1079    SADB_SASTATE_LARVAL SAs are created by SADB_GETSPI and it is not
1080    sensible to add a new SA in the DYING or SADB_SASTATE_DEAD state.
1081    Therefore, the sadb_sa_state field of all submitted SAs MUST be
1082    SADB_SASTATE_MATURE and the kernel MUST return an error if this is
1083    not true.
1084
1085            However, KAME setkey always uses SADB_SASTATE_LARVAL.
1086            Hence, we have to _ignore_ sadb_sa_state, which is also reasonable.
1087          */
1088         if (sa->sadb_sa_auth > SADB_AALG_MAX ||
1089             (hdr->sadb_msg_satype == SADB_X_SATYPE_IPCOMP &&
1090              sa->sadb_sa_encrypt > SADB_X_CALG_MAX) ||
1091             sa->sadb_sa_encrypt > SADB_EALG_MAX)
1092                 return ERR_PTR(-EINVAL);
1093         key = (struct sadb_key*) ext_hdrs[SADB_EXT_KEY_AUTH-1];
1094         if (key != NULL &&
1095             sa->sadb_sa_auth != SADB_X_AALG_NULL &&
1096             ((key->sadb_key_bits+7) / 8 == 0 ||
1097              (key->sadb_key_bits+7) / 8 > key->sadb_key_len * sizeof(uint64_t)))
1098                 return ERR_PTR(-EINVAL);
1099         key = ext_hdrs[SADB_EXT_KEY_ENCRYPT-1];
1100         if (key != NULL &&
1101             sa->sadb_sa_encrypt != SADB_EALG_NULL &&
1102             ((key->sadb_key_bits+7) / 8 == 0 ||
1103              (key->sadb_key_bits+7) / 8 > key->sadb_key_len * sizeof(uint64_t)))
1104                 return ERR_PTR(-EINVAL);
1105
1106         x = xfrm_state_alloc();
1107         if (x == NULL)
1108                 return ERR_PTR(-ENOBUFS);
1109
1110         x->id.proto = proto;
1111         x->id.spi = sa->sadb_sa_spi;
1112         x->props.replay_window = sa->sadb_sa_replay;
1113         if (sa->sadb_sa_flags & SADB_SAFLAGS_NOECN)
1114                 x->props.flags |= XFRM_STATE_NOECN;
1115         if (sa->sadb_sa_flags & SADB_SAFLAGS_DECAP_DSCP)
1116                 x->props.flags |= XFRM_STATE_DECAP_DSCP;
1117         if (sa->sadb_sa_flags & SADB_SAFLAGS_NOPMTUDISC)
1118                 x->props.flags |= XFRM_STATE_NOPMTUDISC;
1119
1120         lifetime = (struct sadb_lifetime*) ext_hdrs[SADB_EXT_LIFETIME_HARD-1];
1121         if (lifetime != NULL) {
1122                 x->lft.hard_packet_limit = _KEY2X(lifetime->sadb_lifetime_allocations);
1123                 x->lft.hard_byte_limit = _KEY2X(lifetime->sadb_lifetime_bytes);
1124                 x->lft.hard_add_expires_seconds = lifetime->sadb_lifetime_addtime;
1125                 x->lft.hard_use_expires_seconds = lifetime->sadb_lifetime_usetime;
1126         }
1127         lifetime = (struct sadb_lifetime*) ext_hdrs[SADB_EXT_LIFETIME_SOFT-1];
1128         if (lifetime != NULL) {
1129                 x->lft.soft_packet_limit = _KEY2X(lifetime->sadb_lifetime_allocations);
1130                 x->lft.soft_byte_limit = _KEY2X(lifetime->sadb_lifetime_bytes);
1131                 x->lft.soft_add_expires_seconds = lifetime->sadb_lifetime_addtime;
1132                 x->lft.soft_use_expires_seconds = lifetime->sadb_lifetime_usetime;
1133         }
1134
1135         sec_ctx = (struct sadb_x_sec_ctx *) ext_hdrs[SADB_X_EXT_SEC_CTX-1];
1136         if (sec_ctx != NULL) {
1137                 struct xfrm_user_sec_ctx *uctx = pfkey_sadb2xfrm_user_sec_ctx(sec_ctx);
1138
1139                 if (!uctx)
1140                         goto out;
1141
1142                 err = security_xfrm_state_alloc(x, uctx);
1143                 kfree(uctx);
1144
1145                 if (err)
1146                         goto out;
1147         }
1148
1149         key = (struct sadb_key*) ext_hdrs[SADB_EXT_KEY_AUTH-1];
1150         if (sa->sadb_sa_auth) {
1151                 int keysize = 0;
1152                 struct xfrm_algo_desc *a = xfrm_aalg_get_byid(sa->sadb_sa_auth);
1153                 if (!a) {
1154                         err = -ENOSYS;
1155                         goto out;
1156                 }
1157                 if (key)
1158                         keysize = (key->sadb_key_bits + 7) / 8;
1159                 x->aalg = kmalloc(sizeof(*x->aalg) + keysize, GFP_KERNEL);
1160                 if (!x->aalg)
1161                         goto out;
1162                 strcpy(x->aalg->alg_name, a->name);
1163                 x->aalg->alg_key_len = 0;
1164                 if (key) {
1165                         x->aalg->alg_key_len = key->sadb_key_bits;
1166                         memcpy(x->aalg->alg_key, key+1, keysize);
1167                 }
1168                 x->props.aalgo = sa->sadb_sa_auth;
1169                 /* x->algo.flags = sa->sadb_sa_flags; */
1170         }
1171         if (sa->sadb_sa_encrypt) {
1172                 if (hdr->sadb_msg_satype == SADB_X_SATYPE_IPCOMP) {
1173                         struct xfrm_algo_desc *a = xfrm_calg_get_byid(sa->sadb_sa_encrypt);
1174                         if (!a) {
1175                                 err = -ENOSYS;
1176                                 goto out;
1177                         }
1178                         x->calg = kmalloc(sizeof(*x->calg), GFP_KERNEL);
1179                         if (!x->calg)
1180                                 goto out;
1181                         strcpy(x->calg->alg_name, a->name);
1182                         x->props.calgo = sa->sadb_sa_encrypt;
1183                 } else {
1184                         int keysize = 0;
1185                         struct xfrm_algo_desc *a = xfrm_ealg_get_byid(sa->sadb_sa_encrypt);
1186                         if (!a) {
1187                                 err = -ENOSYS;
1188                                 goto out;
1189                         }
1190                         key = (struct sadb_key*) ext_hdrs[SADB_EXT_KEY_ENCRYPT-1];
1191                         if (key)
1192                                 keysize = (key->sadb_key_bits + 7) / 8;
1193                         x->ealg = kmalloc(sizeof(*x->ealg) + keysize, GFP_KERNEL);
1194                         if (!x->ealg)
1195                                 goto out;
1196                         strcpy(x->ealg->alg_name, a->name);
1197                         x->ealg->alg_key_len = 0;
1198                         if (key) {
1199                                 x->ealg->alg_key_len = key->sadb_key_bits;
1200                                 memcpy(x->ealg->alg_key, key+1, keysize);
1201                         }
1202                         x->props.ealgo = sa->sadb_sa_encrypt;
1203                 }
1204         }
1205         /* x->algo.flags = sa->sadb_sa_flags; */
1206
1207         x->props.family = pfkey_sadb_addr2xfrm_addr((struct sadb_address *) ext_hdrs[SADB_EXT_ADDRESS_SRC-1],
1208                                                     &x->props.saddr);
1209         if (!x->props.family) {
1210                 err = -EAFNOSUPPORT;
1211                 goto out;
1212         }
1213         pfkey_sadb_addr2xfrm_addr((struct sadb_address *) ext_hdrs[SADB_EXT_ADDRESS_DST-1],
1214                                   &x->id.daddr);
1215
1216         if (ext_hdrs[SADB_X_EXT_SA2-1]) {
1217                 struct sadb_x_sa2 *sa2 = (void*)ext_hdrs[SADB_X_EXT_SA2-1];
1218                 int mode = pfkey_mode_to_xfrm(sa2->sadb_x_sa2_mode);
1219                 if (mode < 0) {
1220                         err = -EINVAL;
1221                         goto out;
1222                 }
1223                 x->props.mode = mode;
1224                 x->props.reqid = sa2->sadb_x_sa2_reqid;
1225         }
1226
1227         if (ext_hdrs[SADB_EXT_ADDRESS_PROXY-1]) {
1228                 struct sadb_address *addr = ext_hdrs[SADB_EXT_ADDRESS_PROXY-1];
1229
1230                 /* Nobody uses this, but we try. */
1231                 x->sel.family = pfkey_sadb_addr2xfrm_addr(addr, &x->sel.saddr);
1232                 x->sel.prefixlen_s = addr->sadb_address_prefixlen;
1233         }
1234
1235         if (!x->sel.family)
1236                 x->sel.family = x->props.family;
1237
1238         if (ext_hdrs[SADB_X_EXT_NAT_T_TYPE-1]) {
1239                 struct sadb_x_nat_t_type* n_type;
1240                 struct xfrm_encap_tmpl *natt;
1241
1242                 x->encap = kmalloc(sizeof(*x->encap), GFP_KERNEL);
1243                 if (!x->encap)
1244                         goto out;
1245
1246                 natt = x->encap;
1247                 n_type = ext_hdrs[SADB_X_EXT_NAT_T_TYPE-1];
1248                 natt->encap_type = n_type->sadb_x_nat_t_type_type;
1249
1250                 if (ext_hdrs[SADB_X_EXT_NAT_T_SPORT-1]) {
1251                         struct sadb_x_nat_t_port* n_port =
1252                                 ext_hdrs[SADB_X_EXT_NAT_T_SPORT-1];
1253                         natt->encap_sport = n_port->sadb_x_nat_t_port_port;
1254                 }
1255                 if (ext_hdrs[SADB_X_EXT_NAT_T_DPORT-1]) {
1256                         struct sadb_x_nat_t_port* n_port =
1257                                 ext_hdrs[SADB_X_EXT_NAT_T_DPORT-1];
1258                         natt->encap_dport = n_port->sadb_x_nat_t_port_port;
1259                 }
1260         }
1261
1262         err = xfrm_init_state(x);
1263         if (err)
1264                 goto out;
1265
1266         x->km.seq = hdr->sadb_msg_seq;
1267         return x;
1268
1269 out:
1270         x->km.state = XFRM_STATE_DEAD;
1271         xfrm_state_put(x);
1272         return ERR_PTR(err);
1273 }
1274
1275 static int pfkey_reserved(struct sock *sk, struct sk_buff *skb, struct sadb_msg *hdr, void **ext_hdrs)
1276 {
1277         return -EOPNOTSUPP;
1278 }
1279
1280 static int pfkey_getspi(struct sock *sk, struct sk_buff *skb, struct sadb_msg *hdr, void **ext_hdrs)
1281 {
1282         struct sk_buff *resp_skb;
1283         struct sadb_x_sa2 *sa2;
1284         struct sadb_address *saddr, *daddr;
1285         struct sadb_msg *out_hdr;
1286         struct sadb_spirange *range;
1287         struct xfrm_state *x = NULL;
1288         int mode;
1289         int err;
1290         u32 min_spi, max_spi;
1291         u32 reqid;
1292         u8 proto;
1293         unsigned short family;
1294         xfrm_address_t *xsaddr = NULL, *xdaddr = NULL;
1295
1296         if (!present_and_same_family(ext_hdrs[SADB_EXT_ADDRESS_SRC-1],
1297                                      ext_hdrs[SADB_EXT_ADDRESS_DST-1]))
1298                 return -EINVAL;
1299
1300         proto = pfkey_satype2proto(hdr->sadb_msg_satype);
1301         if (proto == 0)
1302                 return -EINVAL;
1303
1304         if ((sa2 = ext_hdrs[SADB_X_EXT_SA2-1]) != NULL) {
1305                 mode = pfkey_mode_to_xfrm(sa2->sadb_x_sa2_mode);
1306                 if (mode < 0)
1307                         return -EINVAL;
1308                 reqid = sa2->sadb_x_sa2_reqid;
1309         } else {
1310                 mode = 0;
1311                 reqid = 0;
1312         }
1313
1314         saddr = ext_hdrs[SADB_EXT_ADDRESS_SRC-1];
1315         daddr = ext_hdrs[SADB_EXT_ADDRESS_DST-1];
1316
1317         family = ((struct sockaddr *)(saddr + 1))->sa_family;
1318         switch (family) {
1319         case AF_INET:
1320                 xdaddr = (xfrm_address_t *)&((struct sockaddr_in *)(daddr + 1))->sin_addr.s_addr;
1321                 xsaddr = (xfrm_address_t *)&((struct sockaddr_in *)(saddr + 1))->sin_addr.s_addr;
1322                 break;
1323 #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
1324         case AF_INET6:
1325                 xdaddr = (xfrm_address_t *)&((struct sockaddr_in6 *)(daddr + 1))->sin6_addr;
1326                 xsaddr = (xfrm_address_t *)&((struct sockaddr_in6 *)(saddr + 1))->sin6_addr;
1327                 break;
1328 #endif
1329         }
1330
1331         if (hdr->sadb_msg_seq) {
1332                 x = xfrm_find_acq_byseq(hdr->sadb_msg_seq);
1333                 if (x && xfrm_addr_cmp(&x->id.daddr, xdaddr, family)) {
1334                         xfrm_state_put(x);
1335                         x = NULL;
1336                 }
1337         }
1338
1339         if (!x)
1340                 x = xfrm_find_acq(mode, reqid, proto, xdaddr, xsaddr, 1, family);
1341
1342         if (x == NULL)
1343                 return -ENOENT;
1344
1345         min_spi = 0x100;
1346         max_spi = 0x0fffffff;
1347
1348         range = ext_hdrs[SADB_EXT_SPIRANGE-1];
1349         if (range) {
1350                 min_spi = range->sadb_spirange_min;
1351                 max_spi = range->sadb_spirange_max;
1352         }
1353
1354         err = xfrm_alloc_spi(x, min_spi, max_spi);
1355         resp_skb = err ? ERR_PTR(err) : pfkey_xfrm_state2msg(x);
1356
1357         if (IS_ERR(resp_skb)) {
1358                 xfrm_state_put(x);
1359                 return  PTR_ERR(resp_skb);
1360         }
1361
1362         out_hdr = (struct sadb_msg *) resp_skb->data;
1363         out_hdr->sadb_msg_version = hdr->sadb_msg_version;
1364         out_hdr->sadb_msg_type = SADB_GETSPI;
1365         out_hdr->sadb_msg_satype = pfkey_proto2satype(proto);
1366         out_hdr->sadb_msg_errno = 0;
1367         out_hdr->sadb_msg_reserved = 0;
1368         out_hdr->sadb_msg_seq = hdr->sadb_msg_seq;
1369         out_hdr->sadb_msg_pid = hdr->sadb_msg_pid;
1370
1371         xfrm_state_put(x);
1372
1373         pfkey_broadcast(resp_skb, GFP_KERNEL, BROADCAST_ONE, sk);
1374
1375         return 0;
1376 }
1377
1378 static int pfkey_acquire(struct sock *sk, struct sk_buff *skb, struct sadb_msg *hdr, void **ext_hdrs)
1379 {
1380         struct xfrm_state *x;
1381
1382         if (hdr->sadb_msg_len != sizeof(struct sadb_msg)/8)
1383                 return -EOPNOTSUPP;
1384
1385         if (hdr->sadb_msg_seq == 0 || hdr->sadb_msg_errno == 0)
1386                 return 0;
1387
1388         x = xfrm_find_acq_byseq(hdr->sadb_msg_seq);
1389         if (x == NULL)
1390                 return 0;
1391
1392         spin_lock_bh(&x->lock);
1393         if (x->km.state == XFRM_STATE_ACQ) {
1394                 x->km.state = XFRM_STATE_ERROR;
1395                 wake_up(&km_waitq);
1396         }
1397         spin_unlock_bh(&x->lock);
1398         xfrm_state_put(x);
1399         return 0;
1400 }
1401
1402 static inline int event2poltype(int event)
1403 {
1404         switch (event) {
1405         case XFRM_MSG_DELPOLICY:
1406                 return SADB_X_SPDDELETE;
1407         case XFRM_MSG_NEWPOLICY:
1408                 return SADB_X_SPDADD;
1409         case XFRM_MSG_UPDPOLICY:
1410                 return SADB_X_SPDUPDATE;
1411         case XFRM_MSG_POLEXPIRE:
1412         //      return SADB_X_SPDEXPIRE;
1413         default:
1414                 printk("pfkey: Unknown policy event %d\n", event);
1415                 break;
1416         }
1417
1418         return 0;
1419 }
1420
1421 static inline int event2keytype(int event)
1422 {
1423         switch (event) {
1424         case XFRM_MSG_DELSA:
1425                 return SADB_DELETE;
1426         case XFRM_MSG_NEWSA:
1427                 return SADB_ADD;
1428         case XFRM_MSG_UPDSA:
1429                 return SADB_UPDATE;
1430         case XFRM_MSG_EXPIRE:
1431                 return SADB_EXPIRE;
1432         default:
1433                 printk("pfkey: Unknown SA event %d\n", event);
1434                 break;
1435         }
1436
1437         return 0;
1438 }
1439
1440 /* ADD/UPD/DEL */
1441 static int key_notify_sa(struct xfrm_state *x, struct km_event *c)
1442 {
1443         struct sk_buff *skb;
1444         struct sadb_msg *hdr;
1445
1446         skb = pfkey_xfrm_state2msg(x);
1447
1448         if (IS_ERR(skb))
1449                 return PTR_ERR(skb);
1450
1451         hdr = (struct sadb_msg *) skb->data;
1452         hdr->sadb_msg_version = PF_KEY_V2;
1453         hdr->sadb_msg_type = event2keytype(c->event);
1454         hdr->sadb_msg_satype = pfkey_proto2satype(x->id.proto);
1455         hdr->sadb_msg_errno = 0;
1456         hdr->sadb_msg_reserved = 0;
1457         hdr->sadb_msg_seq = c->seq;
1458         hdr->sadb_msg_pid = c->pid;
1459
1460         pfkey_broadcast(skb, GFP_ATOMIC, BROADCAST_ALL, NULL);
1461
1462         return 0;
1463 }
1464
1465 static int pfkey_add(struct sock *sk, struct sk_buff *skb, struct sadb_msg *hdr, void **ext_hdrs)
1466 {
1467         struct xfrm_state *x;
1468         int err;
1469         struct km_event c;
1470
1471         x = pfkey_msg2xfrm_state(hdr, ext_hdrs);
1472         if (IS_ERR(x))
1473                 return PTR_ERR(x);
1474
1475         xfrm_state_hold(x);
1476         if (hdr->sadb_msg_type == SADB_ADD)
1477                 err = xfrm_state_add(x);
1478         else
1479                 err = xfrm_state_update(x);
1480
1481         xfrm_audit_state_add(x, err ? 0 : 1,
1482                              audit_get_loginuid(current),
1483                              audit_get_sessionid(current), 0);
1484
1485         if (err < 0) {
1486                 x->km.state = XFRM_STATE_DEAD;
1487                 __xfrm_state_put(x);
1488                 goto out;
1489         }
1490
1491         if (hdr->sadb_msg_type == SADB_ADD)
1492                 c.event = XFRM_MSG_NEWSA;
1493         else
1494                 c.event = XFRM_MSG_UPDSA;
1495         c.seq = hdr->sadb_msg_seq;
1496         c.pid = hdr->sadb_msg_pid;
1497         km_state_notify(x, &c);
1498 out:
1499         xfrm_state_put(x);
1500         return err;
1501 }
1502
1503 static int pfkey_delete(struct sock *sk, struct sk_buff *skb, struct sadb_msg *hdr, void **ext_hdrs)
1504 {
1505         struct xfrm_state *x;
1506         struct km_event c;
1507         int err;
1508
1509         if (!ext_hdrs[SADB_EXT_SA-1] ||
1510             !present_and_same_family(ext_hdrs[SADB_EXT_ADDRESS_SRC-1],
1511                                      ext_hdrs[SADB_EXT_ADDRESS_DST-1]))
1512                 return -EINVAL;
1513
1514         x = pfkey_xfrm_state_lookup(hdr, ext_hdrs);
1515         if (x == NULL)
1516                 return -ESRCH;
1517
1518         if ((err = security_xfrm_state_delete(x)))
1519                 goto out;
1520
1521         if (xfrm_state_kern(x)) {
1522                 err = -EPERM;
1523                 goto out;
1524         }
1525
1526         err = xfrm_state_delete(x);
1527
1528         if (err < 0)
1529                 goto out;
1530
1531         c.seq = hdr->sadb_msg_seq;
1532         c.pid = hdr->sadb_msg_pid;
1533         c.event = XFRM_MSG_DELSA;
1534         km_state_notify(x, &c);
1535 out:
1536         xfrm_audit_state_delete(x, err ? 0 : 1,
1537                                 audit_get_loginuid(current),
1538                                 audit_get_sessionid(current), 0);
1539         xfrm_state_put(x);
1540
1541         return err;
1542 }
1543
1544 static int pfkey_get(struct sock *sk, struct sk_buff *skb, struct sadb_msg *hdr, void **ext_hdrs)
1545 {
1546         __u8 proto;
1547         struct sk_buff *out_skb;
1548         struct sadb_msg *out_hdr;
1549         struct xfrm_state *x;
1550
1551         if (!ext_hdrs[SADB_EXT_SA-1] ||
1552             !present_and_same_family(ext_hdrs[SADB_EXT_ADDRESS_SRC-1],
1553                                      ext_hdrs[SADB_EXT_ADDRESS_DST-1]))
1554                 return -EINVAL;
1555
1556         x = pfkey_xfrm_state_lookup(hdr, ext_hdrs);
1557         if (x == NULL)
1558                 return -ESRCH;
1559
1560         out_skb = pfkey_xfrm_state2msg(x);
1561         proto = x->id.proto;
1562         xfrm_state_put(x);
1563         if (IS_ERR(out_skb))
1564                 return  PTR_ERR(out_skb);
1565
1566         out_hdr = (struct sadb_msg *) out_skb->data;
1567         out_hdr->sadb_msg_version = hdr->sadb_msg_version;
1568         out_hdr->sadb_msg_type = SADB_GET;
1569         out_hdr->sadb_msg_satype = pfkey_proto2satype(proto);
1570         out_hdr->sadb_msg_errno = 0;
1571         out_hdr->sadb_msg_reserved = 0;
1572         out_hdr->sadb_msg_seq = hdr->sadb_msg_seq;
1573         out_hdr->sadb_msg_pid = hdr->sadb_msg_pid;
1574         pfkey_broadcast(out_skb, GFP_ATOMIC, BROADCAST_ONE, sk);
1575
1576         return 0;
1577 }
1578
1579 static struct sk_buff *compose_sadb_supported(struct sadb_msg *orig,
1580                                               gfp_t allocation)
1581 {
1582         struct sk_buff *skb;
1583         struct sadb_msg *hdr;
1584         int len, auth_len, enc_len, i;
1585
1586         auth_len = xfrm_count_auth_supported();
1587         if (auth_len) {
1588                 auth_len *= sizeof(struct sadb_alg);
1589                 auth_len += sizeof(struct sadb_supported);
1590         }
1591
1592         enc_len = xfrm_count_enc_supported();
1593         if (enc_len) {
1594                 enc_len *= sizeof(struct sadb_alg);
1595                 enc_len += sizeof(struct sadb_supported);
1596         }
1597
1598         len = enc_len + auth_len + sizeof(struct sadb_msg);
1599
1600         skb = alloc_skb(len + 16, allocation);
1601         if (!skb)
1602                 goto out_put_algs;
1603
1604         hdr = (struct sadb_msg *) skb_put(skb, sizeof(*hdr));
1605         pfkey_hdr_dup(hdr, orig);
1606         hdr->sadb_msg_errno = 0;
1607         hdr->sadb_msg_len = len / sizeof(uint64_t);
1608
1609         if (auth_len) {
1610                 struct sadb_supported *sp;
1611                 struct sadb_alg *ap;
1612
1613                 sp = (struct sadb_supported *) skb_put(skb, auth_len);
1614                 ap = (struct sadb_alg *) (sp + 1);
1615
1616                 sp->sadb_supported_len = auth_len / sizeof(uint64_t);
1617                 sp->sadb_supported_exttype = SADB_EXT_SUPPORTED_AUTH;
1618
1619                 for (i = 0; ; i++) {
1620                         struct xfrm_algo_desc *aalg = xfrm_aalg_get_byidx(i);
1621                         if (!aalg)
1622                                 break;
1623                         if (aalg->available)
1624                                 *ap++ = aalg->desc;
1625                 }
1626         }
1627
1628         if (enc_len) {
1629                 struct sadb_supported *sp;
1630                 struct sadb_alg *ap;
1631
1632                 sp = (struct sadb_supported *) skb_put(skb, enc_len);
1633                 ap = (struct sadb_alg *) (sp + 1);
1634
1635                 sp->sadb_supported_len = enc_len / sizeof(uint64_t);
1636                 sp->sadb_supported_exttype = SADB_EXT_SUPPORTED_ENCRYPT;
1637
1638                 for (i = 0; ; i++) {
1639                         struct xfrm_algo_desc *ealg = xfrm_ealg_get_byidx(i);
1640                         if (!ealg)
1641                                 break;
1642                         if (ealg->available)
1643                                 *ap++ = ealg->desc;
1644                 }
1645         }
1646
1647 out_put_algs:
1648         return skb;
1649 }
1650
1651 static int pfkey_register(struct sock *sk, struct sk_buff *skb, struct sadb_msg *hdr, void **ext_hdrs)
1652 {
1653         struct pfkey_sock *pfk = pfkey_sk(sk);
1654         struct sk_buff *supp_skb;
1655
1656         if (hdr->sadb_msg_satype > SADB_SATYPE_MAX)
1657                 return -EINVAL;
1658
1659         if (hdr->sadb_msg_satype != SADB_SATYPE_UNSPEC) {
1660                 if (pfk->registered&(1<<hdr->sadb_msg_satype))
1661                         return -EEXIST;
1662                 pfk->registered |= (1<<hdr->sadb_msg_satype);
1663         }
1664
1665         xfrm_probe_algs();
1666
1667         supp_skb = compose_sadb_supported(hdr, GFP_KERNEL);
1668         if (!supp_skb) {
1669                 if (hdr->sadb_msg_satype != SADB_SATYPE_UNSPEC)
1670                         pfk->registered &= ~(1<<hdr->sadb_msg_satype);
1671
1672                 return -ENOBUFS;
1673         }
1674
1675         pfkey_broadcast(supp_skb, GFP_KERNEL, BROADCAST_REGISTERED, sk);
1676
1677         return 0;
1678 }
1679
1680 static int key_notify_sa_flush(struct km_event *c)
1681 {
1682         struct sk_buff *skb;
1683         struct sadb_msg *hdr;
1684
1685         skb = alloc_skb(sizeof(struct sadb_msg) + 16, GFP_ATOMIC);
1686         if (!skb)
1687                 return -ENOBUFS;
1688         hdr = (struct sadb_msg *) skb_put(skb, sizeof(struct sadb_msg));
1689         hdr->sadb_msg_satype = pfkey_proto2satype(c->data.proto);
1690         hdr->sadb_msg_type = SADB_FLUSH;
1691         hdr->sadb_msg_seq = c->seq;
1692         hdr->sadb_msg_pid = c->pid;
1693         hdr->sadb_msg_version = PF_KEY_V2;
1694         hdr->sadb_msg_errno = (uint8_t) 0;
1695         hdr->sadb_msg_len = (sizeof(struct sadb_msg) / sizeof(uint64_t));
1696
1697         pfkey_broadcast(skb, GFP_ATOMIC, BROADCAST_ALL, NULL);
1698
1699         return 0;
1700 }
1701
1702 static int pfkey_flush(struct sock *sk, struct sk_buff *skb, struct sadb_msg *hdr, void **ext_hdrs)
1703 {
1704         unsigned proto;
1705         struct km_event c;
1706         struct xfrm_audit audit_info;
1707         int err;
1708
1709         proto = pfkey_satype2proto(hdr->sadb_msg_satype);
1710         if (proto == 0)
1711                 return -EINVAL;
1712
1713         audit_info.loginuid = audit_get_loginuid(current);
1714         audit_info.sessionid = audit_get_sessionid(current);
1715         audit_info.secid = 0;
1716         err = xfrm_state_flush(proto, &audit_info);
1717         if (err)
1718                 return err;
1719         c.data.proto = proto;
1720         c.seq = hdr->sadb_msg_seq;
1721         c.pid = hdr->sadb_msg_pid;
1722         c.event = XFRM_MSG_FLUSHSA;
1723         km_state_notify(NULL, &c);
1724
1725         return 0;
1726 }
1727
1728 static int dump_sa(struct xfrm_state *x, int count, void *ptr)
1729 {
1730         struct pfkey_sock *pfk = ptr;
1731         struct sk_buff *out_skb;
1732         struct sadb_msg *out_hdr;
1733
1734         if (!pfkey_can_dump(&pfk->sk))
1735                 return -ENOBUFS;
1736
1737         out_skb = pfkey_xfrm_state2msg(x);
1738         if (IS_ERR(out_skb))
1739                 return PTR_ERR(out_skb);
1740
1741         out_hdr = (struct sadb_msg *) out_skb->data;
1742         out_hdr->sadb_msg_version = pfk->dump.msg_version;
1743         out_hdr->sadb_msg_type = SADB_DUMP;
1744         out_hdr->sadb_msg_satype = pfkey_proto2satype(x->id.proto);
1745         out_hdr->sadb_msg_errno = 0;
1746         out_hdr->sadb_msg_reserved = 0;
1747         out_hdr->sadb_msg_seq = count;
1748         out_hdr->sadb_msg_pid = pfk->dump.msg_pid;
1749         pfkey_broadcast(out_skb, GFP_ATOMIC, BROADCAST_ONE, &pfk->sk);
1750         return 0;
1751 }
1752
1753 static int pfkey_dump_sa(struct pfkey_sock *pfk)
1754 {
1755         return xfrm_state_walk(&pfk->dump.u.state, dump_sa, (void *) pfk);
1756 }
1757
1758 static void pfkey_dump_sa_done(struct pfkey_sock *pfk)
1759 {
1760         xfrm_state_walk_done(&pfk->dump.u.state);
1761 }
1762
1763 static int pfkey_dump(struct sock *sk, struct sk_buff *skb, struct sadb_msg *hdr, void **ext_hdrs)
1764 {
1765         u8 proto;
1766         struct pfkey_sock *pfk = pfkey_sk(sk);
1767
1768         if (pfk->dump.dump != NULL)
1769                 return -EBUSY;
1770
1771         proto = pfkey_satype2proto(hdr->sadb_msg_satype);
1772         if (proto == 0)
1773                 return -EINVAL;
1774
1775         pfk->dump.msg_version = hdr->sadb_msg_version;
1776         pfk->dump.msg_pid = hdr->sadb_msg_pid;
1777         pfk->dump.dump = pfkey_dump_sa;
1778         pfk->dump.done = pfkey_dump_sa_done;
1779         xfrm_state_walk_init(&pfk->dump.u.state, proto);
1780
1781         return pfkey_do_dump(pfk);
1782 }
1783
1784 static int pfkey_promisc(struct sock *sk, struct sk_buff *skb, struct sadb_msg *hdr, void **ext_hdrs)
1785 {
1786         struct pfkey_sock *pfk = pfkey_sk(sk);
1787         int satype = hdr->sadb_msg_satype;
1788
1789         if (hdr->sadb_msg_len == (sizeof(*hdr) / sizeof(uint64_t))) {
1790                 /* XXX we mangle packet... */
1791                 hdr->sadb_msg_errno = 0;
1792                 if (satype != 0 && satype != 1)
1793                         return -EINVAL;
1794                 pfk->promisc = satype;
1795         }
1796         pfkey_broadcast(skb_clone(skb, GFP_KERNEL), GFP_KERNEL, BROADCAST_ALL, NULL);
1797         return 0;
1798 }
1799
1800 static int check_reqid(struct xfrm_policy *xp, int dir, int count, void *ptr)
1801 {
1802         int i;
1803         u32 reqid = *(u32*)ptr;
1804
1805         for (i=0; i<xp->xfrm_nr; i++) {
1806                 if (xp->xfrm_vec[i].reqid == reqid)
1807                         return -EEXIST;
1808         }
1809         return 0;
1810 }
1811
1812 static u32 gen_reqid(void)
1813 {
1814         struct xfrm_policy_walk walk;
1815         u32 start;
1816         int rc;
1817         static u32 reqid = IPSEC_MANUAL_REQID_MAX;
1818
1819         start = reqid;
1820         do {
1821                 ++reqid;
1822                 if (reqid == 0)
1823                         reqid = IPSEC_MANUAL_REQID_MAX+1;
1824                 xfrm_policy_walk_init(&walk, XFRM_POLICY_TYPE_MAIN);
1825                 rc = xfrm_policy_walk(&walk, check_reqid, (void*)&reqid);
1826                 xfrm_policy_walk_done(&walk);
1827                 if (rc != -EEXIST)
1828                         return reqid;
1829         } while (reqid != start);
1830         return 0;
1831 }
1832
1833 static int
1834 parse_ipsecrequest(struct xfrm_policy *xp, struct sadb_x_ipsecrequest *rq)
1835 {
1836         struct xfrm_tmpl *t = xp->xfrm_vec + xp->xfrm_nr;
1837         int mode;
1838
1839         if (xp->xfrm_nr >= XFRM_MAX_DEPTH)
1840                 return -ELOOP;
1841
1842         if (rq->sadb_x_ipsecrequest_mode == 0)
1843                 return -EINVAL;
1844
1845         t->id.proto = rq->sadb_x_ipsecrequest_proto; /* XXX check proto */
1846         if ((mode = pfkey_mode_to_xfrm(rq->sadb_x_ipsecrequest_mode)) < 0)
1847                 return -EINVAL;
1848         t->mode = mode;
1849         if (rq->sadb_x_ipsecrequest_level == IPSEC_LEVEL_USE)
1850                 t->optional = 1;
1851         else if (rq->sadb_x_ipsecrequest_level == IPSEC_LEVEL_UNIQUE) {
1852                 t->reqid = rq->sadb_x_ipsecrequest_reqid;
1853                 if (t->reqid > IPSEC_MANUAL_REQID_MAX)
1854                         t->reqid = 0;
1855                 if (!t->reqid && !(t->reqid = gen_reqid()))
1856                         return -ENOBUFS;
1857         }
1858
1859         /* addresses present only in tunnel mode */
1860         if (t->mode == XFRM_MODE_TUNNEL) {
1861                 u8 *sa = (u8 *) (rq + 1);
1862                 int family, socklen;
1863
1864                 family = pfkey_sockaddr_extract((struct sockaddr *)sa,
1865                                                 &t->saddr);
1866                 if (!family)
1867                         return -EINVAL;
1868
1869                 socklen = pfkey_sockaddr_len(family);
1870                 if (pfkey_sockaddr_extract((struct sockaddr *)(sa + socklen),
1871                                            &t->id.daddr) != family)
1872                         return -EINVAL;
1873                 t->encap_family = family;
1874         } else
1875                 t->encap_family = xp->family;
1876
1877         /* No way to set this via kame pfkey */
1878         t->allalgs = 1;
1879         xp->xfrm_nr++;
1880         return 0;
1881 }
1882
1883 static int
1884 parse_ipsecrequests(struct xfrm_policy *xp, struct sadb_x_policy *pol)
1885 {
1886         int err;
1887         int len = pol->sadb_x_policy_len*8 - sizeof(struct sadb_x_policy);
1888         struct sadb_x_ipsecrequest *rq = (void*)(pol+1);
1889
1890         while (len >= sizeof(struct sadb_x_ipsecrequest)) {
1891                 if ((err = parse_ipsecrequest(xp, rq)) < 0)
1892                         return err;
1893                 len -= rq->sadb_x_ipsecrequest_len;
1894                 rq = (void*)((u8*)rq + rq->sadb_x_ipsecrequest_len);
1895         }
1896         return 0;
1897 }
1898
1899 static inline int pfkey_xfrm_policy2sec_ctx_size(struct xfrm_policy *xp)
1900 {
1901   struct xfrm_sec_ctx *xfrm_ctx = xp->security;
1902
1903         if (xfrm_ctx) {
1904                 int len = sizeof(struct sadb_x_sec_ctx);
1905                 len += xfrm_ctx->ctx_len;
1906                 return PFKEY_ALIGN8(len);
1907         }
1908         return 0;
1909 }
1910
1911 static int pfkey_xfrm_policy2msg_size(struct xfrm_policy *xp)
1912 {
1913         struct xfrm_tmpl *t;
1914         int sockaddr_size = pfkey_sockaddr_size(xp->family);
1915         int socklen = 0;
1916         int i;
1917
1918         for (i=0; i<xp->xfrm_nr; i++) {
1919                 t = xp->xfrm_vec + i;
1920                 socklen += pfkey_sockaddr_len(t->encap_family);
1921         }
1922
1923         return sizeof(struct sadb_msg) +
1924                 (sizeof(struct sadb_lifetime) * 3) +
1925                 (sizeof(struct sadb_address) * 2) +
1926                 (sockaddr_size * 2) +
1927                 sizeof(struct sadb_x_policy) +
1928                 (xp->xfrm_nr * sizeof(struct sadb_x_ipsecrequest)) +
1929                 (socklen * 2) +
1930                 pfkey_xfrm_policy2sec_ctx_size(xp);
1931 }
1932
1933 static struct sk_buff * pfkey_xfrm_policy2msg_prep(struct xfrm_policy *xp)
1934 {
1935         struct sk_buff *skb;
1936         int size;
1937
1938         size = pfkey_xfrm_policy2msg_size(xp);
1939
1940         skb =  alloc_skb(size + 16, GFP_ATOMIC);
1941         if (skb == NULL)
1942                 return ERR_PTR(-ENOBUFS);
1943
1944         return skb;
1945 }
1946
1947 static int pfkey_xfrm_policy2msg(struct sk_buff *skb, struct xfrm_policy *xp, int dir)
1948 {
1949         struct sadb_msg *hdr;
1950         struct sadb_address *addr;
1951         struct sadb_lifetime *lifetime;
1952         struct sadb_x_policy *pol;
1953         struct sadb_x_sec_ctx *sec_ctx;
1954         struct xfrm_sec_ctx *xfrm_ctx;
1955         int i;
1956         int size;
1957         int sockaddr_size = pfkey_sockaddr_size(xp->family);
1958         int socklen = pfkey_sockaddr_len(xp->family);
1959
1960         size = pfkey_xfrm_policy2msg_size(xp);
1961
1962         /* call should fill header later */
1963         hdr = (struct sadb_msg *) skb_put(skb, sizeof(struct sadb_msg));
1964         memset(hdr, 0, size);   /* XXX do we need this ? */
1965
1966         /* src address */
1967         addr = (struct sadb_address*) skb_put(skb,
1968                                               sizeof(struct sadb_address)+sockaddr_size);
1969         addr->sadb_address_len =
1970                 (sizeof(struct sadb_address)+sockaddr_size)/
1971                         sizeof(uint64_t);
1972         addr->sadb_address_exttype = SADB_EXT_ADDRESS_SRC;
1973         addr->sadb_address_proto = pfkey_proto_from_xfrm(xp->selector.proto);
1974         addr->sadb_address_prefixlen = xp->selector.prefixlen_s;
1975         addr->sadb_address_reserved = 0;
1976         if (!pfkey_sockaddr_fill(&xp->selector.saddr,
1977                                  xp->selector.sport,
1978                                  (struct sockaddr *) (addr + 1),
1979                                  xp->family))
1980                 BUG();
1981
1982         /* dst address */
1983         addr = (struct sadb_address*) skb_put(skb,
1984                                               sizeof(struct sadb_address)+sockaddr_size);
1985         addr->sadb_address_len =
1986                 (sizeof(struct sadb_address)+sockaddr_size)/
1987                         sizeof(uint64_t);
1988         addr->sadb_address_exttype = SADB_EXT_ADDRESS_DST;
1989         addr->sadb_address_proto = pfkey_proto_from_xfrm(xp->selector.proto);
1990         addr->sadb_address_prefixlen = xp->selector.prefixlen_d;
1991         addr->sadb_address_reserved = 0;
1992
1993         pfkey_sockaddr_fill(&xp->selector.daddr, xp->selector.dport,
1994                             (struct sockaddr *) (addr + 1),
1995                             xp->family);
1996
1997         /* hard time */
1998         lifetime = (struct sadb_lifetime *)  skb_put(skb,
1999                                                      sizeof(struct sadb_lifetime));
2000         lifetime->sadb_lifetime_len =
2001                 sizeof(struct sadb_lifetime)/sizeof(uint64_t);
2002         lifetime->sadb_lifetime_exttype = SADB_EXT_LIFETIME_HARD;
2003         lifetime->sadb_lifetime_allocations =  _X2KEY(xp->lft.hard_packet_limit);
2004         lifetime->sadb_lifetime_bytes = _X2KEY(xp->lft.hard_byte_limit);
2005         lifetime->sadb_lifetime_addtime = xp->lft.hard_add_expires_seconds;
2006         lifetime->sadb_lifetime_usetime = xp->lft.hard_use_expires_seconds;
2007         /* soft time */
2008         lifetime = (struct sadb_lifetime *)  skb_put(skb,
2009                                                      sizeof(struct sadb_lifetime));
2010         lifetime->sadb_lifetime_len =
2011                 sizeof(struct sadb_lifetime)/sizeof(uint64_t);
2012         lifetime->sadb_lifetime_exttype = SADB_EXT_LIFETIME_SOFT;
2013         lifetime->sadb_lifetime_allocations =  _X2KEY(xp->lft.soft_packet_limit);
2014         lifetime->sadb_lifetime_bytes = _X2KEY(xp->lft.soft_byte_limit);
2015         lifetime->sadb_lifetime_addtime = xp->lft.soft_add_expires_seconds;
2016         lifetime->sadb_lifetime_usetime = xp->lft.soft_use_expires_seconds;
2017         /* current time */
2018         lifetime = (struct sadb_lifetime *)  skb_put(skb,
2019                                                      sizeof(struct sadb_lifetime));
2020         lifetime->sadb_lifetime_len =
2021                 sizeof(struct sadb_lifetime)/sizeof(uint64_t);
2022         lifetime->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
2023         lifetime->sadb_lifetime_allocations = xp->curlft.packets;
2024         lifetime->sadb_lifetime_bytes = xp->curlft.bytes;
2025         lifetime->sadb_lifetime_addtime = xp->curlft.add_time;
2026         lifetime->sadb_lifetime_usetime = xp->curlft.use_time;
2027
2028         pol = (struct sadb_x_policy *)  skb_put(skb, sizeof(struct sadb_x_policy));
2029         pol->sadb_x_policy_len = sizeof(struct sadb_x_policy)/sizeof(uint64_t);
2030         pol->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
2031         pol->sadb_x_policy_type = IPSEC_POLICY_DISCARD;
2032         if (xp->action == XFRM_POLICY_ALLOW) {
2033                 if (xp->xfrm_nr)
2034                         pol->sadb_x_policy_type = IPSEC_POLICY_IPSEC;
2035                 else
2036                         pol->sadb_x_policy_type = IPSEC_POLICY_NONE;
2037         }
2038         pol->sadb_x_policy_dir = dir+1;
2039         pol->sadb_x_policy_id = xp->index;
2040         pol->sadb_x_policy_priority = xp->priority;
2041
2042         for (i=0; i<xp->xfrm_nr; i++) {
2043                 struct sadb_x_ipsecrequest *rq;
2044                 struct xfrm_tmpl *t = xp->xfrm_vec + i;
2045                 int req_size;
2046                 int mode;
2047
2048                 req_size = sizeof(struct sadb_x_ipsecrequest);
2049                 if (t->mode == XFRM_MODE_TUNNEL) {
2050                         socklen = pfkey_sockaddr_len(t->encap_family);
2051                         req_size += socklen * 2;
2052                 } else {
2053                         size -= 2*socklen;
2054                         socklen = 0;
2055                 }
2056                 rq = (void*)skb_put(skb, req_size);
2057                 pol->sadb_x_policy_len += req_size/8;
2058                 memset(rq, 0, sizeof(*rq));
2059                 rq->sadb_x_ipsecrequest_len = req_size;
2060                 rq->sadb_x_ipsecrequest_proto = t->id.proto;
2061                 if ((mode = pfkey_mode_from_xfrm(t->mode)) < 0)
2062                         return -EINVAL;
2063                 rq->sadb_x_ipsecrequest_mode = mode;
2064                 rq->sadb_x_ipsecrequest_level = IPSEC_LEVEL_REQUIRE;
2065                 if (t->reqid)
2066                         rq->sadb_x_ipsecrequest_level = IPSEC_LEVEL_UNIQUE;
2067                 if (t->optional)
2068                         rq->sadb_x_ipsecrequest_level = IPSEC_LEVEL_USE;
2069                 rq->sadb_x_ipsecrequest_reqid = t->reqid;
2070
2071                 if (t->mode == XFRM_MODE_TUNNEL) {
2072                         u8 *sa = (void *)(rq + 1);
2073                         pfkey_sockaddr_fill(&t->saddr, 0,
2074                                             (struct sockaddr *)sa,
2075                                             t->encap_family);
2076                         pfkey_sockaddr_fill(&t->id.daddr, 0,
2077                                             (struct sockaddr *) (sa + socklen),
2078                                             t->encap_family);
2079                 }
2080         }
2081
2082         /* security context */
2083         if ((xfrm_ctx = xp->security)) {
2084                 int ctx_size = pfkey_xfrm_policy2sec_ctx_size(xp);
2085
2086                 sec_ctx = (struct sadb_x_sec_ctx *) skb_put(skb, ctx_size);
2087                 sec_ctx->sadb_x_sec_len = ctx_size / sizeof(uint64_t);
2088                 sec_ctx->sadb_x_sec_exttype = SADB_X_EXT_SEC_CTX;
2089                 sec_ctx->sadb_x_ctx_doi = xfrm_ctx->ctx_doi;
2090                 sec_ctx->sadb_x_ctx_alg = xfrm_ctx->ctx_alg;
2091                 sec_ctx->sadb_x_ctx_len = xfrm_ctx->ctx_len;
2092                 memcpy(sec_ctx + 1, xfrm_ctx->ctx_str,
2093                        xfrm_ctx->ctx_len);
2094         }
2095
2096         hdr->sadb_msg_len = size / sizeof(uint64_t);
2097         hdr->sadb_msg_reserved = atomic_read(&xp->refcnt);
2098
2099         return 0;
2100 }
2101
2102 static int key_notify_policy(struct xfrm_policy *xp, int dir, struct km_event *c)
2103 {
2104         struct sk_buff *out_skb;
2105         struct sadb_msg *out_hdr;
2106         int err;
2107
2108         out_skb = pfkey_xfrm_policy2msg_prep(xp);
2109         if (IS_ERR(out_skb)) {
2110                 err = PTR_ERR(out_skb);
2111                 goto out;
2112         }
2113         err = pfkey_xfrm_policy2msg(out_skb, xp, dir);
2114         if (err < 0)
2115                 return err;
2116
2117         out_hdr = (struct sadb_msg *) out_skb->data;
2118         out_hdr->sadb_msg_version = PF_KEY_V2;
2119
2120         if (c->data.byid && c->event == XFRM_MSG_DELPOLICY)
2121                 out_hdr->sadb_msg_type = SADB_X_SPDDELETE2;
2122         else
2123                 out_hdr->sadb_msg_type = event2poltype(c->event);
2124         out_hdr->sadb_msg_errno = 0;
2125         out_hdr->sadb_msg_seq = c->seq;
2126         out_hdr->sadb_msg_pid = c->pid;
2127         pfkey_broadcast(out_skb, GFP_ATOMIC, BROADCAST_ALL, NULL);
2128 out:
2129         return 0;
2130
2131 }
2132
2133 static int pfkey_spdadd(struct sock *sk, struct sk_buff *skb, struct sadb_msg *hdr, void **ext_hdrs)
2134 {
2135         int err = 0;
2136         struct sadb_lifetime *lifetime;
2137         struct sadb_address *sa;
2138         struct sadb_x_policy *pol;
2139         struct xfrm_policy *xp;
2140         struct km_event c;
2141         struct sadb_x_sec_ctx *sec_ctx;
2142
2143         if (!present_and_same_family(ext_hdrs[SADB_EXT_ADDRESS_SRC-1],
2144                                      ext_hdrs[SADB_EXT_ADDRESS_DST-1]) ||
2145             !ext_hdrs[SADB_X_EXT_POLICY-1])
2146                 return -EINVAL;
2147
2148         pol = ext_hdrs[SADB_X_EXT_POLICY-1];
2149         if (pol->sadb_x_policy_type > IPSEC_POLICY_IPSEC)
2150                 return -EINVAL;
2151         if (!pol->sadb_x_policy_dir || pol->sadb_x_policy_dir >= IPSEC_DIR_MAX)
2152                 return -EINVAL;
2153
2154         xp = xfrm_policy_alloc(GFP_KERNEL);
2155         if (xp == NULL)
2156                 return -ENOBUFS;
2157
2158         xp->action = (pol->sadb_x_policy_type == IPSEC_POLICY_DISCARD ?
2159                       XFRM_POLICY_BLOCK : XFRM_POLICY_ALLOW);
2160         xp->priority = pol->sadb_x_policy_priority;
2161
2162         sa = ext_hdrs[SADB_EXT_ADDRESS_SRC-1],
2163         xp->family = pfkey_sadb_addr2xfrm_addr(sa, &xp->selector.saddr);
2164         if (!xp->family) {
2165                 err = -EINVAL;
2166                 goto out;
2167         }
2168         xp->selector.family = xp->family;
2169         xp->selector.prefixlen_s = sa->sadb_address_prefixlen;
2170         xp->selector.proto = pfkey_proto_to_xfrm(sa->sadb_address_proto);
2171         xp->selector.sport = ((struct sockaddr_in *)(sa+1))->sin_port;
2172         if (xp->selector.sport)
2173                 xp->selector.sport_mask = htons(0xffff);
2174
2175         sa = ext_hdrs[SADB_EXT_ADDRESS_DST-1],
2176         pfkey_sadb_addr2xfrm_addr(sa, &xp->selector.daddr);
2177         xp->selector.prefixlen_d = sa->sadb_address_prefixlen;
2178
2179         /* Amusing, we set this twice.  KAME apps appear to set same value
2180          * in both addresses.
2181          */
2182         xp->selector.proto = pfkey_proto_to_xfrm(sa->sadb_address_proto);
2183
2184         xp->selector.dport = ((struct sockaddr_in *)(sa+1))->sin_port;
2185         if (xp->selector.dport)
2186                 xp->selector.dport_mask = htons(0xffff);
2187
2188         sec_ctx = (struct sadb_x_sec_ctx *) ext_hdrs[SADB_X_EXT_SEC_CTX-1];
2189         if (sec_ctx != NULL) {
2190                 struct xfrm_user_sec_ctx *uctx = pfkey_sadb2xfrm_user_sec_ctx(sec_ctx);
2191
2192                 if (!uctx) {
2193                         err = -ENOBUFS;
2194                         goto out;
2195                 }
2196
2197                 err = security_xfrm_policy_alloc(&xp->security, uctx);
2198                 kfree(uctx);
2199
2200                 if (err)
2201                         goto out;
2202         }
2203
2204         xp->lft.soft_byte_limit = XFRM_INF;
2205         xp->lft.hard_byte_limit = XFRM_INF;
2206         xp->lft.soft_packet_limit = XFRM_INF;
2207         xp->lft.hard_packet_limit = XFRM_INF;
2208         if ((lifetime = ext_hdrs[SADB_EXT_LIFETIME_HARD-1]) != NULL) {
2209                 xp->lft.hard_packet_limit = _KEY2X(lifetime->sadb_lifetime_allocations);
2210                 xp->lft.hard_byte_limit = _KEY2X(lifetime->sadb_lifetime_bytes);
2211                 xp->lft.hard_add_expires_seconds = lifetime->sadb_lifetime_addtime;
2212                 xp->lft.hard_use_expires_seconds = lifetime->sadb_lifetime_usetime;
2213         }
2214         if ((lifetime = ext_hdrs[SADB_EXT_LIFETIME_SOFT-1]) != NULL) {
2215                 xp->lft.soft_packet_limit = _KEY2X(lifetime->sadb_lifetime_allocations);
2216                 xp->lft.soft_byte_limit = _KEY2X(lifetime->sadb_lifetime_bytes);
2217                 xp->lft.soft_add_expires_seconds = lifetime->sadb_lifetime_addtime;
2218                 xp->lft.soft_use_expires_seconds = lifetime->sadb_lifetime_usetime;
2219         }
2220         xp->xfrm_nr = 0;
2221         if (pol->sadb_x_policy_type == IPSEC_POLICY_IPSEC &&
2222             (err = parse_ipsecrequests(xp, pol)) < 0)
2223                 goto out;
2224
2225         err = xfrm_policy_insert(pol->sadb_x_policy_dir-1, xp,
2226                                  hdr->sadb_msg_type != SADB_X_SPDUPDATE);
2227
2228         xfrm_audit_policy_add(xp, err ? 0 : 1,
2229                               audit_get_loginuid(current),
2230                               audit_get_sessionid(current), 0);
2231
2232         if (err)
2233                 goto out;
2234
2235         if (hdr->sadb_msg_type == SADB_X_SPDUPDATE)
2236                 c.event = XFRM_MSG_UPDPOLICY;
2237         else
2238                 c.event = XFRM_MSG_NEWPOLICY;
2239
2240         c.seq = hdr->sadb_msg_seq;
2241         c.pid = hdr->sadb_msg_pid;
2242
2243         km_policy_notify(xp, pol->sadb_x_policy_dir-1, &c);
2244         xfrm_pol_put(xp);
2245         return 0;
2246
2247 out:
2248         xp->dead = 1;
2249         xfrm_policy_destroy(xp);
2250         return err;
2251 }
2252
2253 static int pfkey_spddelete(struct sock *sk, struct sk_buff *skb, struct sadb_msg *hdr, void **ext_hdrs)
2254 {
2255         int err;
2256         struct sadb_address *sa;
2257         struct sadb_x_policy *pol;
2258         struct xfrm_policy *xp;
2259         struct xfrm_selector sel;
2260         struct km_event c;
2261         struct sadb_x_sec_ctx *sec_ctx;
2262         struct xfrm_sec_ctx *pol_ctx = NULL;
2263
2264         if (!present_and_same_family(ext_hdrs[SADB_EXT_ADDRESS_SRC-1],
2265                                      ext_hdrs[SADB_EXT_ADDRESS_DST-1]) ||
2266             !ext_hdrs[SADB_X_EXT_POLICY-1])
2267                 return -EINVAL;
2268
2269         pol = ext_hdrs[SADB_X_EXT_POLICY-1];
2270         if (!pol->sadb_x_policy_dir || pol->sadb_x_policy_dir >= IPSEC_DIR_MAX)
2271                 return -EINVAL;
2272
2273         memset(&sel, 0, sizeof(sel));
2274
2275         sa = ext_hdrs[SADB_EXT_ADDRESS_SRC-1],
2276         sel.family = pfkey_sadb_addr2xfrm_addr(sa, &sel.saddr);
2277         sel.prefixlen_s = sa->sadb_address_prefixlen;
2278         sel.proto = pfkey_proto_to_xfrm(sa->sadb_address_proto);
2279         sel.sport = ((struct sockaddr_in *)(sa+1))->sin_port;
2280         if (sel.sport)
2281                 sel.sport_mask = htons(0xffff);
2282
2283         sa = ext_hdrs[SADB_EXT_ADDRESS_DST-1],
2284         pfkey_sadb_addr2xfrm_addr(sa, &sel.daddr);
2285         sel.prefixlen_d = sa->sadb_address_prefixlen;
2286         sel.proto = pfkey_proto_to_xfrm(sa->sadb_address_proto);
2287         sel.dport = ((struct sockaddr_in *)(sa+1))->sin_port;
2288         if (sel.dport)
2289                 sel.dport_mask = htons(0xffff);
2290
2291         sec_ctx = (struct sadb_x_sec_ctx *) ext_hdrs[SADB_X_EXT_SEC_CTX-1];
2292         if (sec_ctx != NULL) {
2293                 struct xfrm_user_sec_ctx *uctx = pfkey_sadb2xfrm_user_sec_ctx(sec_ctx);
2294
2295                 if (!uctx)
2296                         return -ENOMEM;
2297
2298                 err = security_xfrm_policy_alloc(&pol_ctx, uctx);
2299                 kfree(uctx);
2300                 if (err)
2301                         return err;
2302         }
2303
2304         xp = xfrm_policy_bysel_ctx(XFRM_POLICY_TYPE_MAIN,
2305                                    pol->sadb_x_policy_dir - 1, &sel, pol_ctx,
2306                                    1, &err);
2307         security_xfrm_policy_free(pol_ctx);
2308         if (xp == NULL)
2309                 return -ENOENT;
2310
2311         xfrm_audit_policy_delete(xp, err ? 0 : 1,
2312                                  audit_get_loginuid(current),
2313                                  audit_get_sessionid(current), 0);
2314
2315         if (err)
2316                 goto out;
2317
2318         c.seq = hdr->sadb_msg_seq;
2319         c.pid = hdr->sadb_msg_pid;
2320         c.event = XFRM_MSG_DELPOLICY;
2321         km_policy_notify(xp, pol->sadb_x_policy_dir-1, &c);
2322
2323 out:
2324         xfrm_pol_put(xp);
2325         return err;
2326 }
2327
2328 static int key_pol_get_resp(struct sock *sk, struct xfrm_policy *xp, struct sadb_msg *hdr, int dir)
2329 {
2330         int err;
2331         struct sk_buff *out_skb;
2332         struct sadb_msg *out_hdr;
2333         err = 0;
2334
2335         out_skb = pfkey_xfrm_policy2msg_prep(xp);
2336         if (IS_ERR(out_skb)) {
2337                 err =  PTR_ERR(out_skb);
2338                 goto out;
2339         }
2340         err = pfkey_xfrm_policy2msg(out_skb, xp, dir);
2341         if (err < 0)
2342                 goto out;
2343
2344         out_hdr = (struct sadb_msg *) out_skb->data;
2345         out_hdr->sadb_msg_version = hdr->sadb_msg_version;
2346         out_hdr->sadb_msg_type = hdr->sadb_msg_type;
2347         out_hdr->sadb_msg_satype = 0;
2348         out_hdr->sadb_msg_errno = 0;
2349         out_hdr->sadb_msg_seq = hdr->sadb_msg_seq;
2350         out_hdr->sadb_msg_pid = hdr->sadb_msg_pid;
2351         pfkey_broadcast(out_skb, GFP_ATOMIC, BROADCAST_ONE, sk);
2352         err = 0;
2353
2354 out:
2355         return err;
2356 }
2357
2358 #ifdef CONFIG_NET_KEY_MIGRATE
2359 static int pfkey_sockaddr_pair_size(sa_family_t family)
2360 {
2361         return PFKEY_ALIGN8(pfkey_sockaddr_len(family) * 2);
2362 }
2363
2364 static int parse_sockaddr_pair(struct sadb_x_ipsecrequest *rq,
2365                                xfrm_address_t *saddr, xfrm_address_t *daddr,
2366                                u16 *family)
2367 {
2368         u8 *sa = (u8 *) (rq + 1);
2369         int af, socklen;
2370
2371         if (rq->sadb_x_ipsecrequest_len <
2372             pfkey_sockaddr_pair_size(((struct sockaddr *)sa)->sa_family))
2373                 return -EINVAL;
2374
2375         af = pfkey_sockaddr_extract((struct sockaddr *) sa,
2376                                     saddr);
2377         if (!af)
2378                 return -EINVAL;
2379
2380         socklen = pfkey_sockaddr_len(af);
2381         if (pfkey_sockaddr_extract((struct sockaddr *) (sa + socklen),
2382                                    daddr) != af)
2383                 return -EINVAL;
2384
2385         *family = af;
2386         return 0;
2387 }
2388
2389 static int ipsecrequests_to_migrate(struct sadb_x_ipsecrequest *rq1, int len,
2390                                     struct xfrm_migrate *m)
2391 {
2392         int err;
2393         struct sadb_x_ipsecrequest *rq2;
2394         int mode;
2395
2396         if (len <= sizeof(struct sadb_x_ipsecrequest) ||
2397             len < rq1->sadb_x_ipsecrequest_len)
2398                 return -EINVAL;
2399
2400         /* old endoints */
2401         err = parse_sockaddr_pair(rq1, &m->old_saddr, &m->old_daddr,
2402                                   &m->old_family);
2403         if (err)
2404                 return err;
2405
2406         rq2 = (struct sadb_x_ipsecrequest *)((u8 *)rq1 + rq1->sadb_x_ipsecrequest_len);
2407         len -= rq1->sadb_x_ipsecrequest_len;
2408
2409         if (len <= sizeof(struct sadb_x_ipsecrequest) ||
2410             len < rq2->sadb_x_ipsecrequest_len)
2411                 return -EINVAL;
2412
2413         /* new endpoints */
2414         err = parse_sockaddr_pair(rq2, &m->new_saddr, &m->new_daddr,
2415                                   &m->new_family);
2416         if (err)
2417                 return err;
2418
2419         if (rq1->sadb_x_ipsecrequest_proto != rq2->sadb_x_ipsecrequest_proto ||
2420             rq1->sadb_x_ipsecrequest_mode != rq2->sadb_x_ipsecrequest_mode ||
2421             rq1->sadb_x_ipsecrequest_reqid != rq2->sadb_x_ipsecrequest_reqid)
2422                 return -EINVAL;
2423
2424         m->proto = rq1->sadb_x_ipsecrequest_proto;
2425         if ((mode = pfkey_mode_to_xfrm(rq1->sadb_x_ipsecrequest_mode)) < 0)
2426                 return -EINVAL;
2427         m->mode = mode;
2428         m->reqid = rq1->sadb_x_ipsecrequest_reqid;
2429
2430         return ((int)(rq1->sadb_x_ipsecrequest_len +
2431                       rq2->sadb_x_ipsecrequest_len));
2432 }
2433
2434 static int pfkey_migrate(struct sock *sk, struct sk_buff *skb,
2435                          struct sadb_msg *hdr, void **ext_hdrs)
2436 {
2437         int i, len, ret, err = -EINVAL;
2438         u8 dir;
2439         struct sadb_address *sa;
2440         struct sadb_x_policy *pol;
2441         struct sadb_x_ipsecrequest *rq;
2442         struct xfrm_selector sel;
2443         struct xfrm_migrate m[XFRM_MAX_DEPTH];
2444
2445         if (!present_and_same_family(ext_hdrs[SADB_EXT_ADDRESS_SRC - 1],
2446             ext_hdrs[SADB_EXT_ADDRESS_DST - 1]) ||
2447             !ext_hdrs[SADB_X_EXT_POLICY - 1]) {
2448                 err = -EINVAL;
2449                 goto out;
2450         }
2451
2452         pol = ext_hdrs[SADB_X_EXT_POLICY - 1];
2453         if (!pol) {
2454                 err = -EINVAL;
2455                 goto out;
2456         }
2457
2458         if (pol->sadb_x_policy_dir >= IPSEC_DIR_MAX) {
2459                 err = -EINVAL;
2460                 goto out;
2461         }
2462
2463         dir = pol->sadb_x_policy_dir - 1;
2464         memset(&sel, 0, sizeof(sel));
2465
2466         /* set source address info of selector */
2467         sa = ext_hdrs[SADB_EXT_ADDRESS_SRC - 1];
2468         sel.family = pfkey_sadb_addr2xfrm_addr(sa, &sel.saddr);
2469         sel.prefixlen_s = sa->sadb_address_prefixlen;
2470         sel.proto = pfkey_proto_to_xfrm(sa->sadb_address_proto);
2471         sel.sport = ((struct sockaddr_in *)(sa + 1))->sin_port;
2472         if (sel.sport)
2473                 sel.sport_mask = htons(0xffff);
2474
2475         /* set destination address info of selector */
2476         sa = ext_hdrs[SADB_EXT_ADDRESS_DST - 1],
2477         pfkey_sadb_addr2xfrm_addr(sa, &sel.daddr);
2478         sel.prefixlen_d = sa->sadb_address_prefixlen;
2479         sel.proto = pfkey_proto_to_xfrm(sa->sadb_address_proto);
2480         sel.dport = ((struct sockaddr_in *)(sa + 1))->sin_port;
2481         if (sel.dport)
2482                 sel.dport_mask = htons(0xffff);
2483
2484         rq = (struct sadb_x_ipsecrequest *)(pol + 1);
2485
2486         /* extract ipsecrequests */
2487         i = 0;
2488         len = pol->sadb_x_policy_len * 8 - sizeof(struct sadb_x_policy);
2489
2490         while (len > 0 && i < XFRM_MAX_DEPTH) {
2491                 ret = ipsecrequests_to_migrate(rq, len, &m[i]);
2492                 if (ret < 0) {
2493                         err = ret;
2494                         goto out;
2495                 } else {
2496                         rq = (struct sadb_x_ipsecrequest *)((u8 *)rq + ret);
2497                         len -= ret;
2498                         i++;
2499                 }
2500         }
2501
2502         if (!i || len > 0) {
2503                 err = -EINVAL;
2504                 goto out;
2505         }
2506
2507         return xfrm_migrate(&sel, dir, XFRM_POLICY_TYPE_MAIN, m, i);
2508
2509  out:
2510         return err;
2511 }
2512 #else
2513 static int pfkey_migrate(struct sock *sk, struct sk_buff *skb,
2514                          struct sadb_msg *hdr, void **ext_hdrs)
2515 {
2516         return -ENOPROTOOPT;
2517 }
2518 #endif
2519
2520
2521 static int pfkey_spdget(struct sock *sk, struct sk_buff *skb, struct sadb_msg *hdr, void **ext_hdrs)
2522 {
2523         unsigned int dir;
2524         int err = 0, delete;
2525         struct sadb_x_policy *pol;
2526         struct xfrm_policy *xp;
2527         struct km_event c;
2528
2529         if ((pol = ext_hdrs[SADB_X_EXT_POLICY-1]) == NULL)
2530                 return -EINVAL;
2531
2532         dir = xfrm_policy_id2dir(pol->sadb_x_policy_id);
2533         if (dir >= XFRM_POLICY_MAX)
2534                 return -EINVAL;
2535
2536         delete = (hdr->sadb_msg_type == SADB_X_SPDDELETE2);
2537         xp = xfrm_policy_byid(XFRM_POLICY_TYPE_MAIN, dir, pol->sadb_x_policy_id,
2538                               delete, &err);
2539         if (xp == NULL)
2540                 return -ENOENT;
2541
2542         if (delete) {
2543                 xfrm_audit_policy_delete(xp, err ? 0 : 1,
2544                                 audit_get_loginuid(current),
2545                                 audit_get_sessionid(current), 0);
2546
2547                 if (err)
2548                         goto out;
2549                 c.seq = hdr->sadb_msg_seq;
2550                 c.pid = hdr->sadb_msg_pid;
2551                 c.data.byid = 1;
2552                 c.event = XFRM_MSG_DELPOLICY;
2553                 km_policy_notify(xp, dir, &c);
2554         } else {
2555                 err = key_pol_get_resp(sk, xp, hdr, dir);
2556         }
2557
2558 out:
2559         xfrm_pol_put(xp);
2560         return err;
2561 }
2562
2563 static int dump_sp(struct xfrm_policy *xp, int dir, int count, void *ptr)
2564 {
2565         struct pfkey_sock *pfk = ptr;
2566         struct sk_buff *out_skb;
2567         struct sadb_msg *out_hdr;
2568         int err;
2569
2570         if (!pfkey_can_dump(&pfk->sk))
2571                 return -ENOBUFS;
2572
2573         out_skb = pfkey_xfrm_policy2msg_prep(xp);
2574         if (IS_ERR(out_skb))
2575                 return PTR_ERR(out_skb);
2576
2577         err = pfkey_xfrm_policy2msg(out_skb, xp, dir);
2578         if (err < 0)
2579                 return err;
2580
2581         out_hdr = (struct sadb_msg *) out_skb->data;
2582         out_hdr->sadb_msg_version = pfk->dump.msg_version;
2583         out_hdr->sadb_msg_type = SADB_X_SPDDUMP;
2584         out_hdr->sadb_msg_satype = SADB_SATYPE_UNSPEC;
2585         out_hdr->sadb_msg_errno = 0;
2586         out_hdr->sadb_msg_seq = count;
2587         out_hdr->sadb_msg_pid = pfk->dump.msg_pid;
2588         pfkey_broadcast(out_skb, GFP_ATOMIC, BROADCAST_ONE, &pfk->sk);
2589         return 0;
2590 }
2591
2592 static int pfkey_dump_sp(struct pfkey_sock *pfk)
2593 {
2594         return xfrm_policy_walk(&pfk->dump.u.policy, dump_sp, (void *) pfk);
2595 }
2596
2597 static void pfkey_dump_sp_done(struct pfkey_sock *pfk)
2598 {
2599         xfrm_policy_walk_done(&pfk->dump.u.policy);
2600 }
2601
2602 static int pfkey_spddump(struct sock *sk, struct sk_buff *skb, struct sadb_msg *hdr, void **ext_hdrs)
2603 {
2604         struct pfkey_sock *pfk = pfkey_sk(sk);
2605
2606         if (pfk->dump.dump != NULL)
2607                 return -EBUSY;
2608
2609         pfk->dump.msg_version = hdr->sadb_msg_version;
2610         pfk->dump.msg_pid = hdr->sadb_msg_pid;
2611         pfk->dump.dump = pfkey_dump_sp;
2612         pfk->dump.done = pfkey_dump_sp_done;
2613         xfrm_policy_walk_init(&pfk->dump.u.policy, XFRM_POLICY_TYPE_MAIN);
2614
2615         return pfkey_do_dump(pfk);
2616 }
2617
2618 static int key_notify_policy_flush(struct km_event *c)
2619 {
2620         struct sk_buff *skb_out;
2621         struct sadb_msg *hdr;
2622
2623         skb_out = alloc_skb(sizeof(struct sadb_msg) + 16, GFP_ATOMIC);
2624         if (!skb_out)
2625                 return -ENOBUFS;
2626         hdr = (struct sadb_msg *) skb_put(skb_out, sizeof(struct sadb_msg));
2627         hdr->sadb_msg_type = SADB_X_SPDFLUSH;
2628         hdr->sadb_msg_seq = c->seq;
2629         hdr->sadb_msg_pid = c->pid;
2630         hdr->sadb_msg_version = PF_KEY_V2;
2631         hdr->sadb_msg_errno = (uint8_t) 0;
2632         hdr->sadb_msg_len = (sizeof(struct sadb_msg) / sizeof(uint64_t));
2633         pfkey_broadcast(skb_out, GFP_ATOMIC, BROADCAST_ALL, NULL);
2634         return 0;
2635
2636 }
2637
2638 static int pfkey_spdflush(struct sock *sk, struct sk_buff *skb, struct sadb_msg *hdr, void **ext_hdrs)
2639 {
2640         struct km_event c;
2641         struct xfrm_audit audit_info;
2642         int err;
2643
2644         audit_info.loginuid = audit_get_loginuid(current);
2645         audit_info.sessionid = audit_get_sessionid(current);
2646         audit_info.secid = 0;
2647         err = xfrm_policy_flush(XFRM_POLICY_TYPE_MAIN, &audit_info);
2648         if (err)
2649                 return err;
2650         c.data.type = XFRM_POLICY_TYPE_MAIN;
2651         c.event = XFRM_MSG_FLUSHPOLICY;
2652         c.pid = hdr->sadb_msg_pid;
2653         c.seq = hdr->sadb_msg_seq;
2654         km_policy_notify(NULL, 0, &c);
2655
2656         return 0;
2657 }
2658
2659 typedef int (*pfkey_handler)(struct sock *sk, struct sk_buff *skb,
2660                              struct sadb_msg *hdr, void **ext_hdrs);
2661 static pfkey_handler pfkey_funcs[SADB_MAX + 1] = {
2662         [SADB_RESERVED]         = pfkey_reserved,
2663         [SADB_GETSPI]           = pfkey_getspi,
2664         [SADB_UPDATE]           = pfkey_add,
2665         [SADB_ADD]              = pfkey_add,
2666         [SADB_DELETE]           = pfkey_delete,
2667         [SADB_GET]              = pfkey_get,
2668         [SADB_ACQUIRE]          = pfkey_acquire,
2669         [SADB_REGISTER]         = pfkey_register,
2670         [SADB_EXPIRE]           = NULL,
2671         [SADB_FLUSH]            = pfkey_flush,
2672         [SADB_DUMP]             = pfkey_dump,
2673         [SADB_X_PROMISC]        = pfkey_promisc,
2674         [SADB_X_PCHANGE]        = NULL,
2675         [SADB_X_SPDUPDATE]      = pfkey_spdadd,
2676         [SADB_X_SPDADD]         = pfkey_spdadd,
2677         [SADB_X_SPDDELETE]      = pfkey_spddelete,
2678         [SADB_X_SPDGET]         = pfkey_spdget,
2679         [SADB_X_SPDACQUIRE]     = NULL,
2680         [SADB_X_SPDDUMP]        = pfkey_spddump,
2681         [SADB_X_SPDFLUSH]       = pfkey_spdflush,
2682         [SADB_X_SPDSETIDX]      = pfkey_spdadd,
2683         [SADB_X_SPDDELETE2]     = pfkey_spdget,
2684         [SADB_X_MIGRATE]        = pfkey_migrate,
2685 };
2686
2687 static int pfkey_process(struct sock *sk, struct sk_buff *skb, struct sadb_msg *hdr)
2688 {
2689         void *ext_hdrs[SADB_EXT_MAX];
2690         int err;
2691
2692         pfkey_broadcast(skb_clone(skb, GFP_KERNEL), GFP_KERNEL,
2693                         BROADCAST_PROMISC_ONLY, NULL);
2694
2695         memset(ext_hdrs, 0, sizeof(ext_hdrs));
2696         err = parse_exthdrs(skb, hdr, ext_hdrs);
2697         if (!err) {
2698                 err = -EOPNOTSUPP;
2699                 if (pfkey_funcs[hdr->sadb_msg_type])
2700                         err = pfkey_funcs[hdr->sadb_msg_type](sk, skb, hdr, ext_hdrs);
2701         }
2702         return err;
2703 }
2704
2705 static struct sadb_msg *pfkey_get_base_msg(struct sk_buff *skb, int *errp)
2706 {
2707         struct sadb_msg *hdr = NULL;
2708
2709         if (skb->len < sizeof(*hdr)) {
2710                 *errp = -EMSGSIZE;
2711         } else {
2712                 hdr = (struct sadb_msg *) skb->data;
2713                 if (hdr->sadb_msg_version != PF_KEY_V2 ||
2714                     hdr->sadb_msg_reserved != 0 ||
2715                     (hdr->sadb_msg_type <= SADB_RESERVED ||
2716                      hdr->sadb_msg_type > SADB_MAX)) {
2717                         hdr = NULL;
2718                         *errp = -EINVAL;
2719                 } else if (hdr->sadb_msg_len != (skb->len /
2720                                                  sizeof(uint64_t)) ||
2721                            hdr->sadb_msg_len < (sizeof(struct sadb_msg) /
2722                                                 sizeof(uint64_t))) {
2723                         hdr = NULL;
2724                         *errp = -EMSGSIZE;
2725                 } else {
2726                         *errp = 0;
2727                 }
2728         }
2729         return hdr;
2730 }
2731
2732 static inline int aalg_tmpl_set(struct xfrm_tmpl *t, struct xfrm_algo_desc *d)
2733 {
2734         unsigned int id = d->desc.sadb_alg_id;
2735
2736         if (id >= sizeof(t->aalgos) * 8)
2737                 return 0;
2738
2739         return (t->aalgos >> id) & 1;
2740 }
2741
2742 static inline int ealg_tmpl_set(struct xfrm_tmpl *t, struct xfrm_algo_desc *d)
2743 {
2744         unsigned int id = d->desc.sadb_alg_id;
2745
2746         if (id >= sizeof(t->ealgos) * 8)
2747                 return 0;
2748
2749         return (t->ealgos >> id) & 1;
2750 }
2751
2752 static int count_ah_combs(struct xfrm_tmpl *t)
2753 {
2754         int i, sz = 0;
2755
2756         for (i = 0; ; i++) {
2757                 struct xfrm_algo_desc *aalg = xfrm_aalg_get_byidx(i);
2758                 if (!aalg)
2759                         break;
2760                 if (aalg_tmpl_set(t, aalg) && aalg->available)
2761                         sz += sizeof(struct sadb_comb);
2762         }
2763         return sz + sizeof(struct sadb_prop);
2764 }
2765
2766 static int count_esp_combs(struct xfrm_tmpl *t)
2767 {
2768         int i, k, sz = 0;
2769
2770         for (i = 0; ; i++) {
2771                 struct xfrm_algo_desc *ealg = xfrm_ealg_get_byidx(i);
2772                 if (!ealg)
2773                         break;
2774
2775                 if (!(ealg_tmpl_set(t, ealg) && ealg->available))
2776                         continue;
2777
2778                 for (k = 1; ; k++) {
2779                         struct xfrm_algo_desc *aalg = xfrm_aalg_get_byidx(k);
2780                         if (!aalg)
2781                                 break;
2782
2783                         if (aalg_tmpl_set(t, aalg) && aalg->available)
2784                                 sz += sizeof(struct sadb_comb);
2785                 }
2786         }
2787         return sz + sizeof(struct sadb_prop);
2788 }
2789
2790 static void dump_ah_combs(struct sk_buff *skb, struct xfrm_tmpl *t)
2791 {
2792         struct sadb_prop *p;
2793         int i;
2794
2795         p = (struct sadb_prop*)skb_put(skb, sizeof(struct sadb_prop));
2796         p->sadb_prop_len = sizeof(struct sadb_prop)/8;
2797         p->sadb_prop_exttype = SADB_EXT_PROPOSAL;
2798         p->sadb_prop_replay = 32;
2799         memset(p->sadb_prop_reserved, 0, sizeof(p->sadb_prop_reserved));
2800
2801         for (i = 0; ; i++) {
2802                 struct xfrm_algo_desc *aalg = xfrm_aalg_get_byidx(i);
2803                 if (!aalg)
2804                         break;
2805
2806                 if (aalg_tmpl_set(t, aalg) && aalg->available) {
2807                         struct sadb_comb *c;
2808                         c = (struct sadb_comb*)skb_put(skb, sizeof(struct sadb_comb));
2809                         memset(c, 0, sizeof(*c));
2810                         p->sadb_prop_len += sizeof(struct sadb_comb)/8;
2811                         c->sadb_comb_auth = aalg->desc.sadb_alg_id;
2812                         c->sadb_comb_auth_minbits = aalg->desc.sadb_alg_minbits;
2813                         c->sadb_comb_auth_maxbits = aalg->desc.sadb_alg_maxbits;
2814                         c->sadb_comb_hard_addtime = 24*60*60;
2815                         c->sadb_comb_soft_addtime = 20*60*60;
2816                         c->sadb_comb_hard_usetime = 8*60*60;
2817                         c->sadb_comb_soft_usetime = 7*60*60;
2818                 }
2819         }
2820 }
2821
2822 static void dump_esp_combs(struct sk_buff *skb, struct xfrm_tmpl *t)
2823 {
2824         struct sadb_prop *p;
2825         int i, k;
2826
2827         p = (struct sadb_prop*)skb_put(skb, sizeof(struct sadb_prop));
2828         p->sadb_prop_len = sizeof(struct sadb_prop)/8;
2829         p->sadb_prop_exttype = SADB_EXT_PROPOSAL;
2830         p->sadb_prop_replay = 32;
2831         memset(p->sadb_prop_reserved, 0, sizeof(p->sadb_prop_reserved));
2832
2833         for (i=0; ; i++) {
2834                 struct xfrm_algo_desc *ealg = xfrm_ealg_get_byidx(i);
2835                 if (!ealg)
2836                         break;
2837
2838                 if (!(ealg_tmpl_set(t, ealg) && ealg->available))
2839                         continue;
2840
2841                 for (k = 1; ; k++) {
2842                         struct sadb_comb *c;
2843                         struct xfrm_algo_desc *aalg = xfrm_aalg_get_byidx(k);
2844                         if (!aalg)
2845                                 break;
2846                         if (!(aalg_tmpl_set(t, aalg) && aalg->available))
2847                                 continue;
2848                         c = (struct sadb_comb*)skb_put(skb, sizeof(struct sadb_comb));
2849                         memset(c, 0, sizeof(*c));
2850                         p->sadb_prop_len += sizeof(struct sadb_comb)/8;
2851                         c->sadb_comb_auth = aalg->desc.sadb_alg_id;
2852                         c->sadb_comb_auth_minbits = aalg->desc.sadb_alg_minbits;
2853                         c->sadb_comb_auth_maxbits = aalg->desc.sadb_alg_maxbits;
2854                         c->sadb_comb_encrypt = ealg->desc.sadb_alg_id;
2855                         c->sadb_comb_encrypt_minbits = ealg->desc.sadb_alg_minbits;
2856                         c->sadb_comb_encrypt_maxbits = ealg->desc.sadb_alg_maxbits;
2857                         c->sadb_comb_hard_addtime = 24*60*60;
2858                         c->sadb_comb_soft_addtime = 20*60*60;
2859                         c->sadb_comb_hard_usetime = 8*60*60;
2860                         c->sadb_comb_soft_usetime = 7*60*60;
2861                 }
2862         }
2863 }
2864
2865 static int key_notify_policy_expire(struct xfrm_policy *xp, struct km_event *c)
2866 {
2867         return 0;
2868 }
2869
2870 static int key_notify_sa_expire(struct xfrm_state *x, struct km_event *c)
2871 {
2872         struct sk_buff *out_skb;
2873         struct sadb_msg *out_hdr;
2874         int hard;
2875         int hsc;
2876
2877         hard = c->data.hard;
2878         if (hard)
2879                 hsc = 2;
2880         else
2881                 hsc = 1;
2882
2883         out_skb = pfkey_xfrm_state2msg_expire(x, hsc);
2884         if (IS_ERR(out_skb))
2885                 return PTR_ERR(out_skb);
2886
2887         out_hdr = (struct sadb_msg *) out_skb->data;
2888         out_hdr->sadb_msg_version = PF_KEY_V2;
2889         out_hdr->sadb_msg_type = SADB_EXPIRE;
2890         out_hdr->sadb_msg_satype = pfkey_proto2satype(x->id.proto);
2891         out_hdr->sadb_msg_errno = 0;
2892         out_hdr->sadb_msg_reserved = 0;
2893         out_hdr->sadb_msg_seq = 0;
2894         out_hdr->sadb_msg_pid = 0;
2895
2896         pfkey_broadcast(out_skb, GFP_ATOMIC, BROADCAST_REGISTERED, NULL);
2897         return 0;
2898 }
2899
2900 static int pfkey_send_notify(struct xfrm_state *x, struct km_event *c)
2901 {
2902         if (atomic_read(&pfkey_socks_nr) == 0)
2903                 return 0;
2904
2905         switch (c->event) {
2906         case XFRM_MSG_EXPIRE:
2907                 return key_notify_sa_expire(x, c);
2908         case XFRM_MSG_DELSA:
2909         case XFRM_MSG_NEWSA:
2910         case XFRM_MSG_UPDSA:
2911                 return key_notify_sa(x, c);
2912         case XFRM_MSG_FLUSHSA:
2913                 return key_notify_sa_flush(c);
2914         case XFRM_MSG_NEWAE: /* not yet supported */
2915                 break;
2916         default:
2917                 printk("pfkey: Unknown SA event %d\n", c->event);
2918                 break;
2919         }
2920
2921         return 0;
2922 }
2923
2924 static int pfkey_send_policy_notify(struct xfrm_policy *xp, int dir, struct km_event *c)
2925 {
2926         if (xp && xp->type != XFRM_POLICY_TYPE_MAIN)
2927                 return 0;
2928
2929         switch (c->event) {
2930         case XFRM_MSG_POLEXPIRE:
2931                 return key_notify_policy_expire(xp, c);
2932         case XFRM_MSG_DELPOLICY:
2933         case XFRM_MSG_NEWPOLICY:
2934         case XFRM_MSG_UPDPOLICY:
2935                 return key_notify_policy(xp, dir, c);
2936         case XFRM_MSG_FLUSHPOLICY:
2937                 if (c->data.type != XFRM_POLICY_TYPE_MAIN)
2938                         break;
2939                 return key_notify_policy_flush(c);
2940         default:
2941                 printk("pfkey: Unknown policy event %d\n", c->event);
2942                 break;
2943         }
2944
2945         return 0;
2946 }
2947
2948 static u32 get_acqseq(void)
2949 {
2950         u32 res;
2951         static u32 acqseq;
2952         static DEFINE_SPINLOCK(acqseq_lock);
2953
2954         spin_lock_bh(&acqseq_lock);
2955         res = (++acqseq ? : ++acqseq);
2956         spin_unlock_bh(&acqseq_lock);
2957         return res;
2958 }
2959
2960 static int pfkey_send_acquire(struct xfrm_state *x, struct xfrm_tmpl *t, struct xfrm_policy *xp, int dir)
2961 {
2962         struct sk_buff *skb;
2963         struct sadb_msg *hdr;
2964         struct sadb_address *addr;
2965         struct sadb_x_policy *pol;
2966         int sockaddr_size;
2967         int size;
2968         struct sadb_x_sec_ctx *sec_ctx;
2969         struct xfrm_sec_ctx *xfrm_ctx;
2970         int ctx_size = 0;
2971
2972         sockaddr_size = pfkey_sockaddr_size(x->props.family);
2973         if (!sockaddr_size)
2974                 return -EINVAL;
2975
2976         size = sizeof(struct sadb_msg) +
2977                 (sizeof(struct sadb_address) * 2) +
2978                 (sockaddr_size * 2) +
2979                 sizeof(struct sadb_x_policy);
2980
2981         if (x->id.proto == IPPROTO_AH)
2982                 size += count_ah_combs(t);
2983         else if (x->id.proto == IPPROTO_ESP)
2984                 size += count_esp_combs(t);
2985
2986         if ((xfrm_ctx = x->security)) {
2987                 ctx_size = PFKEY_ALIGN8(xfrm_ctx->ctx_len);
2988                 size +=  sizeof(struct sadb_x_sec_ctx) + ctx_size;
2989         }
2990
2991         skb =  alloc_skb(size + 16, GFP_ATOMIC);
2992         if (skb == NULL)
2993                 return -ENOMEM;
2994
2995         hdr = (struct sadb_msg *) skb_put(skb, sizeof(struct sadb_msg));
2996         hdr->sadb_msg_version = PF_KEY_V2;
2997         hdr->sadb_msg_type = SADB_ACQUIRE;
2998         hdr->sadb_msg_satype = pfkey_proto2satype(x->id.proto);
2999         hdr->sadb_msg_len = size / sizeof(uint64_t);
3000         hdr->sadb_msg_errno = 0;
3001         hdr->sadb_msg_reserved = 0;
3002         hdr->sadb_msg_seq = x->km.seq = get_acqseq();
3003         hdr->sadb_msg_pid = 0;
3004
3005         /* src address */
3006         addr = (struct sadb_address*) skb_put(skb,
3007                                               sizeof(struct sadb_address)+sockaddr_size);
3008         addr->sadb_address_len =
3009                 (sizeof(struct sadb_address)+sockaddr_size)/
3010                         sizeof(uint64_t);
3011         addr->sadb_address_exttype = SADB_EXT_ADDRESS_SRC;
3012         addr->sadb_address_proto = 0;
3013         addr->sadb_address_reserved = 0;
3014         addr->sadb_address_prefixlen =
3015                 pfkey_sockaddr_fill(&x->props.saddr, 0,
3016                                     (struct sockaddr *) (addr + 1),
3017                                     x->props.family);
3018         if (!addr->sadb_address_prefixlen)
3019                 BUG();
3020
3021         /* dst address */
3022         addr = (struct sadb_address*) skb_put(skb,
3023                                               sizeof(struct sadb_address)+sockaddr_size);
3024         addr->sadb_address_len =
3025                 (sizeof(struct sadb_address)+sockaddr_size)/
3026                         sizeof(uint64_t);
3027         addr->sadb_address_exttype = SADB_EXT_ADDRESS_DST;
3028         addr->sadb_address_proto = 0;
3029         addr->sadb_address_reserved = 0;
3030         addr->sadb_address_prefixlen =
3031                 pfkey_sockaddr_fill(&x->id.daddr, 0,
3032                                     (struct sockaddr *) (addr + 1),
3033                                     x->props.family);
3034         if (!addr->sadb_address_prefixlen)
3035                 BUG();
3036
3037         pol = (struct sadb_x_policy *)  skb_put(skb, sizeof(struct sadb_x_policy));
3038         pol->sadb_x_policy_len = sizeof(struct sadb_x_policy)/sizeof(uint64_t);
3039         pol->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
3040         pol->sadb_x_policy_type = IPSEC_POLICY_IPSEC;
3041         pol->sadb_x_policy_dir = dir+1;
3042         pol->sadb_x_policy_id = xp->index;
3043
3044         /* Set sadb_comb's. */
3045         if (x->id.proto == IPPROTO_AH)
3046                 dump_ah_combs(skb, t);
3047         else if (x->id.proto == IPPROTO_ESP)
3048                 dump_esp_combs(skb, t);
3049
3050         /* security context */
3051         if (xfrm_ctx) {
3052                 sec_ctx = (struct sadb_x_sec_ctx *) skb_put(skb,
3053                                 sizeof(struct sadb_x_sec_ctx) + ctx_size);
3054                 sec_ctx->sadb_x_sec_len =
3055                   (sizeof(struct sadb_x_sec_ctx) + ctx_size) / sizeof(uint64_t);
3056                 sec_ctx->sadb_x_sec_exttype = SADB_X_EXT_SEC_CTX;
3057                 sec_ctx->sadb_x_ctx_doi = xfrm_ctx->ctx_doi;
3058                 sec_ctx->sadb_x_ctx_alg = xfrm_ctx->ctx_alg;
3059                 sec_ctx->sadb_x_ctx_len = xfrm_ctx->ctx_len;
3060                 memcpy(sec_ctx + 1, xfrm_ctx->ctx_str,
3061                        xfrm_ctx->ctx_len);
3062         }
3063
3064         return pfkey_broadcast(skb, GFP_ATOMIC, BROADCAST_REGISTERED, NULL);
3065 }
3066
3067 static struct xfrm_policy *pfkey_compile_policy(struct sock *sk, int opt,
3068                                                 u8 *data, int len, int *dir)
3069 {
3070         struct xfrm_policy *xp;
3071         struct sadb_x_policy *pol = (struct sadb_x_policy*)data;
3072         struct sadb_x_sec_ctx *sec_ctx;
3073
3074         switch (sk->sk_family) {
3075         case AF_INET:
3076                 if (opt != IP_IPSEC_POLICY) {
3077                         *dir = -EOPNOTSUPP;
3078                         return NULL;
3079                 }
3080                 break;
3081 #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
3082         case AF_INET6:
3083                 if (opt != IPV6_IPSEC_POLICY) {
3084                         *dir = -EOPNOTSUPP;
3085                         return NULL;
3086                 }
3087                 break;
3088 #endif
3089         default:
3090                 *dir = -EINVAL;
3091                 return NULL;
3092         }
3093
3094         *dir = -EINVAL;
3095
3096         if (len < sizeof(struct sadb_x_policy) ||
3097             pol->sadb_x_policy_len*8 > len ||
3098             pol->sadb_x_policy_type > IPSEC_POLICY_BYPASS ||
3099             (!pol->sadb_x_policy_dir || pol->sadb_x_policy_dir > IPSEC_DIR_OUTBOUND))
3100                 return NULL;
3101
3102         xp = xfrm_policy_alloc(GFP_ATOMIC);
3103         if (xp == NULL) {
3104                 *dir = -ENOBUFS;
3105                 return NULL;
3106         }
3107
3108         xp->action = (pol->sadb_x_policy_type == IPSEC_POLICY_DISCARD ?
3109                       XFRM_POLICY_BLOCK : XFRM_POLICY_ALLOW);
3110
3111         xp->lft.soft_byte_limit = XFRM_INF;
3112         xp->lft.hard_byte_limit = XFRM_INF;
3113         xp->lft.soft_packet_limit = XFRM_INF;
3114         xp->lft.hard_packet_limit = XFRM_INF;
3115         xp->family = sk->sk_family;
3116
3117         xp->xfrm_nr = 0;
3118         if (pol->sadb_x_policy_type == IPSEC_POLICY_IPSEC &&
3119             (*dir = parse_ipsecrequests(xp, pol)) < 0)
3120                 goto out;
3121
3122         /* security context too */
3123         if (len >= (pol->sadb_x_policy_len*8 +
3124             sizeof(struct sadb_x_sec_ctx))) {
3125                 char *p = (char *)pol;
3126                 struct xfrm_user_sec_ctx *uctx;
3127
3128                 p += pol->sadb_x_policy_len*8;
3129                 sec_ctx = (struct sadb_x_sec_ctx *)p;
3130                 if (len < pol->sadb_x_policy_len*8 +
3131                     sec_ctx->sadb_x_sec_len) {
3132                         *dir = -EINVAL;
3133                         goto out;
3134                 }
3135                 if ((*dir = verify_sec_ctx_len(p)))
3136                         goto out;
3137                 uctx = pfkey_sadb2xfrm_user_sec_ctx(sec_ctx);
3138                 *dir = security_xfrm_policy_alloc(&xp->security, uctx);
3139                 kfree(uctx);
3140
3141                 if (*dir)
3142                         goto out;
3143         }
3144
3145         *dir = pol->sadb_x_policy_dir-1;
3146         return xp;
3147
3148 out:
3149         xfrm_policy_destroy(xp);
3150         return NULL;
3151 }
3152
3153 static int pfkey_send_new_mapping(struct xfrm_state *x, xfrm_address_t *ipaddr, __be16 sport)
3154 {
3155         struct sk_buff *skb;
3156         struct sadb_msg *hdr;
3157         struct sadb_sa *sa;
3158         struct sadb_address *addr;
3159         struct sadb_x_nat_t_port *n_port;
3160         int sockaddr_size;
3161         int size;
3162         __u8 satype = (x->id.proto == IPPROTO_ESP ? SADB_SATYPE_ESP : 0);
3163         struct xfrm_encap_tmpl *natt = NULL;
3164
3165         sockaddr_size = pfkey_sockaddr_size(x->props.family);
3166         if (!sockaddr_size)
3167                 return -EINVAL;
3168
3169         if (!satype)
3170                 return -EINVAL;
3171
3172         if (!x->encap)
3173                 return -EINVAL;
3174
3175         natt = x->encap;
3176
3177         /* Build an SADB_X_NAT_T_NEW_MAPPING message:
3178          *
3179          * HDR | SA | ADDRESS_SRC (old addr) | NAT_T_SPORT (old port) |
3180          * ADDRESS_DST (new addr) | NAT_T_DPORT (new port)
3181          */
3182
3183         size = sizeof(struct sadb_msg) +
3184                 sizeof(struct sadb_sa) +
3185                 (sizeof(struct sadb_address) * 2) +
3186                 (sockaddr_size * 2) +
3187                 (sizeof(struct sadb_x_nat_t_port) * 2);
3188
3189         skb =  alloc_skb(size + 16, GFP_ATOMIC);
3190         if (skb == NULL)
3191                 return -ENOMEM;
3192
3193         hdr = (struct sadb_msg *) skb_put(skb, sizeof(struct sadb_msg));
3194         hdr->sadb_msg_version = PF_KEY_V2;
3195         hdr->sadb_msg_type = SADB_X_NAT_T_NEW_MAPPING;
3196         hdr->sadb_msg_satype = satype;
3197         hdr->sadb_msg_len = size / sizeof(uint64_t);
3198         hdr->sadb_msg_errno = 0;
3199         hdr->sadb_msg_reserved = 0;
3200         hdr->sadb_msg_seq = x->km.seq = get_acqseq();
3201         hdr->sadb_msg_pid = 0;
3202
3203         /* SA */
3204         sa = (struct sadb_sa *) skb_put(skb, sizeof(struct sadb_sa));
3205         sa->sadb_sa_len = sizeof(struct sadb_sa)/sizeof(uint64_t);
3206         sa->sadb_sa_exttype = SADB_EXT_SA;
3207         sa->sadb_sa_spi = x->id.spi;
3208         sa->sadb_sa_replay = 0;
3209         sa->sadb_sa_state = 0;
3210         sa->sadb_sa_auth = 0;
3211         sa->sadb_sa_encrypt = 0;
3212         sa->sadb_sa_flags = 0;
3213
3214         /* ADDRESS_SRC (old addr) */
3215         addr = (struct sadb_address*)
3216                 skb_put(skb, sizeof(struct sadb_address)+sockaddr_size);
3217         addr->sadb_address_len =
3218                 (sizeof(struct sadb_address)+sockaddr_size)/
3219                         sizeof(uint64_t);
3220         addr->sadb_address_exttype = SADB_EXT_ADDRESS_SRC;
3221         addr->sadb_address_proto = 0;
3222         addr->sadb_address_reserved = 0;
3223         addr->sadb_address_prefixlen =
3224                 pfkey_sockaddr_fill(&x->props.saddr, 0,
3225                                     (struct sockaddr *) (addr + 1),
3226                                     x->props.family);
3227         if (!addr->sadb_address_prefixlen)
3228                 BUG();
3229
3230         /* NAT_T_SPORT (old port) */
3231         n_port = (struct sadb_x_nat_t_port*) skb_put(skb, sizeof (*n_port));
3232         n_port->sadb_x_nat_t_port_len = sizeof(*n_port)/sizeof(uint64_t);
3233         n_port->sadb_x_nat_t_port_exttype = SADB_X_EXT_NAT_T_SPORT;
3234         n_port->sadb_x_nat_t_port_port = natt->encap_sport;
3235         n_port->sadb_x_nat_t_port_reserved = 0;
3236
3237         /* ADDRESS_DST (new addr) */
3238         addr = (struct sadb_address*)
3239                 skb_put(skb, sizeof(struct sadb_address)+sockaddr_size);
3240         addr->sadb_address_len =
3241                 (sizeof(struct sadb_address)+sockaddr_size)/
3242                         sizeof(uint64_t);
3243         addr->sadb_address_exttype = SADB_EXT_ADDRESS_DST;
3244         addr->sadb_address_proto = 0;
3245         addr->sadb_address_reserved = 0;
3246         addr->sadb_address_prefixlen =
3247                 pfkey_sockaddr_fill(ipaddr, 0,
3248                                     (struct sockaddr *) (addr + 1),
3249                                     x->props.family);
3250         if (!addr->sadb_address_prefixlen)
3251                 BUG();
3252
3253         /* NAT_T_DPORT (new port) */
3254         n_port = (struct sadb_x_nat_t_port*) skb_put(skb, sizeof (*n_port));
3255         n_port->sadb_x_nat_t_port_len = sizeof(*n_port)/sizeof(uint64_t);
3256         n_port->sadb_x_nat_t_port_exttype = SADB_X_EXT_NAT_T_DPORT;
3257         n_port->sadb_x_nat_t_port_port = sport;
3258         n_port->sadb_x_nat_t_port_reserved = 0;
3259
3260         return pfkey_broadcast(skb, GFP_ATOMIC, BROADCAST_REGISTERED, NULL);
3261 }
3262
3263 #ifdef CONFIG_NET_KEY_MIGRATE
3264 static int set_sadb_address(struct sk_buff *skb, int sasize, int type,
3265                             struct xfrm_selector *sel)
3266 {
3267         struct sadb_address *addr;
3268         addr = (struct sadb_address *)skb_put(skb, sizeof(struct sadb_address) + sasize);
3269         addr->sadb_address_len = (sizeof(struct sadb_address) + sasize)/8;
3270         addr->sadb_address_exttype = type;
3271         addr->sadb_address_proto = sel->proto;
3272         addr->sadb_address_reserved = 0;
3273
3274         switch (type) {
3275         case SADB_EXT_ADDRESS_SRC:
3276                 addr->sadb_address_prefixlen = sel->prefixlen_s;
3277                 pfkey_sockaddr_fill(&sel->saddr, 0,
3278                                     (struct sockaddr *)(addr + 1),
3279                                     sel->family);
3280                 break;
3281         case SADB_EXT_ADDRESS_DST:
3282                 addr->sadb_address_prefixlen = sel->prefixlen_d;
3283                 pfkey_sockaddr_fill(&sel->daddr, 0,
3284                                     (struct sockaddr *)(addr + 1),
3285                                     sel->family);
3286                 break;
3287         default:
3288                 return -EINVAL;
3289         }
3290
3291         return 0;
3292 }
3293
3294 static int set_ipsecrequest(struct sk_buff *skb,
3295                             uint8_t proto, uint8_t mode, int level,
3296                             uint32_t reqid, uint8_t family,
3297                             xfrm_address_t *src, xfrm_address_t *dst)
3298 {
3299         struct sadb_x_ipsecrequest *rq;
3300         u8 *sa;
3301         int socklen = pfkey_sockaddr_len(family);
3302         int size_req;
3303
3304         size_req = sizeof(struct sadb_x_ipsecrequest) +
3305                    pfkey_sockaddr_pair_size(family);
3306
3307         rq = (struct sadb_x_ipsecrequest *)skb_put(skb, size_req);
3308         memset(rq, 0, size_req);
3309         rq->sadb_x_ipsecrequest_len = size_req;
3310         rq->sadb_x_ipsecrequest_proto = proto;
3311         rq->sadb_x_ipsecrequest_mode = mode;
3312         rq->sadb_x_ipsecrequest_level = level;
3313         rq->sadb_x_ipsecrequest_reqid = reqid;
3314
3315         sa = (u8 *) (rq + 1);
3316         if (!pfkey_sockaddr_fill(src, 0, (struct sockaddr *)sa, family) ||
3317             !pfkey_sockaddr_fill(dst, 0, (struct sockaddr *)(sa + socklen), family))
3318                 return -EINVAL;
3319
3320         return 0;
3321 }
3322 #endif
3323
3324 #ifdef CONFIG_NET_KEY_MIGRATE
3325 static int pfkey_send_migrate(struct xfrm_selector *sel, u8 dir, u8 type,
3326                               struct xfrm_migrate *m, int num_bundles)
3327 {
3328         int i;
3329         int sasize_sel;
3330         int size = 0;
3331         int size_pol = 0;
3332         struct sk_buff *skb;
3333         struct sadb_msg *hdr;
3334         struct sadb_x_policy *pol;
3335         struct xfrm_migrate *mp;
3336
3337         if (type != XFRM_POLICY_TYPE_MAIN)
3338                 return 0;
3339
3340         if (num_bundles <= 0 || num_bundles > XFRM_MAX_DEPTH)
3341                 return -EINVAL;
3342
3343         /* selector */
3344         sasize_sel = pfkey_sockaddr_size(sel->family);
3345         if (!sasize_sel)
3346                 return -EINVAL;
3347         size += (sizeof(struct sadb_address) + sasize_sel) * 2;
3348
3349         /* policy info */
3350         size_pol += sizeof(struct sadb_x_policy);
3351
3352         /* ipsecrequests */
3353         for (i = 0, mp = m; i < num_bundles; i++, mp++) {
3354                 /* old locator pair */
3355                 size_pol += sizeof(struct sadb_x_ipsecrequest) +
3356                             pfkey_sockaddr_pair_size(mp->old_family);
3357                 /* new locator pair */
3358                 size_pol += sizeof(struct sadb_x_ipsecrequest) +
3359                             pfkey_sockaddr_pair_size(mp->new_family);
3360         }
3361
3362         size += sizeof(struct sadb_msg) + size_pol;
3363
3364         /* alloc buffer */
3365         skb = alloc_skb(size, GFP_ATOMIC);
3366         if (skb == NULL)
3367                 return -ENOMEM;
3368
3369         hdr = (struct sadb_msg *)skb_put(skb, sizeof(struct sadb_msg));
3370         hdr->sadb_msg_version = PF_KEY_V2;
3371         hdr->sadb_msg_type = SADB_X_MIGRATE;
3372         hdr->sadb_msg_satype = pfkey_proto2satype(m->proto);
3373         hdr->sadb_msg_len = size / 8;
3374         hdr->sadb_msg_errno = 0;
3375         hdr->sadb_msg_reserved = 0;
3376         hdr->sadb_msg_seq = 0;
3377         hdr->sadb_msg_pid = 0;
3378
3379         /* selector src */
3380         set_sadb_address(skb, sasize_sel, SADB_EXT_ADDRESS_SRC, sel);
3381
3382         /* selector dst */
3383         set_sadb_address(skb, sasize_sel, SADB_EXT_ADDRESS_DST, sel);
3384
3385         /* policy information */
3386         pol = (struct sadb_x_policy *)skb_put(skb, sizeof(struct sadb_x_policy));
3387         pol->sadb_x_policy_len = size_pol / 8;
3388         pol->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
3389         pol->sadb_x_policy_type = IPSEC_POLICY_IPSEC;
3390         pol->sadb_x_policy_dir = dir + 1;
3391         pol->sadb_x_policy_id = 0;
3392         pol->sadb_x_policy_priority = 0;
3393
3394         for (i = 0, mp = m; i < num_bundles; i++, mp++) {
3395                 /* old ipsecrequest */
3396                 int mode = pfkey_mode_from_xfrm(mp->mode);
3397                 if (mode < 0)
3398                         goto err;
3399                 if (set_ipsecrequest(skb, mp->proto, mode,
3400                                      (mp->reqid ?  IPSEC_LEVEL_UNIQUE : IPSEC_LEVEL_REQUIRE),
3401                                      mp->reqid, mp->old_family,
3402                                      &mp->old_saddr, &mp->old_daddr) < 0)
3403                         goto err;
3404
3405                 /* new ipsecrequest */
3406                 if (set_ipsecrequest(skb, mp->proto, mode,
3407                                      (mp->reqid ? IPSEC_LEVEL_UNIQUE : IPSEC_LEVEL_REQUIRE),
3408                                      mp->reqid, mp->new_family,
3409                                      &mp->new_saddr, &mp->new_daddr) < 0)
3410                         goto err;
3411         }
3412
3413         /* broadcast migrate message to sockets */
3414         pfkey_broadcast(skb, GFP_ATOMIC, BROADCAST_ALL, NULL);
3415
3416         return 0;
3417
3418 err:
3419         kfree_skb(skb);
3420         return -EINVAL;
3421 }
3422 #else
3423 static int pfkey_send_migrate(struct xfrm_selector *sel, u8 dir, u8 type,
3424                               struct xfrm_migrate *m, int num_bundles)
3425 {
3426         return -ENOPROTOOPT;
3427 }
3428 #endif
3429
3430 static int pfkey_sendmsg(struct kiocb *kiocb,
3431                          struct socket *sock, struct msghdr *msg, size_t len)
3432 {
3433         struct sock *sk = sock->sk;
3434         struct sk_buff *skb = NULL;
3435         struct sadb_msg *hdr = NULL;
3436         int err;
3437
3438         err = -EOPNOTSUPP;
3439         if (msg->msg_flags & MSG_OOB)
3440                 goto out;
3441
3442         err = -EMSGSIZE;
3443         if ((unsigned)len > sk->sk_sndbuf - 32)
3444                 goto out;
3445
3446         err = -ENOBUFS;
3447         skb = alloc_skb(len, GFP_KERNEL);
3448         if (skb == NULL)
3449                 goto out;
3450
3451         err = -EFAULT;
3452         if (memcpy_fromiovec(skb_put(skb,len), msg->msg_iov, len))
3453                 goto out;
3454
3455         hdr = pfkey_get_base_msg(skb, &err);
3456         if (!hdr)
3457                 goto out;
3458
3459         mutex_lock(&xfrm_cfg_mutex);
3460         err = pfkey_process(sk, skb, hdr);
3461         mutex_unlock(&xfrm_cfg_mutex);
3462
3463 out:
3464         if (err && hdr && pfkey_error(hdr, err, sk) == 0)
3465                 err = 0;
3466         if (skb)
3467                 kfree_skb(skb);
3468
3469         return err ? : len;
3470 }
3471
3472 static int pfkey_recvmsg(struct kiocb *kiocb,
3473                          struct socket *sock, struct msghdr *msg, size_t len,
3474                          int flags)
3475 {
3476         struct sock *sk = sock->sk;
3477         struct pfkey_sock *pfk = pfkey_sk(sk);
3478         struct sk_buff *skb;
3479         int copied, err;
3480
3481         err = -EINVAL;
3482         if (flags & ~(MSG_PEEK|MSG_DONTWAIT|MSG_TRUNC|MSG_CMSG_COMPAT))
3483                 goto out;
3484
3485         msg->msg_namelen = 0;
3486         skb = skb_recv_datagram(sk, flags, flags & MSG_DONTWAIT, &err);
3487         if (skb == NULL)
3488                 goto out;
3489
3490         copied = skb->len;
3491         if (copied > len) {
3492                 msg->msg_flags |= MSG_TRUNC;
3493                 copied = len;
3494         }
3495
3496         skb_reset_transport_header(skb);
3497         err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
3498         if (err)
3499                 goto out_free;
3500
3501         sock_recv_timestamp(msg, sk, skb);
3502
3503         err = (flags & MSG_TRUNC) ? skb->len : copied;
3504
3505         if (pfk->dump.dump != NULL &&
3506             3 * atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf)
3507                 pfkey_do_dump(pfk);
3508
3509 out_free:
3510         skb_free_datagram(sk, skb);
3511 out:
3512         return err;
3513 }
3514
3515 static const struct proto_ops pfkey_ops = {
3516         .family         =       PF_KEY,
3517         .owner          =       THIS_MODULE,
3518         /* Operations that make no sense on pfkey sockets. */
3519         .bind           =       sock_no_bind,
3520         .connect        =       sock_no_connect,
3521         .socketpair     =       sock_no_socketpair,
3522         .accept         =       sock_no_accept,
3523         .getname        =       sock_no_getname,
3524         .ioctl          =       sock_no_ioctl,
3525         .listen         =       sock_no_listen,
3526         .shutdown       =       sock_no_shutdown,
3527         .setsockopt     =       sock_no_setsockopt,
3528         .getsockopt     =       sock_no_getsockopt,
3529         .mmap           =       sock_no_mmap,
3530         .sendpage       =       sock_no_sendpage,
3531
3532         /* Now the operations that really occur. */
3533         .release        =       pfkey_release,
3534         .poll           =       datagram_poll,
3535         .sendmsg        =       pfkey_sendmsg,
3536         .recvmsg        =       pfkey_recvmsg,
3537 };
3538
3539 static struct net_proto_family pfkey_family_ops = {
3540         .family =       PF_KEY,
3541         .create =       pfkey_create,
3542         .owner  =       THIS_MODULE,
3543 };
3544
3545 #ifdef CONFIG_PROC_FS
3546 static int pfkey_seq_show(struct seq_file *f, void *v)
3547 {
3548         struct sock *s;
3549
3550         s = (struct sock *)v;
3551         if (v == SEQ_START_TOKEN)
3552                 seq_printf(f ,"sk       RefCnt Rmem   Wmem   User   Inode\n");
3553         else
3554                 seq_printf(f ,"%p %-6d %-6u %-6u %-6u %-6lu\n",
3555                                s,
3556                                atomic_read(&s->sk_refcnt),
3557                                atomic_read(&s->sk_rmem_alloc),
3558                                atomic_read(&s->sk_wmem_alloc),
3559                                sock_i_uid(s),
3560                                sock_i_ino(s)
3561                                );
3562         return 0;
3563 }
3564
3565 static void *pfkey_seq_start(struct seq_file *f, loff_t *ppos)
3566 {
3567         struct sock *s;
3568         struct hlist_node *node;
3569         loff_t pos = *ppos;
3570
3571         read_lock(&pfkey_table_lock);
3572         if (pos == 0)
3573                 return SEQ_START_TOKEN;
3574
3575         sk_for_each(s, node, &pfkey_table)
3576                 if (pos-- == 1)
3577                         return s;
3578
3579         return NULL;
3580 }
3581
3582 static void *pfkey_seq_next(struct seq_file *f, void *v, loff_t *ppos)
3583 {
3584         ++*ppos;
3585         return (v == SEQ_START_TOKEN) ?
3586                 sk_head(&pfkey_table) :
3587                         sk_next((struct sock *)v);
3588 }
3589
3590 static void pfkey_seq_stop(struct seq_file *f, void *v)
3591 {
3592         read_unlock(&pfkey_table_lock);
3593 }
3594
3595 static struct seq_operations pfkey_seq_ops = {
3596         .start  = pfkey_seq_start,
3597         .next   = pfkey_seq_next,
3598         .stop   = pfkey_seq_stop,
3599         .show   = pfkey_seq_show,
3600 };
3601
3602 static int pfkey_seq_open(struct inode *inode, struct file *file)
3603 {
3604         return seq_open(file, &pfkey_seq_ops);
3605 }
3606
3607 static struct file_operations pfkey_proc_ops = {
3608         .open    = pfkey_seq_open,
3609         .read    = seq_read,
3610         .llseek  = seq_lseek,
3611         .release = seq_release,
3612 };
3613
3614 static int pfkey_init_proc(void)
3615 {
3616         struct proc_dir_entry *e;
3617
3618         e = proc_net_fops_create(&init_net, "pfkey", 0, &pfkey_proc_ops);
3619         if (e == NULL)
3620                 return -ENOMEM;
3621
3622         return 0;
3623 }
3624
3625 static void pfkey_exit_proc(void)
3626 {
3627         proc_net_remove(&init_net, "pfkey");
3628 }
3629 #else
3630 static inline int pfkey_init_proc(void)
3631 {
3632         return 0;
3633 }
3634
3635 static inline void pfkey_exit_proc(void)
3636 {
3637 }
3638 #endif
3639
3640 static struct xfrm_mgr pfkeyv2_mgr =
3641 {
3642         .id             = "pfkeyv2",
3643         .notify         = pfkey_send_notify,
3644         .acquire        = pfkey_send_acquire,
3645         .compile_policy = pfkey_compile_policy,
3646         .new_mapping    = pfkey_send_new_mapping,
3647         .notify_policy  = pfkey_send_policy_notify,
3648         .migrate        = pfkey_send_migrate,
3649 };
3650
3651 static void __exit ipsec_pfkey_exit(void)
3652 {
3653         xfrm_unregister_km(&pfkeyv2_mgr);
3654         pfkey_exit_proc();
3655         sock_unregister(PF_KEY);
3656         proto_unregister(&key_proto);
3657 }
3658
3659 static int __init ipsec_pfkey_init(void)
3660 {
3661         int err = proto_register(&key_proto, 0);
3662
3663         if (err != 0)
3664                 goto out;
3665
3666         err = sock_register(&pfkey_family_ops);
3667         if (err != 0)
3668                 goto out_unregister_key_proto;
3669         err = pfkey_init_proc();
3670         if (err != 0)
3671                 goto out_sock_unregister;
3672         err = xfrm_register_km(&pfkeyv2_mgr);
3673         if (err != 0)
3674                 goto out_remove_proc_entry;
3675 out:
3676         return err;
3677 out_remove_proc_entry:
3678         pfkey_exit_proc();
3679 out_sock_unregister:
3680         sock_unregister(PF_KEY);
3681 out_unregister_key_proto:
3682         proto_unregister(&key_proto);
3683         goto out;
3684 }
3685
3686 module_init(ipsec_pfkey_init);
3687 module_exit(ipsec_pfkey_exit);
3688 MODULE_LICENSE("GPL");
3689 MODULE_ALIAS_NETPROTO(PF_KEY);