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