a76df738020d307b6a67d5bd5b2af58cf7c647c9
[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
50 #include <sys/thread2.h>
51 #include <sys/msgport2.h>
52
53 #include <net/raw_cb.h>
54 #include <net/route.h>
55 #include <net/netmsg.h>
56 #include <netinet/in.h>
57
58 #include <net/pfkeyv2.h>
59 #include <net/netmsg2.h>
60
61 #include "keydb.h"
62 #include "key.h"
63 #include "keysock.h"
64 #include "key_debug.h"
65
66 #include <machine/stdarg.h>
67
68 struct sockaddr key_dst = { 2, PF_KEY, };
69 struct sockaddr key_src = { 2, PF_KEY, };
70
71 static int key_sendup0 (struct rawcb *, struct mbuf *, int);
72
73 struct pfkeystat pfkeystat;
74
75 /*
76  * key_output()
77  */
78 int
79 key_output(struct mbuf *m, struct socket *so, ...)
80 {
81         struct sadb_msg *msg;
82         int len, error = 0;
83
84         if (m == 0)
85                 panic("key_output: NULL pointer was passed.\n");
86
87         pfkeystat.out_total++;
88         pfkeystat.out_bytes += m->m_pkthdr.len;
89
90         len = m->m_pkthdr.len;
91         if (len < sizeof(struct sadb_msg)) {
92                 pfkeystat.out_tooshort++;
93                 error = EINVAL;
94                 goto end;
95         }
96
97         if (m->m_len < sizeof(struct sadb_msg)) {
98                 if ((m = m_pullup(m, sizeof(struct sadb_msg))) == 0) {
99                         pfkeystat.out_nomem++;
100                         error = ENOBUFS;
101                         goto end;
102                 }
103         }
104
105         if ((m->m_flags & M_PKTHDR) == 0)
106                 panic("key_output: not M_PKTHDR ??");
107
108         KEYDEBUG(KEYDEBUG_KEY_DUMP, kdebug_mbuf(m));
109
110         msg = mtod(m, struct sadb_msg *);
111         pfkeystat.out_msgtype[msg->sadb_msg_type]++;
112         if (len != PFKEY_UNUNIT64(msg->sadb_msg_len)) {
113                 pfkeystat.out_invlen++;
114                 error = EINVAL;
115                 goto end;
116         }
117
118         /*XXX giant lock*/
119         lwkt_gettoken(&key_token);
120         error = key_parse(m, so);
121         m = NULL;
122         lwkt_reltoken(&key_token);
123 end:
124         if (m)
125                 m_freem(m);
126         return error;
127 }
128
129 /*
130  * send message to the socket.
131  */
132 static int
133 key_sendup0(struct rawcb *rp, struct mbuf *m, int promisc)
134 {
135         int error;
136
137         if (promisc) {
138                 struct sadb_msg *pmsg;
139
140                 M_PREPEND(m, sizeof(struct sadb_msg), MB_DONTWAIT);
141                 if (m && m->m_len < sizeof(struct sadb_msg))
142                         m = m_pullup(m, sizeof(struct sadb_msg));
143                 if (!m) {
144                         pfkeystat.in_nomem++;
145                         m_freem(m);
146                         return ENOBUFS;
147                 }
148                 m->m_pkthdr.len += sizeof(*pmsg);
149
150                 pmsg = mtod(m, struct sadb_msg *);
151                 bzero(pmsg, sizeof(*pmsg));
152                 pmsg->sadb_msg_version = PF_KEY_V2;
153                 pmsg->sadb_msg_type = SADB_X_PROMISC;
154                 pmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
155                 /* pid and seq? */
156
157                 pfkeystat.in_msgtype[pmsg->sadb_msg_type]++;
158         }
159
160         lwkt_gettoken(&key_token);
161         if (!ssb_appendaddr(&rp->rcb_socket->so_rcv,
162                             (struct sockaddr *)&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 == 0 || msg == 0)
189                 panic("key_sendup: NULL pointer was passed.\n");
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, MB_DONTWAIT, MT_DATA);
217                         n->m_len = MHLEN;
218                 } else {
219                         MGET(n, MB_DONTWAIT, 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, MB_DONTWAIT);
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.\n");
273         if (so == NULL && target == KEY_SENDUP_ONE)
274                 panic("key_sendup_mbuf: NULL pointer was passed.\n");
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) != 0) {
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
418         netmsg_init(&smsg.base, so, &netisr_adone_rport, 0,
419                     raw_usrreqs.pru_attach);
420         smsg.base.lmsg.ms_flags &= ~(MSGF_REPLY | MSGF_DONE);
421         smsg.base.lmsg.ms_flags |= MSGF_SYNC;
422         smsg.nm_proto = proto;
423         smsg.nm_ai = ai;
424         raw_usrreqs.pru_attach((netmsg_t)&smsg);
425         error = smsg.base.lmsg.ms_error;
426
427         kp = (struct keycb *)sotorawcb(so);
428         if (error) {
429                 kfree(kp, M_PCB);
430                 so->so_pcb = (caddr_t) 0;
431                 lwkt_reltoken(&key_token);
432                 goto out;
433         }
434
435         kp->kp_promisc = kp->kp_registered = 0;
436
437         if (kp->kp_raw.rcb_proto.sp_protocol == PF_KEY) /* XXX: AF_KEY */
438                 key_cb.key_count++;
439         key_cb.any_count++;
440         kp->kp_raw.rcb_laddr = &key_src;
441         kp->kp_raw.rcb_faddr = &key_dst;
442         soisconnected(so);
443         so->so_options |= SO_USELOOPBACK;
444
445         lwkt_reltoken(&key_token);
446         error = 0;
447 out:
448         lwkt_replymsg(&msg->attach.base.lmsg, error);
449 }
450
451 /*
452  * key_bind()
453  * derived from net/rtsock.c:rts_bind()
454  */
455 static void
456 key_bind(netmsg_t msg)
457 {
458         lwkt_gettoken(&key_token);
459
460         raw_usrreqs.pru_bind(msg); /* xxx just EINVAL */
461         /* msg invalid now */
462
463         lwkt_reltoken(&key_token);
464 }
465
466 /*
467  * key_connect()
468  * derived from net/rtsock.c:rts_connect()
469  */
470 static void
471 key_connect(netmsg_t msg)
472 {
473         lwkt_gettoken(&key_token);
474
475         raw_usrreqs.pru_connect(msg); /* XXX just EINVAL */
476         /* msg invalid now */
477
478         lwkt_reltoken(&key_token);
479 }
480
481 /*
482  * key_detach()
483  * derived from net/rtsock.c:rts_detach()
484  */
485 static void
486 key_detach(netmsg_t msg)
487 {
488         struct socket *so = msg->detach.base.nm_so;
489         struct keycb *kp = (struct keycb *)sotorawcb(so);
490
491         lwkt_gettoken(&key_token);
492
493         if (kp != NULL) {
494                 if (kp->kp_raw.rcb_proto.sp_protocol == PF_KEY) {
495                         /* XXX: AF_KEY */
496                         key_cb.key_count--;
497                 }
498                 key_cb.any_count--;
499
500                 key_freereg(so);
501         }
502         raw_usrreqs.pru_detach(msg);
503         /* msg invalid now */
504
505         lwkt_reltoken(&key_token);
506 }
507
508 /*
509  * key_disconnect()
510  * derived from net/rtsock.c:key_disconnect()
511  */
512 static void
513 key_disconnect(netmsg_t msg)
514 {
515         lwkt_gettoken(&key_token);
516
517         raw_usrreqs.pru_disconnect(msg);
518         /* msg invalid now */
519
520         lwkt_reltoken(&key_token);
521 }
522
523 /*
524  * key_peeraddr()
525  * derived from net/rtsock.c:rts_peeraddr()
526  */
527 static void
528 key_peeraddr(netmsg_t msg)
529 {
530         lwkt_gettoken(&key_token);
531
532         raw_usrreqs.pru_peeraddr(msg);
533         /* msg invalid now */
534
535         lwkt_reltoken(&key_token);
536 }
537
538 /*
539  * key_send()
540  * derived from net/rtsock.c:rts_send()
541  */
542 static void
543 key_send(netmsg_t msg)
544 {
545         lwkt_gettoken(&key_token);
546
547         raw_usrreqs.pru_send(msg);
548         /* msg invalid now */
549
550         lwkt_reltoken(&key_token);
551 }
552
553 /*
554  * key_shutdown()
555  * derived from net/rtsock.c:rts_shutdown()
556  */
557 static void
558 key_shutdown(netmsg_t msg)
559 {
560         lwkt_gettoken(&key_token);
561
562         raw_usrreqs.pru_shutdown(msg);
563         /* msg invalid now */
564
565         lwkt_reltoken(&key_token);
566 }
567
568 /*
569  * key_sockaddr()
570  * derived from net/rtsock.c:rts_sockaddr()
571  */
572 static void
573 key_sockaddr(netmsg_t msg)
574 {
575         lwkt_gettoken(&key_token);
576
577         raw_usrreqs.pru_sockaddr(msg);
578         /* msg invalid now */
579
580         lwkt_reltoken(&key_token);
581 }
582
583 struct pr_usrreqs key_usrreqs = {
584         .pru_abort = key_abort,
585         .pru_accept = pr_generic_notsupp,
586         .pru_attach = key_attach,
587         .pru_bind = key_bind,
588         .pru_connect = key_connect,
589         .pru_connect2 = pr_generic_notsupp,
590         .pru_control = pr_generic_notsupp,
591         .pru_detach = key_detach,
592         .pru_disconnect = key_disconnect,
593         .pru_listen = pr_generic_notsupp,
594         .pru_peeraddr = key_peeraddr,
595         .pru_rcvd =  pr_generic_notsupp,
596         .pru_rcvoob = pr_generic_notsupp,
597         .pru_send = key_send,
598         .pru_sense = pru_sense_null,
599         .pru_shutdown = key_shutdown,
600         .pru_sockaddr = key_sockaddr,
601         .pru_sosend = sosend,
602         .pru_soreceive = soreceive
603 };
604
605 /* sysctl */
606 SYSCTL_NODE(_net, PF_KEY, key, CTLFLAG_RW, 0, "Key Family");
607
608 /*
609  * Definitions of protocols supported in the KEY domain.
610  */
611
612 extern struct domain keydomain;
613
614 struct protosw keysw[] = {
615     {
616         .pr_type = SOCK_RAW,
617         .pr_domain = &keydomain,
618         .pr_protocol = PF_KEY_V2,
619         .pr_flags = PR_ATOMIC|PR_ADDR,
620
621         .pr_input = NULL,
622         .pr_output = key_output,
623         .pr_ctlinput = raw_ctlinput,
624         .pr_ctloutput = NULL,
625
626         .pr_ctlport = cpu0_ctlport,
627         .pr_init = raw_init,
628         .pr_usrreqs = &key_usrreqs
629     }
630 };
631
632 struct domain keydomain = {
633         PF_KEY, "key", key_init, NULL, NULL,
634         keysw, &keysw[NELEM(keysw)],
635 };
636
637 DOMAIN_SET(key);