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