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