652dd09ccd3a653cb3340960dc90d872ad38bdd4
[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         err = xfrm_init_state(x);
1100         if (err)
1101                 goto out;
1102
1103         x->km.seq = hdr->sadb_msg_seq;
1104         return x;
1105
1106 out:
1107         x->km.state = XFRM_STATE_DEAD;
1108         xfrm_state_put(x);
1109         return ERR_PTR(err);
1110 }
1111
1112 static int pfkey_reserved(struct sock *sk, struct sk_buff *skb, struct sadb_msg *hdr, void **ext_hdrs)
1113 {
1114         return -EOPNOTSUPP;
1115 }
1116
1117 static int pfkey_getspi(struct sock *sk, struct sk_buff *skb, struct sadb_msg *hdr, void **ext_hdrs)
1118 {
1119         struct sk_buff *resp_skb;
1120         struct sadb_x_sa2 *sa2;
1121         struct sadb_address *saddr, *daddr;
1122         struct sadb_msg *out_hdr;
1123         struct xfrm_state *x = NULL;
1124         u8 mode;
1125         u32 reqid;
1126         u8 proto;
1127         unsigned short family;
1128         xfrm_address_t *xsaddr = NULL, *xdaddr = NULL;
1129
1130         if (!present_and_same_family(ext_hdrs[SADB_EXT_ADDRESS_SRC-1],
1131                                      ext_hdrs[SADB_EXT_ADDRESS_DST-1]))
1132                 return -EINVAL;
1133
1134         proto = pfkey_satype2proto(hdr->sadb_msg_satype);
1135         if (proto == 0)
1136                 return -EINVAL;
1137
1138         if ((sa2 = ext_hdrs[SADB_X_EXT_SA2-1]) != NULL) {
1139                 mode = sa2->sadb_x_sa2_mode - 1;
1140                 reqid = sa2->sadb_x_sa2_reqid;
1141         } else {
1142                 mode = 0;
1143                 reqid = 0;
1144         }
1145
1146         saddr = ext_hdrs[SADB_EXT_ADDRESS_SRC-1];
1147         daddr = ext_hdrs[SADB_EXT_ADDRESS_DST-1];
1148
1149         family = ((struct sockaddr *)(saddr + 1))->sa_family;
1150         switch (family) {
1151         case AF_INET:
1152                 xdaddr = (xfrm_address_t *)&((struct sockaddr_in *)(daddr + 1))->sin_addr.s_addr;
1153                 xsaddr = (xfrm_address_t *)&((struct sockaddr_in *)(saddr + 1))->sin_addr.s_addr;
1154                 break;
1155 #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
1156         case AF_INET6:
1157                 xdaddr = (xfrm_address_t *)&((struct sockaddr_in6 *)(daddr + 1))->sin6_addr;
1158                 xsaddr = (xfrm_address_t *)&((struct sockaddr_in6 *)(saddr + 1))->sin6_addr;
1159                 break;
1160 #endif
1161         }
1162
1163         if (hdr->sadb_msg_seq) {
1164                 x = xfrm_find_acq_byseq(hdr->sadb_msg_seq);
1165                 if (x && xfrm_addr_cmp(&x->id.daddr, xdaddr, family)) {
1166                         xfrm_state_put(x);
1167                         x = NULL;
1168                 }
1169         }
1170
1171         if (!x)
1172                 x = xfrm_find_acq(mode, reqid, proto, xdaddr, xsaddr, 1, family);
1173
1174         if (x == NULL)
1175                 return -ENOENT;
1176
1177         resp_skb = ERR_PTR(-ENOENT);
1178
1179         spin_lock_bh(&x->lock);
1180         if (x->km.state != XFRM_STATE_DEAD) {
1181                 struct sadb_spirange *range = ext_hdrs[SADB_EXT_SPIRANGE-1];
1182                 u32 min_spi, max_spi;
1183
1184                 if (range != NULL) {
1185                         min_spi = range->sadb_spirange_min;
1186                         max_spi = range->sadb_spirange_max;
1187                 } else {
1188                         min_spi = 0x100;
1189                         max_spi = 0x0fffffff;
1190                 }
1191                 xfrm_alloc_spi(x, htonl(min_spi), htonl(max_spi));
1192                 if (x->id.spi)
1193                         resp_skb = pfkey_xfrm_state2msg(x, 0, 3);
1194         }
1195         spin_unlock_bh(&x->lock);
1196
1197         if (IS_ERR(resp_skb)) {
1198                 xfrm_state_put(x);
1199                 return  PTR_ERR(resp_skb);
1200         }
1201
1202         out_hdr = (struct sadb_msg *) resp_skb->data;
1203         out_hdr->sadb_msg_version = hdr->sadb_msg_version;
1204         out_hdr->sadb_msg_type = SADB_GETSPI;
1205         out_hdr->sadb_msg_satype = pfkey_proto2satype(proto);
1206         out_hdr->sadb_msg_errno = 0;
1207         out_hdr->sadb_msg_reserved = 0;
1208         out_hdr->sadb_msg_seq = hdr->sadb_msg_seq;
1209         out_hdr->sadb_msg_pid = hdr->sadb_msg_pid;
1210
1211         xfrm_state_put(x);
1212
1213         pfkey_broadcast(resp_skb, GFP_KERNEL, BROADCAST_ONE, sk);
1214
1215         return 0;
1216 }
1217
1218 static int pfkey_acquire(struct sock *sk, struct sk_buff *skb, struct sadb_msg *hdr, void **ext_hdrs)
1219 {
1220         struct xfrm_state *x;
1221
1222         if (hdr->sadb_msg_len != sizeof(struct sadb_msg)/8)
1223                 return -EOPNOTSUPP;
1224
1225         if (hdr->sadb_msg_seq == 0 || hdr->sadb_msg_errno == 0)
1226                 return 0;
1227
1228         x = xfrm_find_acq_byseq(hdr->sadb_msg_seq);
1229         if (x == NULL)
1230                 return 0;
1231
1232         spin_lock_bh(&x->lock);
1233         if (x->km.state == XFRM_STATE_ACQ) {
1234                 x->km.state = XFRM_STATE_ERROR;
1235                 wake_up(&km_waitq);
1236         }
1237         spin_unlock_bh(&x->lock);
1238         xfrm_state_put(x);
1239         return 0;
1240 }
1241
1242 static inline int event2poltype(int event)
1243 {
1244         switch (event) {
1245         case XFRM_MSG_DELPOLICY:
1246                 return SADB_X_SPDDELETE;
1247         case XFRM_MSG_NEWPOLICY:
1248                 return SADB_X_SPDADD;
1249         case XFRM_MSG_UPDPOLICY:
1250                 return SADB_X_SPDUPDATE;
1251         case XFRM_MSG_POLEXPIRE:
1252         //      return SADB_X_SPDEXPIRE;
1253         default:
1254                 printk("pfkey: Unknown policy event %d\n", event);
1255                 break;
1256         }
1257
1258         return 0;
1259 }
1260
1261 static inline int event2keytype(int event)
1262 {
1263         switch (event) {
1264         case XFRM_MSG_DELSA:
1265                 return SADB_DELETE;
1266         case XFRM_MSG_NEWSA:
1267                 return SADB_ADD;
1268         case XFRM_MSG_UPDSA:
1269                 return SADB_UPDATE;
1270         case XFRM_MSG_EXPIRE:
1271                 return SADB_EXPIRE;
1272         default:
1273                 printk("pfkey: Unknown SA event %d\n", event);
1274                 break;
1275         }
1276
1277         return 0;
1278 }
1279
1280 /* ADD/UPD/DEL */
1281 static int key_notify_sa(struct xfrm_state *x, struct km_event *c)
1282 {
1283         struct sk_buff *skb;
1284         struct sadb_msg *hdr;
1285         int hsc = 3;
1286
1287         if (c->event == XFRM_MSG_DELSA)
1288                 hsc = 0;
1289
1290         skb = pfkey_xfrm_state2msg(x, 0, hsc);
1291
1292         if (IS_ERR(skb))
1293                 return PTR_ERR(skb);
1294
1295         hdr = (struct sadb_msg *) skb->data;
1296         hdr->sadb_msg_version = PF_KEY_V2;
1297         hdr->sadb_msg_type = event2keytype(c->event);
1298         hdr->sadb_msg_satype = pfkey_proto2satype(x->id.proto);
1299         hdr->sadb_msg_errno = 0;
1300         hdr->sadb_msg_reserved = 0;
1301         hdr->sadb_msg_seq = c->seq;
1302         hdr->sadb_msg_pid = c->pid;
1303
1304         pfkey_broadcast(skb, GFP_ATOMIC, BROADCAST_ALL, NULL);
1305
1306         return 0;
1307 }
1308
1309 static int pfkey_add(struct sock *sk, struct sk_buff *skb, struct sadb_msg *hdr, void **ext_hdrs)
1310 {
1311         struct xfrm_state *x;
1312         int err;
1313         struct km_event c;
1314
1315         xfrm_probe_algs();
1316         
1317         x = pfkey_msg2xfrm_state(hdr, ext_hdrs);
1318         if (IS_ERR(x))
1319                 return PTR_ERR(x);
1320
1321         xfrm_state_hold(x);
1322         if (hdr->sadb_msg_type == SADB_ADD)
1323                 err = xfrm_state_add(x);
1324         else
1325                 err = xfrm_state_update(x);
1326
1327         if (err < 0) {
1328                 x->km.state = XFRM_STATE_DEAD;
1329                 xfrm_state_put(x);
1330                 goto out;
1331         }
1332
1333         if (hdr->sadb_msg_type == SADB_ADD)
1334                 c.event = XFRM_MSG_NEWSA;
1335         else
1336                 c.event = XFRM_MSG_UPDSA;
1337         c.seq = hdr->sadb_msg_seq;
1338         c.pid = hdr->sadb_msg_pid;
1339         km_state_notify(x, &c);
1340 out:
1341         xfrm_state_put(x);
1342         return err;
1343 }
1344
1345 static int pfkey_delete(struct sock *sk, struct sk_buff *skb, struct sadb_msg *hdr, void **ext_hdrs)
1346 {
1347         struct xfrm_state *x;
1348         struct km_event c;
1349         int err;
1350
1351         if (!ext_hdrs[SADB_EXT_SA-1] ||
1352             !present_and_same_family(ext_hdrs[SADB_EXT_ADDRESS_SRC-1],
1353                                      ext_hdrs[SADB_EXT_ADDRESS_DST-1]))
1354                 return -EINVAL;
1355
1356         x = pfkey_xfrm_state_lookup(hdr, ext_hdrs);
1357         if (x == NULL)
1358                 return -ESRCH;
1359
1360         if (xfrm_state_kern(x)) {
1361                 xfrm_state_put(x);
1362                 return -EPERM;
1363         }
1364         
1365         err = xfrm_state_delete(x);
1366         if (err < 0) {
1367                 xfrm_state_put(x);
1368                 return err;
1369         }
1370
1371         c.seq = hdr->sadb_msg_seq;
1372         c.pid = hdr->sadb_msg_pid;
1373         c.event = XFRM_MSG_DELSA;
1374         km_state_notify(x, &c);
1375         xfrm_state_put(x);
1376
1377         return err;
1378 }
1379
1380 static int pfkey_get(struct sock *sk, struct sk_buff *skb, struct sadb_msg *hdr, void **ext_hdrs)
1381 {
1382         __u8 proto;
1383         struct sk_buff *out_skb;
1384         struct sadb_msg *out_hdr;
1385         struct xfrm_state *x;
1386
1387         if (!ext_hdrs[SADB_EXT_SA-1] ||
1388             !present_and_same_family(ext_hdrs[SADB_EXT_ADDRESS_SRC-1],
1389                                      ext_hdrs[SADB_EXT_ADDRESS_DST-1]))
1390                 return -EINVAL;
1391
1392         x = pfkey_xfrm_state_lookup(hdr, ext_hdrs);
1393         if (x == NULL)
1394                 return -ESRCH;
1395
1396         out_skb = pfkey_xfrm_state2msg(x, 1, 3);
1397         proto = x->id.proto;
1398         xfrm_state_put(x);
1399         if (IS_ERR(out_skb))
1400                 return  PTR_ERR(out_skb);
1401
1402         out_hdr = (struct sadb_msg *) out_skb->data;
1403         out_hdr->sadb_msg_version = hdr->sadb_msg_version;
1404         out_hdr->sadb_msg_type = SADB_DUMP;
1405         out_hdr->sadb_msg_satype = pfkey_proto2satype(proto);
1406         out_hdr->sadb_msg_errno = 0;
1407         out_hdr->sadb_msg_reserved = 0;
1408         out_hdr->sadb_msg_seq = hdr->sadb_msg_seq;
1409         out_hdr->sadb_msg_pid = hdr->sadb_msg_pid;
1410         pfkey_broadcast(out_skb, GFP_ATOMIC, BROADCAST_ONE, sk);
1411
1412         return 0;
1413 }
1414
1415 static struct sk_buff *compose_sadb_supported(struct sadb_msg *orig, int allocation)
1416 {
1417         struct sk_buff *skb;
1418         struct sadb_msg *hdr;
1419         int len, auth_len, enc_len, i;
1420
1421         auth_len = xfrm_count_auth_supported();
1422         if (auth_len) {
1423                 auth_len *= sizeof(struct sadb_alg);
1424                 auth_len += sizeof(struct sadb_supported);
1425         }
1426         
1427         enc_len = xfrm_count_enc_supported();
1428         if (enc_len) {
1429                 enc_len *= sizeof(struct sadb_alg);
1430                 enc_len += sizeof(struct sadb_supported);
1431         }
1432         
1433         len = enc_len + auth_len + sizeof(struct sadb_msg);
1434
1435         skb = alloc_skb(len + 16, allocation);
1436         if (!skb)
1437                 goto out_put_algs;
1438
1439         hdr = (struct sadb_msg *) skb_put(skb, sizeof(*hdr));
1440         pfkey_hdr_dup(hdr, orig);
1441         hdr->sadb_msg_errno = 0;
1442         hdr->sadb_msg_len = len / sizeof(uint64_t);
1443
1444         if (auth_len) {
1445                 struct sadb_supported *sp;
1446                 struct sadb_alg *ap;
1447
1448                 sp = (struct sadb_supported *) skb_put(skb, auth_len);
1449                 ap = (struct sadb_alg *) (sp + 1);
1450
1451                 sp->sadb_supported_len = auth_len / sizeof(uint64_t);
1452                 sp->sadb_supported_exttype = SADB_EXT_SUPPORTED_AUTH;
1453
1454                 for (i = 0; ; i++) {
1455                         struct xfrm_algo_desc *aalg = xfrm_aalg_get_byidx(i);
1456                         if (!aalg)
1457                                 break;
1458                         if (aalg->available)
1459                                 *ap++ = aalg->desc;
1460                 }
1461         }
1462
1463         if (enc_len) {
1464                 struct sadb_supported *sp;
1465                 struct sadb_alg *ap;
1466
1467                 sp = (struct sadb_supported *) skb_put(skb, enc_len);
1468                 ap = (struct sadb_alg *) (sp + 1);
1469
1470                 sp->sadb_supported_len = enc_len / sizeof(uint64_t);
1471                 sp->sadb_supported_exttype = SADB_EXT_SUPPORTED_ENCRYPT;
1472
1473                 for (i = 0; ; i++) {
1474                         struct xfrm_algo_desc *ealg = xfrm_ealg_get_byidx(i);
1475                         if (!ealg)
1476                                 break;
1477                         if (ealg->available)
1478                                 *ap++ = ealg->desc;
1479                 }
1480         }
1481
1482 out_put_algs:
1483         return skb;
1484 }
1485
1486 static int pfkey_register(struct sock *sk, struct sk_buff *skb, struct sadb_msg *hdr, void **ext_hdrs)
1487 {
1488         struct pfkey_sock *pfk = pfkey_sk(sk);
1489         struct sk_buff *supp_skb;
1490
1491         if (hdr->sadb_msg_satype > SADB_SATYPE_MAX)
1492                 return -EINVAL;
1493
1494         if (hdr->sadb_msg_satype != SADB_SATYPE_UNSPEC) {
1495                 if (pfk->registered&(1<<hdr->sadb_msg_satype))
1496                         return -EEXIST;
1497                 pfk->registered |= (1<<hdr->sadb_msg_satype);
1498         }
1499
1500         xfrm_probe_algs();
1501         
1502         supp_skb = compose_sadb_supported(hdr, GFP_KERNEL);
1503         if (!supp_skb) {
1504                 if (hdr->sadb_msg_satype != SADB_SATYPE_UNSPEC)
1505                         pfk->registered &= ~(1<<hdr->sadb_msg_satype);
1506
1507                 return -ENOBUFS;
1508         }
1509
1510         pfkey_broadcast(supp_skb, GFP_KERNEL, BROADCAST_REGISTERED, sk);
1511
1512         return 0;
1513 }
1514
1515 static int key_notify_sa_flush(struct km_event *c)
1516 {
1517         struct sk_buff *skb;
1518         struct sadb_msg *hdr;
1519
1520         skb = alloc_skb(sizeof(struct sadb_msg) + 16, GFP_ATOMIC);
1521         if (!skb)
1522                 return -ENOBUFS;
1523         hdr = (struct sadb_msg *) skb_put(skb, sizeof(struct sadb_msg));
1524         hdr->sadb_msg_satype = pfkey_proto2satype(c->data.proto);
1525         hdr->sadb_msg_seq = c->seq;
1526         hdr->sadb_msg_pid = c->pid;
1527         hdr->sadb_msg_version = PF_KEY_V2;
1528         hdr->sadb_msg_errno = (uint8_t) 0;
1529         hdr->sadb_msg_len = (sizeof(struct sadb_msg) / sizeof(uint64_t));
1530
1531         pfkey_broadcast(skb, GFP_ATOMIC, BROADCAST_ALL, NULL);
1532
1533         return 0;
1534 }
1535
1536 static int pfkey_flush(struct sock *sk, struct sk_buff *skb, struct sadb_msg *hdr, void **ext_hdrs)
1537 {
1538         unsigned proto;
1539         struct km_event c;
1540
1541         proto = pfkey_satype2proto(hdr->sadb_msg_satype);
1542         if (proto == 0)
1543                 return -EINVAL;
1544
1545         xfrm_state_flush(proto);
1546         c.data.proto = proto;
1547         c.seq = hdr->sadb_msg_seq;
1548         c.pid = hdr->sadb_msg_pid;
1549         c.event = XFRM_MSG_FLUSHSA;
1550         km_state_notify(NULL, &c);
1551
1552         return 0;
1553 }
1554
1555 struct pfkey_dump_data
1556 {
1557         struct sk_buff *skb;
1558         struct sadb_msg *hdr;
1559         struct sock *sk;
1560 };
1561
1562 static int dump_sa(struct xfrm_state *x, int count, void *ptr)
1563 {
1564         struct pfkey_dump_data *data = ptr;
1565         struct sk_buff *out_skb;
1566         struct sadb_msg *out_hdr;
1567
1568         out_skb = pfkey_xfrm_state2msg(x, 1, 3);
1569         if (IS_ERR(out_skb))
1570                 return PTR_ERR(out_skb);
1571
1572         out_hdr = (struct sadb_msg *) out_skb->data;
1573         out_hdr->sadb_msg_version = data->hdr->sadb_msg_version;
1574         out_hdr->sadb_msg_type = SADB_DUMP;
1575         out_hdr->sadb_msg_satype = pfkey_proto2satype(x->id.proto);
1576         out_hdr->sadb_msg_errno = 0;
1577         out_hdr->sadb_msg_reserved = 0;
1578         out_hdr->sadb_msg_seq = count;
1579         out_hdr->sadb_msg_pid = data->hdr->sadb_msg_pid;
1580         pfkey_broadcast(out_skb, GFP_ATOMIC, BROADCAST_ONE, data->sk);
1581         return 0;
1582 }
1583
1584 static int pfkey_dump(struct sock *sk, struct sk_buff *skb, struct sadb_msg *hdr, void **ext_hdrs)
1585 {
1586         u8 proto;
1587         struct pfkey_dump_data data = { .skb = skb, .hdr = hdr, .sk = sk };
1588
1589         proto = pfkey_satype2proto(hdr->sadb_msg_satype);
1590         if (proto == 0)
1591                 return -EINVAL;
1592
1593         return xfrm_state_walk(proto, dump_sa, &data);
1594 }
1595
1596 static int pfkey_promisc(struct sock *sk, struct sk_buff *skb, struct sadb_msg *hdr, void **ext_hdrs)
1597 {
1598         struct pfkey_sock *pfk = pfkey_sk(sk);
1599         int satype = hdr->sadb_msg_satype;
1600
1601         if (hdr->sadb_msg_len == (sizeof(*hdr) / sizeof(uint64_t))) {
1602                 /* XXX we mangle packet... */
1603                 hdr->sadb_msg_errno = 0;
1604                 if (satype != 0 && satype != 1)
1605                         return -EINVAL;
1606                 pfk->promisc = satype;
1607         }
1608         pfkey_broadcast(skb_clone(skb, GFP_KERNEL), GFP_KERNEL, BROADCAST_ALL, NULL);
1609         return 0;
1610 }
1611
1612 static int check_reqid(struct xfrm_policy *xp, int dir, int count, void *ptr)
1613 {
1614         int i;
1615         u32 reqid = *(u32*)ptr;
1616
1617         for (i=0; i<xp->xfrm_nr; i++) {
1618                 if (xp->xfrm_vec[i].reqid == reqid)
1619                         return -EEXIST;
1620         }
1621         return 0;
1622 }
1623
1624 static u32 gen_reqid(void)
1625 {
1626         u32 start;
1627         static u32 reqid = IPSEC_MANUAL_REQID_MAX;
1628
1629         start = reqid;
1630         do {
1631                 ++reqid;
1632                 if (reqid == 0)
1633                         reqid = IPSEC_MANUAL_REQID_MAX+1;
1634                 if (xfrm_policy_walk(check_reqid, (void*)&reqid) != -EEXIST)
1635                         return reqid;
1636         } while (reqid != start);
1637         return 0;
1638 }
1639
1640 static int
1641 parse_ipsecrequest(struct xfrm_policy *xp, struct sadb_x_ipsecrequest *rq)
1642 {
1643         struct xfrm_tmpl *t = xp->xfrm_vec + xp->xfrm_nr;
1644         struct sockaddr_in *sin;
1645 #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
1646         struct sockaddr_in6 *sin6;
1647 #endif
1648
1649         if (xp->xfrm_nr >= XFRM_MAX_DEPTH)
1650                 return -ELOOP;
1651
1652         if (rq->sadb_x_ipsecrequest_mode == 0)
1653                 return -EINVAL;
1654
1655         t->id.proto = rq->sadb_x_ipsecrequest_proto; /* XXX check proto */
1656         t->mode = rq->sadb_x_ipsecrequest_mode-1;
1657         if (rq->sadb_x_ipsecrequest_level == IPSEC_LEVEL_USE)
1658                 t->optional = 1;
1659         else if (rq->sadb_x_ipsecrequest_level == IPSEC_LEVEL_UNIQUE) {
1660                 t->reqid = rq->sadb_x_ipsecrequest_reqid;
1661                 if (t->reqid > IPSEC_MANUAL_REQID_MAX)
1662                         t->reqid = 0;
1663                 if (!t->reqid && !(t->reqid = gen_reqid()))
1664                         return -ENOBUFS;
1665         }
1666
1667         /* addresses present only in tunnel mode */
1668         if (t->mode) {
1669                 switch (xp->family) {
1670                 case AF_INET:
1671                         sin = (void*)(rq+1);
1672                         if (sin->sin_family != AF_INET)
1673                                 return -EINVAL;
1674                         t->saddr.a4 = sin->sin_addr.s_addr;
1675                         sin++;
1676                         if (sin->sin_family != AF_INET)
1677                                 return -EINVAL;
1678                         t->id.daddr.a4 = sin->sin_addr.s_addr;
1679                         break;
1680 #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
1681                 case AF_INET6:
1682                         sin6 = (void *)(rq+1);
1683                         if (sin6->sin6_family != AF_INET6)
1684                                 return -EINVAL;
1685                         memcpy(t->saddr.a6, &sin6->sin6_addr, sizeof(struct in6_addr));
1686                         sin6++;
1687                         if (sin6->sin6_family != AF_INET6)
1688                                 return -EINVAL;
1689                         memcpy(t->id.daddr.a6, &sin6->sin6_addr, sizeof(struct in6_addr));
1690                         break;
1691 #endif
1692                 default:
1693                         return -EINVAL;
1694                 }
1695         }
1696         /* No way to set this via kame pfkey */
1697         t->aalgos = t->ealgos = t->calgos = ~0;
1698         xp->xfrm_nr++;
1699         return 0;
1700 }
1701
1702 static int
1703 parse_ipsecrequests(struct xfrm_policy *xp, struct sadb_x_policy *pol)
1704 {
1705         int err;
1706         int len = pol->sadb_x_policy_len*8 - sizeof(struct sadb_x_policy);
1707         struct sadb_x_ipsecrequest *rq = (void*)(pol+1);
1708
1709         while (len >= sizeof(struct sadb_x_ipsecrequest)) {
1710                 if ((err = parse_ipsecrequest(xp, rq)) < 0)
1711                         return err;
1712                 len -= rq->sadb_x_ipsecrequest_len;
1713                 rq = (void*)((u8*)rq + rq->sadb_x_ipsecrequest_len);
1714         }
1715         return 0;
1716 }
1717
1718 static int pfkey_xfrm_policy2msg_size(struct xfrm_policy *xp)
1719 {
1720         int sockaddr_size = pfkey_sockaddr_size(xp->family);
1721         int socklen = (xp->family == AF_INET ?
1722                        sizeof(struct sockaddr_in) :
1723                        sizeof(struct sockaddr_in6));
1724
1725         return sizeof(struct sadb_msg) +
1726                 (sizeof(struct sadb_lifetime) * 3) +
1727                 (sizeof(struct sadb_address) * 2) + 
1728                 (sockaddr_size * 2) +
1729                 sizeof(struct sadb_x_policy) +
1730                 (xp->xfrm_nr * (sizeof(struct sadb_x_ipsecrequest) +
1731                                 (socklen * 2)));
1732 }
1733
1734 static struct sk_buff * pfkey_xfrm_policy2msg_prep(struct xfrm_policy *xp)
1735 {
1736         struct sk_buff *skb;
1737         int size;
1738
1739         size = pfkey_xfrm_policy2msg_size(xp);
1740
1741         skb =  alloc_skb(size + 16, GFP_ATOMIC);
1742         if (skb == NULL)
1743                 return ERR_PTR(-ENOBUFS);
1744
1745         return skb;
1746 }
1747
1748 static void pfkey_xfrm_policy2msg(struct sk_buff *skb, struct xfrm_policy *xp, int dir)
1749 {
1750         struct sadb_msg *hdr;
1751         struct sadb_address *addr;
1752         struct sadb_lifetime *lifetime;
1753         struct sadb_x_policy *pol;
1754         struct sockaddr_in   *sin;
1755 #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
1756         struct sockaddr_in6  *sin6;
1757 #endif
1758         int i;
1759         int size;
1760         int sockaddr_size = pfkey_sockaddr_size(xp->family);
1761         int socklen = (xp->family == AF_INET ?
1762                        sizeof(struct sockaddr_in) :
1763                        sizeof(struct sockaddr_in6));
1764
1765         size = pfkey_xfrm_policy2msg_size(xp);
1766
1767         /* call should fill header later */
1768         hdr = (struct sadb_msg *) skb_put(skb, sizeof(struct sadb_msg));
1769         memset(hdr, 0, size);   /* XXX do we need this ? */
1770
1771         /* src address */
1772         addr = (struct sadb_address*) skb_put(skb, 
1773                                               sizeof(struct sadb_address)+sockaddr_size);
1774         addr->sadb_address_len = 
1775                 (sizeof(struct sadb_address)+sockaddr_size)/
1776                         sizeof(uint64_t);
1777         addr->sadb_address_exttype = SADB_EXT_ADDRESS_SRC;
1778         addr->sadb_address_proto = pfkey_proto_from_xfrm(xp->selector.proto);
1779         addr->sadb_address_prefixlen = xp->selector.prefixlen_s;
1780         addr->sadb_address_reserved = 0;
1781         /* src address */
1782         if (xp->family == AF_INET) {
1783                 sin = (struct sockaddr_in *) (addr + 1);
1784                 sin->sin_family = AF_INET;
1785                 sin->sin_addr.s_addr = xp->selector.saddr.a4;
1786                 sin->sin_port = xp->selector.sport;
1787                 memset(sin->sin_zero, 0, sizeof(sin->sin_zero));
1788         }
1789 #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
1790         else if (xp->family == AF_INET6) {
1791                 sin6 = (struct sockaddr_in6 *) (addr + 1);
1792                 sin6->sin6_family = AF_INET6;
1793                 sin6->sin6_port = xp->selector.sport;
1794                 sin6->sin6_flowinfo = 0;
1795                 memcpy(&sin6->sin6_addr, xp->selector.saddr.a6,
1796                        sizeof(struct in6_addr));
1797                 sin6->sin6_scope_id = 0;
1798         }
1799 #endif
1800         else
1801                 BUG();
1802
1803         /* dst address */
1804         addr = (struct sadb_address*) skb_put(skb, 
1805                                               sizeof(struct sadb_address)+sockaddr_size);
1806         addr->sadb_address_len =
1807                 (sizeof(struct sadb_address)+sockaddr_size)/
1808                         sizeof(uint64_t);
1809         addr->sadb_address_exttype = SADB_EXT_ADDRESS_DST;
1810         addr->sadb_address_proto = pfkey_proto_from_xfrm(xp->selector.proto);
1811         addr->sadb_address_prefixlen = xp->selector.prefixlen_d; 
1812         addr->sadb_address_reserved = 0;
1813         if (xp->family == AF_INET) {
1814                 sin = (struct sockaddr_in *) (addr + 1);
1815                 sin->sin_family = AF_INET;
1816                 sin->sin_addr.s_addr = xp->selector.daddr.a4;
1817                 sin->sin_port = xp->selector.dport;
1818                 memset(sin->sin_zero, 0, sizeof(sin->sin_zero));
1819         }
1820 #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
1821         else if (xp->family == AF_INET6) {
1822                 sin6 = (struct sockaddr_in6 *) (addr + 1);
1823                 sin6->sin6_family = AF_INET6;
1824                 sin6->sin6_port = xp->selector.dport;
1825                 sin6->sin6_flowinfo = 0;
1826                 memcpy(&sin6->sin6_addr, xp->selector.daddr.a6,
1827                        sizeof(struct in6_addr));
1828                 sin6->sin6_scope_id = 0;
1829         }
1830 #endif
1831         else
1832                 BUG();
1833
1834         /* hard time */
1835         lifetime = (struct sadb_lifetime *)  skb_put(skb, 
1836                                                      sizeof(struct sadb_lifetime));
1837         lifetime->sadb_lifetime_len =
1838                 sizeof(struct sadb_lifetime)/sizeof(uint64_t);
1839         lifetime->sadb_lifetime_exttype = SADB_EXT_LIFETIME_HARD;
1840         lifetime->sadb_lifetime_allocations =  _X2KEY(xp->lft.hard_packet_limit);
1841         lifetime->sadb_lifetime_bytes = _X2KEY(xp->lft.hard_byte_limit);
1842         lifetime->sadb_lifetime_addtime = xp->lft.hard_add_expires_seconds;
1843         lifetime->sadb_lifetime_usetime = xp->lft.hard_use_expires_seconds;
1844         /* soft time */
1845         lifetime = (struct sadb_lifetime *)  skb_put(skb, 
1846                                                      sizeof(struct sadb_lifetime));
1847         lifetime->sadb_lifetime_len =
1848                 sizeof(struct sadb_lifetime)/sizeof(uint64_t);
1849         lifetime->sadb_lifetime_exttype = SADB_EXT_LIFETIME_SOFT;
1850         lifetime->sadb_lifetime_allocations =  _X2KEY(xp->lft.soft_packet_limit);
1851         lifetime->sadb_lifetime_bytes = _X2KEY(xp->lft.soft_byte_limit);
1852         lifetime->sadb_lifetime_addtime = xp->lft.soft_add_expires_seconds;
1853         lifetime->sadb_lifetime_usetime = xp->lft.soft_use_expires_seconds;
1854         /* current time */
1855         lifetime = (struct sadb_lifetime *)  skb_put(skb, 
1856                                                      sizeof(struct sadb_lifetime));
1857         lifetime->sadb_lifetime_len =
1858                 sizeof(struct sadb_lifetime)/sizeof(uint64_t);
1859         lifetime->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
1860         lifetime->sadb_lifetime_allocations = xp->curlft.packets;
1861         lifetime->sadb_lifetime_bytes = xp->curlft.bytes;
1862         lifetime->sadb_lifetime_addtime = xp->curlft.add_time;
1863         lifetime->sadb_lifetime_usetime = xp->curlft.use_time;
1864
1865         pol = (struct sadb_x_policy *)  skb_put(skb, sizeof(struct sadb_x_policy));
1866         pol->sadb_x_policy_len = sizeof(struct sadb_x_policy)/sizeof(uint64_t);
1867         pol->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
1868         pol->sadb_x_policy_type = IPSEC_POLICY_DISCARD;
1869         if (xp->action == XFRM_POLICY_ALLOW) {
1870                 if (xp->xfrm_nr)
1871                         pol->sadb_x_policy_type = IPSEC_POLICY_IPSEC;
1872                 else
1873                         pol->sadb_x_policy_type = IPSEC_POLICY_NONE;
1874         }
1875         pol->sadb_x_policy_dir = dir+1;
1876         pol->sadb_x_policy_id = xp->index;
1877         pol->sadb_x_policy_priority = xp->priority;
1878
1879         for (i=0; i<xp->xfrm_nr; i++) {
1880                 struct sadb_x_ipsecrequest *rq;
1881                 struct xfrm_tmpl *t = xp->xfrm_vec + i;
1882                 int req_size;
1883
1884                 req_size = sizeof(struct sadb_x_ipsecrequest);
1885                 if (t->mode)
1886                         req_size += 2*socklen;
1887                 else
1888                         size -= 2*socklen;
1889                 rq = (void*)skb_put(skb, req_size);
1890                 pol->sadb_x_policy_len += req_size/8;
1891                 memset(rq, 0, sizeof(*rq));
1892                 rq->sadb_x_ipsecrequest_len = req_size;
1893                 rq->sadb_x_ipsecrequest_proto = t->id.proto;
1894                 rq->sadb_x_ipsecrequest_mode = t->mode+1;
1895                 rq->sadb_x_ipsecrequest_level = IPSEC_LEVEL_REQUIRE;
1896                 if (t->reqid)
1897                         rq->sadb_x_ipsecrequest_level = IPSEC_LEVEL_UNIQUE;
1898                 if (t->optional)
1899                         rq->sadb_x_ipsecrequest_level = IPSEC_LEVEL_USE;
1900                 rq->sadb_x_ipsecrequest_reqid = t->reqid;
1901                 if (t->mode) {
1902                         switch (xp->family) {
1903                         case AF_INET:
1904                                 sin = (void*)(rq+1);
1905                                 sin->sin_family = AF_INET;
1906                                 sin->sin_addr.s_addr = t->saddr.a4;
1907                                 sin->sin_port = 0;
1908                                 memset(sin->sin_zero, 0, sizeof(sin->sin_zero));
1909                                 sin++;
1910                                 sin->sin_family = AF_INET;
1911                                 sin->sin_addr.s_addr = t->id.daddr.a4;
1912                                 sin->sin_port = 0;
1913                                 memset(sin->sin_zero, 0, sizeof(sin->sin_zero));
1914                                 break;
1915 #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
1916                         case AF_INET6:
1917                                 sin6 = (void*)(rq+1);
1918                                 sin6->sin6_family = AF_INET6;
1919                                 sin6->sin6_port = 0;
1920                                 sin6->sin6_flowinfo = 0;
1921                                 memcpy(&sin6->sin6_addr, t->saddr.a6,
1922                                        sizeof(struct in6_addr));
1923                                 sin6->sin6_scope_id = 0;
1924
1925                                 sin6++;
1926                                 sin6->sin6_family = AF_INET6;
1927                                 sin6->sin6_port = 0;
1928                                 sin6->sin6_flowinfo = 0;
1929                                 memcpy(&sin6->sin6_addr, t->id.daddr.a6,
1930                                        sizeof(struct in6_addr));
1931                                 sin6->sin6_scope_id = 0;
1932                                 break;
1933 #endif
1934                         default:
1935                                 break;
1936                         }
1937                 }
1938         }
1939         hdr->sadb_msg_len = size / sizeof(uint64_t);
1940         hdr->sadb_msg_reserved = atomic_read(&xp->refcnt);
1941 }
1942
1943 static int key_notify_policy(struct xfrm_policy *xp, int dir, struct km_event *c)
1944 {
1945         struct sk_buff *out_skb;
1946         struct sadb_msg *out_hdr;
1947         int err;
1948
1949         out_skb = pfkey_xfrm_policy2msg_prep(xp);
1950         if (IS_ERR(out_skb)) {
1951                 err = PTR_ERR(out_skb);
1952                 goto out;
1953         }
1954         pfkey_xfrm_policy2msg(out_skb, xp, dir);
1955
1956         out_hdr = (struct sadb_msg *) out_skb->data;
1957         out_hdr->sadb_msg_version = PF_KEY_V2;
1958
1959         if (c->data.byid && c->event == XFRM_MSG_DELPOLICY)
1960                 out_hdr->sadb_msg_type = SADB_X_SPDDELETE2;
1961         else
1962                 out_hdr->sadb_msg_type = event2poltype(c->event);
1963         out_hdr->sadb_msg_errno = 0;
1964         out_hdr->sadb_msg_seq = c->seq;
1965         out_hdr->sadb_msg_pid = c->pid;
1966         pfkey_broadcast(out_skb, GFP_ATOMIC, BROADCAST_ALL, NULL);
1967 out:
1968         return 0;
1969
1970 }
1971
1972 static int pfkey_spdadd(struct sock *sk, struct sk_buff *skb, struct sadb_msg *hdr, void **ext_hdrs)
1973 {
1974         int err;
1975         struct sadb_lifetime *lifetime;
1976         struct sadb_address *sa;
1977         struct sadb_x_policy *pol;
1978         struct xfrm_policy *xp;
1979         struct km_event c;
1980
1981         if (!present_and_same_family(ext_hdrs[SADB_EXT_ADDRESS_SRC-1],
1982                                      ext_hdrs[SADB_EXT_ADDRESS_DST-1]) ||
1983             !ext_hdrs[SADB_X_EXT_POLICY-1])
1984                 return -EINVAL;
1985
1986         pol = ext_hdrs[SADB_X_EXT_POLICY-1];
1987         if (pol->sadb_x_policy_type > IPSEC_POLICY_IPSEC)
1988                 return -EINVAL;
1989         if (!pol->sadb_x_policy_dir || pol->sadb_x_policy_dir >= IPSEC_DIR_MAX)
1990                 return -EINVAL;
1991
1992         xp = xfrm_policy_alloc(GFP_KERNEL);
1993         if (xp == NULL)
1994                 return -ENOBUFS;
1995
1996         xp->action = (pol->sadb_x_policy_type == IPSEC_POLICY_DISCARD ?
1997                       XFRM_POLICY_BLOCK : XFRM_POLICY_ALLOW);
1998         xp->priority = pol->sadb_x_policy_priority;
1999
2000         sa = ext_hdrs[SADB_EXT_ADDRESS_SRC-1], 
2001         xp->family = pfkey_sadb_addr2xfrm_addr(sa, &xp->selector.saddr);
2002         if (!xp->family) {
2003                 err = -EINVAL;
2004                 goto out;
2005         }
2006         xp->selector.family = xp->family;
2007         xp->selector.prefixlen_s = sa->sadb_address_prefixlen;
2008         xp->selector.proto = pfkey_proto_to_xfrm(sa->sadb_address_proto);
2009         xp->selector.sport = ((struct sockaddr_in *)(sa+1))->sin_port;
2010         if (xp->selector.sport)
2011                 xp->selector.sport_mask = ~0;
2012
2013         sa = ext_hdrs[SADB_EXT_ADDRESS_DST-1], 
2014         pfkey_sadb_addr2xfrm_addr(sa, &xp->selector.daddr);
2015         xp->selector.prefixlen_d = sa->sadb_address_prefixlen;
2016
2017         /* Amusing, we set this twice.  KAME apps appear to set same value
2018          * in both addresses.
2019          */
2020         xp->selector.proto = pfkey_proto_to_xfrm(sa->sadb_address_proto);
2021
2022         xp->selector.dport = ((struct sockaddr_in *)(sa+1))->sin_port;
2023         if (xp->selector.dport)
2024                 xp->selector.dport_mask = ~0;
2025
2026         xp->lft.soft_byte_limit = XFRM_INF;
2027         xp->lft.hard_byte_limit = XFRM_INF;
2028         xp->lft.soft_packet_limit = XFRM_INF;
2029         xp->lft.hard_packet_limit = XFRM_INF;
2030         if ((lifetime = ext_hdrs[SADB_EXT_LIFETIME_HARD-1]) != NULL) {
2031                 xp->lft.hard_packet_limit = _KEY2X(lifetime->sadb_lifetime_allocations);
2032                 xp->lft.hard_byte_limit = _KEY2X(lifetime->sadb_lifetime_bytes);
2033                 xp->lft.hard_add_expires_seconds = lifetime->sadb_lifetime_addtime;
2034                 xp->lft.hard_use_expires_seconds = lifetime->sadb_lifetime_usetime;
2035         }
2036         if ((lifetime = ext_hdrs[SADB_EXT_LIFETIME_SOFT-1]) != NULL) {
2037                 xp->lft.soft_packet_limit = _KEY2X(lifetime->sadb_lifetime_allocations);
2038                 xp->lft.soft_byte_limit = _KEY2X(lifetime->sadb_lifetime_bytes);
2039                 xp->lft.soft_add_expires_seconds = lifetime->sadb_lifetime_addtime;
2040                 xp->lft.soft_use_expires_seconds = lifetime->sadb_lifetime_usetime;
2041         }
2042         xp->xfrm_nr = 0;
2043         if (pol->sadb_x_policy_type == IPSEC_POLICY_IPSEC &&
2044             (err = parse_ipsecrequests(xp, pol)) < 0)
2045                 goto out;
2046
2047         err = xfrm_policy_insert(pol->sadb_x_policy_dir-1, xp,
2048                                  hdr->sadb_msg_type != SADB_X_SPDUPDATE);
2049         if (err) {
2050                 kfree(xp);
2051                 return err;
2052         }
2053
2054         if (hdr->sadb_msg_type == SADB_X_SPDUPDATE)
2055                 c.event = XFRM_MSG_UPDPOLICY;
2056         else 
2057                 c.event = XFRM_MSG_NEWPOLICY;
2058
2059         c.seq = hdr->sadb_msg_seq;
2060         c.pid = hdr->sadb_msg_pid;
2061
2062         km_policy_notify(xp, pol->sadb_x_policy_dir-1, &c);
2063         xfrm_pol_put(xp);
2064         return 0;
2065
2066 out:
2067         kfree(xp);
2068         return err;
2069 }
2070
2071 static int pfkey_spddelete(struct sock *sk, struct sk_buff *skb, struct sadb_msg *hdr, void **ext_hdrs)
2072 {
2073         int err;
2074         struct sadb_address *sa;
2075         struct sadb_x_policy *pol;
2076         struct xfrm_policy *xp;
2077         struct xfrm_selector sel;
2078         struct km_event c;
2079
2080         if (!present_and_same_family(ext_hdrs[SADB_EXT_ADDRESS_SRC-1],
2081                                      ext_hdrs[SADB_EXT_ADDRESS_DST-1]) ||
2082             !ext_hdrs[SADB_X_EXT_POLICY-1])
2083                 return -EINVAL;
2084
2085         pol = ext_hdrs[SADB_X_EXT_POLICY-1];
2086         if (!pol->sadb_x_policy_dir || pol->sadb_x_policy_dir >= IPSEC_DIR_MAX)
2087                 return -EINVAL;
2088
2089         memset(&sel, 0, sizeof(sel));
2090
2091         sa = ext_hdrs[SADB_EXT_ADDRESS_SRC-1], 
2092         sel.family = pfkey_sadb_addr2xfrm_addr(sa, &sel.saddr);
2093         sel.prefixlen_s = sa->sadb_address_prefixlen;
2094         sel.proto = pfkey_proto_to_xfrm(sa->sadb_address_proto);
2095         sel.sport = ((struct sockaddr_in *)(sa+1))->sin_port;
2096         if (sel.sport)
2097                 sel.sport_mask = ~0;
2098
2099         sa = ext_hdrs[SADB_EXT_ADDRESS_DST-1], 
2100         pfkey_sadb_addr2xfrm_addr(sa, &sel.daddr);
2101         sel.prefixlen_d = sa->sadb_address_prefixlen;
2102         sel.proto = pfkey_proto_to_xfrm(sa->sadb_address_proto);
2103         sel.dport = ((struct sockaddr_in *)(sa+1))->sin_port;
2104         if (sel.dport)
2105                 sel.dport_mask = ~0;
2106
2107         xp = xfrm_policy_bysel(pol->sadb_x_policy_dir-1, &sel, 1);
2108         if (xp == NULL)
2109                 return -ENOENT;
2110
2111         err = 0;
2112
2113         c.seq = hdr->sadb_msg_seq;
2114         c.pid = hdr->sadb_msg_pid;
2115         c.event = XFRM_MSG_DELPOLICY;
2116         km_policy_notify(xp, pol->sadb_x_policy_dir-1, &c);
2117
2118         xfrm_pol_put(xp);
2119         return err;
2120 }
2121
2122 static int key_pol_get_resp(struct sock *sk, struct xfrm_policy *xp, struct sadb_msg *hdr, int dir)
2123 {
2124         int err;
2125         struct sk_buff *out_skb;
2126         struct sadb_msg *out_hdr;
2127         err = 0;
2128
2129         out_skb = pfkey_xfrm_policy2msg_prep(xp);
2130         if (IS_ERR(out_skb)) {
2131                 err =  PTR_ERR(out_skb);
2132                 goto out;
2133         }
2134         pfkey_xfrm_policy2msg(out_skb, xp, dir);
2135
2136         out_hdr = (struct sadb_msg *) out_skb->data;
2137         out_hdr->sadb_msg_version = hdr->sadb_msg_version;
2138         out_hdr->sadb_msg_type = hdr->sadb_msg_type;
2139         out_hdr->sadb_msg_satype = 0;
2140         out_hdr->sadb_msg_errno = 0;
2141         out_hdr->sadb_msg_seq = hdr->sadb_msg_seq;
2142         out_hdr->sadb_msg_pid = hdr->sadb_msg_pid;
2143         pfkey_broadcast(out_skb, GFP_ATOMIC, BROADCAST_ONE, sk);
2144         err = 0;
2145
2146 out:
2147         return err;
2148 }
2149
2150 static int pfkey_spdget(struct sock *sk, struct sk_buff *skb, struct sadb_msg *hdr, void **ext_hdrs)
2151 {
2152         int err;
2153         struct sadb_x_policy *pol;
2154         struct xfrm_policy *xp;
2155         struct km_event c;
2156
2157         if ((pol = ext_hdrs[SADB_X_EXT_POLICY-1]) == NULL)
2158                 return -EINVAL;
2159
2160         xp = xfrm_policy_byid(0, pol->sadb_x_policy_id,
2161                               hdr->sadb_msg_type == SADB_X_SPDDELETE2);
2162         if (xp == NULL)
2163                 return -ENOENT;
2164
2165         err = 0;
2166
2167         c.seq = hdr->sadb_msg_seq;
2168         c.pid = hdr->sadb_msg_pid;
2169         if (hdr->sadb_msg_type == SADB_X_SPDDELETE2) {
2170                 c.data.byid = 1;
2171                 c.event = XFRM_MSG_DELPOLICY;
2172                 km_policy_notify(xp, pol->sadb_x_policy_dir-1, &c);
2173         } else {
2174                 err = key_pol_get_resp(sk, xp, hdr, pol->sadb_x_policy_dir-1);
2175         }
2176
2177         xfrm_pol_put(xp);
2178         return err;
2179 }
2180
2181 static int dump_sp(struct xfrm_policy *xp, int dir, int count, void *ptr)
2182 {
2183         struct pfkey_dump_data *data = ptr;
2184         struct sk_buff *out_skb;
2185         struct sadb_msg *out_hdr;
2186
2187         out_skb = pfkey_xfrm_policy2msg_prep(xp);
2188         if (IS_ERR(out_skb))
2189                 return PTR_ERR(out_skb);
2190
2191         pfkey_xfrm_policy2msg(out_skb, xp, dir);
2192
2193         out_hdr = (struct sadb_msg *) out_skb->data;
2194         out_hdr->sadb_msg_version = data->hdr->sadb_msg_version;
2195         out_hdr->sadb_msg_type = SADB_X_SPDDUMP;
2196         out_hdr->sadb_msg_satype = SADB_SATYPE_UNSPEC;
2197         out_hdr->sadb_msg_errno = 0;
2198         out_hdr->sadb_msg_seq = count;
2199         out_hdr->sadb_msg_pid = data->hdr->sadb_msg_pid;
2200         pfkey_broadcast(out_skb, GFP_ATOMIC, BROADCAST_ONE, data->sk);
2201         return 0;
2202 }
2203
2204 static int pfkey_spddump(struct sock *sk, struct sk_buff *skb, struct sadb_msg *hdr, void **ext_hdrs)
2205 {
2206         struct pfkey_dump_data data = { .skb = skb, .hdr = hdr, .sk = sk };
2207
2208         return xfrm_policy_walk(dump_sp, &data);
2209 }
2210
2211 static int key_notify_policy_flush(struct km_event *c)
2212 {
2213         struct sk_buff *skb_out;
2214         struct sadb_msg *hdr;
2215
2216         skb_out = alloc_skb(sizeof(struct sadb_msg) + 16, GFP_ATOMIC);
2217         if (!skb_out)
2218                 return -ENOBUFS;
2219         hdr = (struct sadb_msg *) skb_put(skb_out, sizeof(struct sadb_msg));
2220         hdr->sadb_msg_seq = c->seq;
2221         hdr->sadb_msg_pid = c->pid;
2222         hdr->sadb_msg_version = PF_KEY_V2;
2223         hdr->sadb_msg_errno = (uint8_t) 0;
2224         hdr->sadb_msg_len = (sizeof(struct sadb_msg) / sizeof(uint64_t));
2225         pfkey_broadcast(skb_out, GFP_ATOMIC, BROADCAST_ALL, NULL);
2226         return 0;
2227
2228 }
2229
2230 static int pfkey_spdflush(struct sock *sk, struct sk_buff *skb, struct sadb_msg *hdr, void **ext_hdrs)
2231 {
2232         struct km_event c;
2233
2234         xfrm_policy_flush();
2235         c.event = XFRM_MSG_FLUSHPOLICY;
2236         c.pid = hdr->sadb_msg_pid;
2237         c.seq = hdr->sadb_msg_seq;
2238         km_policy_notify(NULL, 0, &c);
2239
2240         return 0;
2241 }
2242
2243 typedef int (*pfkey_handler)(struct sock *sk, struct sk_buff *skb,
2244                              struct sadb_msg *hdr, void **ext_hdrs);
2245 static pfkey_handler pfkey_funcs[SADB_MAX + 1] = {
2246         [SADB_RESERVED]         = pfkey_reserved,
2247         [SADB_GETSPI]           = pfkey_getspi,
2248         [SADB_UPDATE]           = pfkey_add,
2249         [SADB_ADD]              = pfkey_add,
2250         [SADB_DELETE]           = pfkey_delete,
2251         [SADB_GET]              = pfkey_get,
2252         [SADB_ACQUIRE]          = pfkey_acquire,
2253         [SADB_REGISTER]         = pfkey_register,
2254         [SADB_EXPIRE]           = NULL,
2255         [SADB_FLUSH]            = pfkey_flush,
2256         [SADB_DUMP]             = pfkey_dump,
2257         [SADB_X_PROMISC]        = pfkey_promisc,
2258         [SADB_X_PCHANGE]        = NULL,
2259         [SADB_X_SPDUPDATE]      = pfkey_spdadd,
2260         [SADB_X_SPDADD]         = pfkey_spdadd,
2261         [SADB_X_SPDDELETE]      = pfkey_spddelete,
2262         [SADB_X_SPDGET]         = pfkey_spdget,
2263         [SADB_X_SPDACQUIRE]     = NULL,
2264         [SADB_X_SPDDUMP]        = pfkey_spddump,
2265         [SADB_X_SPDFLUSH]       = pfkey_spdflush,
2266         [SADB_X_SPDSETIDX]      = pfkey_spdadd,
2267         [SADB_X_SPDDELETE2]     = pfkey_spdget,
2268 };
2269
2270 static int pfkey_process(struct sock *sk, struct sk_buff *skb, struct sadb_msg *hdr)
2271 {
2272         void *ext_hdrs[SADB_EXT_MAX];
2273         int err;
2274
2275         pfkey_broadcast(skb_clone(skb, GFP_KERNEL), GFP_KERNEL,
2276                         BROADCAST_PROMISC_ONLY, NULL);
2277
2278         memset(ext_hdrs, 0, sizeof(ext_hdrs));
2279         err = parse_exthdrs(skb, hdr, ext_hdrs);
2280         if (!err) {
2281                 err = -EOPNOTSUPP;
2282                 if (pfkey_funcs[hdr->sadb_msg_type])
2283                         err = pfkey_funcs[hdr->sadb_msg_type](sk, skb, hdr, ext_hdrs);
2284         }
2285         return err;
2286 }
2287
2288 static struct sadb_msg *pfkey_get_base_msg(struct sk_buff *skb, int *errp)
2289 {
2290         struct sadb_msg *hdr = NULL;
2291
2292         if (skb->len < sizeof(*hdr)) {
2293                 *errp = -EMSGSIZE;
2294         } else {
2295                 hdr = (struct sadb_msg *) skb->data;
2296                 if (hdr->sadb_msg_version != PF_KEY_V2 ||
2297                     hdr->sadb_msg_reserved != 0 ||
2298                     (hdr->sadb_msg_type <= SADB_RESERVED ||
2299                      hdr->sadb_msg_type > SADB_MAX)) {
2300                         hdr = NULL;
2301                         *errp = -EINVAL;
2302                 } else if (hdr->sadb_msg_len != (skb->len /
2303                                                  sizeof(uint64_t)) ||
2304                            hdr->sadb_msg_len < (sizeof(struct sadb_msg) /
2305                                                 sizeof(uint64_t))) {
2306                         hdr = NULL;
2307                         *errp = -EMSGSIZE;
2308                 } else {
2309                         *errp = 0;
2310                 }
2311         }
2312         return hdr;
2313 }
2314
2315 static inline int aalg_tmpl_set(struct xfrm_tmpl *t, struct xfrm_algo_desc *d)
2316 {
2317         return t->aalgos & (1 << d->desc.sadb_alg_id);
2318 }
2319
2320 static inline int ealg_tmpl_set(struct xfrm_tmpl *t, struct xfrm_algo_desc *d)
2321 {
2322         return t->ealgos & (1 << d->desc.sadb_alg_id);
2323 }
2324
2325 static int count_ah_combs(struct xfrm_tmpl *t)
2326 {
2327         int i, sz = 0;
2328
2329         for (i = 0; ; i++) {
2330                 struct xfrm_algo_desc *aalg = xfrm_aalg_get_byidx(i);
2331                 if (!aalg)
2332                         break;
2333                 if (aalg_tmpl_set(t, aalg) && aalg->available)
2334                         sz += sizeof(struct sadb_comb);
2335         }
2336         return sz + sizeof(struct sadb_prop);
2337 }
2338
2339 static int count_esp_combs(struct xfrm_tmpl *t)
2340 {
2341         int i, k, sz = 0;
2342
2343         for (i = 0; ; i++) {
2344                 struct xfrm_algo_desc *ealg = xfrm_ealg_get_byidx(i);
2345                 if (!ealg)
2346                         break;
2347                         
2348                 if (!(ealg_tmpl_set(t, ealg) && ealg->available))
2349                         continue;
2350                         
2351                 for (k = 1; ; k++) {
2352                         struct xfrm_algo_desc *aalg = xfrm_aalg_get_byidx(k);
2353                         if (!aalg)
2354                                 break;
2355                                 
2356                         if (aalg_tmpl_set(t, aalg) && aalg->available)
2357                                 sz += sizeof(struct sadb_comb);
2358                 }
2359         }
2360         return sz + sizeof(struct sadb_prop);
2361 }
2362
2363 static void dump_ah_combs(struct sk_buff *skb, struct xfrm_tmpl *t)
2364 {
2365         struct sadb_prop *p;
2366         int i;
2367
2368         p = (struct sadb_prop*)skb_put(skb, sizeof(struct sadb_prop));
2369         p->sadb_prop_len = sizeof(struct sadb_prop)/8;
2370         p->sadb_prop_exttype = SADB_EXT_PROPOSAL;
2371         p->sadb_prop_replay = 32;
2372         memset(p->sadb_prop_reserved, 0, sizeof(p->sadb_prop_reserved));
2373
2374         for (i = 0; ; i++) {
2375                 struct xfrm_algo_desc *aalg = xfrm_aalg_get_byidx(i);
2376                 if (!aalg)
2377                         break;
2378
2379                 if (aalg_tmpl_set(t, aalg) && aalg->available) {
2380                         struct sadb_comb *c;
2381                         c = (struct sadb_comb*)skb_put(skb, sizeof(struct sadb_comb));
2382                         memset(c, 0, sizeof(*c));
2383                         p->sadb_prop_len += sizeof(struct sadb_comb)/8;
2384                         c->sadb_comb_auth = aalg->desc.sadb_alg_id;
2385                         c->sadb_comb_auth_minbits = aalg->desc.sadb_alg_minbits;
2386                         c->sadb_comb_auth_maxbits = aalg->desc.sadb_alg_maxbits;
2387                         c->sadb_comb_hard_addtime = 24*60*60;
2388                         c->sadb_comb_soft_addtime = 20*60*60;
2389                         c->sadb_comb_hard_usetime = 8*60*60;
2390                         c->sadb_comb_soft_usetime = 7*60*60;
2391                 }
2392         }
2393 }
2394
2395 static void dump_esp_combs(struct sk_buff *skb, struct xfrm_tmpl *t)
2396 {
2397         struct sadb_prop *p;
2398         int i, k;
2399
2400         p = (struct sadb_prop*)skb_put(skb, sizeof(struct sadb_prop));
2401         p->sadb_prop_len = sizeof(struct sadb_prop)/8;
2402         p->sadb_prop_exttype = SADB_EXT_PROPOSAL;
2403         p->sadb_prop_replay = 32;
2404         memset(p->sadb_prop_reserved, 0, sizeof(p->sadb_prop_reserved));
2405
2406         for (i=0; ; i++) {
2407                 struct xfrm_algo_desc *ealg = xfrm_ealg_get_byidx(i);
2408                 if (!ealg)
2409                         break;
2410         
2411                 if (!(ealg_tmpl_set(t, ealg) && ealg->available))
2412                         continue;
2413                         
2414                 for (k = 1; ; k++) {
2415                         struct sadb_comb *c;
2416                         struct xfrm_algo_desc *aalg = xfrm_aalg_get_byidx(k);
2417                         if (!aalg)
2418                                 break;
2419                         if (!(aalg_tmpl_set(t, aalg) && aalg->available))
2420                                 continue;
2421                         c = (struct sadb_comb*)skb_put(skb, sizeof(struct sadb_comb));
2422                         memset(c, 0, sizeof(*c));
2423                         p->sadb_prop_len += sizeof(struct sadb_comb)/8;
2424                         c->sadb_comb_auth = aalg->desc.sadb_alg_id;
2425                         c->sadb_comb_auth_minbits = aalg->desc.sadb_alg_minbits;
2426                         c->sadb_comb_auth_maxbits = aalg->desc.sadb_alg_maxbits;
2427                         c->sadb_comb_encrypt = ealg->desc.sadb_alg_id;
2428                         c->sadb_comb_encrypt_minbits = ealg->desc.sadb_alg_minbits;
2429                         c->sadb_comb_encrypt_maxbits = ealg->desc.sadb_alg_maxbits;
2430                         c->sadb_comb_hard_addtime = 24*60*60;
2431                         c->sadb_comb_soft_addtime = 20*60*60;
2432                         c->sadb_comb_hard_usetime = 8*60*60;
2433                         c->sadb_comb_soft_usetime = 7*60*60;
2434                 }
2435         }
2436 }
2437
2438 static int key_notify_policy_expire(struct xfrm_policy *xp, struct km_event *c)
2439 {
2440         return 0;
2441 }
2442
2443 static int key_notify_sa_expire(struct xfrm_state *x, struct km_event *c)
2444 {
2445         struct sk_buff *out_skb;
2446         struct sadb_msg *out_hdr;
2447         int hard;
2448         int hsc;
2449
2450         hard = c->data.hard;
2451         if (hard)
2452                 hsc = 2;
2453         else
2454                 hsc = 1;
2455
2456         out_skb = pfkey_xfrm_state2msg(x, 0, hsc);
2457         if (IS_ERR(out_skb))
2458                 return PTR_ERR(out_skb);
2459
2460         out_hdr = (struct sadb_msg *) out_skb->data;
2461         out_hdr->sadb_msg_version = PF_KEY_V2;
2462         out_hdr->sadb_msg_type = SADB_EXPIRE;
2463         out_hdr->sadb_msg_satype = pfkey_proto2satype(x->id.proto);
2464         out_hdr->sadb_msg_errno = 0;
2465         out_hdr->sadb_msg_reserved = 0;
2466         out_hdr->sadb_msg_seq = 0;
2467         out_hdr->sadb_msg_pid = 0;
2468
2469         pfkey_broadcast(out_skb, GFP_ATOMIC, BROADCAST_REGISTERED, NULL);
2470         return 0;
2471 }
2472
2473 static int pfkey_send_notify(struct xfrm_state *x, struct km_event *c)
2474 {
2475         switch (c->event) {
2476         case XFRM_MSG_EXPIRE:
2477                 return key_notify_sa_expire(x, c);
2478         case XFRM_MSG_DELSA:
2479         case XFRM_MSG_NEWSA:
2480         case XFRM_MSG_UPDSA:
2481                 return key_notify_sa(x, c);
2482         case XFRM_MSG_FLUSHSA:
2483                 return key_notify_sa_flush(c);
2484         default:
2485                 printk("pfkey: Unknown SA event %d\n", c->event);
2486                 break;
2487         }
2488
2489         return 0;
2490 }
2491
2492 static int pfkey_send_policy_notify(struct xfrm_policy *xp, int dir, struct km_event *c)
2493 {
2494         switch (c->event) {
2495         case XFRM_MSG_POLEXPIRE:
2496                 return key_notify_policy_expire(xp, c);
2497         case XFRM_MSG_DELPOLICY:
2498         case XFRM_MSG_NEWPOLICY:
2499         case XFRM_MSG_UPDPOLICY:
2500                 return key_notify_policy(xp, dir, c);
2501         case XFRM_MSG_FLUSHPOLICY:
2502                 return key_notify_policy_flush(c);
2503         default:
2504                 printk("pfkey: Unknown policy event %d\n", c->event);
2505                 break;
2506         }
2507
2508         return 0;
2509 }
2510
2511 static u32 get_acqseq(void)
2512 {
2513         u32 res;
2514         static u32 acqseq;
2515         static DEFINE_SPINLOCK(acqseq_lock);
2516
2517         spin_lock_bh(&acqseq_lock);
2518         res = (++acqseq ? : ++acqseq);
2519         spin_unlock_bh(&acqseq_lock);
2520         return res;
2521 }
2522
2523 static int pfkey_send_acquire(struct xfrm_state *x, struct xfrm_tmpl *t, struct xfrm_policy *xp, int dir)
2524 {
2525         struct sk_buff *skb;
2526         struct sadb_msg *hdr;
2527         struct sadb_address *addr;
2528         struct sadb_x_policy *pol;
2529         struct sockaddr_in *sin;
2530 #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
2531         struct sockaddr_in6 *sin6;
2532 #endif
2533         int sockaddr_size;
2534         int size;
2535         
2536         sockaddr_size = pfkey_sockaddr_size(x->props.family);
2537         if (!sockaddr_size)
2538                 return -EINVAL;
2539
2540         size = sizeof(struct sadb_msg) +
2541                 (sizeof(struct sadb_address) * 2) +
2542                 (sockaddr_size * 2) +
2543                 sizeof(struct sadb_x_policy);
2544         
2545         if (x->id.proto == IPPROTO_AH)
2546                 size += count_ah_combs(t);
2547         else if (x->id.proto == IPPROTO_ESP)
2548                 size += count_esp_combs(t);
2549
2550         skb =  alloc_skb(size + 16, GFP_ATOMIC);
2551         if (skb == NULL)
2552                 return -ENOMEM;
2553         
2554         hdr = (struct sadb_msg *) skb_put(skb, sizeof(struct sadb_msg));
2555         hdr->sadb_msg_version = PF_KEY_V2;
2556         hdr->sadb_msg_type = SADB_ACQUIRE;
2557         hdr->sadb_msg_satype = pfkey_proto2satype(x->id.proto);
2558         hdr->sadb_msg_len = size / sizeof(uint64_t);
2559         hdr->sadb_msg_errno = 0;
2560         hdr->sadb_msg_reserved = 0;
2561         hdr->sadb_msg_seq = x->km.seq = get_acqseq();
2562         hdr->sadb_msg_pid = 0;
2563
2564         /* src address */
2565         addr = (struct sadb_address*) skb_put(skb, 
2566                                               sizeof(struct sadb_address)+sockaddr_size);
2567         addr->sadb_address_len = 
2568                 (sizeof(struct sadb_address)+sockaddr_size)/
2569                         sizeof(uint64_t);
2570         addr->sadb_address_exttype = SADB_EXT_ADDRESS_SRC;
2571         addr->sadb_address_proto = 0;
2572         addr->sadb_address_reserved = 0;
2573         if (x->props.family == AF_INET) {
2574                 addr->sadb_address_prefixlen = 32;
2575
2576                 sin = (struct sockaddr_in *) (addr + 1);
2577                 sin->sin_family = AF_INET;
2578                 sin->sin_addr.s_addr = x->props.saddr.a4;
2579                 sin->sin_port = 0;
2580                 memset(sin->sin_zero, 0, sizeof(sin->sin_zero));
2581         }
2582 #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
2583         else if (x->props.family == AF_INET6) {
2584                 addr->sadb_address_prefixlen = 128;
2585
2586                 sin6 = (struct sockaddr_in6 *) (addr + 1);
2587                 sin6->sin6_family = AF_INET6;
2588                 sin6->sin6_port = 0;
2589                 sin6->sin6_flowinfo = 0;
2590                 memcpy(&sin6->sin6_addr,
2591                        x->props.saddr.a6, sizeof(struct in6_addr));
2592                 sin6->sin6_scope_id = 0;
2593         }
2594 #endif
2595         else
2596                 BUG();
2597         
2598         /* dst address */
2599         addr = (struct sadb_address*) skb_put(skb, 
2600                                               sizeof(struct sadb_address)+sockaddr_size);
2601         addr->sadb_address_len =
2602                 (sizeof(struct sadb_address)+sockaddr_size)/
2603                         sizeof(uint64_t);
2604         addr->sadb_address_exttype = SADB_EXT_ADDRESS_DST;
2605         addr->sadb_address_proto = 0;
2606         addr->sadb_address_reserved = 0;
2607         if (x->props.family == AF_INET) {
2608                 addr->sadb_address_prefixlen = 32; 
2609
2610                 sin = (struct sockaddr_in *) (addr + 1);
2611                 sin->sin_family = AF_INET;
2612                 sin->sin_addr.s_addr = x->id.daddr.a4;
2613                 sin->sin_port = 0;
2614                 memset(sin->sin_zero, 0, sizeof(sin->sin_zero));
2615         }
2616 #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
2617         else if (x->props.family == AF_INET6) {
2618                 addr->sadb_address_prefixlen = 128; 
2619
2620                 sin6 = (struct sockaddr_in6 *) (addr + 1);
2621                 sin6->sin6_family = AF_INET6;
2622                 sin6->sin6_port = 0;
2623                 sin6->sin6_flowinfo = 0;
2624                 memcpy(&sin6->sin6_addr,
2625                        x->id.daddr.a6, sizeof(struct in6_addr));
2626                 sin6->sin6_scope_id = 0;
2627         }
2628 #endif
2629         else
2630                 BUG();
2631
2632         pol = (struct sadb_x_policy *)  skb_put(skb, sizeof(struct sadb_x_policy));
2633         pol->sadb_x_policy_len = sizeof(struct sadb_x_policy)/sizeof(uint64_t);
2634         pol->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
2635         pol->sadb_x_policy_type = IPSEC_POLICY_IPSEC;
2636         pol->sadb_x_policy_dir = dir+1;
2637         pol->sadb_x_policy_id = xp->index;
2638
2639         /* Set sadb_comb's. */
2640         if (x->id.proto == IPPROTO_AH)
2641                 dump_ah_combs(skb, t);
2642         else if (x->id.proto == IPPROTO_ESP)
2643                 dump_esp_combs(skb, t);
2644
2645         return pfkey_broadcast(skb, GFP_ATOMIC, BROADCAST_REGISTERED, NULL);
2646 }
2647
2648 static struct xfrm_policy *pfkey_compile_policy(u16 family, int opt,
2649                                                 u8 *data, int len, int *dir)
2650 {
2651         struct xfrm_policy *xp;
2652         struct sadb_x_policy *pol = (struct sadb_x_policy*)data;
2653
2654         switch (family) {
2655         case AF_INET:
2656                 if (opt != IP_IPSEC_POLICY) {
2657                         *dir = -EOPNOTSUPP;
2658                         return NULL;
2659                 }
2660                 break;
2661 #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
2662         case AF_INET6:
2663                 if (opt != IPV6_IPSEC_POLICY) {
2664                         *dir = -EOPNOTSUPP;
2665                         return NULL;
2666                 }
2667                 break;
2668 #endif
2669         default:
2670                 *dir = -EINVAL;
2671                 return NULL;
2672         }
2673
2674         *dir = -EINVAL;
2675
2676         if (len < sizeof(struct sadb_x_policy) ||
2677             pol->sadb_x_policy_len*8 > len ||
2678             pol->sadb_x_policy_type > IPSEC_POLICY_BYPASS ||
2679             (!pol->sadb_x_policy_dir || pol->sadb_x_policy_dir > IPSEC_DIR_OUTBOUND))
2680                 return NULL;
2681
2682         xp = xfrm_policy_alloc(GFP_ATOMIC);
2683         if (xp == NULL) {
2684                 *dir = -ENOBUFS;
2685                 return NULL;
2686         }
2687
2688         xp->action = (pol->sadb_x_policy_type == IPSEC_POLICY_DISCARD ?
2689                       XFRM_POLICY_BLOCK : XFRM_POLICY_ALLOW);
2690
2691         xp->lft.soft_byte_limit = XFRM_INF;
2692         xp->lft.hard_byte_limit = XFRM_INF;
2693         xp->lft.soft_packet_limit = XFRM_INF;
2694         xp->lft.hard_packet_limit = XFRM_INF;
2695         xp->family = family;
2696
2697         xp->xfrm_nr = 0;
2698         if (pol->sadb_x_policy_type == IPSEC_POLICY_IPSEC &&
2699             (*dir = parse_ipsecrequests(xp, pol)) < 0)
2700                 goto out;
2701
2702         *dir = pol->sadb_x_policy_dir-1;
2703         return xp;
2704
2705 out:
2706         kfree(xp);
2707         return NULL;
2708 }
2709
2710 static int pfkey_send_new_mapping(struct xfrm_state *x, xfrm_address_t *ipaddr, u16 sport)
2711 {
2712         struct sk_buff *skb;
2713         struct sadb_msg *hdr;
2714         struct sadb_sa *sa;
2715         struct sadb_address *addr;
2716         struct sadb_x_nat_t_port *n_port;
2717         struct sockaddr_in *sin;
2718 #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
2719         struct sockaddr_in6 *sin6;
2720 #endif
2721         int sockaddr_size;
2722         int size;
2723         __u8 satype = (x->id.proto == IPPROTO_ESP ? SADB_SATYPE_ESP : 0);
2724         struct xfrm_encap_tmpl *natt = NULL;
2725
2726         sockaddr_size = pfkey_sockaddr_size(x->props.family);
2727         if (!sockaddr_size)
2728                 return -EINVAL;
2729
2730         if (!satype)
2731                 return -EINVAL;
2732
2733         if (!x->encap)
2734                 return -EINVAL;
2735
2736         natt = x->encap;
2737
2738         /* Build an SADB_X_NAT_T_NEW_MAPPING message:
2739          *
2740          * HDR | SA | ADDRESS_SRC (old addr) | NAT_T_SPORT (old port) |
2741          * ADDRESS_DST (new addr) | NAT_T_DPORT (new port)
2742          */
2743         
2744         size = sizeof(struct sadb_msg) +
2745                 sizeof(struct sadb_sa) +
2746                 (sizeof(struct sadb_address) * 2) +
2747                 (sockaddr_size * 2) +
2748                 (sizeof(struct sadb_x_nat_t_port) * 2);
2749         
2750         skb =  alloc_skb(size + 16, GFP_ATOMIC);
2751         if (skb == NULL)
2752                 return -ENOMEM;
2753         
2754         hdr = (struct sadb_msg *) skb_put(skb, sizeof(struct sadb_msg));
2755         hdr->sadb_msg_version = PF_KEY_V2;
2756         hdr->sadb_msg_type = SADB_X_NAT_T_NEW_MAPPING;
2757         hdr->sadb_msg_satype = satype;
2758         hdr->sadb_msg_len = size / sizeof(uint64_t);
2759         hdr->sadb_msg_errno = 0;
2760         hdr->sadb_msg_reserved = 0;
2761         hdr->sadb_msg_seq = x->km.seq = get_acqseq();
2762         hdr->sadb_msg_pid = 0;
2763
2764         /* SA */
2765         sa = (struct sadb_sa *) skb_put(skb, sizeof(struct sadb_sa));
2766         sa->sadb_sa_len = sizeof(struct sadb_sa)/sizeof(uint64_t);
2767         sa->sadb_sa_exttype = SADB_EXT_SA;
2768         sa->sadb_sa_spi = x->id.spi;
2769         sa->sadb_sa_replay = 0;
2770         sa->sadb_sa_state = 0;
2771         sa->sadb_sa_auth = 0;
2772         sa->sadb_sa_encrypt = 0;
2773         sa->sadb_sa_flags = 0;
2774
2775         /* ADDRESS_SRC (old addr) */
2776         addr = (struct sadb_address*)
2777                 skb_put(skb, sizeof(struct sadb_address)+sockaddr_size);
2778         addr->sadb_address_len = 
2779                 (sizeof(struct sadb_address)+sockaddr_size)/
2780                         sizeof(uint64_t);
2781         addr->sadb_address_exttype = SADB_EXT_ADDRESS_SRC;
2782         addr->sadb_address_proto = 0;
2783         addr->sadb_address_reserved = 0;
2784         if (x->props.family == AF_INET) {
2785                 addr->sadb_address_prefixlen = 32;
2786
2787                 sin = (struct sockaddr_in *) (addr + 1);
2788                 sin->sin_family = AF_INET;
2789                 sin->sin_addr.s_addr = x->props.saddr.a4;
2790                 sin->sin_port = 0;
2791                 memset(sin->sin_zero, 0, sizeof(sin->sin_zero));
2792         }
2793 #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
2794         else if (x->props.family == AF_INET6) {
2795                 addr->sadb_address_prefixlen = 128;
2796
2797                 sin6 = (struct sockaddr_in6 *) (addr + 1);
2798                 sin6->sin6_family = AF_INET6;
2799                 sin6->sin6_port = 0;
2800                 sin6->sin6_flowinfo = 0;
2801                 memcpy(&sin6->sin6_addr,
2802                        x->props.saddr.a6, sizeof(struct in6_addr));
2803                 sin6->sin6_scope_id = 0;
2804         }
2805 #endif
2806         else
2807                 BUG();
2808
2809         /* NAT_T_SPORT (old port) */
2810         n_port = (struct sadb_x_nat_t_port*) skb_put(skb, sizeof (*n_port));
2811         n_port->sadb_x_nat_t_port_len = sizeof(*n_port)/sizeof(uint64_t);
2812         n_port->sadb_x_nat_t_port_exttype = SADB_X_EXT_NAT_T_SPORT;
2813         n_port->sadb_x_nat_t_port_port = natt->encap_sport;
2814         n_port->sadb_x_nat_t_port_reserved = 0;
2815
2816         /* ADDRESS_DST (new addr) */
2817         addr = (struct sadb_address*)
2818                 skb_put(skb, sizeof(struct sadb_address)+sockaddr_size);
2819         addr->sadb_address_len = 
2820                 (sizeof(struct sadb_address)+sockaddr_size)/
2821                         sizeof(uint64_t);
2822         addr->sadb_address_exttype = SADB_EXT_ADDRESS_DST;
2823         addr->sadb_address_proto = 0;
2824         addr->sadb_address_reserved = 0;
2825         if (x->props.family == AF_INET) {
2826                 addr->sadb_address_prefixlen = 32;
2827
2828                 sin = (struct sockaddr_in *) (addr + 1);
2829                 sin->sin_family = AF_INET;
2830                 sin->sin_addr.s_addr = ipaddr->a4;
2831                 sin->sin_port = 0;
2832                 memset(sin->sin_zero, 0, sizeof(sin->sin_zero));
2833         }
2834 #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
2835         else if (x->props.family == AF_INET6) {
2836                 addr->sadb_address_prefixlen = 128;
2837
2838                 sin6 = (struct sockaddr_in6 *) (addr + 1);
2839                 sin6->sin6_family = AF_INET6;
2840                 sin6->sin6_port = 0;
2841                 sin6->sin6_flowinfo = 0;
2842                 memcpy(&sin6->sin6_addr, &ipaddr->a6, sizeof(struct in6_addr));
2843                 sin6->sin6_scope_id = 0;
2844         }
2845 #endif
2846         else
2847                 BUG();
2848
2849         /* NAT_T_DPORT (new port) */
2850         n_port = (struct sadb_x_nat_t_port*) skb_put(skb, sizeof (*n_port));
2851         n_port->sadb_x_nat_t_port_len = sizeof(*n_port)/sizeof(uint64_t);
2852         n_port->sadb_x_nat_t_port_exttype = SADB_X_EXT_NAT_T_DPORT;
2853         n_port->sadb_x_nat_t_port_port = sport;
2854         n_port->sadb_x_nat_t_port_reserved = 0;
2855
2856         return pfkey_broadcast(skb, GFP_ATOMIC, BROADCAST_REGISTERED, NULL);
2857 }
2858
2859 static int pfkey_sendmsg(struct kiocb *kiocb,
2860                          struct socket *sock, struct msghdr *msg, size_t len)
2861 {
2862         struct sock *sk = sock->sk;
2863         struct sk_buff *skb = NULL;
2864         struct sadb_msg *hdr = NULL;
2865         int err;
2866
2867         err = -EOPNOTSUPP;
2868         if (msg->msg_flags & MSG_OOB)
2869                 goto out;
2870
2871         err = -EMSGSIZE;
2872         if ((unsigned)len > sk->sk_sndbuf - 32)
2873                 goto out;
2874
2875         err = -ENOBUFS;
2876         skb = alloc_skb(len, GFP_KERNEL);
2877         if (skb == NULL)
2878                 goto out;
2879
2880         err = -EFAULT;
2881         if (memcpy_fromiovec(skb_put(skb,len), msg->msg_iov, len))
2882                 goto out;
2883
2884         hdr = pfkey_get_base_msg(skb, &err);
2885         if (!hdr)
2886                 goto out;
2887
2888         down(&xfrm_cfg_sem);
2889         err = pfkey_process(sk, skb, hdr);
2890         up(&xfrm_cfg_sem);
2891
2892 out:
2893         if (err && hdr && pfkey_error(hdr, err, sk) == 0)
2894                 err = 0;
2895         if (skb)
2896                 kfree_skb(skb);
2897
2898         return err ? : len;
2899 }
2900
2901 static int pfkey_recvmsg(struct kiocb *kiocb,
2902                          struct socket *sock, struct msghdr *msg, size_t len,
2903                          int flags)
2904 {
2905         struct sock *sk = sock->sk;
2906         struct sk_buff *skb;
2907         int copied, err;
2908
2909         err = -EINVAL;
2910         if (flags & ~(MSG_PEEK|MSG_DONTWAIT|MSG_TRUNC|MSG_CMSG_COMPAT))
2911                 goto out;
2912
2913         msg->msg_namelen = 0;
2914         skb = skb_recv_datagram(sk, flags, flags & MSG_DONTWAIT, &err);
2915         if (skb == NULL)
2916                 goto out;
2917
2918         copied = skb->len;
2919         if (copied > len) {
2920                 msg->msg_flags |= MSG_TRUNC;
2921                 copied = len;
2922         }
2923
2924         skb->h.raw = skb->data;
2925         err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
2926         if (err)
2927                 goto out_free;
2928
2929         sock_recv_timestamp(msg, sk, skb);
2930
2931         err = (flags & MSG_TRUNC) ? skb->len : copied;
2932
2933 out_free:
2934         skb_free_datagram(sk, skb);
2935 out:
2936         return err;
2937 }
2938
2939 static struct proto_ops pfkey_ops = {
2940         .family         =       PF_KEY,
2941         .owner          =       THIS_MODULE,
2942         /* Operations that make no sense on pfkey sockets. */
2943         .bind           =       sock_no_bind,
2944         .connect        =       sock_no_connect,
2945         .socketpair     =       sock_no_socketpair,
2946         .accept         =       sock_no_accept,
2947         .getname        =       sock_no_getname,
2948         .ioctl          =       sock_no_ioctl,
2949         .listen         =       sock_no_listen,
2950         .shutdown       =       sock_no_shutdown,
2951         .setsockopt     =       sock_no_setsockopt,
2952         .getsockopt     =       sock_no_getsockopt,
2953         .mmap           =       sock_no_mmap,
2954         .sendpage       =       sock_no_sendpage,
2955
2956         /* Now the operations that really occur. */
2957         .release        =       pfkey_release,
2958         .poll           =       datagram_poll,
2959         .sendmsg        =       pfkey_sendmsg,
2960         .recvmsg        =       pfkey_recvmsg,
2961 };
2962
2963 static struct net_proto_family pfkey_family_ops = {
2964         .family =       PF_KEY,
2965         .create =       pfkey_create,
2966         .owner  =       THIS_MODULE,
2967 };
2968
2969 #ifdef CONFIG_PROC_FS
2970 static int pfkey_read_proc(char *buffer, char **start, off_t offset,
2971                            int length, int *eof, void *data)
2972 {
2973         off_t pos = 0;
2974         off_t begin = 0;
2975         int len = 0;
2976         struct sock *s;
2977         struct hlist_node *node;
2978
2979         len += sprintf(buffer,"sk       RefCnt Rmem   Wmem   User   Inode\n");
2980
2981         read_lock(&pfkey_table_lock);
2982
2983         sk_for_each(s, node, &pfkey_table) {
2984                 len += sprintf(buffer+len,"%p %-6d %-6u %-6u %-6u %-6lu",
2985                                s,
2986                                atomic_read(&s->sk_refcnt),
2987                                atomic_read(&s->sk_rmem_alloc),
2988                                atomic_read(&s->sk_wmem_alloc),
2989                                sock_i_uid(s),
2990                                sock_i_ino(s)
2991                                );
2992
2993                 buffer[len++] = '\n';
2994                 
2995                 pos = begin + len;
2996                 if (pos < offset) {
2997                         len = 0;
2998                         begin = pos;
2999                 }
3000                 if(pos > offset + length)
3001                         goto done;
3002         }
3003         *eof = 1;
3004
3005 done:
3006         read_unlock(&pfkey_table_lock);
3007
3008         *start = buffer + (offset - begin);
3009         len -= (offset - begin);
3010
3011         if (len > length)
3012                 len = length;
3013         if (len < 0)
3014                 len = 0;
3015
3016         return len;
3017 }
3018 #endif
3019
3020 static struct xfrm_mgr pfkeyv2_mgr =
3021 {
3022         .id             = "pfkeyv2",
3023         .notify         = pfkey_send_notify,
3024         .acquire        = pfkey_send_acquire,
3025         .compile_policy = pfkey_compile_policy,
3026         .new_mapping    = pfkey_send_new_mapping,
3027         .notify_policy  = pfkey_send_policy_notify,
3028 };
3029
3030 static void __exit ipsec_pfkey_exit(void)
3031 {
3032         xfrm_unregister_km(&pfkeyv2_mgr);
3033         remove_proc_entry("net/pfkey", NULL);
3034         sock_unregister(PF_KEY);
3035         proto_unregister(&key_proto);
3036 }
3037
3038 static int __init ipsec_pfkey_init(void)
3039 {
3040         int err = proto_register(&key_proto, 0);
3041
3042         if (err != 0)
3043                 goto out;
3044
3045         err = sock_register(&pfkey_family_ops);
3046         if (err != 0)
3047                 goto out_unregister_key_proto;
3048 #ifdef CONFIG_PROC_FS
3049         err = -ENOMEM;
3050         if (create_proc_read_entry("net/pfkey", 0, NULL, pfkey_read_proc, NULL) == NULL)
3051                 goto out_sock_unregister;
3052 #endif
3053         err = xfrm_register_km(&pfkeyv2_mgr);
3054         if (err != 0)
3055                 goto out_remove_proc_entry;
3056 out:
3057         return err;
3058 out_remove_proc_entry:
3059 #ifdef CONFIG_PROC_FS
3060         remove_proc_entry("net/pfkey", NULL);
3061 out_sock_unregister:
3062 #endif
3063         sock_unregister(PF_KEY);
3064 out_unregister_key_proto:
3065         proto_unregister(&key_proto);
3066         goto out;
3067 }
3068
3069 module_init(ipsec_pfkey_init);
3070 module_exit(ipsec_pfkey_exit);
3071 MODULE_LICENSE("GPL");
3072 MODULE_ALIAS_NETPROTO(PF_KEY);