Merge branch 'vendor/BMAKE'
[dragonfly.git] / sys / netproto / key / keysock.c
1 /*
2  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the project nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  * $FreeBSD: src/sys/netkey/keysock.c,v 1.1.2.4 2003/01/11 19:10:59 ume Exp $
30  * $KAME: keysock.c,v 1.25 2001/08/13 20:07:41 itojun Exp $
31  */
32
33 #include "opt_ipsec.h"
34
35 /* This code has derived from sys/net/rtsock.c on FreeBSD2.2.5 */
36
37 #include <sys/types.h>
38 #include <sys/param.h>
39 #include <sys/systm.h>
40 #include <sys/kernel.h>
41 #include <sys/sysctl.h>
42 #include <sys/mbuf.h>
43 #include <sys/malloc.h>
44 #include <sys/socket.h>
45 #include <sys/socketvar.h>
46 #include <sys/domain.h>
47 #include <sys/protosw.h>
48 #include <sys/errno.h>
49 #include <sys/socketvar2.h>
50
51 #include <sys/thread2.h>
52 #include <sys/msgport2.h>
53
54 #include <net/raw_cb.h>
55 #include <net/route.h>
56 #include <net/netmsg.h>
57 #include <netinet/in.h>
58
59 #include <net/pfkeyv2.h>
60 #include <net/netmsg2.h>
61
62 #include "keydb.h"
63 #include "key.h"
64 #include "keysock.h"
65 #include "key_debug.h"
66
67 #include <machine/stdarg.h>
68
69 struct sockaddr key_dst = { 2, PF_KEY, };
70 struct sockaddr key_src = { 2, PF_KEY, };
71
72 static int key_sendup0 (struct rawcb *, struct mbuf *, int);
73
74 struct pfkeystat pfkeystat;
75
76 /*
77  * key_output()
78  */
79 int
80 key_output(struct mbuf *m, struct socket *so, ...)
81 {
82         struct sadb_msg *msg;
83         int len, error = 0;
84
85         if (m == NULL)
86                 panic("key_output: NULL pointer was passed.");
87
88         pfkeystat.out_total++;
89         pfkeystat.out_bytes += m->m_pkthdr.len;
90
91         len = m->m_pkthdr.len;
92         if (len < sizeof(struct sadb_msg)) {
93                 pfkeystat.out_tooshort++;
94                 error = EINVAL;
95                 goto end;
96         }
97
98         if (m->m_len < sizeof(struct sadb_msg)) {
99                 if ((m = m_pullup(m, sizeof(struct sadb_msg))) == NULL) {
100                         pfkeystat.out_nomem++;
101                         error = ENOBUFS;
102                         goto end;
103                 }
104         }
105
106         if ((m->m_flags & M_PKTHDR) == 0)
107                 panic("key_output: not M_PKTHDR ??");
108
109         KEYDEBUG(KEYDEBUG_KEY_DUMP, kdebug_mbuf(m));
110
111         msg = mtod(m, struct sadb_msg *);
112         pfkeystat.out_msgtype[msg->sadb_msg_type]++;
113         if (len != PFKEY_UNUNIT64(msg->sadb_msg_len)) {
114                 pfkeystat.out_invlen++;
115                 error = EINVAL;
116                 goto end;
117         }
118
119         /*XXX giant lock*/
120         lwkt_gettoken(&key_token);
121         error = key_parse(m, so);
122         m = NULL;
123         lwkt_reltoken(&key_token);
124 end:
125         if (m)
126                 m_freem(m);
127         return error;
128 }
129
130 /*
131  * send message to the socket.
132  */
133 static int
134 key_sendup0(struct rawcb *rp, struct mbuf *m, int promisc)
135 {
136         int error;
137
138         if (promisc) {
139                 struct sadb_msg *pmsg;
140
141                 M_PREPEND(m, sizeof(struct sadb_msg), M_NOWAIT);
142                 if (m && m->m_len < sizeof(struct sadb_msg))
143                         m = m_pullup(m, sizeof(struct sadb_msg));
144                 if (!m) {
145                         pfkeystat.in_nomem++;
146                         m_freem(m);
147                         return ENOBUFS;
148                 }
149                 m->m_pkthdr.len += sizeof(*pmsg);
150
151                 pmsg = mtod(m, struct sadb_msg *);
152                 bzero(pmsg, sizeof(*pmsg));
153                 pmsg->sadb_msg_version = PF_KEY_V2;
154                 pmsg->sadb_msg_type = SADB_X_PROMISC;
155                 pmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
156                 /* pid and seq? */
157
158                 pfkeystat.in_msgtype[pmsg->sadb_msg_type]++;
159         }
160
161         lwkt_gettoken(&key_token);
162         if (!ssb_appendaddr(&rp->rcb_socket->so_rcv, &key_src, m, NULL)) {
163                 pfkeystat.in_nomem++;
164                 m_freem(m);
165                 error = ENOBUFS;
166         } else {
167                 error = 0;
168         }
169         lwkt_reltoken(&key_token);
170         sorwakeup(rp->rcb_socket);
171         return error;
172 }
173
174 /*
175  * XXX this interface should be obsoleted.
176  *
177  * Parameters:
178  *      target: target of the resulting message
179  */
180 int
181 key_sendup(struct socket *so, struct sadb_msg *msg, u_int len,
182            int target)
183 {
184         struct mbuf *m, *n, *mprev;
185         int tlen;
186
187         /* sanity check */
188         if (so == NULL || msg == NULL)
189                 panic("key_sendup: NULL pointer was passed.");
190
191         KEYDEBUG(KEYDEBUG_KEY_DUMP,
192                 kprintf("key_sendup: \n");
193                 kdebug_sadb(msg));
194
195         /*
196          * we increment statistics here, just in case we have ENOBUFS
197          * in this function.
198          */
199         pfkeystat.in_total++;
200         pfkeystat.in_bytes += len;
201         pfkeystat.in_msgtype[msg->sadb_msg_type]++;
202
203         /*
204          * Get mbuf chain whenever possible (not clusters),
205          * to save socket buffer.  We'll be generating many SADB_ACQUIRE
206          * messages to listening key sockets.  If we simply allocate clusters,
207          * ssb_appendaddr() will raise ENOBUFS due to too little ssb_space().
208          * ssb_space() computes # of actual data bytes AND mbuf region.
209          *
210          * TODO: SADB_ACQUIRE filters should be implemented.
211          */
212         tlen = len;
213         m = mprev = NULL;
214         while (tlen > 0) {
215                 if (tlen == len) {
216                         MGETHDR(n, M_NOWAIT, MT_DATA);
217                         n->m_len = MHLEN;
218                 } else {
219                         MGET(n, M_NOWAIT, MT_DATA);
220                         n->m_len = MLEN;
221                 }
222                 if (!n) {
223                         pfkeystat.in_nomem++;
224                         return ENOBUFS;
225                 }
226                 if (tlen >= MCLBYTES) { /*XXX better threshold? */
227                         MCLGET(n, M_NOWAIT);
228                         if ((n->m_flags & M_EXT) == 0) {
229                                 m_free(n);
230                                 m_freem(m);
231                                 pfkeystat.in_nomem++;
232                                 return ENOBUFS;
233                         }
234                         n->m_len = MCLBYTES;
235                 }
236
237                 if (tlen < n->m_len)
238                         n->m_len = tlen;
239                 n->m_next = NULL;
240                 if (m == NULL)
241                         m = mprev = n;
242                 else {
243                         mprev->m_next = n;
244                         mprev = n;
245                 }
246                 tlen -= n->m_len;
247                 n = NULL;
248         }
249         m->m_pkthdr.len = len;
250         m->m_pkthdr.rcvif = NULL;
251         m_copyback(m, 0, len, (caddr_t)msg);
252
253         /* avoid duplicated statistics */
254         pfkeystat.in_total--;
255         pfkeystat.in_bytes -= len;
256         pfkeystat.in_msgtype[msg->sadb_msg_type]--;
257
258         return key_sendup_mbuf(so, m, target);
259 }
260
261 /* so can be NULL if target != KEY_SENDUP_ONE */
262 int
263 key_sendup_mbuf(struct socket *so, struct mbuf *m, int target)
264 {
265         struct mbuf *n;
266         struct keycb *kp;
267         int sendup;
268         struct rawcb *rp;
269         int error = 0;
270
271         if (m == NULL)
272                 panic("key_sendup_mbuf: NULL pointer was passed.");
273         if (so == NULL && target == KEY_SENDUP_ONE)
274                 panic("key_sendup_mbuf: NULL pointer was passed.");
275
276         pfkeystat.in_total++;
277         pfkeystat.in_bytes += m->m_pkthdr.len;
278         if (m->m_len < sizeof(struct sadb_msg)) {
279 #if 1
280                 m = m_pullup(m, sizeof(struct sadb_msg));
281                 if (m == NULL) {
282                         pfkeystat.in_nomem++;
283                         return ENOBUFS;
284                 }
285 #else
286                 /* don't bother pulling it up just for stats */
287 #endif
288         }
289         if (m->m_len >= sizeof(struct sadb_msg)) {
290                 struct sadb_msg *msg;
291                 msg = mtod(m, struct sadb_msg *);
292                 pfkeystat.in_msgtype[msg->sadb_msg_type]++;
293         }
294
295         lwkt_gettoken(&key_token);
296
297         LIST_FOREACH(rp, &rawcb_list, list)
298         {
299                 if (rp->rcb_proto.sp_family != PF_KEY)
300                         continue;
301                 if (rp->rcb_proto.sp_protocol
302                  && rp->rcb_proto.sp_protocol != PF_KEY_V2) {
303                         continue;
304                 }
305
306                 kp = (struct keycb *)rp;
307
308                 /*
309                  * If you are in promiscuous mode, and when you get broadcasted
310                  * reply, you'll get two PF_KEY messages.
311                  * (based on pf_key@inner.net message on 14 Oct 1998)
312                  */
313                 if (((struct keycb *)rp)->kp_promisc) {
314                         if ((n = m_copy(m, 0, (int)M_COPYALL)) != NULL) {
315                                 key_sendup0(rp, n, 1);
316                                 n = NULL;
317                         }
318                 }
319
320                 /* the exact target will be processed later */
321                 if (so && sotorawcb(so) == rp)
322                         continue;
323
324                 sendup = 0;
325                 switch (target) {
326                 case KEY_SENDUP_ONE:
327                         /* the statement has no effect */
328                         if (so && sotorawcb(so) == rp)
329                                 sendup++;
330                         break;
331                 case KEY_SENDUP_ALL:
332                         sendup++;
333                         break;
334                 case KEY_SENDUP_REGISTERED:
335                         if (kp->kp_registered)
336                                 sendup++;
337                         break;
338                 }
339                 pfkeystat.in_msgtarget[target]++;
340
341                 if (!sendup)
342                         continue;
343
344                 if ((n = m_copy(m, 0, (int)M_COPYALL)) == NULL) {
345                         m_freem(m);
346                         pfkeystat.in_nomem++;
347                         lwkt_reltoken(&key_token);
348                         return ENOBUFS;
349                 }
350
351                 if ((error = key_sendup0(rp, n, 0)) != 0) {
352                         lwkt_reltoken(&key_token);
353                         m_freem(m);
354                         return error;
355                 }
356
357                 n = NULL;
358         }
359         lwkt_reltoken(&key_token);
360
361         if (so) {
362                 error = key_sendup0(sotorawcb(so), m, 0);
363                 m = NULL;
364         } else {
365                 error = 0;
366                 m_freem(m);
367         }
368         return error;
369 }
370
371 /*
372  * key_abort()
373  * derived from net/rtsock.c:rts_abort()
374  */
375 static void
376 key_abort(netmsg_t msg)
377 {
378         lwkt_gettoken(&key_token);
379
380         raw_usrreqs.pru_abort(msg);
381         /* msg invalid now */
382
383         lwkt_reltoken(&key_token);
384 }
385
386 /*
387  * key_attach()
388  * derived from net/rtsock.c:rts_attach()
389  */
390 static void
391 key_attach(netmsg_t msg)
392 {
393         struct socket *so = msg->attach.base.nm_so;
394         int proto = msg->attach.nm_proto;
395         struct pru_attach_info *ai = msg->attach.nm_ai;
396         struct keycb *kp;
397         struct netmsg_pru_attach smsg;
398         int error;
399
400         if (sotorawcb(so) != NULL) {
401                 error = EISCONN;        /* XXX panic? */
402                 goto out;
403         }
404
405         /* XXX */
406         kp = kmalloc(sizeof *kp, M_PCB, M_WAITOK | M_ZERO);
407
408         /*
409          * The critical section is necessary to block protocols from sending
410          * error notifications (like RTM_REDIRECT or RTM_LOSING) while
411          * this PCB is extant but incompletely initialized.
412          * Probably we should try to do more of this work beforehand and
413          * eliminate the critical section.
414          */
415         lwkt_gettoken(&key_token);
416         so->so_pcb = (caddr_t)kp;
417         soreference(so);        /* so_pcb assignment */
418
419         netmsg_init(&smsg.base, so, &netisr_adone_rport, 0,
420                     raw_usrreqs.pru_attach);
421         smsg.base.lmsg.ms_flags &= ~(MSGF_REPLY | MSGF_DONE);
422         smsg.base.lmsg.ms_flags |= MSGF_SYNC;
423         smsg.nm_proto = proto;
424         smsg.nm_ai = ai;
425         raw_usrreqs.pru_attach((netmsg_t)&smsg);
426         error = smsg.base.lmsg.ms_error;
427
428         kp = (struct keycb *)sotorawcb(so);
429         if (error) {
430                 kfree(kp, M_PCB);
431                 atomic_add_int(&so->so_refs, -1);
432                 so->so_pcb = (caddr_t) 0;
433                 lwkt_reltoken(&key_token);
434                 goto out;
435         }
436
437         kp->kp_promisc = kp->kp_registered = 0;
438
439         if (kp->kp_raw.rcb_proto.sp_protocol == PF_KEY) /* XXX: AF_KEY */
440                 key_cb.key_count++;
441         key_cb.any_count++;
442         kp->kp_raw.rcb_laddr = &key_src;
443         kp->kp_raw.rcb_faddr = &key_dst;
444         soisconnected(so);
445         so->so_options |= SO_USELOOPBACK;
446
447         lwkt_reltoken(&key_token);
448         error = 0;
449 out:
450         lwkt_replymsg(&msg->attach.base.lmsg, error);
451 }
452
453 /*
454  * key_bind()
455  * derived from net/rtsock.c:rts_bind()
456  */
457 static void
458 key_bind(netmsg_t msg)
459 {
460         lwkt_gettoken(&key_token);
461
462         raw_usrreqs.pru_bind(msg); /* xxx just EINVAL */
463         /* msg invalid now */
464
465         lwkt_reltoken(&key_token);
466 }
467
468 /*
469  * key_connect()
470  * derived from net/rtsock.c:rts_connect()
471  */
472 static void
473 key_connect(netmsg_t msg)
474 {
475         lwkt_gettoken(&key_token);
476
477         raw_usrreqs.pru_connect(msg); /* XXX just EINVAL */
478         /* msg invalid now */
479
480         lwkt_reltoken(&key_token);
481 }
482
483 /*
484  * key_detach()
485  * derived from net/rtsock.c:rts_detach()
486  */
487 static void
488 key_detach(netmsg_t msg)
489 {
490         struct socket *so = msg->detach.base.nm_so;
491         struct keycb *kp = (struct keycb *)sotorawcb(so);
492
493         lwkt_gettoken(&key_token);
494
495         if (kp != NULL) {
496                 if (kp->kp_raw.rcb_proto.sp_protocol == PF_KEY) {
497                         /* XXX: AF_KEY */
498                         key_cb.key_count--;
499                 }
500                 key_cb.any_count--;
501
502                 key_freereg(so);
503         }
504         raw_usrreqs.pru_detach(msg);
505         /* msg invalid now */
506
507         lwkt_reltoken(&key_token);
508 }
509
510 /*
511  * key_disconnect()
512  * derived from net/rtsock.c:key_disconnect()
513  */
514 static void
515 key_disconnect(netmsg_t msg)
516 {
517         lwkt_gettoken(&key_token);
518
519         raw_usrreqs.pru_disconnect(msg);
520         /* msg invalid now */
521
522         lwkt_reltoken(&key_token);
523 }
524
525 /*
526  * key_peeraddr()
527  * derived from net/rtsock.c:rts_peeraddr()
528  */
529 static void
530 key_peeraddr(netmsg_t msg)
531 {
532         lwkt_gettoken(&key_token);
533
534         raw_usrreqs.pru_peeraddr(msg);
535         /* msg invalid now */
536
537         lwkt_reltoken(&key_token);
538 }
539
540 /*
541  * key_send()
542  * derived from net/rtsock.c:rts_send()
543  */
544 static void
545 key_send(netmsg_t msg)
546 {
547         lwkt_gettoken(&key_token);
548
549         raw_usrreqs.pru_send(msg);
550         /* msg invalid now */
551
552         lwkt_reltoken(&key_token);
553 }
554
555 /*
556  * key_shutdown()
557  * derived from net/rtsock.c:rts_shutdown()
558  */
559 static void
560 key_shutdown(netmsg_t msg)
561 {
562         lwkt_gettoken(&key_token);
563
564         raw_usrreqs.pru_shutdown(msg);
565         /* msg invalid now */
566
567         lwkt_reltoken(&key_token);
568 }
569
570 /*
571  * key_sockaddr()
572  * derived from net/rtsock.c:rts_sockaddr()
573  */
574 static void
575 key_sockaddr(netmsg_t msg)
576 {
577         lwkt_gettoken(&key_token);
578
579         raw_usrreqs.pru_sockaddr(msg);
580         /* msg invalid now */
581
582         lwkt_reltoken(&key_token);
583 }
584
585 struct pr_usrreqs key_usrreqs = {
586         .pru_abort = key_abort,
587         .pru_accept = pr_generic_notsupp,
588         .pru_attach = key_attach,
589         .pru_bind = key_bind,
590         .pru_connect = key_connect,
591         .pru_connect2 = pr_generic_notsupp,
592         .pru_control = pr_generic_notsupp,
593         .pru_detach = key_detach,
594         .pru_disconnect = key_disconnect,
595         .pru_listen = pr_generic_notsupp,
596         .pru_peeraddr = key_peeraddr,
597         .pru_rcvd =  pr_generic_notsupp,
598         .pru_rcvoob = pr_generic_notsupp,
599         .pru_send = key_send,
600         .pru_sense = pru_sense_null,
601         .pru_shutdown = key_shutdown,
602         .pru_sockaddr = key_sockaddr,
603         .pru_sosend = sosend,
604         .pru_soreceive = soreceive
605 };
606
607 /* sysctl */
608 SYSCTL_NODE(_net, PF_KEY, key, CTLFLAG_RW, 0, "Key Family");
609
610 /*
611  * Definitions of protocols supported in the KEY domain.
612  */
613
614 extern struct domain keydomain;
615
616 struct protosw keysw[] = {
617     {
618         .pr_type = SOCK_RAW,
619         .pr_domain = &keydomain,
620         .pr_protocol = PF_KEY_V2,
621         .pr_flags = PR_ATOMIC|PR_ADDR,
622
623         .pr_input = NULL,
624         .pr_output = key_output,
625         .pr_ctlinput = raw_ctlinput,
626         .pr_ctloutput = NULL,
627
628         .pr_ctlport = cpu0_ctlport,
629         .pr_init = raw_init,
630         .pr_usrreqs = &key_usrreqs
631     }
632 };
633
634 struct domain keydomain = {
635         PF_KEY, "key", key_init, NULL, NULL,
636         keysw, &keysw[NELEM(keysw)],
637 };
638
639 DOMAIN_SET(key);