Commit untouched SCTP files from KAME originally written by Randall Stewart.
[dragonfly.git] / sys / netinet / sctp_pcb.c
1 /*      $KAME: sctp_pcb.c,v 1.37 2004/08/17 06:28:02 t-momose Exp $     */
2 /*      $DragonFly: src/sys/netinet/sctp_pcb.c,v 1.1 2005/07/15 14:46:17 eirikn Exp $   */
3
4 /*
5  * Copyright (c) 2001, 2002, 2003, 2004 Cisco Systems, Inc.
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. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgement:
18  *      This product includes software developed by Cisco Systems, Inc.
19  * 4. Neither the name of the project nor the names of its contributors
20  *    may be used to endorse or promote products derived from this software
21  *    without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY CISCO SYSTEMS AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL CISCO SYSTEMS OR CONTRIBUTORS BE LIABLE
27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  */
35 #if !(defined(__OpenBSD__) || defined(__APPLE__))
36 #include "opt_ipsec.h"
37 #endif
38 #if defined(__FreeBSD__)
39 #include "opt_compat.h"
40 #include "opt_inet6.h"
41 #include "opt_inet.h"
42 #endif
43 #if defined(__NetBSD__)
44 #include "opt_inet.h"
45 #endif
46 #ifdef __APPLE__
47 #include <sctp.h>
48 #elif !defined(__OpenBSD__)
49 #include "opt_sctp.h"
50 #endif
51
52 #include <sys/param.h>
53 #include <sys/systm.h>
54 #include <sys/malloc.h>
55 #include <sys/mbuf.h>
56 #include <sys/domain.h>
57 #include <sys/protosw.h>
58 #include <sys/socket.h>
59 #include <sys/socketvar.h>
60 #include <sys/proc.h>
61 #include <sys/kernel.h>
62 #include <sys/sysctl.h>
63 #if defined(__FreeBSD__) || defined(__APPLE__)
64 #include <sys/random.h>
65 #endif
66 #if defined(__NetBSD__)
67 #include <sys/rnd.h>
68 #endif
69 #if defined(__OpenBSD__)
70 #include <dev/rndvar.h>
71 #endif
72
73 #if defined(__APPLE__)
74 #include <netinet/sctp_callout.h>
75 #elif defined(__OpenBSD__)
76 #include <sys/timeout.h>
77 #else
78 #include <sys/callout.h>
79 #endif
80
81 #if (defined(__FreeBSD__) && __FreeBSD_version >= 500000)
82 #include <sys/limits.h>
83 #else
84 #include <machine/limits.h>
85 #endif
86 #include <machine/cpu.h>
87
88 #include <net/if.h>
89 #include <net/if_types.h>
90 #include <net/route.h>
91 #include <netinet/in.h>
92 #include <netinet/in_systm.h>
93 #include <netinet/ip.h>
94 #include <netinet/in_pcb.h>
95 #include <netinet/in_var.h>
96 #include <netinet/ip_var.h>
97
98 #ifdef INET6
99 #include <netinet/ip6.h>
100 #include <netinet6/ip6_var.h>
101 #include <netinet6/scope6_var.h>
102 #if defined(__FreeBSD__) || (__NetBSD__)
103 #include <netinet6/in6_pcb.h>
104 #elif defined(__OpenBSD__)
105 #include <netinet/in_pcb.h>
106 #endif
107 #endif /* INET6 */
108
109 #ifdef IPSEC
110 #ifndef __OpenBSD__
111 #include <netinet6/ipsec.h>
112 #include <netkey/key.h>
113 #else
114 #undef IPSEC
115 #endif
116 #endif /* IPSEC */
117
118 #include <netinet/sctp_var.h>
119 #include <netinet/sctp_pcb.h>
120 #include <netinet/sctputil.h>
121 #include <netinet/sctp.h>
122 #include <netinet/sctp_header.h>
123 #include <netinet/sctp_asconf.h>
124 #include <netinet/sctp_output.h>
125 #include <netinet/sctp_timer.h>
126
127 #ifndef SCTP_PCBHASHSIZE
128 /* default number of association hash buckets in each endpoint */
129 #define SCTP_PCBHASHSIZE 256
130 #endif
131
132 #ifdef SCTP_DEBUG
133 u_int32_t sctp_debug_on = 0;
134 #endif /* SCTP_DEBUG */
135
136 u_int32_t sctp_pegs[SCTP_NUMBER_OF_PEGS];
137
138 int sctp_pcbtblsize = SCTP_PCBHASHSIZE;
139
140 struct sctp_epinfo sctppcbinfo;
141
142 /* FIX: we don't handle multiple link local scopes */
143 /* "scopeless" replacement IN6_ARE_ADDR_EQUAL */
144 int
145 SCTP6_ARE_ADDR_EQUAL(struct in6_addr *a, struct in6_addr *b)
146 {
147         struct in6_addr tmp_a, tmp_b;
148         /* use a copy of a and b */
149         tmp_a = *a;
150         tmp_b = *b;
151         in6_clearscope(&tmp_a);
152         in6_clearscope(&tmp_b);
153         return (IN6_ARE_ADDR_EQUAL(&tmp_a, &tmp_b));
154 }
155
156 #ifdef __OpenBSD__
157 extern int ipport_firstauto;
158 extern int ipport_lastauto;
159 extern int ipport_hifirstauto;
160 extern int ipport_hilastauto;
161 #endif
162
163 #if defined(__FreeBSD__) && __FreeBSD_version > 500000
164
165 #ifndef xyzzy
166 void sctp_validate_no_locks(void);
167
168 void
169 SCTP_INP_RLOCK(struct sctp_inpcb *inp)
170 {
171         struct sctp_tcb *stcb;
172         LIST_FOREACH(stcb, &inp->sctp_asoc_list, sctp_tcblist) {
173                 if (mtx_owned(&(stcb)->tcb_mtx))
174                         panic("I own TCB lock?");
175         }
176         if (mtx_owned(&(inp)->inp_mtx))
177                 panic("INP Recursive Lock-R");
178         mtx_lock(&(inp)->inp_mtx);
179 }
180
181 void
182 SCTP_INP_WLOCK(struct sctp_inpcb *inp)
183 {
184         SCTP_INP_RLOCK(inp);
185 }
186
187 void
188 SCTP_INP_INFO_RLOCK()
189 {
190         struct sctp_inpcb *inp;
191         struct sctp_tcb *stcb;
192         LIST_FOREACH(inp, &sctppcbinfo.listhead, sctp_list) {
193                 if (mtx_owned(&(inp)->inp_mtx))
194                         panic("info-lock and own inp lock?");
195                 LIST_FOREACH(stcb, &inp->sctp_asoc_list, sctp_tcblist) {
196                         if (mtx_owned(&(stcb)->tcb_mtx))
197                                 panic("Info lock and own a tcb lock?");
198                 }
199         }
200         if (mtx_owned(&sctppcbinfo.ipi_ep_mtx))
201                 panic("INP INFO Recursive Lock-R");
202         mtx_lock(&sctppcbinfo.ipi_ep_mtx);
203 }
204
205 void
206 SCTP_INP_INFO_WLOCK()
207 {
208         SCTP_INP_INFO_RLOCK();
209 }
210
211
212 void sctp_validate_no_locks()
213 {
214         struct sctp_inpcb *inp;
215         struct sctp_tcb *stcb;
216
217         if (mtx_owned(&sctppcbinfo.ipi_ep_mtx))
218                 panic("INP INFO lock is owned?");
219
220         LIST_FOREACH(inp, &sctppcbinfo.listhead, sctp_list) {
221                 if (mtx_owned(&(inp)->inp_mtx))
222                         panic("You own an INP lock?");
223                 LIST_FOREACH(stcb, &inp->sctp_asoc_list, sctp_tcblist) {
224                         if (mtx_owned(&(stcb)->tcb_mtx))
225                                 panic("You own a TCB lock?");
226                 }
227         }
228 }
229
230 #endif
231 #endif
232
233 void
234 sctp_fill_pcbinfo(struct sctp_pcbinfo *spcb)
235 {
236         /* We really don't need
237          * to lock this, but I will
238          * just because it does not hurt.
239          */
240         SCTP_INP_INFO_RLOCK();
241         spcb->ep_count = sctppcbinfo.ipi_count_ep;
242         spcb->asoc_count = sctppcbinfo.ipi_count_asoc;
243         spcb->laddr_count = sctppcbinfo.ipi_count_laddr;
244         spcb->raddr_count = sctppcbinfo.ipi_count_raddr;
245         spcb->chk_count = sctppcbinfo.ipi_count_chunk;
246         spcb->sockq_count = sctppcbinfo.ipi_count_sockq;
247         spcb->mbuf_track = sctppcbinfo.mbuf_track;
248         SCTP_INP_INFO_RUNLOCK();
249 }
250
251
252 /*
253  * Notes on locks for FreeBSD 5 and up. All association
254  * lookups that have a definte ep, the INP structure is
255  * assumed to be locked for reading. If we need to go
256  * find the INP (ususally when a **inp is passed) then
257  * we must lock the INFO structure first and if needed
258  * lock the INP too. Note that if we lock it we must
259  *
260  */
261
262
263 /*
264  * Given a endpoint, look and find in its association list any association
265  * with the "to" address given. This can be a "from" address, too, for
266  * inbound packets. For outbound packets it is a true "to" address.
267  */
268 static struct sctp_tcb *
269 sctp_tcb_special_locate(struct sctp_inpcb **inp_p, struct sockaddr *from,
270                         struct sockaddr *to, struct sctp_nets **netp)
271 {
272         /**** ASSUMSES THE CALLER holds the INP_INFO_RLOCK */
273
274         /*
275          * Note for this module care must be taken when observing what to is
276          * for. In most of the rest of the code the TO field represents my
277          * peer and the FROM field represents my address. For this module it
278          * is reversed of that.
279          */
280         /*
281          * If we support the TCP model, then we must now dig through to
282          * see if we can find our endpoint in the list of tcp ep's.
283          */
284         uint16_t lport, rport;
285         struct sctppcbhead *ephead;
286         struct sctp_inpcb *inp;
287         struct sctp_laddr *laddr;
288         struct sctp_tcb *stcb;
289         struct sctp_nets *net;
290
291         if ((to == NULL) || (from == NULL)) {
292                 return (NULL);
293         }
294
295         if (to->sa_family == AF_INET && from->sa_family == AF_INET) {
296                 lport = ((struct sockaddr_in *)to)->sin_port;
297                 rport = ((struct sockaddr_in *)from)->sin_port;
298         } else if (to->sa_family == AF_INET6 && from->sa_family == AF_INET6) {
299                 lport = ((struct sockaddr_in6 *)to)->sin6_port;
300                 rport = ((struct sockaddr_in6 *)from)->sin6_port;
301         } else {
302                 return NULL;
303         }
304         ephead = &sctppcbinfo.sctp_tcpephash[SCTP_PCBHASH_ALLADDR(
305                                                      (lport + rport), sctppcbinfo.hashtcpmark)];
306         /*
307          * Ok now for each of the guys in this bucket we must look
308          * and see:
309          *  - Does the remote port match.
310          *  - Does there single association's addresses match this
311          *    address (to).
312          * If so we update p_ep to point to this ep and return the
313          * tcb from it.
314          */
315         LIST_FOREACH(inp, ephead, sctp_hash) {
316                 if (lport != inp->sctp_lport) {
317                         continue;
318                 }
319                 SCTP_INP_RLOCK(inp);
320                 /* check to see if the ep has one of the addresses */
321                 if ((inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) == 0) {
322                         /* We are NOT bound all, so look further */
323                         int match = 0;
324
325                         LIST_FOREACH(laddr, &inp->sctp_addr_list, sctp_nxt_addr) {
326                                 if (laddr->ifa == NULL) {
327 #ifdef SCTP_DEBUG
328                                         if (sctp_debug_on & SCTP_DEBUG_PCB1) {
329                                                 printf("An ounce of prevention is worth a pound of cure\n");
330                                         }
331 #endif
332                                         continue;
333                                 }
334                                 if (laddr->ifa->ifa_addr == NULL) {
335 #ifdef SCTP_DEBUG
336                                         if (sctp_debug_on & SCTP_DEBUG_PCB1) {
337                                                 printf("ifa with a NULL address\n");
338                                         }
339 #endif
340                                         continue;
341                                 }
342                                 if (laddr->ifa->ifa_addr->sa_family ==
343                                     to->sa_family) {
344                                         /* see if it matches */
345                                         struct sockaddr_in *intf_addr, *sin;
346                                         intf_addr = (struct sockaddr_in *)
347                                                 laddr->ifa->ifa_addr;
348                                         sin = (struct sockaddr_in *)to;
349                                         if (from->sa_family == AF_INET) {
350                                                 if (sin->sin_addr.s_addr ==
351                                                     intf_addr->sin_addr.s_addr) {
352                                                         match = 1;
353                                                         SCTP_INP_RUNLOCK(inp);
354                                                         break;
355                                                 }
356                                         } else {
357                                                 struct sockaddr_in6 *intf_addr6;
358                                                 struct sockaddr_in6 *sin6;
359                                                 sin6 = (struct sockaddr_in6 *)
360                                                         to;
361                                                 intf_addr6 = (struct sockaddr_in6 *)
362                                                         laddr->ifa->ifa_addr;
363
364                                                 if (SCTP6_ARE_ADDR_EQUAL(&sin6->sin6_addr,
365                                                                          &intf_addr6->sin6_addr)) {
366                                                         match = 1;
367                                                         SCTP_INP_RUNLOCK(inp);
368                                                         break;
369                                                 }
370                                         }
371                                 }
372                         }
373                         if (match == 0) {
374                                 /* This endpoint does not have this address */
375                                 SCTP_INP_RUNLOCK(inp);
376                                 continue;
377                         }
378                 }
379                 /*
380                  * Ok if we hit here the ep has the address, does it hold the
381                  * tcb?
382                  */
383
384                 stcb = LIST_FIRST(&inp->sctp_asoc_list);
385                 if (stcb == NULL) {
386                         SCTP_INP_RUNLOCK(inp);
387                         continue;
388                 }
389                 SCTP_TCB_LOCK(stcb);
390                 if (stcb->rport != rport) {
391                         /* remote port does not match. */
392                         SCTP_TCB_UNLOCK(stcb);
393                         SCTP_INP_RUNLOCK(inp);
394                         continue;
395                 }
396                 /* Does this TCB have a matching address? */
397                 TAILQ_FOREACH(net, &stcb->asoc.nets, sctp_next) {
398                         if (net->ro._l_addr.sa.sa_family != from->sa_family) {
399                                 /* not the same family, can't be a match */
400                                 continue;
401                         }
402                         if (from->sa_family == AF_INET) {
403                                 struct sockaddr_in *sin, *rsin;
404                                 sin = (struct sockaddr_in *)&net->ro._l_addr;
405                                 rsin = (struct sockaddr_in *)from;
406                                 if (sin->sin_addr.s_addr ==
407                                     rsin->sin_addr.s_addr) {
408                                         /* found it */
409                                         if (netp != NULL) {
410                                                 *netp = net;
411                                         }
412                                         /* Update the endpoint pointer */
413                                         *inp_p = inp;
414                                         SCTP_INP_RUNLOCK(inp);
415                                         return (stcb);
416                                 }
417                         } else {
418                                 struct sockaddr_in6 *sin6, *rsin6;
419                                 sin6 = (struct sockaddr_in6 *)&net->ro._l_addr;
420                                 rsin6 = (struct sockaddr_in6 *)from;
421                                 if (SCTP6_ARE_ADDR_EQUAL(&sin6->sin6_addr,
422                                                          &rsin6->sin6_addr)) {
423                                         /* found it */
424                                         if (netp != NULL) {
425                                                 *netp = net;
426                                         }
427                                         /* Update the endpoint pointer */
428                                         *inp_p = inp;
429                                         SCTP_INP_RUNLOCK(inp);
430                                         return (stcb);
431                                 }
432                         }
433                 }
434                 SCTP_TCB_UNLOCK(stcb);
435
436                 SCTP_INP_RUNLOCK(inp);
437         }
438         return (NULL);
439 }
440
441 struct sctp_tcb *
442 sctp_findassociation_ep_asconf(struct mbuf *m, int iphlen, int offset,
443     struct sctphdr *sh, struct sctp_inpcb **inp_p, struct sctp_nets **netp)
444 {
445         struct sctp_tcb *stcb;
446         struct sockaddr_in *sin;
447         struct sockaddr_in6 *sin6;
448         struct sockaddr_storage local_store, remote_store;
449         struct ip *iph;
450         struct sctp_paramhdr parm_buf, *phdr;
451         int ptype;
452
453         memset(&local_store, 0, sizeof(local_store));
454         memset(&remote_store, 0, sizeof(remote_store));
455
456         /* First get the destination address setup too. */
457         iph = mtod(m, struct ip *);
458         if (iph->ip_v == IPVERSION) {
459                 /* its IPv4 */
460                 sin = (struct sockaddr_in *)&local_store;
461                 sin->sin_family = AF_INET;
462                 sin->sin_len = sizeof(*sin);
463                 sin->sin_port = sh->dest_port;
464                 sin->sin_addr.s_addr = iph->ip_dst.s_addr ;
465         } else if (iph->ip_v == (IPV6_VERSION >> 4)) {
466                 /* its IPv6 */
467                 struct ip6_hdr *ip6;
468                 ip6 = mtod(m, struct ip6_hdr *);
469                 sin6 = (struct sockaddr_in6 *)&local_store;
470                 sin6->sin6_family = AF_INET6;
471                 sin6->sin6_len = sizeof(*sin6);
472                 sin6->sin6_port = sh->dest_port;
473                 sin6->sin6_addr = ip6->ip6_dst;
474         } else {
475                 return NULL;
476         }
477
478         phdr = sctp_get_next_param(m, offset + sizeof(struct sctp_asconf_chunk),
479             &parm_buf, sizeof(struct sctp_paramhdr));
480         if (phdr == NULL) {
481 #ifdef SCTP_DEBUG
482                 if (sctp_debug_on & SCTP_DEBUG_INPUT3) {
483                         printf("sctp_process_control: failed to get asconf lookup addr\n");
484                 }
485 #endif /* SCTP_DEBUG */
486                 return NULL;
487         }
488         ptype = (int)((u_int)ntohs(phdr->param_type));
489         /* get the correlation address */
490         if (ptype == SCTP_IPV6_ADDRESS) {
491                 /* ipv6 address param */
492                 struct sctp_ipv6addr_param *p6, p6_buf;
493                 if (ntohs(phdr->param_length) != sizeof(struct sctp_ipv6addr_param)) {
494                         return NULL;
495                 }
496
497                 p6 = (struct sctp_ipv6addr_param *)sctp_get_next_param(m,
498                     offset + sizeof(struct sctp_asconf_chunk),
499                     &p6_buf.ph, sizeof(*p6));
500                 if (p6 == NULL) {
501 #ifdef SCTP_DEBUG
502                         if (sctp_debug_on & SCTP_DEBUG_INPUT3) {
503                                 printf("sctp_process_control: failed to get asconf v6 lookup addr\n");
504                         }
505 #endif /* SCTP_DEBUG */
506                         return (NULL);
507                 }
508                 sin6 = (struct sockaddr_in6 *)&remote_store;
509                 sin6->sin6_family = AF_INET6;
510                 sin6->sin6_len = sizeof(*sin6);
511                 sin6->sin6_port = sh->src_port;
512                 memcpy(&sin6->sin6_addr, &p6->addr, sizeof(struct in6_addr));
513         } else if (ptype == SCTP_IPV4_ADDRESS) {
514                 /* ipv4 address param */
515                 struct sctp_ipv4addr_param *p4, p4_buf;
516                 if (ntohs(phdr->param_length) != sizeof(struct sctp_ipv4addr_param)) {
517                         return NULL;
518                 }
519
520                 p4 = (struct sctp_ipv4addr_param *)sctp_get_next_param(m,
521                     offset + sizeof(struct sctp_asconf_chunk),
522                     &p4_buf.ph, sizeof(*p4));
523                 if (p4 == NULL) {
524 #ifdef SCTP_DEBUG
525                         if (sctp_debug_on & SCTP_DEBUG_INPUT3) {
526                                 printf("sctp_process_control: failed to get asconf v4 lookup addr\n");
527                         }
528 #endif /* SCTP_DEBUG */
529                         return (NULL);
530                 }
531                 sin = (struct sockaddr_in *)&remote_store;
532                 sin->sin_family = AF_INET;
533                 sin->sin_len = sizeof(*sin);
534                 sin->sin_port = sh->src_port;
535                 memcpy(&sin->sin_addr, &p4->addr, sizeof(struct in_addr));
536         } else {
537                 /* invalid address param type */
538                 return NULL;
539         }
540
541         stcb = sctp_findassociation_ep_addr(inp_p,
542             (struct sockaddr *)&remote_store, netp,
543             (struct sockaddr *)&local_store, NULL);
544         return (stcb);
545 }
546
547 struct sctp_tcb *
548 sctp_findassociation_ep_addr(struct sctp_inpcb **inp_p, struct sockaddr *remote,
549     struct sctp_nets **netp, struct sockaddr *local, struct sctp_tcb *locked_tcb)
550 {
551         struct sctpasochead *head;
552         struct sctp_inpcb *inp;
553         struct sctp_tcb *stcb;
554         struct sctp_nets *net;
555         uint16_t rport;
556
557         inp = *inp_p;
558         if (remote->sa_family == AF_INET) {
559                 rport = (((struct sockaddr_in *)remote)->sin_port);
560         } else if (remote->sa_family == AF_INET6) {
561                 rport = (((struct sockaddr_in6 *)remote)->sin6_port);
562         } else {
563                 return (NULL);
564         }
565         if (locked_tcb) {
566                 /* UN-lock so we can do proper locking here
567                  * this occurs when called from load_addresses_from_init.
568                  */
569                 SCTP_TCB_UNLOCK(locked_tcb);
570         }
571         SCTP_INP_INFO_RLOCK();
572         if (inp->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE) {
573                 /*
574                  * Now either this guy is our listner or it's the connector.
575                  * If it is the one that issued the connect, then it's only
576                  * chance is to be the first TCB in the list. If it is the
577                  * acceptor, then do the special_lookup to hash and find the
578                  * real inp.
579                  */
580                 if (inp->sctp_flags & SCTP_PCB_FLAGS_ACCEPTING) {
581                         /* to is peer addr, from is my addr */
582                         stcb = sctp_tcb_special_locate(inp_p, remote, local,
583                                                        netp);
584                         if ((stcb != NULL) && (locked_tcb == NULL)){
585                                 /* we have a locked tcb, lower refcount */
586                                 SCTP_INP_WLOCK(inp);
587                                 SCTP_INP_DECR_REF(inp);
588                                 SCTP_INP_WUNLOCK(inp);
589                         }
590                         if (locked_tcb != NULL) {
591                                 SCTP_INP_RLOCK(locked_tcb->sctp_ep);
592                                 SCTP_TCB_LOCK(locked_tcb);
593                                 SCTP_INP_RUNLOCK(locked_tcb->sctp_ep);
594                                 if (stcb != NULL)
595                                         SCTP_TCB_UNLOCK(stcb);
596                         }
597                         SCTP_INP_INFO_RUNLOCK();
598                         return (stcb);
599                 } else {
600                         SCTP_INP_WLOCK(inp);
601                         stcb = LIST_FIRST(&inp->sctp_asoc_list);
602                         if (stcb == NULL) {
603                                 goto null_return;
604                         }
605                         SCTP_TCB_LOCK(stcb);
606                         if (stcb->rport != rport) {
607                                 /* remote port does not match. */
608                                 SCTP_TCB_UNLOCK(stcb);
609                                 goto null_return;
610                         }
611                         /* now look at the list of remote addresses */
612                         TAILQ_FOREACH(net, &stcb->asoc.nets, sctp_next) {
613                                 if (net->ro._l_addr.sa.sa_family !=
614                                     remote->sa_family) {
615                                         /* not the same family */
616                                         continue;
617                                 }
618                                 if (remote->sa_family == AF_INET) {
619                                         struct sockaddr_in *sin, *rsin;
620                                         sin = (struct sockaddr_in *)
621                                                 &net->ro._l_addr;
622                                         rsin = (struct sockaddr_in *)remote;
623                                         if (sin->sin_addr.s_addr ==
624                                             rsin->sin_addr.s_addr) {
625                                                 /* found it */
626                                                 if (netp != NULL) {
627                                                         *netp = net;
628                                                 }
629                                                 if (locked_tcb == NULL) {
630                                                         SCTP_INP_DECR_REF(inp);
631                                                 }
632                                                 SCTP_INP_WUNLOCK(inp);
633                                                 SCTP_INP_INFO_RUNLOCK();
634                                                 return (stcb);
635                                         }
636                                 } else if (remote->sa_family == AF_INET6) {
637                                         struct sockaddr_in6 *sin6, *rsin6;
638                                         sin6 = (struct sockaddr_in6 *)&net->ro._l_addr;
639                                         rsin6 = (struct sockaddr_in6 *)remote;
640                                         if (SCTP6_ARE_ADDR_EQUAL(&sin6->sin6_addr,
641                                                                  &rsin6->sin6_addr)) {
642                                                 /* found it */
643                                                 if (netp != NULL) {
644                                                         *netp = net;
645                                                 }
646                                                 if (locked_tcb == NULL) {
647                                                         SCTP_INP_DECR_REF(inp);
648                                                 }
649                                                 SCTP_INP_WUNLOCK(inp);
650                                                 SCTP_INP_INFO_RUNLOCK();
651                                                 return (stcb);
652                                         }
653                                 }
654                         }
655                         SCTP_TCB_UNLOCK(stcb);
656                 }
657         } else {
658                 SCTP_INP_WLOCK(inp);
659                 head = &inp->sctp_tcbhash[SCTP_PCBHASH_ALLADDR(rport,
660                                                                inp->sctp_hashmark)];
661                 if (head == NULL) {
662                         goto null_return;
663                 }
664                 LIST_FOREACH(stcb, head, sctp_tcbhash) {
665                         if (stcb->rport != rport) {
666                                 /* remote port does not match */
667                                 continue;
668                         }
669                         /* now look at the list of remote addresses */
670                         SCTP_TCB_LOCK(stcb);
671                         TAILQ_FOREACH(net, &stcb->asoc.nets, sctp_next) {
672                                 if (net->ro._l_addr.sa.sa_family !=
673                                     remote->sa_family) {
674                                         /* not the same family */
675                                         continue;
676                                 }
677                                 if (remote->sa_family == AF_INET) {
678                                         struct sockaddr_in *sin, *rsin;
679                                         sin = (struct sockaddr_in *)
680                                                 &net->ro._l_addr;
681                                         rsin = (struct sockaddr_in *)remote;
682                                         if (sin->sin_addr.s_addr ==
683                                             rsin->sin_addr.s_addr) {
684                                                 /* found it */
685                                                 if (netp != NULL) {
686                                                         *netp = net;
687                                                 }
688                                                 if (locked_tcb == NULL) {
689                                                         SCTP_INP_DECR_REF(inp);
690                                                 }
691                                                 SCTP_INP_WUNLOCK(inp);
692                                                 SCTP_INP_INFO_RUNLOCK();
693                                                 return (stcb);
694                                         }
695                                 } else if (remote->sa_family == AF_INET6) {
696                                         struct sockaddr_in6 *sin6, *rsin6;
697                                         sin6 = (struct sockaddr_in6 *)
698                                                 &net->ro._l_addr;
699                                         rsin6 = (struct sockaddr_in6 *)remote;
700                                         if (SCTP6_ARE_ADDR_EQUAL(&sin6->sin6_addr,
701                                                                  &rsin6->sin6_addr)) {
702                                                 /* found it */
703                                                 if (netp != NULL) {
704                                                         *netp = net;
705                                                 }
706                                                 if (locked_tcb == NULL) {
707                                                         SCTP_INP_DECR_REF(inp);
708                                                 }
709                                                 SCTP_INP_WUNLOCK(inp);
710                                                 SCTP_INP_INFO_RUNLOCK();
711                                                 return (stcb);
712                                         }
713                                 }
714                         }
715                         SCTP_TCB_UNLOCK(stcb);
716                 }
717         }
718  null_return:
719         /* clean up for returning null */
720         if (locked_tcb){
721                 if (locked_tcb->sctp_ep != inp) {
722                         SCTP_INP_RLOCK(locked_tcb->sctp_ep);
723                         SCTP_TCB_LOCK(locked_tcb);
724                         SCTP_INP_RUNLOCK(locked_tcb->sctp_ep);
725                 } else
726                         SCTP_TCB_LOCK(locked_tcb);
727         }
728         SCTP_INP_WUNLOCK(inp);
729         SCTP_INP_INFO_RUNLOCK();
730         /* not found */
731         return (NULL);
732 }
733
734 /*
735  * Find an association for a specific endpoint using the association id
736  * given out in the COMM_UP notification
737  */
738 struct sctp_tcb *
739 sctp_findassociation_ep_asocid(struct sctp_inpcb *inp, caddr_t asoc_id)
740 {
741         /*
742          * Use my the assoc_id to find a endpoint
743          */
744         struct sctpasochead *head;
745         struct sctp_tcb *stcb;
746         u_int32_t vtag;
747
748         if (asoc_id == 0 || inp == NULL) {
749                 return (NULL);
750         }
751         SCTP_INP_INFO_RLOCK();
752         vtag = (u_int32_t)asoc_id;
753         head = &sctppcbinfo.sctp_asochash[SCTP_PCBHASH_ASOC(vtag,
754             sctppcbinfo.hashasocmark)];
755         if (head == NULL) {
756                 /* invalid vtag */
757                 SCTP_INP_INFO_RUNLOCK();
758                 return (NULL);
759         }
760         LIST_FOREACH(stcb, head, sctp_asocs) {
761                 SCTP_INP_RLOCK(stcb->sctp_ep);
762                 SCTP_TCB_LOCK(stcb);
763                 SCTP_INP_RUNLOCK(stcb->sctp_ep);
764                 if (stcb->asoc.my_vtag == vtag) {
765                         /* candidate */
766                         if (inp != stcb->sctp_ep) {
767                                 /* some other guy has the
768                                  * same vtag active (vtag collision).
769                                  */
770                                 sctp_pegs[SCTP_VTAG_BOGUS]++;
771                                 SCTP_TCB_UNLOCK(stcb);
772                                 continue;
773                         }
774                         sctp_pegs[SCTP_VTAG_EXPR]++;
775                         SCTP_INP_INFO_RUNLOCK();
776                         return (stcb);
777                 }
778                 SCTP_TCB_UNLOCK(stcb);
779         }
780         SCTP_INP_INFO_RUNLOCK();
781         return (NULL);
782 }
783
784 static struct sctp_inpcb *
785 sctp_endpoint_probe(struct sockaddr *nam, struct sctppcbhead *head,
786                     uint16_t lport)
787 {
788         struct sctp_inpcb *inp;
789         struct sockaddr_in *sin;
790         struct sockaddr_in6 *sin6;
791         struct sctp_laddr *laddr;
792
793         /* Endpoing probe expects
794          * that the INP_INFO is locked.
795          */
796         if (nam->sa_family == AF_INET) {
797                 sin = (struct sockaddr_in *)nam;
798                 sin6 = NULL;
799         } else if (nam->sa_family == AF_INET6) {
800                 sin6 = (struct sockaddr_in6 *)nam;
801                 sin = NULL;
802         } else {
803                 /* unsupported family */
804                 return (NULL);
805         }
806         if (head == NULL)
807                 return (NULL);
808
809         LIST_FOREACH(inp, head, sctp_hash) {
810                 SCTP_INP_RLOCK(inp);
811
812                 if ((inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) &&
813                     (inp->sctp_lport == lport)) {
814                         /* got it */
815                         if ((nam->sa_family == AF_INET) &&
816                             (inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) &&
817 #if defined(__FreeBSD__) || defined(__APPLE__)
818                             (((struct inpcb *)inp)->inp_flags & IN6P_IPV6_V6ONLY)
819 #else
820 #if defined(__OpenBSD__)
821                             (0) /* For open bsd we do dual bind only */
822 #else
823                             (((struct in6pcb *)inp)->in6p_flags & IN6P_IPV6_V6ONLY)
824 #endif
825 #endif
826                                 ) {
827                                 /* IPv4 on a IPv6 socket with ONLY IPv6 set */
828                                 SCTP_INP_RUNLOCK(inp);
829                                 continue;
830                         }
831                         /* A V6 address and the endpoint is NOT bound V6 */
832                         if (nam->sa_family == AF_INET6 &&
833                            (inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) == 0) {
834                                 SCTP_INP_RUNLOCK(inp);
835                                 continue;
836                         }
837                         SCTP_INP_RUNLOCK(inp);
838                         return (inp);
839                 }
840                 SCTP_INP_RUNLOCK(inp);
841         }
842
843         if ((nam->sa_family == AF_INET) &&
844             (sin->sin_addr.s_addr == INADDR_ANY)) {
845                 /* Can't hunt for one that has no address specified */
846                 return (NULL);
847         } else if ((nam->sa_family == AF_INET6) &&
848                    (IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr))) {
849                 /* Can't hunt for one that has no address specified */
850                 return (NULL);
851         }
852         /*
853          * ok, not bound to all so see if we can find a EP bound to this
854          * address.
855          */
856 #ifdef SCTP_DEBUG
857         if (sctp_debug_on & SCTP_DEBUG_PCB1) {
858                 printf("Ok, there is NO bound-all available for port:%x\n", ntohs(lport));
859         }
860 #endif
861         LIST_FOREACH(inp, head, sctp_hash) {
862                 SCTP_INP_RLOCK(inp);
863                 if ((inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL)) {
864                         SCTP_INP_RUNLOCK(inp);
865                         continue;
866                 }
867                 /*
868                  * Ok this could be a likely candidate, look at all of
869                  * its addresses
870                  */
871                 if (inp->sctp_lport != lport) {
872                         SCTP_INP_RUNLOCK(inp);
873                         continue;
874                 }
875 #ifdef SCTP_DEBUG
876                 if (sctp_debug_on & SCTP_DEBUG_PCB1) {
877                         printf("Ok, found maching local port\n");
878                 }
879 #endif
880                 LIST_FOREACH(laddr, &inp->sctp_addr_list, sctp_nxt_addr) {
881                         if (laddr->ifa == NULL) {
882 #ifdef SCTP_DEBUG
883                                 if (sctp_debug_on & SCTP_DEBUG_PCB1) {
884                                         printf("An ounce of prevention is worth a pound of cure\n");
885                                 }
886 #endif
887                                 continue;
888                         }
889 #ifdef SCTP_DEBUG
890                         if (sctp_debug_on & SCTP_DEBUG_PCB1) {
891                                 printf("Ok laddr->ifa:%p is possible, ",
892                                     laddr->ifa);
893                         }
894 #endif
895                         if (laddr->ifa->ifa_addr == NULL) {
896 #ifdef SCTP_DEBUG
897                                 if (sctp_debug_on & SCTP_DEBUG_PCB1) {
898                                         printf("Huh IFA as an ifa_addr=NULL, ");
899                                 }
900 #endif
901                                 continue;
902                         }
903 #ifdef SCTP_DEBUG
904                         if (sctp_debug_on & SCTP_DEBUG_PCB1) {
905                                 printf("Ok laddr->ifa:%p is possible, ",
906                                     laddr->ifa->ifa_addr);
907                                 sctp_print_address(laddr->ifa->ifa_addr);
908                                 printf("looking for ");
909                                 sctp_print_address(nam);
910                         }
911 #endif
912                         if (laddr->ifa->ifa_addr->sa_family == nam->sa_family) {
913                                 /* possible, see if it matches */
914                                 struct sockaddr_in *intf_addr;
915                                 intf_addr = (struct sockaddr_in *)
916                                     laddr->ifa->ifa_addr;
917                                 if (nam->sa_family == AF_INET) {
918                                         if (sin->sin_addr.s_addr ==
919                                             intf_addr->sin_addr.s_addr) {
920 #ifdef SCTP_DEBUG
921                                                 if (sctp_debug_on & SCTP_DEBUG_PCB1) {
922                                                         printf("YES, return ep:%p\n", inp);
923                                                 }
924 #endif
925                                                 SCTP_INP_RUNLOCK(inp);
926                                                 return (inp);
927                                         }
928                                 } else if (nam->sa_family == AF_INET6) {
929                                         struct sockaddr_in6 *intf_addr6;
930                                         intf_addr6 = (struct sockaddr_in6 *)
931                                             laddr->ifa->ifa_addr;
932                                         if (SCTP6_ARE_ADDR_EQUAL(&sin6->sin6_addr,
933                                             &intf_addr6->sin6_addr)) {
934 #ifdef SCTP_DEBUG
935                                                 if (sctp_debug_on & SCTP_DEBUG_PCB1) {
936                                                         printf("YES, return ep:%p\n", inp);
937                                                 }
938 #endif
939                                                 SCTP_INP_RUNLOCK(inp);
940                                                 return (inp);
941                                         }
942                                 }
943                         }
944                         SCTP_INP_RUNLOCK(inp);
945                 }
946         }
947 #ifdef SCTP_DEBUG
948         if (sctp_debug_on & SCTP_DEBUG_PCB1) {
949                 printf("NO, Falls out to NULL\n");
950         }
951 #endif
952         return (NULL);
953 }
954
955
956 struct sctp_inpcb *
957 sctp_pcb_findep(struct sockaddr *nam, int find_tcp_pool, int have_lock)
958 {
959         /*
960          * First we check the hash table to see if someone has this port
961          * bound with just the port.
962          */
963         struct sctp_inpcb *inp;
964         struct sctppcbhead *head;
965         struct sockaddr_in *sin;
966         struct sockaddr_in6 *sin6;
967         int lport;
968 #ifdef SCTP_DEBUG
969         if (sctp_debug_on & SCTP_DEBUG_PCB1) {
970                 printf("Looking for endpoint %d :",
971                        ntohs(((struct sockaddr_in *)nam)->sin_port));
972                 sctp_print_address(nam);
973         }
974 #endif
975         if (nam->sa_family == AF_INET) {
976                 sin = (struct sockaddr_in *)nam;
977                 lport = ((struct sockaddr_in *)nam)->sin_port;
978         } else if (nam->sa_family == AF_INET6) {
979                 sin6 = (struct sockaddr_in6 *)nam;
980                 lport = ((struct sockaddr_in6 *)nam)->sin6_port;
981         } else {
982                 /* unsupported family */
983                 return (NULL);
984         }
985         /*
986          * I could cheat here and just cast to one of the types but we will
987          * do it right. It also provides the check against an Unsupported
988          * type too.
989          */
990         /* Find the head of the ALLADDR chain */
991         if (have_lock == 0)
992                 SCTP_INP_INFO_RLOCK();
993         head = &sctppcbinfo.sctp_ephash[SCTP_PCBHASH_ALLADDR(lport,
994                                                              sctppcbinfo.hashmark)];
995 #ifdef SCTP_DEBUG
996         if (sctp_debug_on & SCTP_DEBUG_PCB1) {
997                 printf("Main hash to lookup at head:%p\n", head);
998         }
999 #endif
1000         inp = sctp_endpoint_probe(nam, head, lport);
1001
1002         /*
1003          * If the TCP model exists it could be that the main listening
1004          * endpoint is gone but there exists a connected socket for this
1005          * guy yet. If so we can return the first one that we find. This
1006          * may NOT be the correct one but the sctp_findassociation_ep_addr
1007          * has further code to look at all TCP models.
1008          */
1009         if (inp == NULL && find_tcp_pool) {
1010                 unsigned int i;
1011 #ifdef SCTP_DEBUG
1012                 if (sctp_debug_on & SCTP_DEBUG_PCB1) {
1013                         printf("EP was NULL and TCP model is supported\n");
1014                 }
1015 #endif
1016                 for (i = 0; i < sctppcbinfo.hashtblsize; i++) {
1017                         /*
1018                          * This is real gross, but we do NOT have a remote
1019                          * port at this point depending on who is calling. We
1020                          * must therefore look for ANY one that matches our
1021                          * local port :/
1022                          */
1023                         head = &sctppcbinfo.sctp_tcpephash[i];
1024                         if (LIST_FIRST(head)) {
1025                                 inp = sctp_endpoint_probe(nam, head, lport);
1026                                 if (inp) {
1027                                         /* Found one */
1028                                         break;
1029                                 }
1030                         }
1031                 }
1032         }
1033 #ifdef SCTP_DEBUG
1034         if (sctp_debug_on & SCTP_DEBUG_PCB1) {
1035                 printf("EP to return is %p\n", inp);
1036         }
1037 #endif
1038         if (have_lock == 0) {
1039                 if (inp) {
1040                         SCTP_INP_WLOCK(inp);
1041                         SCTP_INP_INCR_REF(inp);
1042                         SCTP_INP_WUNLOCK(inp);
1043                 }
1044                 SCTP_INP_INFO_RUNLOCK();
1045         } else {
1046                 if (inp) {
1047                         SCTP_INP_WLOCK(inp);
1048                         SCTP_INP_INCR_REF(inp);
1049                         SCTP_INP_WUNLOCK(inp);
1050                 }
1051         }
1052         return (inp);
1053 }
1054
1055 /*
1056  * Find an association for an endpoint with the pointer to whom you want
1057  * to send to and the endpoint pointer. The address can be IPv4 or IPv6.
1058  * We may need to change the *to to some other struct like a mbuf...
1059  */
1060 struct sctp_tcb *
1061 sctp_findassociation_addr_sa(struct sockaddr *to, struct sockaddr *from,
1062     struct sctp_inpcb **inp_p, struct sctp_nets **netp, int find_tcp_pool)
1063 {
1064         struct sctp_inpcb *inp;
1065         struct sctp_tcb *retval;
1066
1067         SCTP_INP_INFO_RLOCK();
1068         if (find_tcp_pool) {
1069                 if (inp_p != NULL) {
1070                         retval = sctp_tcb_special_locate(inp_p, from, to, netp);
1071                 } else {
1072                         retval = sctp_tcb_special_locate(&inp, from, to, netp);
1073                 }
1074                 if (retval != NULL) {
1075                         SCTP_INP_INFO_RUNLOCK();
1076                         return (retval);
1077                 }
1078         }
1079         inp = sctp_pcb_findep(to, 0, 1);
1080         if (inp_p != NULL) {
1081                 *inp_p = inp;
1082         }
1083         SCTP_INP_INFO_RUNLOCK();
1084
1085         if (inp == NULL) {
1086                 return (NULL);
1087         }
1088
1089         /*
1090          * ok, we have an endpoint, now lets find the assoc for it (if any)
1091          * we now place the source address or from in the to of the find
1092          * endpoint call. Since in reality this chain is used from the
1093          * inbound packet side.
1094          */
1095         if (inp_p != NULL) {
1096                 return (sctp_findassociation_ep_addr(inp_p, from, netp, to, NULL));
1097         } else {
1098                 return (sctp_findassociation_ep_addr(&inp, from, netp, to, NULL));
1099         }
1100 }
1101
1102
1103 /*
1104  * This routine will grub through the mbuf that is a INIT or INIT-ACK and
1105  * find all addresses that the sender has specified in any address list.
1106  * Each address will be used to lookup the TCB and see if one exits.
1107  */
1108 static struct sctp_tcb *
1109 sctp_findassociation_special_addr(struct mbuf *m, int iphlen, int offset,
1110     struct sctphdr *sh, struct sctp_inpcb **inp_p, struct sctp_nets **netp,
1111     struct sockaddr *dest)
1112 {
1113         struct sockaddr_in sin4;
1114         struct sockaddr_in6 sin6;
1115         struct sctp_paramhdr *phdr, parm_buf;
1116         struct sctp_tcb *retval;
1117         u_int32_t ptype, plen;
1118
1119         memset(&sin4, 0, sizeof(sin4));
1120         memset(&sin6, 0, sizeof(sin6));
1121         sin4.sin_len = sizeof(sin4);
1122         sin4.sin_family = AF_INET;
1123         sin4.sin_port = sh->src_port;
1124         sin6.sin6_len = sizeof(sin6);
1125         sin6.sin6_family = AF_INET6;
1126         sin6.sin6_port = sh->src_port;
1127
1128         retval = NULL;
1129         offset += sizeof(struct sctp_init_chunk);
1130
1131         phdr = sctp_get_next_param(m, offset, &parm_buf, sizeof(parm_buf));
1132         while (phdr != NULL) {
1133                 /* now we must see if we want the parameter */
1134                 ptype = ntohs(phdr->param_type);
1135                 plen = ntohs(phdr->param_length);
1136                 if (plen == 0) {
1137 #ifdef SCTP_DEBUG
1138                         if (sctp_debug_on & SCTP_DEBUG_PCB1) {
1139                                 printf("sctp_findassociation_special_addr: Impossible length in parameter\n");
1140                         }
1141 #endif /* SCTP_DEBUG */
1142                         break;
1143                 }
1144                 if (ptype == SCTP_IPV4_ADDRESS &&
1145                     plen == sizeof(struct sctp_ipv4addr_param)) {
1146                         /* Get the rest of the address */
1147                         struct sctp_ipv4addr_param ip4_parm, *p4;
1148
1149                         phdr = sctp_get_next_param(m, offset,
1150                             (struct sctp_paramhdr *)&ip4_parm, plen);
1151                         if (phdr == NULL) {
1152                                 return (NULL);
1153                         }
1154                         p4 = (struct sctp_ipv4addr_param *)phdr;
1155                         memcpy(&sin4.sin_addr, &p4->addr, sizeof(p4->addr));
1156                         /* look it up */
1157                         retval = sctp_findassociation_ep_addr(inp_p,
1158                             (struct sockaddr *)&sin4, netp, dest, NULL);
1159                         if (retval != NULL) {
1160                                 return (retval);
1161                         }
1162                 } else if (ptype == SCTP_IPV6_ADDRESS &&
1163                     plen == sizeof(struct sctp_ipv6addr_param)) {
1164                         /* Get the rest of the address */
1165                         struct sctp_ipv6addr_param ip6_parm, *p6;
1166
1167                         phdr = sctp_get_next_param(m, offset,
1168                             (struct sctp_paramhdr *)&ip6_parm, plen);
1169                         if (phdr == NULL) {
1170                                 return (NULL);
1171                         }
1172                         p6 = (struct sctp_ipv6addr_param *)phdr;
1173                         memcpy(&sin6.sin6_addr, &p6->addr, sizeof(p6->addr));
1174                         /* look it up */
1175                         retval = sctp_findassociation_ep_addr(inp_p,
1176                             (struct sockaddr *)&sin6, netp, dest, NULL);
1177                         if (retval != NULL) {
1178                                 return (retval);
1179                         }
1180                 }
1181                 offset += SCTP_SIZE32(plen);
1182                 phdr = sctp_get_next_param(m, offset, &parm_buf,
1183                     sizeof(parm_buf));
1184         }
1185         return (NULL);
1186 }
1187
1188 static struct sctp_tcb *
1189 sctp_findassoc_by_vtag(struct sockaddr *from, uint32_t vtag,
1190     struct sctp_inpcb **inp_p, struct sctp_nets **netp, uint16_t rport,
1191     uint16_t lport)
1192 {
1193         /*
1194          * Use my vtag to hash. If we find it we then verify the source addr
1195          * is in the assoc. If all goes well we save a bit on rec of a packet.
1196          */
1197         struct sctpasochead *head;
1198         struct sctp_nets *net;
1199         struct sctp_tcb *stcb;
1200
1201         SCTP_INP_INFO_RLOCK();
1202         head = &sctppcbinfo.sctp_asochash[SCTP_PCBHASH_ASOC(vtag,
1203             sctppcbinfo.hashasocmark)];
1204         if (head == NULL) {
1205                 /* invalid vtag */
1206                 SCTP_INP_INFO_RUNLOCK();
1207                 return (NULL);
1208         }
1209         LIST_FOREACH(stcb, head, sctp_asocs) {
1210                 SCTP_INP_RLOCK(stcb->sctp_ep);
1211                 SCTP_TCB_LOCK(stcb);
1212                 SCTP_INP_RUNLOCK(stcb->sctp_ep);
1213                 if (stcb->asoc.my_vtag == vtag) {
1214                         /* candidate */
1215                         if (stcb->rport != rport) {
1216                                 /*
1217                                  * we could remove this if vtags are unique
1218                                  * across the system.
1219                                  */
1220                                 SCTP_TCB_UNLOCK(stcb);
1221                                 continue;
1222                         }
1223                         if (stcb->sctp_ep->sctp_lport != lport) {
1224                                 /*
1225                                  * we could remove this if vtags are unique
1226                                  * across the system.
1227                                  */
1228                                 SCTP_TCB_UNLOCK(stcb);
1229                                 continue;
1230                         }
1231                         net = sctp_findnet(stcb, from);
1232                         if (net) {
1233                                 /* yep its him. */
1234                                 *netp = net;
1235                                 sctp_pegs[SCTP_VTAG_EXPR]++;
1236                                 *inp_p = stcb->sctp_ep;
1237                                 SCTP_INP_INFO_RUNLOCK();
1238                                 return (stcb);
1239                         } else {
1240                                 /* not him, this should only
1241                                  * happen in rare cases so
1242                                  * I peg it.
1243                                  */
1244                                 sctp_pegs[SCTP_VTAG_BOGUS]++;
1245                         }
1246                 }
1247                 SCTP_TCB_UNLOCK(stcb);
1248         }
1249         SCTP_INP_INFO_RUNLOCK();
1250         return (NULL);
1251 }
1252
1253 /*
1254  * Find an association with the pointer to the inbound IP packet. This
1255  * can be a IPv4 or IPv6 packet.
1256  */
1257 struct sctp_tcb *
1258 sctp_findassociation_addr(struct mbuf *m, int iphlen, int offset,
1259     struct sctphdr *sh, struct sctp_chunkhdr *ch,
1260     struct sctp_inpcb **inp_p, struct sctp_nets **netp)
1261 {
1262         int find_tcp_pool;
1263         struct ip *iph;
1264         struct sctp_tcb *retval;
1265         struct sockaddr_storage to_store, from_store;
1266         struct sockaddr *to = (struct sockaddr *)&to_store;
1267         struct sockaddr *from = (struct sockaddr *)&from_store;
1268         struct sctp_inpcb *inp;
1269
1270
1271         iph = mtod(m, struct ip *);
1272         if (iph->ip_v == IPVERSION) {
1273                 /* its IPv4 */
1274                 struct sockaddr_in *to4, *from4;
1275
1276                 to4 = (struct sockaddr_in *)&to_store;
1277                 from4 = (struct sockaddr_in *)&from_store;
1278                 bzero(to4, sizeof(*to4));
1279                 bzero(from4, sizeof(*from4));
1280                 from4->sin_family = to4->sin_family = AF_INET;
1281                 from4->sin_len = to4->sin_len = sizeof(struct sockaddr_in);
1282                 from4->sin_addr.s_addr  = iph->ip_src.s_addr;
1283                 to4->sin_addr.s_addr = iph->ip_dst.s_addr ;
1284                 from4->sin_port = sh->src_port;
1285                 to4->sin_port = sh->dest_port;
1286         } else if (iph->ip_v == (IPV6_VERSION >> 4)) {
1287                 /* its IPv6 */
1288                 struct ip6_hdr *ip6;
1289                 struct sockaddr_in6 *to6, *from6;
1290
1291                 ip6 = mtod(m, struct ip6_hdr *);
1292                 to6 = (struct sockaddr_in6 *)&to_store;
1293                 from6 = (struct sockaddr_in6 *)&from_store;
1294                 bzero(to6, sizeof(*to6));
1295                 bzero(from6, sizeof(*from6));
1296                 from6->sin6_family = to6->sin6_family = AF_INET6;
1297                 from6->sin6_len = to6->sin6_len = sizeof(struct sockaddr_in6);
1298                 to6->sin6_addr = ip6->ip6_dst;
1299                 from6->sin6_addr = ip6->ip6_src;
1300                 from6->sin6_port = sh->src_port;
1301                 to6->sin6_port = sh->dest_port;
1302                 /* Get the scopes in properly to the sin6 addr's */
1303                 (void)in6_recoverscope(to6, &to6->sin6_addr, NULL);
1304 #if defined(SCTP_BASE_FREEBSD) || defined(__APPLE__)
1305                 (void)in6_embedscope(&to6->sin6_addr, to6, NULL, NULL);
1306 #else
1307                 (void)in6_embedscope(&to6->sin6_addr, to6);
1308 #endif
1309
1310                 (void)in6_recoverscope(from6, &from6->sin6_addr, NULL);
1311 #if defined(SCTP_BASE_FREEBSD) || defined(__APPLE__)
1312                 (void)in6_embedscope(&from6->sin6_addr, from6, NULL, NULL);
1313 #else
1314                 (void)in6_embedscope(&from6->sin6_addr, from6);
1315 #endif
1316         } else {
1317                 /* Currently not supported. */
1318                 return (NULL);
1319         }
1320 #ifdef SCTP_DEBUG
1321         if (sctp_debug_on & SCTP_DEBUG_PCB1) {
1322                 printf("Looking for port %d address :",
1323                        ntohs(((struct sockaddr_in *)to)->sin_port));
1324                 sctp_print_address(to);
1325                 printf("From for port %d address :",
1326                        ntohs(((struct sockaddr_in *)from)->sin_port));
1327                 sctp_print_address(from);
1328         }
1329 #endif
1330
1331         if (sh->v_tag) {
1332                 /* we only go down this path if vtag is non-zero */
1333                 retval = sctp_findassoc_by_vtag(from, ntohl(sh->v_tag),
1334                     inp_p, netp, sh->src_port, sh->dest_port);
1335                 if (retval) {
1336                         return (retval);
1337                 }
1338         }
1339         find_tcp_pool = 0;
1340         if ((ch->chunk_type != SCTP_INITIATION) &&
1341             (ch->chunk_type != SCTP_INITIATION_ACK) &&
1342             (ch->chunk_type != SCTP_COOKIE_ACK) &&
1343             (ch->chunk_type != SCTP_COOKIE_ECHO)) {
1344                 /* Other chunk types go to the tcp pool. */
1345                 find_tcp_pool = 1;
1346         }
1347         if (inp_p) {
1348                 retval = sctp_findassociation_addr_sa(to, from, inp_p, netp,
1349                     find_tcp_pool);
1350                 inp = *inp_p;
1351         } else {
1352                 retval = sctp_findassociation_addr_sa(to, from, &inp, netp,
1353                     find_tcp_pool);
1354         }
1355 #ifdef SCTP_DEBUG
1356         if (sctp_debug_on & SCTP_DEBUG_PCB1) {
1357                 printf("retval:%p inp:%p\n", retval, inp);
1358         }
1359 #endif
1360         if (retval == NULL && inp) {
1361                 /* Found a EP but not this address */
1362 #ifdef SCTP_DEBUG
1363                 if (sctp_debug_on & SCTP_DEBUG_PCB1) {
1364                         printf("Found endpoint %p but no asoc - ep state:%x\n",
1365                             inp, inp->sctp_flags);
1366                 }
1367 #endif
1368                 if ((ch->chunk_type == SCTP_INITIATION) ||
1369                     (ch->chunk_type == SCTP_INITIATION_ACK)) {
1370                         /*
1371                          * special hook, we do NOT return linp or an
1372                          * association that is linked to an existing
1373                          * association that is under the TCP pool (i.e. no
1374                          * listener exists). The endpoint finding routine
1375                          * will always find a listner before examining the
1376                          * TCP pool.
1377                          */
1378                         if (inp->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL) {
1379 #ifdef SCTP_DEBUG
1380                                 if (sctp_debug_on & SCTP_DEBUG_PCB1) {
1381                                         printf("Gak, its in the TCP pool... return NULL");
1382                                 }
1383 #endif
1384                                 if (inp_p) {
1385                                         *inp_p = NULL;
1386                                 }
1387                                 return (NULL);
1388                         }
1389 #ifdef SCTP_DEBUG
1390                         if (sctp_debug_on & SCTP_DEBUG_PCB1) {
1391                                 printf("Now doing SPECIAL find\n");
1392                         }
1393 #endif
1394                         retval = sctp_findassociation_special_addr(m, iphlen,
1395                             offset, sh, inp_p, netp, to);
1396                 }
1397         }
1398 #ifdef SCTP_DEBUG
1399         if (sctp_debug_on & SCTP_DEBUG_PCB1) {
1400             printf("retval is %p\n", retval);
1401         }
1402 #endif
1403         return (retval);
1404 }
1405
1406 extern int sctp_max_burst_default;
1407
1408 extern unsigned int sctp_delayed_sack_time_default;
1409 extern unsigned int sctp_heartbeat_interval_default;
1410 extern unsigned int sctp_pmtu_raise_time_default;
1411 extern unsigned int sctp_shutdown_guard_time_default;
1412 extern unsigned int sctp_secret_lifetime_default;
1413
1414 extern unsigned int sctp_rto_max_default;
1415 extern unsigned int sctp_rto_min_default;
1416 extern unsigned int sctp_rto_initial_default;
1417 extern unsigned int sctp_init_rto_max_default;
1418 extern unsigned int sctp_valid_cookie_life_default;
1419 extern unsigned int sctp_init_rtx_max_default;
1420 extern unsigned int sctp_assoc_rtx_max_default;
1421 extern unsigned int sctp_path_rtx_max_default;
1422 extern unsigned int sctp_nr_outgoing_streams_default;
1423
1424 /*
1425  * allocate a sctp_inpcb and setup a temporary binding to a port/all
1426  * addresses. This way if we don't get a bind we by default pick a ephemeral
1427  * port with all addresses bound.
1428  */
1429 int
1430 sctp_inpcb_alloc(struct socket *so)
1431 {
1432         /*
1433          * we get called when a new endpoint starts up. We need to allocate
1434          * the sctp_inpcb structure from the zone and init it. Mark it as
1435          * unbound and find a port that we can use as an ephemeral with
1436          * INADDR_ANY. If the user binds later no problem we can then add
1437          * in the specific addresses. And setup the default parameters for
1438          * the EP.
1439          */
1440         int i, error;
1441         struct sctp_inpcb *inp, *n_inp;
1442         struct sctp_pcb *m;
1443         struct timeval time;
1444
1445         error = 0;
1446
1447         /* Hack alert:
1448          *
1449          * This code audits the entire INP list to see if
1450          * any ep's that are in the GONE state are now
1451          * all free. This should not happen really since when
1452          * the last association if freed we should end up deleting
1453          * the inpcb. This code including the locks should
1454          * be taken out ... since the last set of fixes I
1455          * have not seen the "Found a GONE on list" has not
1456          * came out. But i am paranoid and we will leave this
1457          * in at the cost of efficency on allocation of PCB's.
1458          * Probably we should move this to the invariant
1459          * compile options
1460          */
1461 /* #ifdef INVARIANTS*/
1462         SCTP_INP_INFO_RLOCK();
1463         inp = LIST_FIRST(&sctppcbinfo.listhead);
1464         while (inp) {
1465                 n_inp = LIST_NEXT(inp, sctp_list);
1466                 if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE) {
1467                         if (LIST_FIRST(&inp->sctp_asoc_list) == NULL) {
1468                                 /* finish the job now */
1469                                 printf("Found a GONE on list\n");
1470                                 SCTP_INP_INFO_RUNLOCK();
1471                                 sctp_inpcb_free(inp, 1);
1472                                 SCTP_INP_INFO_RLOCK();
1473                         }
1474                 }
1475                 inp = n_inp;
1476         }
1477         SCTP_INP_INFO_RUNLOCK();
1478 /* #endif INVARIANTS*/
1479
1480         SCTP_INP_INFO_WLOCK();
1481         inp = (struct sctp_inpcb *)SCTP_ZONE_GET(sctppcbinfo.ipi_zone_ep);
1482         if (inp == NULL) {
1483                 printf("Out of SCTP-INPCB structures - no resources\n");
1484                 SCTP_INP_INFO_WUNLOCK();
1485                 return (ENOBUFS);
1486         }
1487
1488         /* zap it */
1489         bzero(inp, sizeof(*inp));
1490
1491         /* bump generations */
1492         inp->ip_inp.inp.inp_socket = so;
1493
1494         /* setup socket pointers */
1495         inp->sctp_socket = so;
1496
1497         /* setup inpcb socket too */
1498         inp->ip_inp.inp.inp_socket = so;
1499         inp->sctp_frag_point = SCTP_DEFAULT_MAXSEGMENT;
1500 #ifdef IPSEC
1501 #if !(defined(__OpenBSD__) || defined(__APPLE__))
1502         {
1503                 struct inpcbpolicy *pcb_sp = NULL;
1504                 error = ipsec_init_pcbpolicy(so, &pcb_sp);
1505                 /* Arrange to share the policy */
1506                 inp->ip_inp.inp.inp_sp = pcb_sp;
1507                 ((struct in6pcb *)(&inp->ip_inp.inp))->in6p_sp = pcb_sp;
1508         }
1509 #else
1510         /* not sure what to do for openbsd here */
1511         error = 0;
1512 #endif
1513         if (error != 0) {
1514                 SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_ep, inp);
1515                 SCTP_INP_INFO_WUNLOCK();
1516                 return error;
1517         }
1518 #endif /* IPSEC */
1519         sctppcbinfo.ipi_count_ep++;
1520 #if defined(__FreeBSD__) || defined(__APPLE__)
1521         inp->ip_inp.inp.inp_gencnt = ++sctppcbinfo.ipi_gencnt_ep;
1522         inp->ip_inp.inp.inp_ip_ttl = ip_defttl;
1523 #else
1524         inp->inp_ip_ttl = ip_defttl;
1525         inp->inp_ip_tos = 0;
1526 #endif
1527
1528         so->so_pcb = (caddr_t)inp;
1529
1530         if ((so->so_type == SOCK_DGRAM) ||
1531             (so->so_type == SOCK_SEQPACKET)) {
1532                 /* UDP style socket */
1533                 inp->sctp_flags = (SCTP_PCB_FLAGS_UDPTYPE |
1534                     SCTP_PCB_FLAGS_UNBOUND);
1535                 inp->sctp_flags |= (SCTP_PCB_FLAGS_RECVDATAIOEVNT);
1536                 /* Be sure it is NON-BLOCKING IO for UDP */
1537                 /*so->so_state |= SS_NBIO;*/
1538         } else if (so->so_type == SOCK_STREAM) {
1539                 /* TCP style socket */
1540                 inp->sctp_flags = (SCTP_PCB_FLAGS_TCPTYPE |
1541                     SCTP_PCB_FLAGS_UNBOUND);
1542                 inp->sctp_flags |= (SCTP_PCB_FLAGS_RECVDATAIOEVNT);
1543                 /* Be sure we have blocking IO bu default */
1544                 so->so_state &= ~SS_NBIO;
1545         } else {
1546                 /*
1547                  * unsupported socket type (RAW, etc)- in case we missed
1548                  * it in protosw
1549                  */
1550                 SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_ep, inp);
1551                 SCTP_INP_INFO_WUNLOCK();
1552                 return (EOPNOTSUPP);
1553         }
1554         inp->sctp_tcbhash = hashinit(sctp_pcbtblsize,
1555 #ifdef __NetBSD__
1556             HASH_LIST,
1557 #endif
1558             M_PCB,
1559 #if defined(__NetBSD__) || defined(__OpenBSD__)
1560             M_WAITOK,
1561 #endif
1562             &inp->sctp_hashmark);
1563         if (inp->sctp_tcbhash == NULL) {
1564                 printf("Out of SCTP-INPCB->hashinit - no resources\n");
1565                 SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_ep, inp);
1566                 SCTP_INP_INFO_WUNLOCK();
1567                 return (ENOBUFS);
1568         }
1569         /* LOCK init's */
1570         SCTP_INP_LOCK_INIT(inp);
1571         SCTP_ASOC_CREATE_LOCK_INIT(inp);
1572         /* lock the new ep */
1573         SCTP_INP_WLOCK(inp);
1574
1575         /* add it to the info area */
1576         LIST_INSERT_HEAD(&sctppcbinfo.listhead, inp, sctp_list);
1577         SCTP_INP_INFO_WUNLOCK();
1578
1579         LIST_INIT(&inp->sctp_addr_list);
1580         LIST_INIT(&inp->sctp_asoc_list);
1581         TAILQ_INIT(&inp->sctp_queue_list);
1582         /* Init the timer structure for signature change */
1583 #if defined (__FreeBSD__) && __FreeBSD_version >= 500000
1584         callout_init(&inp->sctp_ep.signature_change.timer, 0);
1585 #else
1586         callout_init(&inp->sctp_ep.signature_change.timer);
1587 #endif
1588         inp->sctp_ep.signature_change.type = SCTP_TIMER_TYPE_NEWCOOKIE;
1589
1590         /* now init the actual endpoint default data */
1591         m = &inp->sctp_ep;
1592
1593         /* setup the base timeout information */
1594         m->sctp_timeoutticks[SCTP_TIMER_SEND] = SEC_TO_TICKS(SCTP_SEND_SEC); /* needed ? */
1595         m->sctp_timeoutticks[SCTP_TIMER_INIT] = SEC_TO_TICKS(SCTP_INIT_SEC); /* needed ? */
1596         m->sctp_timeoutticks[SCTP_TIMER_RECV] = MSEC_TO_TICKS(sctp_delayed_sack_time_default);
1597         m->sctp_timeoutticks[SCTP_TIMER_HEARTBEAT] = sctp_heartbeat_interval_default; /* this is in MSEC */
1598         m->sctp_timeoutticks[SCTP_TIMER_PMTU] = SEC_TO_TICKS(sctp_pmtu_raise_time_default);
1599         m->sctp_timeoutticks[SCTP_TIMER_MAXSHUTDOWN] = SEC_TO_TICKS(sctp_shutdown_guard_time_default);
1600         m->sctp_timeoutticks[SCTP_TIMER_SIGNATURE] = SEC_TO_TICKS(sctp_secret_lifetime_default);
1601         /* all max/min max are in ms */
1602         m->sctp_maxrto = sctp_rto_max_default;
1603         m->sctp_minrto = sctp_rto_min_default;
1604         m->initial_rto = sctp_rto_initial_default;
1605         m->initial_init_rto_max = sctp_init_rto_max_default;
1606
1607         m->max_open_streams_intome = MAX_SCTP_STREAMS;
1608
1609         m->max_init_times = sctp_init_rtx_max_default;
1610         m->max_send_times = sctp_assoc_rtx_max_default;
1611         m->def_net_failure = sctp_path_rtx_max_default;
1612         m->sctp_sws_sender = SCTP_SWS_SENDER_DEF;
1613         m->sctp_sws_receiver = SCTP_SWS_RECEIVER_DEF;
1614         m->max_burst = sctp_max_burst_default;
1615         /* number of streams to pre-open on a association */
1616         m->pre_open_stream_count = sctp_nr_outgoing_streams_default;
1617
1618         /* Add adaption cookie */
1619         m->adaption_layer_indicator = 0x504C5253;
1620
1621         /* seed random number generator */
1622         m->random_counter = 1;
1623         m->store_at = SCTP_SIGNATURE_SIZE;
1624 #if defined(__FreeBSD__) && (__FreeBSD_version < 500000)
1625         read_random_unlimited(m->random_numbers, sizeof(m->random_numbers));
1626 #elif defined(__APPLE__) || (__FreeBSD_version > 500000)
1627         read_random(m->random_numbers, sizeof(m->random_numbers));
1628 #elif defined(__OpenBSD__)
1629         get_random_bytes(m->random_numbers, sizeof(m->random_numbers));
1630 #elif defined(__NetBSD__) && NRND > 0
1631         rnd_extract_data(m->random_numbers, sizeof(m->random_numbers),
1632                          RND_EXTRACT_ANY);
1633 #else
1634         {
1635                 u_int32_t *ranm, *ranp;
1636                 ranp = (u_int32_t *)&m->random_numbers;
1637                 ranm = ranp + (SCTP_SIGNATURE_ALOC_SIZE/sizeof(u_int32_t));
1638                 if ((u_long)ranp % 4) {
1639                         /* not a even boundary? */
1640                         ranp = (u_int32_t *)SCTP_SIZE32((u_long)ranp);
1641                 }
1642                 while (ranp < ranm) {
1643                         *ranp = random();
1644                         ranp++;
1645                 }
1646         }
1647 #endif
1648         sctp_fill_random_store(m);
1649
1650         /* Minimum cookie size */
1651         m->size_of_a_cookie = (sizeof(struct sctp_init_msg) * 2) +
1652                 sizeof(struct sctp_state_cookie);
1653         m->size_of_a_cookie += SCTP_SIGNATURE_SIZE;
1654
1655         /* Setup the initial secret */
1656         SCTP_GETTIME_TIMEVAL(&time);
1657         m->time_of_secret_change = time.tv_sec;
1658
1659         for (i = 0; i < SCTP_NUMBER_OF_SECRETS; i++) {
1660                 m->secret_key[0][i] = sctp_select_initial_TSN(m);
1661         }
1662         sctp_timer_start(SCTP_TIMER_TYPE_NEWCOOKIE, inp, NULL, NULL);
1663
1664         /* How long is a cookie good for ? */
1665         m->def_cookie_life = sctp_valid_cookie_life_default;
1666         SCTP_INP_WUNLOCK(inp);
1667         return (error);
1668 }
1669
1670
1671 void
1672 sctp_move_pcb_and_assoc(struct sctp_inpcb *old_inp, struct sctp_inpcb *new_inp,
1673     struct sctp_tcb *stcb)
1674 {
1675         uint16_t lport, rport;
1676         struct sctppcbhead *head;
1677         struct sctp_laddr *laddr, *oladdr;
1678
1679         SCTP_TCB_UNLOCK(stcb);
1680         SCTP_INP_INFO_WLOCK();
1681         SCTP_INP_WLOCK(old_inp);
1682         SCTP_INP_WLOCK(new_inp);
1683         SCTP_TCB_LOCK(stcb);
1684
1685         new_inp->sctp_ep.time_of_secret_change =
1686             old_inp->sctp_ep.time_of_secret_change;
1687         memcpy(new_inp->sctp_ep.secret_key, old_inp->sctp_ep.secret_key,
1688             sizeof(old_inp->sctp_ep.secret_key));
1689         new_inp->sctp_ep.current_secret_number =
1690             old_inp->sctp_ep.current_secret_number;
1691         new_inp->sctp_ep.last_secret_number =
1692             old_inp->sctp_ep.last_secret_number;
1693         new_inp->sctp_ep.size_of_a_cookie = old_inp->sctp_ep.size_of_a_cookie;
1694
1695         /* Copy the port across */
1696         lport = new_inp->sctp_lport = old_inp->sctp_lport;
1697         rport = stcb->rport;
1698         /* Pull the tcb from the old association */
1699         LIST_REMOVE(stcb, sctp_tcbhash);
1700         LIST_REMOVE(stcb, sctp_tcblist);
1701
1702         /* Now insert the new_inp into the TCP connected hash */
1703         head = &sctppcbinfo.sctp_tcpephash[SCTP_PCBHASH_ALLADDR((lport + rport),
1704             sctppcbinfo.hashtcpmark)];
1705
1706         LIST_INSERT_HEAD(head, new_inp, sctp_hash);
1707
1708         /* Now move the tcb into the endpoint list */
1709         LIST_INSERT_HEAD(&new_inp->sctp_asoc_list, stcb, sctp_tcblist);
1710         /*
1711          * Question, do we even need to worry about the ep-hash since
1712          * we only have one connection? Probably not :> so lets
1713          * get rid of it and not suck up any kernel memory in that.
1714          */
1715         SCTP_INP_INFO_WUNLOCK();
1716         stcb->sctp_socket = new_inp->sctp_socket;
1717         stcb->sctp_ep = new_inp;
1718         if (new_inp->sctp_tcbhash != NULL) {
1719                 FREE(new_inp->sctp_tcbhash, M_PCB);
1720                 new_inp->sctp_tcbhash = NULL;
1721         }
1722         if ((new_inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) == 0) {
1723                 /* Subset bound, so copy in the laddr list from the old_inp */
1724                 LIST_FOREACH(oladdr, &old_inp->sctp_addr_list, sctp_nxt_addr) {
1725                         laddr = (struct sctp_laddr *)SCTP_ZONE_GET(
1726                             sctppcbinfo.ipi_zone_laddr);
1727                         if (laddr == NULL) {
1728                                 /*
1729                                  * Gak, what can we do? This assoc is really
1730                                  * HOSED. We probably should send an abort
1731                                  * here.
1732                                  */
1733 #ifdef SCTP_DEBUG
1734                                 if (sctp_debug_on & SCTP_DEBUG_PCB1) {
1735                                         printf("Association hosed in TCP model, out of laddr memory\n");
1736                                 }
1737 #endif /* SCTP_DEBUG */
1738                                 continue;
1739                         }
1740                         sctppcbinfo.ipi_count_laddr++;
1741                         sctppcbinfo.ipi_gencnt_laddr++;
1742                         bzero(laddr, sizeof(*laddr));
1743                         laddr->ifa = oladdr->ifa;
1744                         LIST_INSERT_HEAD(&new_inp->sctp_addr_list, laddr,
1745                             sctp_nxt_addr);
1746                         new_inp->laddr_count++;
1747                 }
1748         }
1749         SCTP_INP_WUNLOCK(new_inp);
1750         SCTP_INP_WUNLOCK(old_inp);
1751 }
1752
1753 static int
1754 sctp_isport_inuse(struct sctp_inpcb *inp, uint16_t lport)
1755 {
1756         struct sctppcbhead *head;
1757         struct sctp_inpcb *t_inp;
1758
1759         head = &sctppcbinfo.sctp_ephash[SCTP_PCBHASH_ALLADDR(lport,
1760             sctppcbinfo.hashmark)];
1761         LIST_FOREACH(t_inp, head, sctp_hash) {
1762                 if (t_inp->sctp_lport != lport) {
1763                         continue;
1764                 }
1765                 /* This one is in use. */
1766                 /* check the v6/v4 binding issue */
1767                 if ((t_inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) &&
1768 #if defined(__FreeBSD__)
1769                     (((struct inpcb *)t_inp)->inp_flags & IN6P_IPV6_V6ONLY)
1770 #else
1771 #if defined(__OpenBSD__)
1772                     (0) /* For open bsd we do dual bind only */
1773 #else
1774                     (((struct in6pcb *)t_inp)->in6p_flags & IN6P_IPV6_V6ONLY)
1775 #endif
1776 #endif
1777                         ) {
1778                         if (inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) {
1779                                 /* collision in V6 space */
1780                                 return (1);
1781                         } else {
1782                                 /* inp is BOUND_V4 no conflict */
1783                                 continue;
1784                         }
1785                 } else if (t_inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) {
1786                         /* t_inp is bound v4 and v6, conflict always */
1787                         return (1);
1788                 } else {
1789                         /* t_inp is bound only V4 */
1790                         if ((inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) &&
1791 #if defined(__FreeBSD__)
1792                             (((struct inpcb *)inp)->inp_flags & IN6P_IPV6_V6ONLY)
1793 #else
1794 #if defined(__OpenBSD__)
1795                             (0) /* For open bsd we do dual bind only */
1796 #else
1797                             (((struct in6pcb *)inp)->in6p_flags & IN6P_IPV6_V6ONLY)
1798 #endif
1799 #endif
1800                                 ) {
1801                                 /* no conflict */
1802                                 continue;
1803                         }
1804                         /* else fall through to conflict */
1805                 }
1806                 return (1);
1807         }
1808         return (0);
1809 }
1810
1811 #if !(defined(__FreeBSD__) || defined(__APPLE__))
1812 /*
1813  * Don't know why, but without this there is an unknown reference when
1814  * compiling NetBSD... hmm
1815  */
1816 extern void in6_sin6_2_sin (struct sockaddr_in *, struct sockaddr_in6 *sin6);
1817 #endif
1818
1819
1820 int
1821 #if defined(__FreeBSD__) && __FreeBSD_version >= 500000
1822 sctp_inpcb_bind(struct socket *so, struct sockaddr *addr, struct thread *p)
1823 #else
1824 sctp_inpcb_bind(struct socket *so, struct sockaddr *addr, struct proc *p)
1825 #endif
1826 {
1827         /* bind a ep to a socket address */
1828         struct sctppcbhead *head;
1829         struct sctp_inpcb *inp, *inp_tmp;
1830         struct inpcb *ip_inp;
1831         int bindall;
1832         uint16_t lport;
1833         int error;
1834
1835         lport = 0;
1836         error = 0;
1837         bindall = 1;
1838         inp = (struct sctp_inpcb *)so->so_pcb;
1839         ip_inp = (struct inpcb *)so->so_pcb;
1840 #ifdef SCTP_DEBUG
1841         if (sctp_debug_on & SCTP_DEBUG_PCB1) {
1842                 if (addr) {
1843                         printf("Bind called port:%d\n",
1844                                ntohs(((struct sockaddr_in *)addr)->sin_port));
1845                         printf("Addr :");
1846                         sctp_print_address(addr);
1847                 }
1848         }
1849 #endif /* SCTP_DEBUG */
1850         if ((inp->sctp_flags & SCTP_PCB_FLAGS_UNBOUND) == 0) {
1851                 /* already did a bind, subsequent binds NOT allowed ! */
1852                 return (EINVAL);
1853         }
1854
1855         if (addr != NULL) {
1856                 if (addr->sa_family == AF_INET) {
1857                         struct sockaddr_in *sin;
1858
1859                         /* IPV6_V6ONLY socket? */
1860                         if (
1861 #if defined(__FreeBSD__) || defined(__APPLE__)
1862                                 (ip_inp->inp_flags & IN6P_IPV6_V6ONLY)
1863 #else
1864 #if defined(__OpenBSD__)
1865                                 (0)     /* For openbsd we do dual bind only */
1866 #else
1867                                 (((struct in6pcb *)inp)->in6p_flags & IN6P_IPV6_V6ONLY)
1868 #endif
1869 #endif
1870                                 ) {
1871                                 return (EINVAL);
1872                         }
1873
1874                         if (addr->sa_len != sizeof(*sin))
1875                                 return (EINVAL);
1876
1877                         sin = (struct sockaddr_in *)addr;
1878                         lport = sin->sin_port;
1879
1880                         if (sin->sin_addr.s_addr != INADDR_ANY) {
1881                                 bindall = 0;
1882                         }
1883                 } else if (addr->sa_family == AF_INET6) {
1884                         /* Only for pure IPv6 Address. (No IPv4 Mapped!) */
1885                         struct sockaddr_in6 *sin6;
1886
1887                         sin6 = (struct sockaddr_in6 *)addr;
1888
1889                         if (addr->sa_len != sizeof(*sin6))
1890                                 return (EINVAL);
1891
1892                         lport = sin6->sin6_port;
1893                         if (!IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr)) {
1894                                 bindall = 0;
1895                                 /* KAME hack: embed scopeid */
1896 #if defined(SCTP_BASE_FREEBSD) || defined(__APPLE__)
1897                                 if (in6_embedscope(&sin6->sin6_addr, sin6,
1898                                     ip_inp, NULL) != 0)
1899                                         return (EINVAL);
1900 #elif defined(__FreeBSD__)
1901                                 error = scope6_check_id(sin6, ip6_use_defzone);
1902                                 if (error != 0)
1903                                         return (error);
1904 #else
1905                                 if (in6_embedscope(&sin6->sin6_addr, sin6) != 0) {
1906                                         return (EINVAL);
1907                                 }
1908 #endif
1909                         }
1910 #ifndef SCOPEDROUTING
1911                         /* this must be cleared for ifa_ifwithaddr() */
1912                         sin6->sin6_scope_id = 0;
1913 #endif /* SCOPEDROUTING */
1914                 } else {
1915                         return (EAFNOSUPPORT);
1916                 }
1917         }
1918         SCTP_INP_INFO_WLOCK();
1919         SCTP_INP_WLOCK(inp);
1920         /* increase our count due to the unlock we do */
1921         SCTP_INP_INCR_REF(inp);
1922         if (lport) {
1923                 /*
1924                  * Did the caller specify a port? if so we must see if a
1925                  * ep already has this one bound.
1926                  */
1927                 /* got to be root to get at low ports */
1928                 if (ntohs(lport) < IPPORT_RESERVED) {
1929                         if (p && (error =
1930 #ifdef __FreeBSD__
1931 #if __FreeBSD_version >= 500000
1932                             suser_cred(p->td_ucred, 0)
1933 #else
1934                             suser(p)
1935 #endif
1936 #elif defined(__NetBSD__) || defined(__APPLE__)
1937                             suser(p->p_ucred, &p->p_acflag)
1938 #else
1939                             suser(p, 0)
1940 #endif
1941                             )) {
1942                                 SCTP_INP_DECR_REF(inp);
1943                                 SCTP_INP_WUNLOCK(inp);
1944                                 SCTP_INP_INFO_WUNLOCK();
1945                                 return (error);
1946                         }
1947                 }
1948                 if (p == NULL) {
1949                         SCTP_INP_DECR_REF(inp);
1950                         SCTP_INP_WUNLOCK(inp);
1951                         SCTP_INP_INFO_WUNLOCK();
1952                         return (error);
1953                 }
1954                 SCTP_INP_WUNLOCK(inp);
1955                 inp_tmp = sctp_pcb_findep(addr, 0, 1);
1956                 if (inp_tmp != NULL) {
1957                         /* lock guy returned and lower count
1958                          * note that we are not bound so inp_tmp
1959                          * should NEVER be inp. And it is this
1960                          * inp (inp_tmp) that gets the reference
1961                          * bump, so we must lower it.
1962                          */
1963                         SCTP_INP_WLOCK(inp_tmp);
1964                         SCTP_INP_DECR_REF(inp_tmp);
1965                         SCTP_INP_WUNLOCK(inp_tmp);
1966
1967                         /* unlock info */
1968                         SCTP_INP_INFO_WUNLOCK();
1969                         return (EADDRNOTAVAIL);
1970                 }
1971                 SCTP_INP_WLOCK(inp);
1972                 if (bindall) {
1973                         /* verify that no lport is not used by a singleton */
1974                         if (sctp_isport_inuse(inp, lport)) {
1975                                 /* Sorry someone already has this one bound */
1976                                 SCTP_INP_DECR_REF(inp);
1977                                 SCTP_INP_WUNLOCK(inp);
1978                                 SCTP_INP_INFO_WUNLOCK();
1979                                 return (EADDRNOTAVAIL);
1980                         }
1981                 }
1982         } else {
1983                 /*
1984                  * get any port but lets make sure no one has any address
1985                  * with this port bound
1986                  */
1987
1988                 /*
1989                  * setup the inp to the top (I could use the union but this
1990                  * is just as easy
1991                  */
1992                 uint32_t port_guess;
1993                 uint16_t port_attempt;
1994                 int not_done=1;
1995
1996                 while (not_done) {
1997                         port_guess = sctp_select_initial_TSN(&inp->sctp_ep);
1998                         port_attempt = (port_guess &  0x0000ffff);
1999                         if (port_attempt == 0) {
2000                                 goto next_half;
2001                         }
2002                         if (port_attempt < IPPORT_RESERVED) {
2003                                 port_attempt += IPPORT_RESERVED;
2004                         }
2005
2006                         if (sctp_isport_inuse(inp, htons(port_attempt)) == 0) {
2007                                 /* got a port we can use */
2008                                 not_done = 0;
2009                                 continue;
2010                         }
2011                         /* try upper half */
2012                 next_half:
2013                         port_attempt = ((port_guess >> 16) &  0x0000ffff);
2014                         if (port_attempt == 0) {
2015                                 goto last_try;
2016                         }
2017                         if (port_attempt < IPPORT_RESERVED) {
2018                                 port_attempt += IPPORT_RESERVED;
2019                         }
2020                         if (sctp_isport_inuse(inp, htons(port_attempt)) == 0) {
2021                                 /* got a port we can use */
2022                                 not_done = 0;
2023                                 continue;
2024                         }
2025                         /* try two half's added together */
2026                 last_try:
2027                         port_attempt = (((port_guess >> 16) &  0x0000ffff) + (port_guess & 0x0000ffff));
2028                         if (port_attempt == 0) {
2029                                 /* get a new random number */
2030                                 continue;
2031                         }
2032                         if (port_attempt < IPPORT_RESERVED) {
2033                                 port_attempt += IPPORT_RESERVED;
2034                         }
2035                         if (sctp_isport_inuse(inp, htons(port_attempt)) == 0) {
2036                                 /* got a port we can use */
2037                                 not_done = 0;
2038                                 continue;
2039                         }
2040                 }
2041                 /* we don't get out of the loop until we have a port */
2042                 lport = htons(port_attempt);
2043         }
2044         SCTP_INP_DECR_REF(inp);
2045         if (inp->sctp_flags & (SCTP_PCB_FLAGS_SOCKET_GONE|SCTP_PCB_FLAGS_SOCKET_ALLGONE)) {
2046                 /* this really should not happen. The guy
2047                  * did a non-blocking bind and then did a close
2048                  * at the same time.
2049                  */
2050                 SCTP_INP_WUNLOCK(inp);
2051                 SCTP_INP_INFO_WUNLOCK();
2052                 return (EINVAL);
2053         }
2054         /* ok we look clear to give out this port, so lets setup the binding */
2055         if (bindall) {
2056                 /* binding to all addresses, so just set in the proper flags */
2057                 inp->sctp_flags |= (SCTP_PCB_FLAGS_BOUNDALL |
2058                     SCTP_PCB_FLAGS_DO_ASCONF);
2059                 /* set the automatic addr changes from kernel flag */
2060                 if (sctp_auto_asconf == 0) {
2061                         inp->sctp_flags &= ~SCTP_PCB_FLAGS_AUTO_ASCONF;
2062                 } else {
2063                         inp->sctp_flags |= SCTP_PCB_FLAGS_AUTO_ASCONF;
2064                 }
2065         } else {
2066                 /*
2067                  * bind specific, make sure flags is off and add a new address
2068                  * structure to the sctp_addr_list inside the ep structure.
2069                  *
2070                  * We will need to allocate one and insert it at the head.
2071                  * The socketopt call can just insert new addresses in there
2072                  * as well. It will also have to do the embed scope kame hack
2073                  * too (before adding).
2074                  */
2075                 struct ifaddr *ifa;
2076                 struct sockaddr_storage store_sa;
2077
2078                 memset(&store_sa, 0, sizeof(store_sa));
2079                 if (addr->sa_family == AF_INET) {
2080                         struct sockaddr_in *sin;
2081
2082                         sin = (struct sockaddr_in *)&store_sa;
2083                         memcpy(sin, addr, sizeof(struct sockaddr_in));
2084                         sin->sin_port = 0;
2085                 } else if (addr->sa_family == AF_INET6) {
2086                         struct sockaddr_in6 *sin6;
2087
2088                         sin6 = (struct sockaddr_in6 *)&store_sa;
2089                         memcpy(sin6, addr, sizeof(struct sockaddr_in6));
2090                         sin6->sin6_port = 0;
2091                 }
2092                 /*
2093                  * first find the interface with the bound address
2094                  * need to zero out the port to find the address! yuck!
2095                  * can't do this earlier since need port for sctp_pcb_findep()
2096                  */
2097                 ifa = sctp_find_ifa_by_addr((struct sockaddr *)&store_sa);
2098                 if (ifa == NULL) {
2099                         /* Can't find an interface with that address */
2100                         SCTP_INP_WUNLOCK(inp);
2101                         SCTP_INP_INFO_WUNLOCK();
2102                         return (EADDRNOTAVAIL);
2103                 }
2104                 if (addr->sa_family == AF_INET6) {
2105                         struct in6_ifaddr *ifa6;
2106                         ifa6 = (struct in6_ifaddr *)ifa;
2107                         /*
2108                          * allow binding of deprecated addresses as per
2109                          * RFC 2462 and ipng discussion
2110                          */
2111                         if (ifa6->ia6_flags & (IN6_IFF_DETACHED |
2112                             IN6_IFF_ANYCAST |
2113                             IN6_IFF_NOTREADY)) {
2114                                 /* Can't bind a non-existent addr. */
2115                                 SCTP_INP_WUNLOCK(inp);
2116                                 SCTP_INP_INFO_WUNLOCK();
2117                                 return (EINVAL);
2118                         }
2119                 }
2120                 /* we're not bound all */
2121                 inp->sctp_flags &= ~SCTP_PCB_FLAGS_BOUNDALL;
2122 #if 0 /* use sysctl now */
2123                 /* don't allow automatic addr changes from kernel */
2124                 inp->sctp_flags &= ~SCTP_PCB_FLAGS_AUTO_ASCONF;
2125 #endif
2126                 /* set the automatic addr changes from kernel flag */
2127                 if (sctp_auto_asconf == 0) {
2128                         inp->sctp_flags &= ~SCTP_PCB_FLAGS_AUTO_ASCONF;
2129                 } else {
2130                         inp->sctp_flags |= SCTP_PCB_FLAGS_AUTO_ASCONF;
2131                 }
2132                 /* allow bindx() to send ASCONF's for binding changes */
2133                 inp->sctp_flags |= SCTP_PCB_FLAGS_DO_ASCONF;
2134                 /* add this address to the endpoint list */
2135                 error = sctp_insert_laddr(&inp->sctp_addr_list, ifa);
2136                 if (error != 0) {
2137                         SCTP_INP_WUNLOCK(inp);
2138                         SCTP_INP_INFO_WUNLOCK();
2139                         return (error);
2140                 }
2141                 inp->laddr_count++;
2142         }
2143         /* find the bucket */
2144         head = &sctppcbinfo.sctp_ephash[SCTP_PCBHASH_ALLADDR(lport,
2145             sctppcbinfo.hashmark)];
2146         /* put it in the bucket */
2147         LIST_INSERT_HEAD(head, inp, sctp_hash);
2148 #ifdef SCTP_DEBUG
2149         if (sctp_debug_on & SCTP_DEBUG_PCB1) {
2150                 printf("Main hash to bind at head:%p, bound port:%d\n", head, ntohs(lport));
2151         }
2152 #endif
2153         /* set in the port */
2154         inp->sctp_lport = lport;
2155
2156         /* turn off just the unbound flag */
2157         inp->sctp_flags &= ~SCTP_PCB_FLAGS_UNBOUND;
2158         SCTP_INP_WUNLOCK(inp);
2159         SCTP_INP_INFO_WUNLOCK();
2160         return (0);
2161 }
2162
2163
2164 static void
2165 sctp_iterator_inp_being_freed(struct sctp_inpcb *inp, struct sctp_inpcb *inp_next)
2166 {
2167         struct sctp_iterator *it;
2168         /* We enter with the only the ITERATOR_LOCK in place and
2169          * A write lock on the inp_info stuff.
2170          */
2171
2172         /* Go through all iterators, we must do this since
2173          * it is possible that some iterator does NOT have
2174          * the lock, but is waiting for it. And the one that
2175          * had the lock has either moved in the last iteration
2176          * or we just cleared it above. We need to find all
2177          * of those guys. The list of iterators should never
2178          * be very big though.
2179          */
2180         LIST_FOREACH(it, &sctppcbinfo.iteratorhead, sctp_nxt_itr) {
2181                 if (it == inp->inp_starting_point_for_iterator)
2182                         /* skip this guy, he's special */
2183                         continue;
2184                 if (it->inp == inp) {
2185                         /* This is tricky and we DON'T lock the iterator.
2186                          * Reason is he's running but waiting for me since
2187                          * inp->inp_starting_point_for_iterator has the lock
2188                          * on me (the guy above we skipped). This tells us
2189                          * its is not running but waiting for inp->inp_starting_point_for_iterator
2190                          * to be released by the guy that does have our INP in a lock.
2191                          */
2192                         if (it->iterator_flags & SCTP_ITERATOR_DO_SINGLE_INP) {
2193                                 it->inp = NULL;
2194                                 it->stcb = NULL;
2195                         } else {
2196                                 /* set him up to do the next guy not me */
2197                                 it->inp = inp_next;
2198                                 it->stcb = NULL;
2199                         }
2200                 }
2201         }
2202         it = inp->inp_starting_point_for_iterator;
2203         if (it) {
2204                 if (it->iterator_flags & SCTP_ITERATOR_DO_SINGLE_INP) {
2205                         it->inp = NULL;
2206                 } else {
2207                         it->inp = inp_next;
2208                 }
2209                 it->stcb = NULL;
2210         }
2211 }
2212
2213 /* release sctp_inpcb unbind the port */
2214 void
2215 sctp_inpcb_free(struct sctp_inpcb *inp, int immediate)
2216 {
2217         /*
2218          * Here we free a endpoint. We must find it (if it is in the Hash
2219          * table) and remove it from there. Then we must also find it in
2220          * the overall list and remove it from there. After all removals are
2221          * complete then any timer has to be stopped. Then start the actual
2222          * freeing.
2223          * a) Any local lists.
2224          * b) Any associations.
2225          * c) The hash of all associations.
2226          * d) finally the ep itself.
2227          */
2228         struct sctp_pcb *m;
2229         struct sctp_inpcb *inp_save;
2230         struct sctp_tcb *asoc, *nasoc;
2231         struct sctp_laddr *laddr, *nladdr;
2232         struct inpcb *ip_pcb;
2233         struct socket *so;
2234         struct sctp_socket_q_list *sq;
2235 #if !defined(__FreeBSD__) || __FreeBSD_version < 500000
2236         struct rtentry *rt;
2237 #endif
2238         int s, cnt;
2239
2240 #if defined(__NetBSD__) || defined(__OpenBSD__)
2241         s = splsoftnet();
2242 #else
2243         s = splnet();
2244 #endif
2245         SCTP_ASOC_CREATE_LOCK(inp);
2246         SCTP_INP_WLOCK(inp);
2247
2248         if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) {
2249                 /* been here before */
2250                 splx(s);
2251                 printf("Endpoint was all gone (dup free)?\n");
2252                 SCTP_INP_WUNLOCK(inp);
2253                 SCTP_ASOC_CREATE_UNLOCK(inp);
2254                 return;
2255         }
2256         sctp_timer_stop(SCTP_TIMER_TYPE_NEWCOOKIE, inp, NULL, NULL);
2257
2258         if (inp->control) {
2259                 sctp_m_freem(inp->control);
2260                 inp->control = NULL;
2261         }
2262         if (inp->pkt) {
2263                 sctp_m_freem(inp->pkt);
2264                 inp->pkt = NULL;
2265         }
2266         so  = inp->sctp_socket;
2267         m = &inp->sctp_ep;
2268         ip_pcb = &inp->ip_inp.inp; /* we could just cast the main
2269                                    * pointer here but I will
2270                                    * be nice :> (i.e. ip_pcb = ep;)
2271                                    */
2272
2273         if (immediate == 0) {
2274                 int cnt_in_sd;
2275                 cnt_in_sd = 0;
2276                 for ((asoc = LIST_FIRST(&inp->sctp_asoc_list)); asoc != NULL;
2277                      asoc = nasoc) {
2278                         nasoc = LIST_NEXT(asoc, sctp_tcblist);
2279                         if ((SCTP_GET_STATE(&asoc->asoc) == SCTP_STATE_COOKIE_WAIT) ||
2280                             (SCTP_GET_STATE(&asoc->asoc) == SCTP_STATE_COOKIE_ECHOED)) {
2281                                 /* Just abandon things in the front states */
2282                                 SCTP_TCB_LOCK(asoc);
2283                                 SCTP_INP_WUNLOCK(inp);
2284                                 sctp_free_assoc(inp, asoc);
2285                                 SCTP_INP_WLOCK(inp);
2286                                 continue;
2287                         } else {
2288                                 asoc->asoc.state |= SCTP_STATE_CLOSED_SOCKET;
2289                         }
2290                         if ((asoc->asoc.size_on_delivery_queue  > 0) ||
2291                             (asoc->asoc.size_on_reasm_queue > 0) ||
2292                             (asoc->asoc.size_on_all_streams > 0) ||
2293                             (so && (so->so_rcv.sb_cc > 0))
2294                                 ) {
2295                                 /* Left with Data unread */
2296                                 struct mbuf *op_err;
2297                                 MGET(op_err, M_DONTWAIT, MT_DATA);
2298                                 if (op_err) {
2299                                         /* Fill in the user initiated abort */
2300                                         struct sctp_paramhdr *ph;
2301                                         op_err->m_len =
2302                                             sizeof(struct sctp_paramhdr);
2303                                         ph = mtod(op_err,
2304                                             struct sctp_paramhdr *);
2305                                         ph->param_type = htons(
2306                                             SCTP_CAUSE_USER_INITIATED_ABT);
2307                                         ph->param_length = htons(op_err->m_len);
2308                                 }
2309                                 SCTP_TCB_LOCK(asoc);
2310                                 sctp_send_abort_tcb(asoc, op_err);
2311
2312                                 SCTP_INP_WUNLOCK(inp);
2313                                 sctp_free_assoc(inp, asoc);
2314                                 SCTP_INP_WLOCK(inp);
2315                                 continue;
2316                         } else if (TAILQ_EMPTY(&asoc->asoc.send_queue) &&
2317                             TAILQ_EMPTY(&asoc->asoc.sent_queue)) {
2318                                 if ((SCTP_GET_STATE(&asoc->asoc) != SCTP_STATE_SHUTDOWN_SENT) &&
2319                                     (SCTP_GET_STATE(&asoc->asoc) != SCTP_STATE_SHUTDOWN_ACK_SENT)) {
2320                                         /* there is nothing queued to send, so I send shutdown */
2321                                         SCTP_TCB_LOCK(asoc);
2322                                         sctp_send_shutdown(asoc, asoc->asoc.primary_destination);
2323                                         asoc->asoc.state = SCTP_STATE_SHUTDOWN_SENT;
2324                                         sctp_timer_start(SCTP_TIMER_TYPE_SHUTDOWN, asoc->sctp_ep, asoc,
2325                                                          asoc->asoc.primary_destination);
2326                                         sctp_timer_start(SCTP_TIMER_TYPE_SHUTDOWNGUARD, asoc->sctp_ep, asoc,
2327                                                          asoc->asoc.primary_destination);
2328                                         sctp_chunk_output(inp, asoc, 1);
2329                                         SCTP_TCB_UNLOCK(asoc);
2330                                 }
2331                         } else {
2332                                 /* mark into shutdown pending */
2333                                 asoc->asoc.state |= SCTP_STATE_SHUTDOWN_PENDING;
2334                         }
2335                         cnt_in_sd++;
2336                 }
2337                 /* now is there some left in our SHUTDOWN state? */
2338                 if (cnt_in_sd) {
2339                         inp->sctp_flags |= SCTP_PCB_FLAGS_SOCKET_GONE;
2340                         splx(s);
2341                         SCTP_INP_WUNLOCK(inp);
2342                         SCTP_ASOC_CREATE_UNLOCK(inp);
2343                         return;
2344                 }
2345         }
2346 #if defined(__FreeBSD__) && __FreeBSD_version >= 503000
2347         if (inp->refcount) {
2348                 sctp_timer_start(SCTP_TIMER_TYPE_INPKILL, inp, NULL, NULL);
2349                 SCTP_INP_WUNLOCK(inp);
2350                 SCTP_ASOC_CREATE_UNLOCK(inp);
2351                 return;
2352         }
2353 #endif
2354         inp->sctp_flags |= SCTP_PCB_FLAGS_SOCKET_ALLGONE;
2355 #if !defined(__FreeBSD__) || __FreeBSD_version < 500000
2356         rt = ip_pcb->inp_route.ro_rt;
2357 #endif
2358
2359         callout_stop(&inp->sctp_ep.signature_change.timer);
2360
2361         if (so) {
2362         /* First take care of socket level things */
2363 #ifdef IPSEC
2364 #ifdef __OpenBSD__
2365         /* XXX IPsec cleanup here */
2366                 int s2 = spltdb();
2367                 if (ip_pcb->inp_tdb_in)
2368                     TAILQ_REMOVE(&ip_pcb->inp_tdb_in->tdb_inp_in,
2369                                  ip_pcb, inp_tdb_in_next);
2370                 if (ip_pcb->inp_tdb_out)
2371                     TAILQ_REMOVE(&ip_pcb->inp_tdb_out->tdb_inp_out, ip_pcb,
2372                                  inp_tdb_out_next);
2373                 if (ip_pcb->inp_ipsec_localid)
2374                     ipsp_reffree(ip_pcb->inp_ipsec_localid);
2375                 if (ip_pcb->inp_ipsec_remoteid)
2376                     ipsp_reffree(ip_pcb->inp_ipsec_remoteid);
2377                 if (ip_pcb->inp_ipsec_localcred)
2378                     ipsp_reffree(ip_pcb->inp_ipsec_localcred);
2379                 if (ip_pcb->inp_ipsec_remotecred)
2380                     ipsp_reffree(ip_pcb->inp_ipsec_remotecred);
2381                 if (ip_pcb->inp_ipsec_localauth)
2382                     ipsp_reffree(ip_pcb->inp_ipsec_localauth);
2383                 if (ip_pcb->inp_ipsec_remoteauth)
2384                     ipsp_reffree(ip_pcb->inp_ipsec_remoteauth);
2385                 splx(s2);
2386 #else
2387                 ipsec4_delete_pcbpolicy(ip_pcb);
2388 #endif
2389 #endif /*IPSEC*/
2390 #if defined(__FreeBSD__) && __FreeBSD_version > 500000
2391                 ACCEPT_LOCK();
2392                 SOCK_LOCK(so);
2393 #endif
2394                 so->so_pcb = 0;
2395 #if defined(__FreeBSD__) && __FreeBSD_version > 500000
2396                 sotryfree(so);
2397 #else
2398                 sofree(so);
2399 #endif
2400         }
2401
2402         if (ip_pcb->inp_options) {
2403                 (void)m_free(ip_pcb->inp_options);
2404                 ip_pcb->inp_options = 0;
2405         }
2406 #if !defined(__FreeBSD__) || __FreeBSD_version < 500000
2407         if (rt) {
2408                 RTFREE(rt);
2409                 ip_pcb->inp_route.ro_rt = 0;
2410         }
2411 #endif
2412         if (ip_pcb->inp_moptions) {
2413                 ip_freemoptions(ip_pcb->inp_moptions);
2414                 ip_pcb->inp_moptions = 0;
2415         }
2416 #if !(defined(__FreeBSD__) || defined(__APPLE__))
2417         inp->inp_vflag = 0;
2418 #else
2419         ip_pcb->inp_vflag = 0;
2420 #endif
2421
2422         /* Now the sctp_pcb things */
2423
2424         /*
2425          * free each asoc if it is not already closed/free. we can't use
2426          * the macro here since le_next will get freed as part of the
2427          * sctp_free_assoc() call.
2428          */
2429         cnt = 0;
2430         for ((asoc = LIST_FIRST(&inp->sctp_asoc_list)); asoc != NULL;
2431              asoc = nasoc) {
2432                 nasoc = LIST_NEXT(asoc, sctp_tcblist);
2433                 SCTP_TCB_LOCK(asoc);
2434                 if (SCTP_GET_STATE(&asoc->asoc) != SCTP_STATE_COOKIE_WAIT) {
2435                         struct mbuf *op_err;
2436                         MGET(op_err, M_DONTWAIT, MT_DATA);
2437                         if (op_err) {
2438                                 /* Fill in the user initiated abort */
2439                                 struct sctp_paramhdr *ph;
2440                                 op_err->m_len = sizeof(struct sctp_paramhdr);
2441                                 ph = mtod(op_err, struct sctp_paramhdr *);
2442                                 ph->param_type = htons(
2443                                     SCTP_CAUSE_USER_INITIATED_ABT);
2444                                 ph->param_length = htons(op_err->m_len);
2445                         }
2446                         sctp_send_abort_tcb(asoc, op_err);
2447                 }
2448                 cnt++;
2449                 /*
2450                  * sctp_free_assoc() will call sctp_inpcb_free(),
2451                  * if SCTP_PCB_FLAGS_SOCKET_GONE set.
2452                  * So, we clear it before sctp_free_assoc() making sure
2453                  * no double sctp_inpcb_free().
2454                  */
2455                 inp->sctp_flags &= ~SCTP_PCB_FLAGS_SOCKET_GONE;
2456                 SCTP_INP_WUNLOCK(inp);
2457                 sctp_free_assoc(inp, asoc);
2458                 SCTP_INP_WLOCK(inp);
2459         }
2460         while ((sq = TAILQ_FIRST(&inp->sctp_queue_list)) != NULL) {
2461                 TAILQ_REMOVE(&inp->sctp_queue_list, sq, next_sq);
2462                 SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_sockq, sq);
2463                 sctppcbinfo.ipi_count_sockq--;
2464                 sctppcbinfo.ipi_gencnt_sockq++;
2465         }
2466         inp->sctp_socket = 0;
2467         /* Now first we remove ourselves from the overall list of all EP's */
2468
2469         /* Unlock inp first, need correct order */
2470         SCTP_INP_WUNLOCK(inp);
2471         /* now iterator lock */
2472         SCTP_ITERATOR_LOCK();
2473         /* now info lock */
2474         SCTP_INP_INFO_WLOCK();
2475         /* now reget the inp lock */
2476         SCTP_INP_WLOCK(inp);
2477
2478         inp_save = LIST_NEXT(inp, sctp_list);
2479         LIST_REMOVE(inp, sctp_list);
2480         /*
2481          * Now the question comes as to if this EP was ever bound at all.
2482          * If it was, then we must pull it out of the EP hash list.
2483          */
2484         if ((inp->sctp_flags & SCTP_PCB_FLAGS_UNBOUND) !=
2485             SCTP_PCB_FLAGS_UNBOUND) {
2486                 /*
2487                  * ok, this guy has been bound. It's port is somewhere
2488                  * in the sctppcbinfo hash table. Remove it!
2489                  */
2490                 LIST_REMOVE(inp, sctp_hash);
2491         }
2492         /* fix any iterators only after out of the list */
2493         sctp_iterator_inp_being_freed(inp, inp_save);
2494         SCTP_ITERATOR_UNLOCK();
2495         /*
2496          * if we have an address list the following will free the list of
2497          * ifaddr's that are set into this ep. Again macro limitations here,
2498          * since the LIST_FOREACH could be a bad idea.
2499          */
2500         for ((laddr = LIST_FIRST(&inp->sctp_addr_list)); laddr != NULL;
2501              laddr = nladdr) {
2502                 nladdr = LIST_NEXT(laddr, sctp_nxt_addr);
2503                 LIST_REMOVE(laddr, sctp_nxt_addr);
2504                 SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_laddr, laddr);
2505                 sctppcbinfo.ipi_gencnt_laddr++;
2506                 sctppcbinfo.ipi_count_laddr--;
2507         }
2508         /* Now lets see about freeing the EP hash table. */
2509         if (inp->sctp_tcbhash != NULL) {
2510                 FREE(inp->sctp_tcbhash, M_PCB);
2511                 inp->sctp_tcbhash = 0;
2512         }
2513         SCTP_INP_WUNLOCK(inp);
2514         SCTP_ASOC_CREATE_UNLOCK(inp);
2515         SCTP_INP_LOCK_DESTROY(inp);
2516         SCTP_ASOC_CREATE_LOCK_DESTROY(inp);
2517
2518         /* Now we must put the ep memory back into the zone pool */
2519         SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_ep, inp);
2520         sctppcbinfo.ipi_count_ep--;
2521
2522         SCTP_INP_INFO_WUNLOCK();
2523         splx(s);
2524 }
2525
2526
2527 struct sctp_nets *
2528 sctp_findnet(struct sctp_tcb *stcb, struct sockaddr *addr)
2529 {
2530         struct sctp_nets *net;
2531         struct sockaddr_in *sin;
2532         struct sockaddr_in6 *sin6;
2533         /* use the peer's/remote port for lookup if unspecified */
2534         sin = (struct sockaddr_in *)addr;
2535         sin6 = (struct sockaddr_in6 *)addr;
2536 #if 0 /* why do we need to check the port for a nets list on an assoc? */
2537         if (stcb->rport != sin->sin_port) {
2538                 /* we cheat and just a sin for this test */
2539                 return (NULL);
2540         }
2541 #endif
2542         /* locate the address */
2543         TAILQ_FOREACH(net, &stcb->asoc.nets, sctp_next) {
2544                 if (sctp_cmpaddr(addr, (struct sockaddr *)&net->ro._l_addr))
2545                         return (net);
2546         }
2547         return (NULL);
2548 }
2549
2550
2551 /*
2552  * add's a remote endpoint address, done with the INIT/INIT-ACK
2553  * as well as when a ASCONF arrives that adds it. It will also
2554  * initialize all the cwnd stats of stuff.
2555  */
2556 int
2557 sctp_is_address_on_local_host(struct sockaddr *addr)
2558 {
2559         struct ifnet *ifn;
2560         struct ifaddr *ifa;
2561         TAILQ_FOREACH(ifn, &ifnet, if_list) {
2562                 TAILQ_FOREACH(ifa, &ifn->if_addrlist, ifa_list) {
2563                         if (addr->sa_family == ifa->ifa_addr->sa_family) {
2564                                 /* same family */
2565                                 if (addr->sa_family == AF_INET) {
2566                                         struct sockaddr_in *sin, *sin_c;
2567                                         sin = (struct sockaddr_in *)addr;
2568                                         sin_c = (struct sockaddr_in *)
2569                                             ifa->ifa_addr;
2570                                         if (sin->sin_addr.s_addr ==
2571                                             sin_c->sin_addr.s_addr) {
2572                                                 /* we are on the same machine */
2573                                                 return (1);
2574                                         }
2575                                 } else if (addr->sa_family == AF_INET6) {
2576                                         struct sockaddr_in6 *sin6, *sin_c6;
2577                                         sin6 = (struct sockaddr_in6 *)addr;
2578                                         sin_c6 = (struct sockaddr_in6 *)
2579                                             ifa->ifa_addr;
2580                                         if (SCTP6_ARE_ADDR_EQUAL(&sin6->sin6_addr,
2581                                             &sin_c6->sin6_addr)) {
2582                                                 /* we are on the same machine */
2583                                                 return (1);
2584                                         }
2585                                 }
2586                         }
2587                 }
2588         }
2589         return (0);
2590 }
2591
2592 int
2593 sctp_add_remote_addr(struct sctp_tcb *stcb, struct sockaddr *newaddr,
2594     int set_scope, int from)
2595 {
2596         /*
2597          * The following is redundant to the same lines in the
2598          * sctp_aloc_assoc() but is needed since other's call the add
2599          * address function
2600          */
2601         struct sctp_nets *net, *netfirst;
2602         int addr_inscope;
2603
2604 #ifdef SCTP_DEBUG
2605         if (sctp_debug_on & SCTP_DEBUG_PCB1) {
2606                 printf("Adding an address (from:%d) to the peer: ", from);
2607                 sctp_print_address(newaddr);
2608         }
2609 #endif
2610         netfirst = sctp_findnet(stcb, newaddr);
2611         if (netfirst) {
2612                 /*
2613                  * Lie and return ok, we don't want to make the association
2614                  * go away for this behavior. It will happen in the TCP model
2615                  * in a connected socket. It does not reach the hash table
2616                  * until after the association is built so it can't be found.
2617                  * Mark as reachable, since the initial creation will have
2618                  * been cleared and the NOT_IN_ASSOC flag will have been
2619                  * added... and we don't want to end up removing it back out.
2620                  */
2621                 if (netfirst->dest_state & SCTP_ADDR_UNCONFIRMED) {
2622                         netfirst->dest_state = (SCTP_ADDR_REACHABLE|
2623                             SCTP_ADDR_UNCONFIRMED);
2624                 } else {
2625                         netfirst->dest_state = SCTP_ADDR_REACHABLE;
2626                 }
2627
2628                 return (0);
2629         }
2630         addr_inscope = 1;
2631         if (newaddr->sa_family == AF_INET) {
2632                 struct sockaddr_in *sin;
2633                 sin = (struct sockaddr_in *)newaddr;
2634                 if (sin->sin_addr.s_addr == 0) {
2635                         /* Invalid address */
2636                         return (-1);
2637                 }
2638                 /* zero out the bzero area */
2639                 memset(&sin->sin_zero, 0, sizeof(sin->sin_zero));
2640
2641                 /* assure len is set */
2642                 sin->sin_len = sizeof(struct sockaddr_in);
2643                 if (set_scope) {
2644 #ifdef SCTP_DONT_DO_PRIVADDR_SCOPE
2645                         stcb->ipv4_local_scope = 1;
2646 #else
2647                         if (IN4_ISPRIVATE_ADDRESS(&sin->sin_addr)) {
2648                                 stcb->asoc.ipv4_local_scope = 1;
2649                         }
2650 #endif /* SCTP_DONT_DO_PRIVADDR_SCOPE */
2651
2652                         if (sctp_is_address_on_local_host(newaddr)) {
2653                                 stcb->asoc.loopback_scope = 1;
2654                                 stcb->asoc.ipv4_local_scope = 1;
2655                                 stcb->asoc.local_scope = 1;
2656                                 stcb->asoc.site_scope = 1;
2657                         }
2658                 } else {
2659                         if (from == 8) {
2660                                 /* From connectx */
2661                                 if (sctp_is_address_on_local_host(newaddr)) {
2662                                         stcb->asoc.loopback_scope = 1;
2663                                         stcb->asoc.ipv4_local_scope = 1;
2664                                         stcb->asoc.local_scope = 1;
2665                                         stcb->asoc.site_scope = 1;
2666                                 }
2667                         }
2668                         /* Validate the address is in scope */
2669                         if ((IN4_ISPRIVATE_ADDRESS(&sin->sin_addr)) &&
2670                             (stcb->asoc.ipv4_local_scope == 0)) {
2671                                 addr_inscope = 0;
2672                         }
2673                 }
2674         } else if (newaddr->sa_family == AF_INET6) {
2675                 struct sockaddr_in6 *sin6;
2676                 sin6 = (struct sockaddr_in6 *)newaddr;
2677                 if (IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr)) {
2678                         /* Invalid address */
2679                         return (-1);
2680                 }
2681                 /* assure len is set */
2682                 sin6->sin6_len = sizeof(struct sockaddr_in6);
2683                 if (set_scope) {
2684                         if (sctp_is_address_on_local_host(newaddr)) {
2685                                 stcb->asoc.loopback_scope = 1;
2686                                 stcb->asoc.local_scope = 1;
2687                                 stcb->asoc.ipv4_local_scope = 1;
2688                                 stcb->asoc.site_scope = 1;
2689                         } else if (IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr)) {
2690                                 /*
2691                                  * If the new destination is a LINK_LOCAL
2692                                  * we must have common site scope. Don't set
2693                                  * the local scope since we may not share all
2694                                  * links, only loopback can do this.
2695                                  * Links on the local network would also
2696                                  * be on our private network for v4 too.
2697                                  */
2698                                 stcb->asoc.ipv4_local_scope = 1;
2699                                 stcb->asoc.site_scope = 1;
2700                         } else if (IN6_IS_ADDR_SITELOCAL(&sin6->sin6_addr)) {
2701                                 /*
2702                                  * If the new destination is SITE_LOCAL
2703                                  * then we must have site scope in common.
2704                                  */
2705                                 stcb->asoc.site_scope = 1;
2706                         }
2707                 } else {
2708                         if (from == 8) {
2709                                 /* From connectx */
2710                                 if (sctp_is_address_on_local_host(newaddr)) {
2711                                         stcb->asoc.loopback_scope = 1;
2712                                         stcb->asoc.ipv4_local_scope = 1;
2713                                         stcb->asoc.local_scope = 1;
2714                                         stcb->asoc.site_scope = 1;
2715                                 }
2716                         }
2717                         /* Validate the address is in scope */
2718                         if (IN6_IS_ADDR_LOOPBACK(&sin6->sin6_addr) &&
2719                             (stcb->asoc.loopback_scope == 0)) {
2720                                 addr_inscope = 0;
2721                         } else if (IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr) &&
2722                                    (stcb->asoc.local_scope == 0)) {
2723                                 addr_inscope = 0;
2724                         } else if (IN6_IS_ADDR_SITELOCAL(&sin6->sin6_addr) &&
2725                                    (stcb->asoc.site_scope == 0)) {
2726                                 addr_inscope = 0;
2727                         }
2728                 }
2729         } else {
2730                 /* not supported family type */
2731                 return (-1);
2732         }
2733         net = (struct sctp_nets *)SCTP_ZONE_GET(sctppcbinfo.ipi_zone_net);
2734         if (net == NULL) {
2735                 return (-1);
2736         }
2737         sctppcbinfo.ipi_count_raddr++;
2738         sctppcbinfo.ipi_gencnt_raddr++;
2739         bzero(net, sizeof(*net));
2740         memcpy(&net->ro._l_addr, newaddr, newaddr->sa_len);
2741         if (newaddr->sa_family == AF_INET) {
2742                 ((struct sockaddr_in *)&net->ro._l_addr)->sin_port = stcb->rport;
2743         } else if (newaddr->sa_family == AF_INET6) {
2744                 ((struct sockaddr_in6 *)&net->ro._l_addr)->sin6_port = stcb->rport;
2745         }
2746         net->addr_is_local = sctp_is_address_on_local_host(newaddr);
2747         net->failure_threshold = stcb->asoc.def_net_failure;
2748         if (addr_inscope == 0) {
2749 #ifdef SCTP_DEBUG
2750                 if (sctp_debug_on & SCTP_DEBUG_PCB1) {
2751                         printf("Adding an address which is OUT OF SCOPE\n");
2752                 }
2753 #endif /* SCTP_DEBUG */
2754                 net->dest_state = (SCTP_ADDR_REACHABLE |
2755                     SCTP_ADDR_OUT_OF_SCOPE);
2756         } else {
2757                 if (from == 8)
2758                         /* 8 is passed by connect_x */
2759                         net->dest_state = SCTP_ADDR_REACHABLE;
2760                 else
2761                         net->dest_state = SCTP_ADDR_REACHABLE |
2762                             SCTP_ADDR_UNCONFIRMED;
2763         }
2764         net->RTO = stcb->asoc.initial_rto;
2765         stcb->asoc.numnets++;
2766         net->ref_count = 1;
2767
2768         /* Init the timer structure */
2769 #if defined(__FreeBSD__) && __FreeBSD_version >= 500000
2770         callout_init(&net->rxt_timer.timer, 0);
2771 #else
2772         callout_init(&net->rxt_timer.timer);
2773 #endif
2774
2775         /* Now generate a route for this guy */
2776         /* KAME hack: embed scopeid */
2777         if (newaddr->sa_family == AF_INET6) {
2778                 struct sockaddr_in6 *sin6;
2779                 sin6 = (struct sockaddr_in6 *)&net->ro._l_addr;
2780 #if defined(SCTP_BASE_FREEBSD) || defined(__APPLE__)
2781                 (void)in6_embedscope(&sin6->sin6_addr, sin6,
2782                     &stcb->sctp_ep->ip_inp.inp, NULL);
2783 #else
2784                 (void)in6_embedscope(&sin6->sin6_addr, sin6);
2785 #endif
2786 #ifndef SCOPEDROUTING
2787                 sin6->sin6_scope_id = 0;
2788 #endif
2789         }
2790 #if defined(__FreeBSD__) || defined(__APPLE__)
2791         rtalloc_ign((struct route *)&net->ro, 0UL);
2792 #else
2793         rtalloc((struct route *)&net->ro);
2794 #endif
2795         if (newaddr->sa_family == AF_INET6) {
2796                 struct sockaddr_in6 *sin6;
2797                 sin6 = (struct sockaddr_in6 *)&net->ro._l_addr;
2798                 (void)in6_recoverscope(sin6, &sin6->sin6_addr, NULL);
2799         }
2800         if ((net->ro.ro_rt) &&
2801             (net->ro.ro_rt->rt_ifp)) {
2802                 net->mtu = net->ro.ro_rt->rt_ifp->if_mtu;
2803                 if (from == 1) {
2804                         stcb->asoc.smallest_mtu = net->mtu;
2805                 }
2806                 /* start things off to match mtu of interface please. */
2807                 net->ro.ro_rt->rt_rmx.rmx_mtu = net->ro.ro_rt->rt_ifp->if_mtu;
2808         } else {
2809                 net->mtu = stcb->asoc.smallest_mtu;
2810         }
2811         if (stcb->asoc.smallest_mtu > net->mtu) {
2812                 stcb->asoc.smallest_mtu = net->mtu;
2813         }
2814         /* We take the max of the burst limit times a MTU or the INITIAL_CWND.
2815          * We then limit this to 4 MTU's of sending.
2816          */
2817         net->cwnd = min((net->mtu * 4), max((stcb->asoc.max_burst * net->mtu), SCTP_INITIAL_CWND));
2818
2819         /* we always get at LEAST 2 MTU's */
2820         if (net->cwnd < (2 * net->mtu)) {
2821                 net->cwnd = 2 * net->mtu;
2822         }
2823
2824         net->ssthresh = stcb->asoc.peers_rwnd;
2825
2826         net->src_addr_selected = 0;
2827         netfirst = TAILQ_FIRST(&stcb->asoc.nets);
2828         if (net->ro.ro_rt == NULL) {
2829                 /* Since we have no route put it at the back */
2830                 TAILQ_INSERT_TAIL(&stcb->asoc.nets, net, sctp_next);
2831         } else if (netfirst == NULL) {
2832                 /* We are the first one in the pool. */
2833                 TAILQ_INSERT_HEAD(&stcb->asoc.nets, net, sctp_next);
2834         } else if (netfirst->ro.ro_rt == NULL) {
2835                 /*
2836                  * First one has NO route. Place this one ahead of the
2837                  * first one.
2838                  */
2839                 TAILQ_INSERT_HEAD(&stcb->asoc.nets, net, sctp_next);
2840         } else if (net->ro.ro_rt->rt_ifp != netfirst->ro.ro_rt->rt_ifp) {
2841                 /*
2842                  * This one has a different interface than the one at the
2843                  * top of the list. Place it ahead.
2844                  */
2845                 TAILQ_INSERT_HEAD(&stcb->asoc.nets, net, sctp_next);
2846         } else {
2847                 /*
2848                  * Ok we have the same interface as the first one. Move
2849                  * forward until we find either
2850                  *   a) one with a NULL route... insert ahead of that
2851                  *   b) one with a different ifp.. insert after that.
2852                  *   c) end of the list.. insert at the tail.
2853                  */
2854                 struct sctp_nets *netlook;
2855                 do {
2856                         netlook = TAILQ_NEXT(netfirst, sctp_next);
2857                         if (netlook == NULL) {
2858                                 /* End of the list */
2859                                 TAILQ_INSERT_TAIL(&stcb->asoc.nets, net,
2860                                     sctp_next);
2861                                 break;
2862                         } else if (netlook->ro.ro_rt == NULL) {
2863                                 /* next one has NO route */
2864                                 TAILQ_INSERT_BEFORE(netfirst, net, sctp_next);
2865                                 break;
2866                         } else if (netlook->ro.ro_rt->rt_ifp !=
2867                                    net->ro.ro_rt->rt_ifp) {
2868                                 TAILQ_INSERT_AFTER(&stcb->asoc.nets, netlook,
2869                                     net, sctp_next);
2870                                 break;
2871                         }
2872                         /* Shift forward */
2873                         netfirst = netlook;
2874                 } while (netlook != NULL);
2875         }
2876         /* got to have a primary set */
2877         if (stcb->asoc.primary_destination == 0) {
2878                 stcb->asoc.primary_destination = net;
2879         } else if ((stcb->asoc.primary_destination->ro.ro_rt == NULL) &&
2880                    (net->ro.ro_rt)) {
2881                 /* No route to current primary adopt new primary */
2882                 stcb->asoc.primary_destination = net;
2883         }
2884         sctp_timer_start(SCTP_TIMER_TYPE_PATHMTURAISE, stcb->sctp_ep, stcb,
2885             net);
2886
2887         return (0);
2888 }
2889
2890
2891 /*
2892  * allocate an association and add it to the endpoint. The caller must
2893  * be careful to add all additional addresses once they are know right
2894  * away or else the assoc will be may experience a blackout scenario.
2895  */
2896 struct sctp_tcb *
2897 sctp_aloc_assoc(struct sctp_inpcb *inp, struct sockaddr *firstaddr,
2898     int for_a_init, int *error,  uint32_t override_tag)
2899 {
2900         struct sctp_tcb *stcb;
2901         struct sctp_association *asoc;
2902         struct sctpasochead *head;
2903         uint16_t rport;
2904         int err;
2905
2906         /*
2907          * Assumption made here:
2908          *  Caller has done a sctp_findassociation_ep_addr(ep, addr's);
2909          *  to make sure the address does not exist already.
2910          */
2911         if (sctppcbinfo.ipi_count_asoc >= SCTP_MAX_NUM_OF_ASOC) {
2912                 /* Hit max assoc, sorry no more */
2913                 *error = ENOBUFS;
2914                 return (NULL);
2915         }
2916         SCTP_INP_RLOCK(inp);
2917         if (inp->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL) {
2918                 /*
2919                  * If its in the TCP pool, its NOT allowed to create an
2920                  * association. The parent listener needs to call
2921                  * sctp_aloc_assoc.. or the one-2-many socket. If a
2922                  * peeled off, or connected one does this.. its an error.
2923                  */
2924                 SCTP_INP_RUNLOCK(inp);
2925                 *error = EINVAL;
2926                 return (NULL);
2927         }
2928
2929 #ifdef SCTP_DEBUG
2930         if (sctp_debug_on & SCTP_DEBUG_PCB3) {
2931                 printf("Allocate an association for peer:");
2932                 if (firstaddr)
2933                         sctp_print_address(firstaddr);
2934                 else
2935                         printf("None\n");
2936                 printf("Port:%d\n",
2937                        ntohs(((struct sockaddr_in *)firstaddr)->sin_port));
2938         }
2939 #endif /* SCTP_DEBUG */
2940         if (firstaddr->sa_family == AF_INET) {
2941                 struct sockaddr_in *sin;
2942                 sin = (struct sockaddr_in *)firstaddr;
2943                 if ((sin->sin_port == 0) || (sin->sin_addr.s_addr == 0)) {
2944                         /* Invalid address */
2945 #ifdef SCTP_DEBUG
2946                         if (sctp_debug_on & SCTP_DEBUG_PCB3) {
2947                                 printf("peer address invalid\n");
2948                         }
2949 #endif
2950                         SCTP_INP_RUNLOCK(inp);
2951                         *error = EINVAL;
2952                         return (NULL);
2953                 }
2954                 rport = sin->sin_port;
2955         } else if (firstaddr->sa_family == AF_INET6) {
2956                 struct sockaddr_in6 *sin6;
2957                 sin6 = (struct sockaddr_in6 *)firstaddr;
2958                 if ((sin6->sin6_port == 0) ||
2959                     (IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr))) {
2960                         /* Invalid address */
2961 #ifdef SCTP_DEBUG
2962                         if (sctp_debug_on & SCTP_DEBUG_PCB3) {
2963                                 printf("peer address invalid\n");
2964                         }
2965 #endif
2966                         SCTP_INP_RUNLOCK(inp);
2967                         *error = EINVAL;
2968                         return (NULL);
2969                 }
2970                 rport = sin6->sin6_port;
2971         } else {
2972                 /* not supported family type */
2973 #ifdef SCTP_DEBUG
2974                 if (sctp_debug_on & SCTP_DEBUG_PCB3) {
2975                         printf("BAD family %d\n", firstaddr->sa_family);
2976                 }
2977 #endif
2978                 SCTP_INP_RUNLOCK(inp);
2979                 *error = EINVAL;
2980                 return (NULL);
2981         }
2982         SCTP_INP_RUNLOCK(inp);
2983         if (inp->sctp_flags & SCTP_PCB_FLAGS_UNBOUND) {
2984                 /*
2985                  * If you have not performed a bind, then we need to do
2986                  * the ephemerial bind for you.
2987                  */
2988 #ifdef SCTP_DEBUG
2989                 if (sctp_debug_on & SCTP_DEBUG_PCB3) {
2990                         printf("Doing implicit BIND\n");
2991                 }
2992 #endif
2993
2994                 if ((err = sctp_inpcb_bind(inp->sctp_socket,
2995                     (struct sockaddr *)NULL,
2996 #if defined(__FreeBSD__) && __FreeBSD_version >= 500000
2997                                            (struct thread *)NULL
2998 #else
2999                                            (struct proc *)NULL
3000 #endif
3001                              ))){
3002                         /* bind error, probably perm */
3003 #ifdef SCTP_DEBUG
3004                         if (sctp_debug_on & SCTP_DEBUG_PCB3) {
3005                                 printf("BIND FAILS ret:%d\n", err);
3006                         }
3007 #endif
3008
3009                         *error = err;
3010                         return (NULL);
3011                 }
3012         }
3013         stcb = (struct sctp_tcb *)SCTP_ZONE_GET(sctppcbinfo.ipi_zone_asoc);
3014         if (stcb == NULL) {
3015                 /* out of memory? */
3016 #ifdef SCTP_DEBUG
3017                 if (sctp_debug_on & SCTP_DEBUG_PCB3) {
3018                         printf("aloc_assoc: no assoc mem left, stcb=NULL\n");
3019                 }
3020 #endif
3021                 *error = ENOMEM;
3022                 return (NULL);
3023         }
3024         sctppcbinfo.ipi_count_asoc++;
3025         sctppcbinfo.ipi_gencnt_asoc++;
3026
3027         bzero(stcb, sizeof(*stcb));
3028         asoc = &stcb->asoc;
3029         SCTP_TCB_LOCK_INIT(stcb);
3030         /* setup back pointer's */
3031         stcb->sctp_ep = inp;
3032         stcb->sctp_socket = inp->sctp_socket;
3033         if ((err = sctp_init_asoc(inp, asoc, for_a_init, override_tag))) {
3034                 /* failed */
3035                 SCTP_TCB_LOCK_DESTROY (stcb);
3036                 SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_asoc, stcb);
3037                 sctppcbinfo.ipi_count_asoc--;
3038 #ifdef SCTP_DEBUG
3039                 if (sctp_debug_on & SCTP_DEBUG_PCB3) {
3040                         printf("aloc_assoc: couldn't init asoc, out of mem?!\n");
3041                 }
3042 #endif
3043                 *error = err;
3044                 return (NULL);
3045         }
3046         /* and the port */
3047         stcb->rport = rport;
3048         SCTP_INP_INFO_WLOCK();
3049         SCTP_INP_WLOCK(inp);
3050         if (inp->sctp_flags & (SCTP_PCB_FLAGS_SOCKET_GONE|SCTP_PCB_FLAGS_SOCKET_ALLGONE)) {
3051                 /* inpcb freed while alloc going on */
3052                 SCTP_TCB_LOCK_DESTROY (stcb);
3053                 SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_asoc, stcb);
3054                 SCTP_INP_WUNLOCK(inp);
3055                 SCTP_INP_INFO_WUNLOCK();
3056                 sctppcbinfo.ipi_count_asoc--;
3057 #ifdef SCTP_DEBUG
3058                 if (sctp_debug_on & SCTP_DEBUG_PCB3) {
3059                         printf("aloc_assoc: couldn't init asoc, out of mem?!\n");
3060                 }
3061 #endif
3062                 *error = EINVAL;
3063                 return (NULL);
3064         }
3065         SCTP_TCB_LOCK(stcb);
3066
3067         /* now that my_vtag is set, add it to the  hash */
3068         head = &sctppcbinfo.sctp_asochash[SCTP_PCBHASH_ASOC(stcb->asoc.my_vtag,
3069              sctppcbinfo.hashasocmark)];
3070         /* put it in the bucket in the vtag hash of assoc's for the system */
3071         LIST_INSERT_HEAD(head, stcb, sctp_asocs);
3072         SCTP_INP_INFO_WUNLOCK();
3073
3074
3075         if ((err = sctp_add_remote_addr(stcb, firstaddr, 1, 1))) {
3076                 /* failure.. memory error? */
3077                 if (asoc->strmout)
3078                         FREE(asoc->strmout, M_PCB);
3079                 if (asoc->mapping_array)
3080                         FREE(asoc->mapping_array, M_PCB);
3081
3082                 SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_asoc, stcb);
3083                 sctppcbinfo.ipi_count_asoc--;
3084 #ifdef SCTP_DEBUG
3085                 if (sctp_debug_on & SCTP_DEBUG_PCB3) {
3086                         printf("aloc_assoc: couldn't add remote addr!\n");
3087                 }
3088 #endif
3089                 SCTP_TCB_LOCK_DESTROY (stcb);
3090                 *error = ENOBUFS;
3091                 return (NULL);
3092         }
3093         /* Init all the timers */
3094 #if defined(__FreeBSD__) && __FreeBSD_version >= 500000
3095         callout_init(&asoc->hb_timer.timer, 0);
3096         callout_init(&asoc->dack_timer.timer, 0);
3097         callout_init(&asoc->asconf_timer.timer, 0);
3098         callout_init(&asoc->shut_guard_timer.timer, 0);
3099         callout_init(&asoc->autoclose_timer.timer, 0);
3100 #else
3101         callout_init(&asoc->hb_timer.timer);
3102         callout_init(&asoc->dack_timer.timer);
3103         callout_init(&asoc->asconf_timer.timer);
3104         callout_init(&asoc->shut_guard_timer.timer);
3105         callout_init(&asoc->autoclose_timer.timer);
3106 #endif
3107         LIST_INSERT_HEAD(&inp->sctp_asoc_list, stcb, sctp_tcblist);
3108         /* now file the port under the hash as well */
3109         if (inp->sctp_tcbhash != NULL) {
3110                 head = &inp->sctp_tcbhash[SCTP_PCBHASH_ALLADDR(stcb->rport,
3111                    inp->sctp_hashmark)];
3112                 LIST_INSERT_HEAD(head, stcb, sctp_tcbhash);
3113         }
3114         SCTP_INP_WUNLOCK(inp);
3115 #ifdef SCTP_DEBUG
3116         if (sctp_debug_on & SCTP_DEBUG_PCB1) {
3117                 printf("Association %p now allocated\n", stcb);
3118         }
3119 #endif
3120         return (stcb);
3121 }
3122
3123 void
3124 sctp_free_remote_addr(struct sctp_nets *net)
3125 {
3126         if (net == NULL)
3127                 return;
3128         net->ref_count--;
3129         if (net->ref_count <= 0) {
3130                 /* stop timer if running */
3131                 callout_stop(&net->rxt_timer.timer);
3132                 callout_stop(&net->pmtu_timer.timer);
3133                 net->dest_state = SCTP_ADDR_NOT_REACHABLE;
3134                 SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_net, net);
3135                 sctppcbinfo.ipi_count_raddr--;
3136         }
3137 }
3138
3139 /*
3140  * remove a remote endpoint address from an association, it
3141  * will fail if the address does not exist.
3142  */
3143 int
3144 sctp_del_remote_addr(struct sctp_tcb *stcb, struct sockaddr *remaddr)
3145 {
3146         /*
3147          * Here we need to remove a remote address. This is quite simple, we
3148          * first find it in the list of address for the association
3149          * (tasoc->asoc.nets) and then if it is there, we do a LIST_REMOVE on
3150          * that item.
3151          * Note we do not allow it to be removed if there are no other
3152          * addresses.
3153          */
3154         struct sctp_association *asoc;
3155         struct sctp_nets *net, *net_tmp;
3156         asoc = &stcb->asoc;
3157         if (asoc->numnets < 2) {
3158                 /* Must have at LEAST two remote addresses */
3159                 return (-1);
3160         }
3161         /* locate the address */
3162         for (net = TAILQ_FIRST(&asoc->nets); net != NULL; net = net_tmp) {
3163                 net_tmp = TAILQ_NEXT(net, sctp_next);
3164                 if (net->ro._l_addr.sa.sa_family != remaddr->sa_family) {
3165                         continue;
3166                 }
3167                 if (sctp_cmpaddr((struct sockaddr *)&net->ro._l_addr,
3168                     remaddr)) {
3169                         /* we found the guy */
3170                         asoc->numnets--;
3171                         TAILQ_REMOVE(&asoc->nets, net, sctp_next);
3172                         sctp_free_remote_addr(net);
3173                         if (net == asoc->primary_destination) {
3174                                 /* Reset primary */
3175                                 struct sctp_nets *lnet;
3176                                 lnet = TAILQ_FIRST(&asoc->nets);
3177                                 /* Try to find a confirmed primary */
3178                                 asoc->primary_destination =
3179                                     sctp_find_alternate_net(stcb, lnet);
3180                         }
3181                         if (net == asoc->last_data_chunk_from) {
3182                                 /* Reset primary */
3183                                 asoc->last_data_chunk_from =
3184                                     TAILQ_FIRST(&asoc->nets);
3185                         }
3186                         if (net == asoc->last_control_chunk_from) {
3187                                 /* Reset primary */
3188                                 asoc->last_control_chunk_from =
3189                                     TAILQ_FIRST(&asoc->nets);
3190                         }
3191                         if (net == asoc->asconf_last_sent_to) {
3192                                 /* Reset primary */
3193                                 asoc->asconf_last_sent_to =
3194                                     TAILQ_FIRST(&asoc->nets);
3195                         }
3196                         return (0);
3197                 }
3198         }
3199         /* not found. */
3200         return (-2);
3201 }
3202
3203
3204 static void
3205 sctp_add_vtag_to_timewait(struct sctp_inpcb *inp, u_int32_t tag)
3206 {
3207         struct sctpvtaghead *chain;
3208         struct sctp_tagblock *twait_block;
3209         struct timeval now;
3210         int set, i;
3211         SCTP_GETTIME_TIMEVAL(&now);
3212         chain = &sctppcbinfo.vtag_timewait[(tag % SCTP_STACK_VTAG_HASH_SIZE)];
3213         set = 0;
3214         if (!LIST_EMPTY(chain)) {
3215                 /* Block(s) present, lets find space, and expire on the fly */
3216                 LIST_FOREACH(twait_block, chain, sctp_nxt_tagblock) {
3217                         for (i = 0; i < SCTP_NUMBER_IN_VTAG_BLOCK; i++) {
3218                                 if ((twait_block->vtag_block[i].v_tag == 0) &&
3219                                     !set) {
3220                                         twait_block->vtag_block[0].tv_sec_at_expire =
3221                                             now.tv_sec + SCTP_TIME_WAIT;
3222                                         twait_block->vtag_block[0].v_tag = tag;
3223                                         set = 1;
3224                                 } else if ((twait_block->vtag_block[i].v_tag) &&
3225                                     ((long)twait_block->vtag_block[i].tv_sec_at_expire >
3226                                     now.tv_sec)) {
3227                                         /* Audit expires this guy */
3228                                         twait_block->vtag_block[i].tv_sec_at_expire = 0;
3229                                         twait_block->vtag_block[i].v_tag = 0;
3230                                         if (set == 0) {
3231                                                 /* Reuse it for my new tag */
3232                                                 twait_block->vtag_block[0].tv_sec_at_expire = now.tv_sec + SCTP_TIME_WAIT;
3233                                                 twait_block->vtag_block[0].v_tag = tag;
3234                                                 set = 1;
3235                                         }
3236                                 }
3237                         }
3238                         if (set) {
3239                                 /*
3240                                  * We only do up to the block where we can
3241                                  * place our tag for audits
3242                                  */
3243                                 break;
3244                         }
3245                 }
3246         }
3247         /* Need to add a new block to chain */
3248         if (!set) {
3249                 MALLOC(twait_block, struct sctp_tagblock *,
3250                        sizeof(struct sctp_tagblock), M_PCB, M_NOWAIT);
3251                 if (twait_block == NULL) {
3252                         return;
3253                 }
3254                 memset(twait_block, 0, sizeof(struct sctp_timewait));
3255                 LIST_INSERT_HEAD(chain, twait_block, sctp_nxt_tagblock);
3256                 twait_block->vtag_block[0].tv_sec_at_expire = now.tv_sec +
3257                     SCTP_TIME_WAIT;
3258                 twait_block->vtag_block[0].v_tag = tag;
3259         }
3260 }
3261
3262
3263 static void
3264 sctp_iterator_asoc_being_freed(struct sctp_inpcb *inp, struct sctp_tcb *stcb)
3265 {
3266         struct sctp_iterator *it;
3267
3268
3269
3270         /* Unlock the tcb lock we do this so
3271          * we avoid a dead lock scenario where
3272          * the iterator is waiting on the TCB lock
3273          * and the TCB lock is waiting on the iterator
3274          * lock.
3275          */
3276         SCTP_ITERATOR_LOCK();
3277         SCTP_INP_INFO_WLOCK();
3278         SCTP_INP_WLOCK(inp);
3279         SCTP_TCB_LOCK(stcb);
3280
3281         it = stcb->asoc.stcb_starting_point_for_iterator;
3282         if (it == NULL) {
3283                 return;
3284         }
3285         if (it->inp != stcb->sctp_ep) {
3286                 /* hm, focused on the wrong one? */
3287                 return;
3288         }
3289         if (it->stcb != stcb) {
3290                 return;
3291         }
3292         it->stcb = LIST_NEXT(stcb, sctp_tcblist);
3293         if (it->stcb == NULL) {
3294                 /* done with all asoc's in this assoc */
3295                 if (it->iterator_flags & SCTP_ITERATOR_DO_SINGLE_INP) {
3296                         it->inp = NULL;
3297                 } else {
3298
3299                         it->inp = LIST_NEXT(inp, sctp_list);
3300                 }
3301         }
3302 }
3303
3304 /*
3305  * Free the association after un-hashing the remote port.
3306  */
3307 void
3308 sctp_free_assoc(struct sctp_inpcb *inp, struct sctp_tcb *stcb)
3309 {
3310         struct sctp_association *asoc;
3311         struct sctp_nets *net, *prev;
3312         struct sctp_laddr *laddr;
3313         struct sctp_tmit_chunk *chk;
3314         struct sctp_asconf_addr *aparam;
3315         struct sctp_socket_q_list *sq;
3316         int s;
3317
3318         /* first, lets purge the entry from the hash table. */
3319 #if defined(__NetBSD__) || defined(__OpenBSD__)
3320         s = splsoftnet();
3321 #else
3322         s = splnet();
3323 #endif
3324         if (stcb->asoc.state == 0) {
3325                 printf("Freeing already free association:%p - huh??\n",
3326                     stcb);
3327                 splx(s);
3328                 return;
3329         }
3330         asoc = &stcb->asoc;
3331         asoc->state = 0;
3332         /* now clean up any other timers */
3333         callout_stop(&asoc->hb_timer.timer);
3334         callout_stop(&asoc->dack_timer.timer);
3335         callout_stop(&asoc->asconf_timer.timer);
3336         callout_stop(&asoc->shut_guard_timer.timer);
3337         callout_stop(&asoc->autoclose_timer.timer);
3338         callout_stop(&asoc->delayed_event_timer.timer);
3339         TAILQ_FOREACH(net, &asoc->nets, sctp_next) {
3340                 callout_stop(&net->rxt_timer.timer);
3341                 callout_stop(&net->pmtu_timer.timer);
3342         }
3343
3344         /* Iterator asoc being freed we send an
3345          * unlocked TCB. It returns with INP_INFO
3346          * and INP write locked and the TCB locked
3347          * too and of course the iterator lock
3348          * in place as well..
3349          */
3350         SCTP_TCB_UNLOCK(stcb);
3351         sctp_iterator_asoc_being_freed(inp, stcb);
3352
3353         /* Null all of my entry's on the socket q */
3354         TAILQ_FOREACH(sq, &inp->sctp_queue_list, next_sq) {
3355                 if (sq->tcb == stcb) {
3356                         sq->tcb = NULL;
3357                 }
3358         }
3359
3360         if (inp->sctp_tcb_at_block == (void *)stcb) {
3361                 inp->error_on_block = ECONNRESET;
3362         }
3363
3364         if (inp->sctp_tcbhash) {
3365                 LIST_REMOVE(stcb, sctp_tcbhash);
3366         }
3367         /* Now lets remove it from the list of ALL associations in the EP */
3368         LIST_REMOVE(stcb, sctp_tcblist);
3369         SCTP_INP_WUNLOCK(inp);
3370         SCTP_ITERATOR_UNLOCK();
3371
3372
3373         /* pull from vtag hash */
3374         LIST_REMOVE(stcb, sctp_asocs);
3375
3376         /*
3377          * Now before we can free the assoc, we must  remove all of the
3378          * networks and any other allocated space.. i.e. add removes here
3379          * before the SCTP_ZONE_FREE() of the tasoc entry.
3380          */
3381
3382         sctp_add_vtag_to_timewait(inp, asoc->my_vtag);
3383         SCTP_INP_INFO_WUNLOCK();
3384         prev = NULL;
3385         while (!TAILQ_EMPTY(&asoc->nets)) {
3386                 net = TAILQ_FIRST(&asoc->nets);
3387                 /* pull from list */
3388                 if ((sctppcbinfo.ipi_count_raddr == 0) || (prev == net)) {
3389                         break;
3390                 }
3391                 prev = net;
3392                 TAILQ_REMOVE(&asoc->nets, net, sctp_next);
3393                 /* free it */
3394                 net->ref_count = 0;
3395                 SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_net, net);
3396                 sctppcbinfo.ipi_count_raddr--;
3397         }
3398         /*
3399          * The chunk lists and such SHOULD be empty but we check them
3400          * just in case.
3401          */
3402         /* anything on the wheel needs to be removed */
3403         while (!TAILQ_EMPTY(&asoc->out_wheel)) {
3404                 struct sctp_stream_out *outs;
3405                 outs = TAILQ_FIRST(&asoc->out_wheel);
3406                 TAILQ_REMOVE(&asoc->out_wheel, outs, next_spoke);
3407                 /* now clean up any chunks here */
3408                 chk = TAILQ_FIRST(&outs->outqueue);
3409                 while (chk) {
3410                         TAILQ_REMOVE(&outs->outqueue, chk, sctp_next);
3411                         if (chk->data) {
3412                                 sctp_m_freem(chk->data);
3413                                 chk->data = NULL;
3414                         }
3415                         chk->whoTo = NULL;
3416                         chk->asoc = NULL;
3417                         /* Free the chunk */
3418                         SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_chunk, chk);
3419                         sctppcbinfo.ipi_count_chunk--;
3420                         sctppcbinfo.ipi_gencnt_chunk++;
3421                         if ((int)sctppcbinfo.ipi_count_chunk < 0) {
3422                                 panic("Chunk count is negative");
3423                         }
3424                         chk = TAILQ_FIRST(&outs->outqueue);
3425                 }
3426                 outs = TAILQ_FIRST(&asoc->out_wheel);
3427         }
3428
3429         if (asoc->pending_reply) {
3430                 FREE(asoc->pending_reply, M_PCB);
3431                 asoc->pending_reply = NULL;
3432         }
3433         chk = TAILQ_FIRST(&asoc->pending_reply_queue);
3434         while (chk) {
3435                 TAILQ_REMOVE(&asoc->pending_reply_queue, chk, sctp_next);
3436                 if (chk->data) {
3437                         sctp_m_freem(chk->data);
3438                         chk->data = NULL;
3439                 }
3440                 chk->whoTo = NULL;
3441                 chk->asoc = NULL;
3442                 /* Free the chunk */
3443                 SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_chunk, chk);
3444                 sctppcbinfo.ipi_count_chunk--;
3445                 sctppcbinfo.ipi_gencnt_chunk++;
3446                 if ((int)sctppcbinfo.ipi_count_chunk < 0) {
3447                         panic("Chunk count is negative");
3448                 }
3449                 chk = TAILQ_FIRST(&asoc->pending_reply_queue);
3450         }
3451         /* pending send queue SHOULD be empty */
3452         if (!TAILQ_EMPTY(&asoc->send_queue)) {
3453                 chk = TAILQ_FIRST(&asoc->send_queue);
3454                 while (chk) {
3455                         TAILQ_REMOVE(&asoc->send_queue, chk, sctp_next);
3456                         if (chk->data) {
3457                                 sctp_m_freem(chk->data);
3458                                 chk->data = NULL;
3459                         }
3460                         SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_chunk, chk);
3461                         sctppcbinfo.ipi_count_chunk--;
3462                         if ((int)sctppcbinfo.ipi_count_chunk < 0) {
3463                                 panic("Chunk count is negative");
3464                         }
3465                         sctppcbinfo.ipi_gencnt_chunk++;
3466                         chk = TAILQ_FIRST(&asoc->send_queue);
3467                 }
3468         }
3469         /* sent queue SHOULD be empty */
3470         if (!TAILQ_EMPTY(&asoc->sent_queue)) {
3471                 chk = TAILQ_FIRST(&asoc->sent_queue);
3472                 while (chk) {
3473                         TAILQ_REMOVE(&asoc->sent_queue, chk, sctp_next);
3474                         if (chk->data) {
3475                                 sctp_m_freem(chk->data);
3476                                 chk->data = NULL;
3477                         }
3478                         SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_chunk, chk);
3479                         sctppcbinfo.ipi_count_chunk--;
3480                         if ((int)sctppcbinfo.ipi_count_chunk < 0) {
3481                                 panic("Chunk count is negative");
3482                         }
3483                         sctppcbinfo.ipi_gencnt_chunk++;
3484                         chk = TAILQ_FIRST(&asoc->sent_queue);
3485                 }
3486         }
3487         /* control queue MAY not be empty */
3488         if (!TAILQ_EMPTY(&asoc->control_send_queue)) {
3489                 chk = TAILQ_FIRST(&asoc->control_send_queue);
3490                 while (chk) {
3491                         TAILQ_REMOVE(&asoc->control_send_queue, chk, sctp_next);
3492                         if (chk->data) {
3493                                 sctp_m_freem(chk->data);
3494                                 chk->data = NULL;
3495                         }
3496                         SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_chunk, chk);
3497                         sctppcbinfo.ipi_count_chunk--;
3498                         if ((int)sctppcbinfo.ipi_count_chunk < 0) {
3499                                 panic("Chunk count is negative");
3500                         }
3501                         sctppcbinfo.ipi_gencnt_chunk++;
3502                         chk = TAILQ_FIRST(&asoc->control_send_queue);
3503                 }
3504         }
3505         if (!TAILQ_EMPTY(&asoc->reasmqueue)) {
3506                 chk = TAILQ_FIRST(&asoc->reasmqueue);
3507                 while (chk) {
3508                         TAILQ_REMOVE(&asoc->reasmqueue, chk, sctp_next);
3509                         if (chk->data) {
3510                                 sctp_m_freem(chk->data);
3511                                 chk->data = NULL;
3512                         }
3513                         SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_chunk, chk);
3514                         sctppcbinfo.ipi_count_chunk--;
3515                         if ((int)sctppcbinfo.ipi_count_chunk < 0) {
3516                                 panic("Chunk count is negative");
3517                         }
3518                         sctppcbinfo.ipi_gencnt_chunk++;
3519                         chk = TAILQ_FIRST(&asoc->reasmqueue);
3520                 }
3521         }
3522         if (!TAILQ_EMPTY(&asoc->delivery_queue)) {
3523                 chk = TAILQ_FIRST(&asoc->delivery_queue);
3524                 while (chk) {
3525                         TAILQ_REMOVE(&asoc->delivery_queue, chk, sctp_next);
3526                         if (chk->data) {
3527                                 sctp_m_freem(chk->data);
3528                                 chk->data = NULL;
3529                         }
3530                         SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_chunk, chk);
3531                         sctppcbinfo.ipi_count_chunk--;
3532                         if ((int)sctppcbinfo.ipi_count_chunk < 0) {
3533                                 panic("Chunk count is negative");
3534                         }
3535                         sctppcbinfo.ipi_gencnt_chunk++;
3536                         chk = TAILQ_FIRST(&asoc->delivery_queue);
3537                 }
3538         }
3539         if (asoc->mapping_array) {
3540                 FREE(asoc->mapping_array, M_PCB);
3541                 asoc->mapping_array = NULL;
3542         }
3543
3544         /* the stream outs */
3545         if (asoc->strmout) {
3546                 FREE(asoc->strmout, M_PCB);
3547                 asoc->strmout = NULL;
3548         }
3549         asoc->streamoutcnt = 0;
3550         if (asoc->strmin) {
3551                 int i;
3552                 for (i = 0; i < asoc->streamincnt; i++) {
3553                         if (!TAILQ_EMPTY(&asoc->strmin[i].inqueue)) {
3554                                 /* We have somethings on the streamin queue */
3555                                 chk = TAILQ_FIRST(&asoc->strmin[i].inqueue);
3556                                 while (chk) {
3557                                         TAILQ_REMOVE(&asoc->strmin[i].inqueue,
3558                                             chk, sctp_next);
3559                                         if (chk->data) {
3560                                                 sctp_m_freem(chk->data);
3561                                                 chk->data = NULL;
3562                                         }
3563                                         SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_chunk,
3564                                             chk);
3565                                         sctppcbinfo.ipi_count_chunk--;
3566                                         if ((int)sctppcbinfo.ipi_count_chunk < 0) {
3567                                                 panic("Chunk count is negative");
3568                                         }
3569                                         sctppcbinfo.ipi_gencnt_chunk++;
3570                                         chk = TAILQ_FIRST(&asoc->strmin[i].inqueue);
3571                                 }
3572                         }
3573                 }
3574                 FREE(asoc->strmin, M_PCB);
3575                 asoc->strmin = NULL;
3576         }
3577         asoc->streamincnt = 0;
3578         /* local addresses, if any */
3579         while (!LIST_EMPTY(&asoc->sctp_local_addr_list)) {
3580                 laddr = LIST_FIRST(&asoc->sctp_local_addr_list);
3581                 LIST_REMOVE(laddr, sctp_nxt_addr);
3582                 SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_laddr, laddr);
3583                 sctppcbinfo.ipi_count_laddr--;
3584         }
3585         /* pending asconf (address) parameters */
3586         while (!TAILQ_EMPTY(&asoc->asconf_queue)) {
3587                 aparam = TAILQ_FIRST(&asoc->asconf_queue);
3588                 TAILQ_REMOVE(&asoc->asconf_queue, aparam, next);
3589                 FREE(aparam, M_PCB);
3590         }
3591         if (asoc->last_asconf_ack_sent != NULL) {
3592                 sctp_m_freem(asoc->last_asconf_ack_sent);
3593                 asoc->last_asconf_ack_sent = NULL;
3594         }
3595         /* Insert new items here :> */
3596
3597         /* Get rid of LOCK */
3598         SCTP_TCB_LOCK_DESTROY(stcb);
3599
3600         /* now clean up the tasoc itself */
3601         SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_asoc, stcb);
3602         sctppcbinfo.ipi_count_asoc--;
3603         if ((inp->sctp_socket->so_snd.sb_cc) ||
3604             (inp->sctp_socket->so_snd.sb_mbcnt)) {
3605                 /* This will happen when a abort is done */
3606                 inp->sctp_socket->so_snd.sb_cc = 0;
3607                 inp->sctp_socket->so_snd.sb_mbcnt = 0;
3608         }
3609         if (inp->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE) {
3610                 if ((inp->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL) == 0) {
3611                         if (inp->sctp_flags & SCTP_PCB_FLAGS_CONNECTED) {
3612                                 /*
3613                                  * For the base fd, that is NOT in TCP pool we
3614                                  * turn off the connected flag. This allows
3615                                  * non-listening endpoints to connect/shutdown/
3616                                  * connect.
3617                                  */
3618                                 inp->sctp_flags &= ~SCTP_PCB_FLAGS_CONNECTED;
3619                                 soisdisconnected(inp->sctp_socket);
3620                         }
3621                         /*
3622                          * For those that are in the TCP pool we just leave
3623                          * so it cannot be used. When they close the fd we
3624                          * will free it all.
3625                          */
3626                 }
3627         }
3628         if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE) {
3629                 sctp_inpcb_free(inp, 0);
3630         }
3631         splx(s);
3632 }
3633
3634
3635 /*
3636  * determine if a destination is "reachable" based upon the addresses
3637  * bound to the current endpoint (e.g. only v4 or v6 currently bound)
3638  */
3639 /*
3640  * FIX: if we allow assoc-level bindx(), then this needs to be fixed
3641  * to use assoc level v4/v6 flags, as the assoc *may* not have the
3642  * same address types bound as its endpoint
3643  */
3644 int
3645 sctp_destination_is_reachable(struct sctp_tcb *stcb, struct sockaddr *destaddr)
3646 {
3647         struct sctp_inpcb *inp;
3648         int answer;
3649
3650         /* No locks here, the TCB, in all cases is already
3651          * locked and an assoc is up. There is either a
3652          * INP lock by the caller applied (in asconf case when
3653          * deleting an address) or NOT in the HB case, however
3654          * if HB then the INP increment is up and the INP
3655          * will not be removed (on top of the fact that
3656          * we have a TCB lock). So we only want to
3657          * read the sctp_flags, which is either bound-all
3658          * or not.. no protection needed since once an
3659          * assoc is up you can't be changing your binding.
3660          */
3661         inp = stcb->sctp_ep;
3662         if (inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) {
3663                 /* if bound all, destination is not restricted */
3664                 /* RRS: Question during lock work: Is this
3665                  * correct? If you are bound-all you still
3666                  * might need to obey the V4--V6 flags???
3667                  * IMO this bound-all stuff needs to be removed!
3668                  */
3669                 return (1);
3670         }
3671         /* NOTE: all "scope" checks are done when local addresses are added */
3672         if (destaddr->sa_family == AF_INET6) {
3673 #if !(defined(__FreeBSD__) || defined(__APPLE__))
3674                 answer = inp->inp_vflag & INP_IPV6;
3675 #else
3676                 answer = inp->ip_inp.inp.inp_vflag & INP_IPV6;
3677 #endif
3678         } else if (destaddr->sa_family == AF_INET) {
3679 #if !(defined(__FreeBSD__) || defined(__APPLE__))
3680                 answer = inp->inp_vflag & INP_IPV4;
3681 #else
3682                 answer = inp->ip_inp.inp.inp_vflag & INP_IPV4;
3683 #endif
3684         } else {
3685                 /* invalid family, so it's unreachable */
3686                 answer = 0;
3687         }
3688         return (answer);
3689 }
3690
3691 /*
3692  * update the inp_vflags on an endpoint
3693  */
3694 static void
3695 sctp_update_ep_vflag(struct sctp_inpcb *inp) {
3696         struct sctp_laddr *laddr;
3697
3698         /* first clear the flag */
3699 #if !(defined(__FreeBSD__) || defined(__APPLE__))
3700         inp->inp_vflag = 0;
3701 #else
3702         inp->ip_inp.inp.inp_vflag = 0;
3703 #endif
3704         /* set the flag based on addresses on the ep list */
3705         LIST_FOREACH(laddr, &inp->sctp_addr_list, sctp_nxt_addr) {
3706                 if (laddr->ifa == NULL) {
3707 #ifdef SCTP_DEBUG
3708                         if (sctp_debug_on & SCTP_DEBUG_PCB1) {
3709                                 printf("An ounce of prevention is worth a pound of cure\n");
3710                         }
3711 #endif /* SCTP_DEBUG */
3712                         continue;
3713                 }
3714                 if (laddr->ifa->ifa_addr) {
3715                         continue;
3716                 }
3717                 if (laddr->ifa->ifa_addr->sa_family == AF_INET6) {
3718 #if !(defined(__FreeBSD__) || defined(__APPLE__))
3719                         inp->inp_vflag |= INP_IPV6;
3720 #else
3721                         inp->ip_inp.inp.inp_vflag |= INP_IPV6;
3722 #endif
3723                 } else if (laddr->ifa->ifa_addr->sa_family == AF_INET) {
3724 #if !(defined(__FreeBSD__) || defined(__APPLE__))
3725                         inp->inp_vflag |= INP_IPV4;
3726 #else
3727                         inp->ip_inp.inp.inp_vflag |= INP_IPV4;
3728 #endif
3729                 }
3730         }
3731 }
3732
3733 /*
3734  * Add the address to the endpoint local address list
3735  * There is nothing to be done if we are bound to all addresses
3736  */
3737 int
3738 sctp_add_local_addr_ep(struct sctp_inpcb *inp, struct ifaddr *ifa)
3739 {
3740         struct sctp_laddr *laddr;
3741         int fnd, error;
3742         fnd = 0;
3743
3744         if (inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) {
3745                 /* You are already bound to all. You have it already */
3746                 return (0);
3747         }
3748         if (ifa->ifa_addr->sa_family == AF_INET6) {
3749                 struct in6_ifaddr *ifa6;
3750                 ifa6 = (struct in6_ifaddr *)ifa;
3751                 if (ifa6->ia6_flags & (IN6_IFF_DETACHED |
3752                     IN6_IFF_DEPRECATED | IN6_IFF_ANYCAST | IN6_IFF_NOTREADY))
3753                         /* Can't bind a non-existent addr. */
3754                         return (-1);
3755         }
3756         /* first, is it already present? */
3757         LIST_FOREACH(laddr, &inp->sctp_addr_list, sctp_nxt_addr) {
3758                 if (laddr->ifa == ifa) {
3759                         fnd = 1;
3760                         break;
3761                 }
3762         }
3763
3764         if (((inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) == 0) && (fnd == 0)) {
3765                 /* Not bound to all */
3766                 error = sctp_insert_laddr(&inp->sctp_addr_list, ifa);
3767                 if (error != 0)
3768                         return (error);
3769                 inp->laddr_count++;
3770                 /* update inp_vflag flags */
3771                 if (ifa->ifa_addr->sa_family == AF_INET6) {
3772 #if !(defined(__FreeBSD__) || defined(__APPLE__))
3773                         inp->inp_vflag |= INP_IPV6;
3774 #else
3775                         inp->ip_inp.inp.inp_vflag |= INP_IPV6;
3776 #endif
3777                 } else if (ifa->ifa_addr->sa_family == AF_INET) {
3778 #if !(defined(__FreeBSD__) || defined(__APPLE__))
3779                         inp->inp_vflag |= INP_IPV4;
3780 #else
3781                         inp->ip_inp.inp.inp_vflag |= INP_IPV4;
3782 #endif
3783                 }
3784         }
3785         return (0);
3786 }
3787
3788
3789 /*
3790  * select a new (hopefully reachable) destination net
3791  * (should only be used when we deleted an ep addr that is the
3792  * only usable source address to reach the destination net)
3793  */
3794 static void
3795 sctp_select_primary_destination(struct sctp_tcb *stcb)
3796 {
3797         struct sctp_nets *net;
3798
3799         TAILQ_FOREACH(net, &stcb->asoc.nets, sctp_next) {
3800                 /* for now, we'll just pick the first reachable one we find */
3801                 if (net->dest_state & SCTP_ADDR_UNCONFIRMED)
3802                         continue;
3803                 if (sctp_destination_is_reachable(stcb,
3804                     (struct sockaddr *)&net->ro._l_addr)) {
3805                         /* found a reachable destination */
3806                         stcb->asoc.primary_destination = net;
3807                 }
3808         }
3809         /* I can't there from here! ...we're gonna die shortly... */
3810 }
3811
3812
3813 /*
3814  * Delete the address from the endpoint local address list
3815  * There is nothing to be done if we are bound to all addresses
3816  */
3817 int
3818 sctp_del_local_addr_ep(struct sctp_inpcb *inp, struct ifaddr *ifa)
3819 {
3820         struct sctp_laddr *laddr;
3821         int fnd;
3822         fnd = 0;
3823         if (inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) {
3824                 /* You are already bound to all. You have it already */
3825                 return (EINVAL);
3826         }
3827
3828         LIST_FOREACH(laddr, &inp->sctp_addr_list, sctp_nxt_addr) {
3829                 if (laddr->ifa == ifa) {
3830                         fnd = 1;
3831                         break;
3832                 }
3833         }
3834         if (fnd && (inp->laddr_count < 2)) {
3835                 /* can't delete unless there are at LEAST 2 addresses */
3836                 return (-1);
3837         }
3838         if (((inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) == 0) && (fnd)) {
3839                 /*
3840                  * clean up any use of this address
3841                  * go through our associations and clear any
3842                  *  last_used_address that match this one
3843                  * for each assoc, see if a new primary_destination is needed
3844                  */
3845                 struct sctp_tcb *stcb;
3846
3847                 /* clean up "next_addr_touse" */
3848                 if (inp->next_addr_touse == laddr)
3849                         /* delete this address */
3850                         inp->next_addr_touse = NULL;
3851
3852                 /* clean up "last_used_address" */
3853                 LIST_FOREACH(stcb, &inp->sctp_asoc_list, sctp_tcblist) {
3854                         if (stcb->asoc.last_used_address == laddr)
3855                                 /* delete this address */
3856                                 stcb->asoc.last_used_address = NULL;
3857                 } /* for each tcb */
3858
3859                 /* remove it from the ep list */
3860                 sctp_remove_laddr(laddr);
3861                 inp->laddr_count--;
3862                 /* update inp_vflag flags */
3863                 sctp_update_ep_vflag(inp);
3864                 /* select a new primary destination if needed */
3865                 LIST_FOREACH(stcb, &inp->sctp_asoc_list, sctp_tcblist) {
3866                         /* presume caller (sctp_asconf.c) already owns INP lock */
3867                         SCTP_TCB_LOCK(stcb);
3868                         if (sctp_destination_is_reachable(stcb,
3869                             (struct sockaddr *)&stcb->asoc.primary_destination->ro._l_addr) == 0) {
3870                                 sctp_select_primary_destination(stcb);
3871                         }
3872                         SCTP_TCB_UNLOCK(stcb);
3873                 } /* for each tcb */
3874         }
3875         return (0);
3876 }
3877
3878 /*
3879  * Add the addr to the TCB local address list
3880  * For the BOUNDALL or dynamic case, this is a "pending" address list
3881  * (eg. addresses waiting for an ASCONF-ACK response)
3882  * For the subset binding, static case, this is a "valid" address list
3883  */
3884 int
3885 sctp_add_local_addr_assoc(struct sctp_tcb *stcb, struct ifaddr *ifa)
3886 {
3887         struct sctp_inpcb *inp;
3888         struct sctp_laddr *laddr;
3889         int error;
3890
3891         /* Assumes TCP is locked.. and possiblye
3892          * the INP. May need to confirm/fix that if
3893          * we need it and is not the case.
3894          */
3895         inp = stcb->sctp_ep;
3896         if (ifa->ifa_addr->sa_family == AF_INET6) {
3897                 struct in6_ifaddr *ifa6;
3898                 ifa6 = (struct in6_ifaddr *)ifa;
3899                 if (ifa6->ia6_flags & (IN6_IFF_DETACHED |
3900                     /* IN6_IFF_DEPRECATED | */
3901                     IN6_IFF_ANYCAST |
3902                     IN6_IFF_NOTREADY))
3903                         /* Can't bind a non-existent addr. */
3904                         return (-1);
3905         }
3906         /* does the address already exist? */
3907         LIST_FOREACH(laddr, &stcb->asoc.sctp_local_addr_list, sctp_nxt_addr) {
3908                 if (laddr->ifa == ifa) {
3909                         return (-1);
3910                 }
3911         }
3912
3913         /* add to the list */
3914         error = sctp_insert_laddr(&stcb->asoc.sctp_local_addr_list, ifa);
3915         if (error != 0)
3916                 return (error);
3917         return (0);
3918 }
3919
3920 /*
3921  * insert an laddr entry with the given ifa for the desired list
3922  */
3923 int
3924 sctp_insert_laddr(struct sctpladdr *list, struct ifaddr *ifa) {
3925         struct sctp_laddr *laddr;
3926         int s;
3927
3928 #if defined(__NetBSD__) || defined(__OpenBSD__)
3929         s = splsoftnet();
3930 #else
3931         s = splnet();
3932 #endif
3933
3934         laddr = (struct sctp_laddr *)SCTP_ZONE_GET(sctppcbinfo.ipi_zone_laddr);
3935         if (laddr == NULL) {
3936                 /* out of memory? */
3937                 splx(s);
3938                 return (EINVAL);
3939         }
3940         sctppcbinfo.ipi_count_laddr++;
3941         sctppcbinfo.ipi_gencnt_laddr++;
3942         bzero(laddr, sizeof(*laddr));
3943         laddr->ifa = ifa;
3944         /* insert it */
3945         LIST_INSERT_HEAD(list, laddr, sctp_nxt_addr);
3946
3947         splx(s);
3948         return (0);
3949 }
3950
3951 /*
3952  * Remove an laddr entry from the local address list (on an assoc)
3953  */
3954 void
3955 sctp_remove_laddr(struct sctp_laddr *laddr)
3956 {
3957         int s;
3958 #if defined(__NetBSD__) || defined(__OpenBSD__)
3959         s = splsoftnet();
3960 #else
3961         s = splnet();
3962 #endif
3963         /* remove from the list */
3964         LIST_REMOVE(laddr, sctp_nxt_addr);
3965         SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_laddr, laddr);
3966         sctppcbinfo.ipi_count_laddr--;
3967         sctppcbinfo.ipi_gencnt_laddr++;
3968
3969         splx(s);
3970 }
3971
3972 /*
3973  * Remove an address from the TCB local address list
3974  */
3975 int
3976 sctp_del_local_addr_assoc(struct sctp_tcb *stcb, struct ifaddr *ifa)
3977 {
3978         struct sctp_inpcb *inp;
3979         struct sctp_laddr *laddr;
3980
3981         /* This is called by asconf work. It is assumed that
3982          * a) The TCB is locked
3983          * and
3984          * b) The INP is locked.
3985          * This is true in as much as I can trace through
3986          * the entry asconf code where I did these locks.
3987          * Again, the ASCONF code is a bit different in
3988          * that it does lock the INP during its work often
3989          * times. This must be since we don't want other
3990          * proc's looking up things while what they are
3991          * looking up is changing :-D
3992          */
3993
3994         inp = stcb->sctp_ep;
3995         /* if subset bound and don't allow ASCONF's, can't delete last */
3996         if (((inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) == 0) &&
3997             ((inp->sctp_flags & SCTP_PCB_FLAGS_DO_ASCONF) == 0)) {
3998                 if (stcb->asoc.numnets < 2) {
3999                         /* can't delete last address */
4000                         return (-1);
4001                 }
4002         }
4003
4004         LIST_FOREACH(laddr, &stcb->asoc.sctp_local_addr_list, sctp_nxt_addr) {
4005                 /* remove the address if it exists */
4006                 if (laddr->ifa == NULL)
4007                         continue;
4008                 if (laddr->ifa == ifa) {
4009                         sctp_remove_laddr(laddr);
4010                         return (0);
4011                 }
4012         }
4013
4014         /* address not found! */
4015         return (-1);
4016 }
4017
4018 /*
4019  * Remove an address from the TCB local address list
4020  * lookup using a sockaddr addr
4021  */
4022 int
4023 sctp_del_local_addr_assoc_sa(struct sctp_tcb *stcb, struct sockaddr *sa)
4024 {
4025         struct sctp_inpcb *inp;
4026         struct sctp_laddr *laddr;
4027         struct sockaddr *l_sa;
4028
4029         /*
4030          * This function I find does not seem to have a caller.
4031          * As such we NEED TO DELETE this code. If we do
4032          * find a caller, the caller MUST have locked the TCB
4033          * at the least and probably the INP as well.
4034          */
4035         inp = stcb->sctp_ep;
4036         /* if subset bound and don't allow ASCONF's, can't delete last */
4037         if (((inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) == 0) &&
4038             ((inp->sctp_flags & SCTP_PCB_FLAGS_DO_ASCONF) == 0)) {
4039                 if (stcb->asoc.numnets < 2) {
4040                         /* can't delete last address */
4041                         return (-1);
4042                 }
4043         }
4044
4045         LIST_FOREACH(laddr, &stcb->asoc.sctp_local_addr_list, sctp_nxt_addr) {
4046                 /* make sure the address exists */
4047                 if (laddr->ifa == NULL)
4048                         continue;
4049                 if (laddr->ifa->ifa_addr == NULL)
4050                         continue;
4051
4052                 l_sa = laddr->ifa->ifa_addr;
4053                 if (l_sa->sa_family == AF_INET6) {
4054                         /* IPv6 address */
4055                         struct sockaddr_in6 *sin1, *sin2;
4056                         sin1 = (struct sockaddr_in6 *)l_sa;
4057                         sin2 = (struct sockaddr_in6 *)sa;
4058                         if (memcmp(&sin1->sin6_addr, &sin2->sin6_addr,
4059                             sizeof(struct in6_addr)) == 0) {
4060                                 /* matched */
4061                                 sctp_remove_laddr(laddr);
4062                                 return (0);
4063                         }
4064                 } else if (l_sa->sa_family == AF_INET) {
4065                         /* IPv4 address */
4066                         struct sockaddr_in *sin1, *sin2;
4067                         sin1 = (struct sockaddr_in *)l_sa;
4068                         sin2 = (struct sockaddr_in *)sa;
4069                         if (sin1->sin_addr.s_addr == sin2->sin_addr.s_addr) {
4070                                 /* matched */
4071                                 sctp_remove_laddr(laddr);
4072                                 return (0);
4073                         }
4074                 } else {
4075                         /* invalid family */
4076                         return (-1);
4077                 }
4078         } /* end foreach */
4079         /* address not found! */
4080         return (-1);
4081 }
4082
4083 static char sctp_pcb_initialized = 0;
4084
4085 #if defined(__FreeBSD__) || defined(__APPLE__)
4086 /* sysctl */
4087 static int sctp_max_number_of_assoc = SCTP_MAX_NUM_OF_ASOC;
4088 static int sctp_scale_up_for_address = SCTP_SCALE_FOR_ADDR;
4089
4090 #endif /* FreeBSD || APPLE */
4091
4092 #ifndef SCTP_TCBHASHSIZE
4093 #define SCTP_TCBHASHSIZE 1024
4094 #endif
4095
4096 #ifndef SCTP_CHUNKQUEUE_SCALE
4097 #define SCTP_CHUNKQUEUE_SCALE 10
4098 #endif
4099
4100 void
4101 sctp_pcb_init()
4102 {
4103         /*
4104          * SCTP initialization for the PCB structures
4105          * should be called by the sctp_init() funciton.
4106          */
4107         int i;
4108         int hashtblsize = SCTP_TCBHASHSIZE;
4109
4110 #if defined(__FreeBSD__) || defined(__APPLE__)
4111         int sctp_chunkscale = SCTP_CHUNKQUEUE_SCALE;
4112 #endif
4113
4114         if (sctp_pcb_initialized != 0) {
4115                 /* error I was called twice */
4116                 return;
4117         }
4118         sctp_pcb_initialized = 1;
4119
4120         /* Init all peg counts */
4121         for (i = 0; i < SCTP_NUMBER_OF_PEGS; i++) {
4122                 sctp_pegs[i] = 0;
4123         }
4124
4125         /* init the empty list of (All) Endpoints */
4126         LIST_INIT(&sctppcbinfo.listhead);
4127
4128         /* init the iterator head */
4129         LIST_INIT(&sctppcbinfo.iteratorhead);
4130
4131         /* init the hash table of endpoints */
4132 #if defined(__FreeBSD__)
4133 #if defined(__FreeBSD_cc_version) && __FreeBSD_cc_version >= 440000
4134         TUNABLE_INT_FETCH("net.inet.sctp.tcbhashsize", &hashtblsize);
4135         TUNABLE_INT_FETCH("net.inet.sctp.pcbhashsize", &sctp_pcbtblsize);
4136         TUNABLE_INT_FETCH("net.inet.sctp.chunkscale", &sctp_chunkscale);
4137 #else
4138         TUNABLE_INT_FETCH("net.inet.sctp.tcbhashsize", SCTP_TCBHASHSIZE,
4139             hashtblsize);
4140         TUNABLE_INT_FETCH("net.inet.sctp.pcbhashsize", SCTP_PCBHASHSIZE,
4141             sctp_pcbtblsize);
4142         TUNABLE_INT_FETCH("net.inet.sctp.chunkscale", SCTP_CHUNKQUEUE_SCALE,
4143             sctp_chunkscale);
4144 #endif
4145 #endif
4146
4147         sctppcbinfo.sctp_asochash = hashinit((hashtblsize * 31),
4148 #ifdef __NetBSD__
4149             HASH_LIST,
4150 #endif
4151             M_PCB,
4152 #if defined(__NetBSD__) || defined(__OpenBSD__)
4153             M_WAITOK,
4154 #endif
4155             &sctppcbinfo.hashasocmark);
4156
4157         sctppcbinfo.sctp_ephash = hashinit(hashtblsize,
4158 #ifdef __NetBSD__
4159             HASH_LIST,
4160 #endif
4161             M_PCB,
4162 #if defined(__NetBSD__) || defined(__OpenBSD__)
4163             M_WAITOK,
4164 #endif
4165             &sctppcbinfo.hashmark);
4166
4167         sctppcbinfo.sctp_tcpephash = hashinit(hashtblsize,
4168 #ifdef __NetBSD__
4169             HASH_LIST,
4170 #endif
4171             M_PCB,
4172 #if defined(__NetBSD__) || defined(__OpenBSD__)
4173             M_WAITOK,
4174 #endif
4175             &sctppcbinfo.hashtcpmark);
4176
4177         sctppcbinfo.hashtblsize = hashtblsize;
4178
4179         /* init the zones */
4180         /*
4181          * FIX ME: Should check for NULL returns, but if it does fail we
4182          * are doomed to panic anyways... add later maybe.
4183          */
4184         SCTP_ZONE_INIT(sctppcbinfo.ipi_zone_ep, "sctp_ep",
4185             sizeof(struct sctp_inpcb), maxsockets);
4186
4187         SCTP_ZONE_INIT(sctppcbinfo.ipi_zone_asoc, "sctp_asoc",
4188             sizeof(struct sctp_tcb), sctp_max_number_of_assoc);
4189
4190         SCTP_ZONE_INIT(sctppcbinfo.ipi_zone_laddr, "sctp_laddr",
4191             sizeof(struct sctp_laddr),
4192             (sctp_max_number_of_assoc * sctp_scale_up_for_address));
4193
4194         SCTP_ZONE_INIT(sctppcbinfo.ipi_zone_net, "sctp_raddr",
4195             sizeof(struct sctp_nets),
4196             (sctp_max_number_of_assoc * sctp_scale_up_for_address));
4197
4198         SCTP_ZONE_INIT(sctppcbinfo.ipi_zone_chunk, "sctp_chunk",
4199             sizeof(struct sctp_tmit_chunk),
4200             (sctp_max_number_of_assoc * sctp_scale_up_for_address *
4201             sctp_chunkscale));
4202
4203         SCTP_ZONE_INIT(sctppcbinfo.ipi_zone_sockq, "sctp_sockq",
4204             sizeof(struct sctp_socket_q_list),
4205             (sctp_max_number_of_assoc * sctp_scale_up_for_address *
4206             sctp_chunkscale));
4207
4208         /* Master Lock INIT for info structure */
4209         SCTP_INP_INFO_LOCK_INIT();
4210         SCTP_ITERATOR_LOCK_INIT();
4211         /* not sure if we need all the counts */
4212         sctppcbinfo.ipi_count_ep = 0;
4213         sctppcbinfo.ipi_gencnt_ep = 0;
4214         /* assoc/tcb zone info */
4215         sctppcbinfo.ipi_count_asoc = 0;
4216         sctppcbinfo.ipi_gencnt_asoc = 0;
4217         /* local addrlist zone info */
4218         sctppcbinfo.ipi_count_laddr = 0;
4219         sctppcbinfo.ipi_gencnt_laddr = 0;
4220         /* remote addrlist zone info */
4221         sctppcbinfo.ipi_count_raddr = 0;
4222         sctppcbinfo.ipi_gencnt_raddr = 0;
4223         /* chunk info */
4224         sctppcbinfo.ipi_count_chunk = 0;
4225         sctppcbinfo.ipi_gencnt_chunk = 0;
4226
4227         /* socket queue zone info */
4228         sctppcbinfo.ipi_count_sockq = 0;
4229         sctppcbinfo.ipi_gencnt_sockq = 0;
4230
4231         /* mbuf tracker */
4232         sctppcbinfo.mbuf_track = 0;
4233         /* port stuff */
4234 #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__APPLE__)
4235         sctppcbinfo.lastlow = ipport_firstauto;
4236 #else
4237         sctppcbinfo.lastlow = anonportmin;
4238 #endif
4239         /* Init the TIMEWAIT list */
4240         for (i = 0; i < SCTP_STACK_VTAG_HASH_SIZE; i++) {
4241                 LIST_INIT(&sctppcbinfo.vtag_timewait[i]);
4242         }
4243
4244 #if defined(_SCTP_NEEDS_CALLOUT_) && !defined(__APPLE__)
4245         TAILQ_INIT(&sctppcbinfo.callqueue);
4246 #endif
4247
4248 }
4249
4250 int
4251 sctp_load_addresses_from_init(struct sctp_tcb *stcb, struct mbuf *m,
4252     int iphlen, int offset, int limit, struct sctphdr *sh,
4253     struct sockaddr *altsa)
4254 {
4255         /*
4256          * grub through the INIT pulling addresses and
4257          * loading them to the nets structure in the asoc.
4258          * The from address in the mbuf should also be loaded
4259          * (if it is not already). This routine can be called
4260          * with either INIT or INIT-ACK's as long as the
4261          * m points to the IP packet and the offset points
4262          * to the beginning of the parameters.
4263          */
4264         struct sctp_inpcb *inp, *l_inp;
4265         struct sctp_nets *net, *net_tmp;
4266         struct ip *iph;
4267         struct sctp_paramhdr *phdr, parm_buf;
4268         struct sctp_tcb *stcb_tmp;
4269         u_int16_t ptype, plen;
4270         struct sockaddr *sa;
4271         struct sockaddr_storage dest_store;
4272         struct sockaddr *local_sa = (struct sockaddr *)&dest_store;
4273         struct sockaddr_in sin;
4274         struct sockaddr_in6 sin6;
4275
4276         /* First get the destination address setup too. */
4277         memset(&sin, 0, sizeof(sin));
4278         memset(&sin6, 0, sizeof(sin6));
4279
4280         sin.sin_family = AF_INET;
4281         sin.sin_len = sizeof(sin);
4282         sin.sin_port = stcb->rport;
4283
4284         sin6.sin6_family = AF_INET6;
4285         sin6.sin6_len = sizeof(struct sockaddr_in6);
4286         sin6.sin6_port = stcb->rport;
4287         if (altsa == NULL) {
4288                 iph = mtod(m, struct ip *);
4289                 if (iph->ip_v == IPVERSION) {
4290                         /* its IPv4 */
4291                         struct sockaddr_in *sin_2;
4292                         sin_2 = (struct sockaddr_in *)(local_sa);
4293                         memset(sin_2, 0, sizeof(sin));
4294                         sin_2->sin_family = AF_INET;
4295                         sin_2->sin_len = sizeof(sin);
4296                         sin_2->sin_port = sh->dest_port;
4297                         sin_2->sin_addr.s_addr = iph->ip_dst.s_addr ;
4298                         sin.sin_addr = iph->ip_src;
4299                         sa = (struct sockaddr *)&sin;
4300                 } else if (iph->ip_v == (IPV6_VERSION >> 4)) {
4301                         /* its IPv6 */
4302                         struct ip6_hdr *ip6;
4303                         struct sockaddr_in6 *sin6_2;
4304
4305                         ip6 = mtod(m, struct ip6_hdr *);
4306                         sin6_2 = (struct sockaddr_in6 *)(local_sa);
4307                         memset(sin6_2, 0, sizeof(sin6));
4308                         sin6_2->sin6_family = AF_INET6;
4309                         sin6_2->sin6_len = sizeof(struct sockaddr_in6);
4310                         sin6_2->sin6_port = sh->dest_port;
4311                         sin6.sin6_addr = ip6->ip6_src;
4312                         sa = (struct sockaddr *)&sin6;
4313                 } else {
4314                         sa = NULL;
4315                 }
4316         } else {
4317                 /*
4318                  * For cookies we use the src address NOT from the packet
4319                  * but from the original INIT
4320                  */
4321                 sa = altsa;
4322         }
4323         /* Turn off ECN until we get through all params */
4324         stcb->asoc.ecn_allowed = 0;
4325
4326         TAILQ_FOREACH(net, &stcb->asoc.nets, sctp_next) {
4327                 /* mark all addresses that we have currently on the list */
4328                 net->dest_state |= SCTP_ADDR_NOT_IN_ASSOC;
4329         }
4330         /* does the source address already exist? if so skip it */
4331         l_inp = inp = stcb->sctp_ep;
4332         stcb_tmp = sctp_findassociation_ep_addr(&inp, sa, &net_tmp, local_sa, stcb);
4333         if ((stcb_tmp == NULL && inp == stcb->sctp_ep) || inp == NULL) {
4334                 /* we must add the source address */
4335                 /* no scope set here since we have a tcb already. */
4336                 if ((sa->sa_family == AF_INET) &&
4337                     (stcb->asoc.ipv4_addr_legal)) {
4338                         if (sctp_add_remote_addr(stcb, sa, 0, 2)) {
4339                                 return (-1);
4340                         }
4341                 } else if ((sa->sa_family == AF_INET6) &&
4342                     (stcb->asoc.ipv6_addr_legal)) {
4343                         if (sctp_add_remote_addr(stcb, sa, 0, 3)) {
4344                                 return (-1);
4345                         }
4346                 }
4347         } else {
4348                 if (net_tmp != NULL && stcb_tmp == stcb) {
4349                         net_tmp->dest_state &= ~SCTP_ADDR_NOT_IN_ASSOC;
4350                 } else if (stcb_tmp != stcb) {
4351                         /* It belongs to another association? */
4352                         return (-1);
4353                 }
4354         }
4355         /* since a unlock occured we must check the
4356          * TCB's state and the pcb's gone flags.
4357          */
4358         if (l_inp->sctp_flags & (SCTP_PCB_FLAGS_SOCKET_GONE|SCTP_PCB_FLAGS_SOCKET_ALLGONE)) {
4359                 /* the user freed the ep */
4360                 return (-1);
4361         }
4362         if (stcb->asoc.state == 0) {
4363                 /* the assoc was freed? */
4364                 return (-1);
4365         }
4366
4367         /* now we must go through each of the params. */
4368         phdr = sctp_get_next_param(m, offset, &parm_buf, sizeof(parm_buf));
4369         while (phdr) {
4370                 ptype = ntohs(phdr->param_type);
4371                 plen = ntohs(phdr->param_length);
4372                 /*printf("ptype => %d, plen => %d\n", ptype, plen);*/
4373                 if (offset + plen > limit) {
4374                         break;
4375                 }
4376                 if (plen == 0) {
4377                         break;
4378                 }
4379                 if ((ptype == SCTP_IPV4_ADDRESS) &&
4380                     (stcb->asoc.ipv4_addr_legal)) {
4381                         struct sctp_ipv4addr_param *p4, p4_buf;
4382                         /* ok get the v4 address and check/add */
4383                         phdr = sctp_get_next_param(m, offset,
4384                             (struct sctp_paramhdr *)&p4_buf, sizeof(p4_buf));
4385                         if (plen != sizeof(struct sctp_ipv4addr_param) ||
4386                             phdr == NULL) {
4387                                 return (-1);
4388                         }
4389                         p4 = (struct sctp_ipv4addr_param *)phdr;
4390                         sin.sin_addr.s_addr = p4->addr;
4391                         sa = (struct sockaddr *)&sin;
4392                         inp = stcb->sctp_ep;
4393                         stcb_tmp = sctp_findassociation_ep_addr(&inp, sa, &net,
4394                             local_sa, stcb);
4395
4396                         if ((stcb_tmp== NULL && inp == stcb->sctp_ep) ||
4397                             inp == NULL) {
4398                                 /* we must add the source address */
4399                                 /* no scope set since we have a tcb already */
4400
4401                                 /* we must validate the state again here */
4402                                 if (l_inp->sctp_flags & (SCTP_PCB_FLAGS_SOCKET_GONE|SCTP_PCB_FLAGS_SOCKET_ALLGONE)) {
4403                                         /* the user freed the ep */
4404                                         return (-1);
4405                                 }
4406                                 if (stcb->asoc.state == 0) {
4407                                         /* the assoc was freed? */
4408                                         return (-1);
4409                                 }
4410                                 if (sctp_add_remote_addr(stcb, sa, 0, 4)) {
4411                                         return (-1);
4412                                 }
4413                         } else if (stcb_tmp == stcb) {
4414                                 if (l_inp->sctp_flags & (SCTP_PCB_FLAGS_SOCKET_GONE|SCTP_PCB_FLAGS_SOCKET_ALLGONE)) {
4415                                         /* the user freed the ep */
4416                                         return (-1);
4417                                 }
4418                                 if (stcb->asoc.state == 0) {
4419                                         /* the assoc was freed? */
4420                                         return (-1);
4421                                 }
4422                                 if (net != NULL) {
4423                                         /* clear flag */
4424                                         net->dest_state &=
4425                                             ~SCTP_ADDR_NOT_IN_ASSOC;
4426                                 }
4427                         } else {
4428                                 /* strange, address is in another assoc?
4429                                  * straighten out locks.
4430                                  */
4431                                 SCTP_TCB_UNLOCK(stcb_tmp);
4432                                 SCTP_INP_RLOCK(inp);
4433                                 if (l_inp->sctp_flags & (SCTP_PCB_FLAGS_SOCKET_GONE|SCTP_PCB_FLAGS_SOCKET_ALLGONE)) {
4434                                         /* the user freed the ep */
4435                                         SCTP_INP_RUNLOCK(l_inp);
4436                                         return (-1);
4437                                 }
4438                                 if (stcb->asoc.state == 0) {
4439                                         /* the assoc was freed? */
4440                                         SCTP_INP_RUNLOCK(l_inp);
4441                                         return (-1);
4442                                 }
4443                                 SCTP_TCB_LOCK(stcb);
4444                                 SCTP_INP_RUNLOCK(stcb->sctp_ep);
4445                                 return (-1);
4446                         }
4447                 } else if ((ptype == SCTP_IPV6_ADDRESS) &&
4448                     (stcb->asoc.ipv6_addr_legal)) {
4449                         /* ok get the v6 address and check/add */
4450                         struct sctp_ipv6addr_param *p6, p6_buf;
4451                         phdr = sctp_get_next_param(m, offset,
4452                             (struct sctp_paramhdr *)&p6_buf, sizeof(p6_buf));
4453                         if (plen != sizeof(struct sctp_ipv6addr_param) ||
4454                             phdr == NULL) {
4455                                 return (-1);
4456                         }
4457                         p6 = (struct sctp_ipv6addr_param *)phdr;
4458                         memcpy((caddr_t)&sin6.sin6_addr, p6->addr,
4459                             sizeof(p6->addr));
4460                         sa = (struct sockaddr *)&sin6;
4461                         inp = stcb->sctp_ep;
4462                         stcb_tmp= sctp_findassociation_ep_addr(&inp, sa, &net,
4463                             local_sa, stcb);
4464                         if (stcb_tmp == NULL && (inp == stcb->sctp_ep ||
4465                             inp == NULL)) {
4466                                 /* we must validate the state again here */
4467                                 if (l_inp->sctp_flags & (SCTP_PCB_FLAGS_SOCKET_GONE|SCTP_PCB_FLAGS_SOCKET_ALLGONE)) {
4468                                         /* the user freed the ep */
4469                                         return (-1);
4470                                 }
4471                                 if (stcb->asoc.state == 0) {
4472                                         /* the assoc was freed? */
4473                                         return (-1);
4474                                 }
4475                                 /* we must add the address, no scope set */
4476                                 if (sctp_add_remote_addr(stcb, sa, 0, 5)) {
4477                                         return (-1);
4478                                 }
4479                         } else if (stcb_tmp == stcb) {
4480                                 /* we must validate the state again here */
4481                                 if (l_inp->sctp_flags & (SCTP_PCB_FLAGS_SOCKET_GONE|SCTP_PCB_FLAGS_SOCKET_ALLGONE)) {
4482                                         /* the user freed the ep */
4483                                         return (-1);
4484                                 }
4485                                 if (stcb->asoc.state == 0) {
4486                                         /* the assoc was freed? */
4487                                         return (-1);
4488                                 }
4489                                 if (net != NULL) {
4490                                         /* clear flag */
4491                                         net->dest_state &=
4492                                             ~SCTP_ADDR_NOT_IN_ASSOC;
4493                                 }
4494                         } else {
4495                                 /* strange, address is in another assoc?
4496                                  * straighten out locks.
4497                                  */
4498                                 SCTP_TCB_UNLOCK(stcb_tmp);
4499                                 SCTP_INP_RLOCK(l_inp);
4500                                 /* we must validate the state again here */
4501                                 if (l_inp->sctp_flags & (SCTP_PCB_FLAGS_SOCKET_GONE|SCTP_PCB_FLAGS_SOCKET_ALLGONE)) {
4502                                         /* the user freed the ep */
4503                                         SCTP_INP_RUNLOCK(l_inp);
4504                                         return (-1);
4505                                 }
4506                                 if (stcb->asoc.state == 0) {
4507                                         /* the assoc was freed? */
4508                                         SCTP_INP_RUNLOCK(l_inp);
4509                                         return (-1);
4510                                 }
4511                                 SCTP_TCB_LOCK(stcb);
4512                                 SCTP_INP_RUNLOCK(l_inp);
4513                                 return (-1);
4514                         }
4515                 } else if (ptype == SCTP_ECN_CAPABLE) {
4516                         stcb->asoc.ecn_allowed = 1;
4517                 } else if (ptype == SCTP_ULP_ADAPTION) {
4518                         if (stcb->asoc.state != SCTP_STATE_OPEN) {
4519                                 struct sctp_adaption_layer_indication ai, *aip;
4520
4521                                 phdr = sctp_get_next_param(m, offset,
4522                                                            (struct sctp_paramhdr *)&ai, sizeof(ai));
4523                                 aip = (struct sctp_adaption_layer_indication *)phdr;
4524                                 sctp_ulp_notify(SCTP_NOTIFY_ADAPTION_INDICATION,
4525                                                 stcb, ntohl(aip->indication), NULL);
4526                         }
4527                 } else if (ptype == SCTP_SET_PRIM_ADDR) {
4528                         struct sctp_asconf_addr_param lstore, *fee;
4529                         struct sctp_asconf_addrv4_param *fii;
4530                         int lptype;
4531                         struct sockaddr *lsa = NULL;
4532
4533                         stcb->asoc.peer_supports_asconf = 1;
4534                         stcb->asoc.peer_supports_asconf_setprim = 1;
4535                         if (plen > sizeof(lstore)) {
4536                                 return (-1);
4537                         }
4538                         phdr = sctp_get_next_param(m, offset,
4539                             (struct sctp_paramhdr *)&lstore, plen);
4540                         if (phdr == NULL) {
4541                                 return (-1);
4542                         }
4543
4544                         fee  = (struct sctp_asconf_addr_param *)phdr;
4545                         lptype = ntohs(fee->addrp.ph.param_type);
4546                         if (lptype == SCTP_IPV4_ADDRESS) {
4547                                 if (plen !=
4548                                     sizeof(struct sctp_asconf_addrv4_param)) {
4549                                         printf("Sizeof setprim in init/init ack not %d but %d - ignored\n",
4550                                            (int)sizeof(struct sctp_asconf_addrv4_param),
4551                                            plen);
4552                                 } else {
4553                                         fii = (struct sctp_asconf_addrv4_param *)fee;
4554                                         sin.sin_addr.s_addr = fii->addrp.addr;
4555                                         lsa = (struct sockaddr *)&sin;
4556                                 }
4557                         } else if (lptype == SCTP_IPV6_ADDRESS) {
4558                                 if (plen !=
4559                                     sizeof(struct sctp_asconf_addr_param)) {
4560                                         printf("Sizeof setprim (v6) in init/init ack not %d but %d - ignored\n",
4561                                            (int)sizeof(struct sctp_asconf_addr_param),
4562                                            plen);
4563                                 } else {
4564                                         memcpy(sin6.sin6_addr.s6_addr,
4565                                             fee->addrp.addr,
4566                                             sizeof(fee->addrp.addr));
4567                                         lsa = (struct sockaddr *)&sin6;
4568                                 }
4569                         }
4570                         if (lsa) {
4571                                 sctp_set_primary_addr(stcb, sa, NULL);
4572                         }
4573
4574                 } else if (ptype == SCTP_PRSCTP_SUPPORTED) {
4575                         /* Peer supports pr-sctp */
4576                         stcb->asoc.peer_supports_prsctp = 1;
4577                 } else if (ptype == SCTP_SUPPORTED_CHUNK_EXT) {
4578                         /* A supported extension chunk */
4579                         struct sctp_supported_chunk_types_param *pr_supported;
4580                         uint8_t local_store[128];
4581                         int num_ent, i;
4582
4583                         phdr = sctp_get_next_param(m, offset,
4584                             (struct sctp_paramhdr *)&local_store, plen);
4585                         if (phdr == NULL) {
4586                                 return (-1);
4587                         }
4588                         stcb->asoc.peer_supports_asconf = 0;
4589                         stcb->asoc.peer_supports_asconf_setprim = 0;
4590                         stcb->asoc.peer_supports_prsctp = 0;
4591                         stcb->asoc.peer_supports_pktdrop = 0;
4592                         stcb->asoc.peer_supports_strreset = 0;
4593                         pr_supported = (struct sctp_supported_chunk_types_param *)phdr;
4594                         num_ent = plen - sizeof(struct sctp_paramhdr);
4595                         for (i=0; i<num_ent; i++) {
4596                                 switch (pr_supported->chunk_types[i]) {
4597                                 case SCTP_ASCONF:
4598                                         stcb->asoc.peer_supports_asconf = 1;
4599                                         stcb->asoc.peer_supports_asconf_setprim = 1;
4600                                         break;
4601                                 case SCTP_ASCONF_ACK:
4602                                         stcb->asoc.peer_supports_asconf = 1;
4603                                         stcb->asoc.peer_supports_asconf_setprim = 1;
4604                                         break;
4605                                 case SCTP_FORWARD_CUM_TSN:
4606                                         stcb->asoc.peer_supports_prsctp = 1;
4607                                         break;
4608                                 case SCTP_PACKET_DROPPED:
4609                                         stcb->asoc.peer_supports_pktdrop = 1;
4610                                         break;
4611                                 case SCTP_STREAM_RESET:
4612                                         stcb->asoc.peer_supports_strreset = 1;
4613                                         break;
4614                                 default:
4615                                         /* one I have not learned yet */
4616                                         break;
4617
4618                                 }
4619                         }
4620                 } else if (ptype == SCTP_ECN_NONCE_SUPPORTED) {
4621                         /* Peer supports ECN-nonce */
4622                         stcb->asoc.peer_supports_ecn_nonce = 1;
4623                         stcb->asoc.ecn_nonce_allowed = 1;
4624                 } else if ((ptype == SCTP_HEARTBEAT_INFO) ||
4625                            (ptype == SCTP_STATE_COOKIE) ||
4626                            (ptype == SCTP_UNRECOG_PARAM) ||
4627                            (ptype == SCTP_COOKIE_PRESERVE) ||
4628                            (ptype == SCTP_SUPPORTED_ADDRTYPE) ||
4629                            (ptype == SCTP_ADD_IP_ADDRESS) ||
4630                            (ptype == SCTP_DEL_IP_ADDRESS) ||
4631                            (ptype == SCTP_ERROR_CAUSE_IND) ||
4632                            (ptype == SCTP_SUCCESS_REPORT)) {
4633                         /* don't care */;
4634                 } else {
4635                         if ((ptype & 0x8000) == 0x0000) {
4636                                 /* must stop processing the rest of
4637                                  * the param's. Any report bits were
4638                                  * handled with the call to sctp_arethere_unrecognized_parameters()
4639                                  * when the INIT or INIT-ACK was first seen.
4640                                  */
4641                                 break;
4642                         }
4643                 }
4644                 offset += SCTP_SIZE32(plen);
4645                 if (offset >= limit) {
4646                         break;
4647                 }
4648                 phdr = sctp_get_next_param(m, offset, &parm_buf,
4649                     sizeof(parm_buf));
4650         }
4651         /* Now check to see if we need to purge any addresses */
4652         for (net = TAILQ_FIRST(&stcb->asoc.nets); net != NULL; net = net_tmp) {
4653                 net_tmp = TAILQ_NEXT(net, sctp_next);
4654                 if ((net->dest_state & SCTP_ADDR_NOT_IN_ASSOC) ==
4655                     SCTP_ADDR_NOT_IN_ASSOC) {
4656                         /* This address has been removed from the asoc */
4657                         /* remove and free it */
4658                         stcb->asoc.numnets--;
4659                         TAILQ_REMOVE(&stcb->asoc.nets, net, sctp_next);
4660                         sctp_free_remote_addr(net);
4661                         if (net == stcb->asoc.primary_destination) {
4662                                 stcb->asoc.primary_destination = NULL;
4663                                 sctp_select_primary_destination(stcb);
4664                         }
4665                 }
4666         }
4667         return (0);
4668 }
4669
4670 int
4671 sctp_set_primary_addr(struct sctp_tcb *stcb, struct sockaddr *sa,
4672     struct sctp_nets *net)
4673 {
4674         /* make sure the requested primary address exists in the assoc */
4675         if (net == NULL && sa)
4676                 net = sctp_findnet(stcb, sa);
4677
4678         if (net == NULL) {
4679                 /* didn't find the requested primary address! */
4680                 return (-1);
4681         } else {
4682                 /* set the primary address */
4683                 if (net->dest_state & SCTP_ADDR_UNCONFIRMED) {
4684                         /* Must be confirmed */
4685                         return (-1);
4686                 }
4687                 stcb->asoc.primary_destination = net;
4688                 net->dest_state &= ~SCTP_ADDR_WAS_PRIMARY;
4689                 return (0);
4690         }
4691 }
4692
4693
4694 int
4695 sctp_is_vtag_good(struct sctp_inpcb *inp, u_int32_t tag, struct timeval *now)
4696 {
4697         /*
4698          * This function serves two purposes. It will see if a TAG can be
4699          * re-used and return 1 for yes it is ok and 0 for don't use that
4700          * tag.
4701          * A secondary function it will do is purge out old tags that can
4702          * be removed.
4703          */
4704         struct sctpasochead *head;
4705         struct sctpvtaghead *chain;
4706         struct sctp_tagblock *twait_block;
4707         struct sctp_tcb *stcb;
4708
4709         int i;
4710         SCTP_INP_INFO_WLOCK();
4711         chain = &sctppcbinfo.vtag_timewait[(tag % SCTP_STACK_VTAG_HASH_SIZE)];
4712         /* First is the vtag in use ? */
4713
4714         head = &sctppcbinfo.sctp_asochash[SCTP_PCBHASH_ASOC(tag,
4715             sctppcbinfo.hashasocmark)];
4716         if (head == NULL) {
4717                 SCTP_INP_INFO_WUNLOCK();
4718                 return (0);
4719         }
4720         LIST_FOREACH(stcb, head, sctp_asocs) {
4721                 if (stcb->asoc.my_vtag == tag) {
4722                         /* We should remove this if and
4723                          * return 0 always if we want vtags
4724                          * unique across all endpoints. For
4725                          * now within a endpoint is ok.
4726                          */
4727                         if (inp == stcb->sctp_ep) {
4728                                 /* bad tag, in use */
4729                                 SCTP_INP_INFO_WUNLOCK();
4730                                 return (0);
4731                         }
4732                 }
4733         }
4734         if (!LIST_EMPTY(chain)) {
4735                 /*
4736                  * Block(s) are present, lets see if we have this tag in
4737                  * the list
4738                  */
4739                 LIST_FOREACH(twait_block, chain, sctp_nxt_tagblock) {
4740                         for (i = 0; i < SCTP_NUMBER_IN_VTAG_BLOCK; i++) {
4741                                 if (twait_block->vtag_block[i].v_tag == 0) {
4742                                         /* not used */
4743                                         continue;
4744                                 } else if ((long)twait_block->vtag_block[i].tv_sec_at_expire >
4745                                     now->tv_sec) {
4746                                         /* Audit expires this guy */
4747                                         twait_block->vtag_block[i].tv_sec_at_expire = 0;
4748                                         twait_block->vtag_block[i].v_tag = 0;
4749                                 } else if (twait_block->vtag_block[i].v_tag ==
4750                                     tag) {
4751                                         /* Bad tag, sorry :< */
4752                                         SCTP_INP_INFO_WUNLOCK();
4753                                         return (0);
4754                                 }
4755                         }
4756                 }
4757         }
4758         /* Not found, ok to use the tag */
4759         SCTP_INP_INFO_WUNLOCK();
4760         return (1);
4761 }
4762
4763
4764 /*
4765  * Delete the address from the endpoint local address list
4766  * Lookup using a sockaddr address (ie. not an ifaddr)
4767  */
4768 int
4769 sctp_del_local_addr_ep_sa(struct sctp_inpcb *inp, struct sockaddr *sa)
4770 {
4771         struct sctp_laddr *laddr;
4772         struct sockaddr *l_sa;
4773         int found = 0;
4774         /* Here is another function I cannot find a
4775          * caller for. As such we SHOULD delete it
4776          * if we have no users. If we find a user that
4777          * user MUST have the INP locked.
4778          *
4779          */
4780
4781         if (inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) {
4782                 /* You are already bound to all. You have it already */
4783                 return (EINVAL);
4784         }
4785
4786         LIST_FOREACH(laddr, &inp->sctp_addr_list, sctp_nxt_addr) {
4787                 /* make sure the address exists */
4788                 if (laddr->ifa == NULL)
4789                         continue;
4790                 if (laddr->ifa->ifa_addr == NULL)
4791                         continue;
4792
4793                 l_sa = laddr->ifa->ifa_addr;
4794                 if (l_sa->sa_family == AF_INET6) {
4795                         /* IPv6 address */
4796                         struct sockaddr_in6 *sin1, *sin2;
4797                         sin1 = (struct sockaddr_in6 *)l_sa;
4798                         sin2 = (struct sockaddr_in6 *)sa;
4799                         if (memcmp(&sin1->sin6_addr, &sin2->sin6_addr,
4800                             sizeof(struct in6_addr)) == 0) {
4801                                 /* matched */
4802                                 found = 1;
4803                                 break;
4804                         }
4805                 } else if (l_sa->sa_family == AF_INET) {
4806                         /* IPv4 address */
4807                         struct sockaddr_in *sin1, *sin2;
4808                         sin1 = (struct sockaddr_in *)l_sa;
4809                         sin2 = (struct sockaddr_in *)sa;
4810                         if (sin1->sin_addr.s_addr == sin2->sin_addr.s_addr) {
4811                                 /* matched */
4812                                 found = 1;
4813                                 break;
4814                         }
4815                 } else {
4816                         /* invalid family */
4817                         return (-1);
4818                 }
4819         }
4820
4821         if (found && inp->laddr_count < 2) {
4822                 /* can't delete unless there are at LEAST 2 addresses */
4823                 return (-1);
4824         }
4825
4826         if (found && (inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) == 0) {
4827                 /*
4828                  * remove it from the ep list, this should NOT be
4829                  * done until its really gone from the interface list and
4830                  * we won't be receiving more of these. Probably right
4831                  * away. If we do allow a removal of an address from
4832                  * an association (sub-set bind) than this should NOT
4833                  * be called until the all ASCONF come back from this
4834                  * association.
4835                  */
4836                 sctp_remove_laddr(laddr);
4837                 return (0);
4838         } else {
4839                 return (-1);
4840         }
4841 }
4842
4843 static void
4844 sctp_drain_mbufs(struct sctp_inpcb *inp, struct sctp_tcb *stcb)
4845 {
4846         /*
4847          * We must hunt this association for MBUF's past the cumack
4848          * (i.e. out of order data that we can renege on).
4849          */
4850         struct sctp_association *asoc;
4851         struct sctp_tmit_chunk *chk, *nchk;
4852         u_int32_t cumulative_tsn_p1, tsn;
4853         int cnt, strmat, gap;
4854         /* We look for anything larger than the cum-ack + 1 */
4855
4856         asoc = &stcb->asoc;
4857         cumulative_tsn_p1 = asoc->cumulative_tsn + 1;
4858         cnt = 0;
4859         /* First look in the re-assembly queue */
4860         chk = TAILQ_FIRST(&asoc->reasmqueue);
4861         while (chk) {
4862                 /* Get the next one */
4863                 nchk = TAILQ_NEXT(chk, sctp_next);
4864                 if (compare_with_wrap(chk->rec.data.TSN_seq,
4865                     cumulative_tsn_p1, MAX_TSN)) {
4866                         /* Yep it is above cum-ack */
4867                         cnt++;
4868                         tsn = chk->rec.data.TSN_seq;
4869                         if (tsn >= asoc->mapping_array_base_tsn) {
4870                                 gap  = tsn - asoc->mapping_array_base_tsn;
4871                         } else {
4872                                 gap = (MAX_TSN - asoc->mapping_array_base_tsn) +
4873                                     tsn + 1;
4874                         }
4875                         asoc->size_on_reasm_queue -= chk->send_size;
4876                         asoc->cnt_on_reasm_queue--;
4877                         SCTP_UNSET_TSN_PRESENT(asoc->mapping_array, gap);
4878                         TAILQ_REMOVE(&asoc->reasmqueue, chk, sctp_next);
4879                         if (chk->data) {
4880                                 sctp_m_freem(chk->data);
4881                                 chk->data = NULL;
4882                         }
4883                         SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_chunk, chk);
4884                         sctppcbinfo.ipi_count_chunk--;
4885                         if ((int)sctppcbinfo.ipi_count_chunk < 0) {
4886                                 panic("Chunk count is negative");
4887                         }
4888                         sctppcbinfo.ipi_gencnt_chunk++;
4889                 }
4890                 chk = nchk;
4891         }
4892         /* Ok that was fun, now we will drain all the inbound streams? */
4893         for (strmat = 0; strmat < asoc->streamincnt; strmat++) {
4894                 chk = TAILQ_FIRST(&asoc->strmin[strmat].inqueue);
4895                 while (chk) {
4896                         nchk = TAILQ_NEXT(chk, sctp_next);
4897                         if (compare_with_wrap(chk->rec.data.TSN_seq,
4898                             cumulative_tsn_p1, MAX_TSN)) {
4899                                 /* Yep it is above cum-ack */
4900                                 cnt++;
4901                                 tsn = chk->rec.data.TSN_seq;
4902                                 if (tsn >= asoc->mapping_array_base_tsn) {
4903                                         gap = tsn -
4904                                             asoc->mapping_array_base_tsn;
4905                                 } else {
4906                                         gap = (MAX_TSN -
4907                                             asoc->mapping_array_base_tsn) +
4908                                             tsn + 1;
4909                                 }
4910                                 asoc->size_on_all_streams -= chk->send_size;
4911                                 asoc->cnt_on_all_streams--;
4912
4913                                 SCTP_UNSET_TSN_PRESENT(asoc->mapping_array,
4914                                     gap);
4915                                 TAILQ_REMOVE(&asoc->strmin[strmat].inqueue,
4916                                     chk, sctp_next);
4917                                 if (chk->data) {
4918                                         sctp_m_freem(chk->data);
4919                                         chk->data = NULL;
4920                                 }
4921                                 SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_chunk, chk);
4922                                 sctppcbinfo.ipi_count_chunk--;
4923                                 if ((int)sctppcbinfo.ipi_count_chunk < 0) {
4924                                         panic("Chunk count is negative");
4925                                 }
4926                                 sctppcbinfo.ipi_gencnt_chunk++;
4927                         }
4928                         chk = nchk;
4929                 }
4930         }
4931         /*
4932          * Question, should we go through the delivery queue?
4933          * The only reason things are on here is the app not reading OR a
4934          * p-d-api up. An attacker COULD send enough in to initiate the
4935          * PD-API and then send a bunch of stuff to other streams... these
4936          * would wind up on the delivery queue.. and then we would not get
4937          * to them. But in order to do this I then have to back-track and
4938          * un-deliver sequence numbers in streams.. el-yucko. I think for
4939          * now we will NOT look at the delivery queue and leave it to be
4940          * something to consider later. An alternative would be to abort
4941          * the P-D-API with a notification and then deliver the data....
4942          * Or another method might be to keep track of how many times the
4943          * situation occurs and if we see a possible attack underway just
4944          * abort the association.
4945          */
4946 #ifdef SCTP_DEBUG
4947         if (sctp_debug_on & SCTP_DEBUG_PCB1) {
4948                 if (cnt) {
4949                         printf("Freed %d chunks from reneg harvest\n", cnt);
4950                 }
4951         }
4952 #endif /* SCTP_DEBUG */
4953
4954         /*
4955          * Another issue, in un-setting the TSN's in the mapping array we
4956          * DID NOT adjust the higest_tsn marker.  This will cause one of
4957          * two things to occur. It may cause us to do extra work in checking
4958          * for our mapping array movement. More importantly it may cause us
4959          * to SACK every datagram. This may not be a bad thing though since
4960          * we will recover once we get our cum-ack above and all this stuff
4961          * we dumped recovered.
4962          */
4963 }
4964
4965 void
4966 sctp_drain()
4967 {
4968         /*
4969          * We must walk the PCB lists for ALL associations here. The system
4970          * is LOW on MBUF's and needs help. This is where reneging will
4971          * occur. We really hope this does NOT happen!
4972          */
4973         struct sctp_inpcb *inp;
4974         struct sctp_tcb *stcb;
4975
4976         SCTP_INP_INFO_RLOCK();
4977         LIST_FOREACH(inp, &sctppcbinfo.listhead, sctp_list) {
4978                 /* For each endpoint */
4979                 SCTP_INP_RLOCK(inp);
4980                 LIST_FOREACH(stcb, &inp->sctp_asoc_list, sctp_tcblist) {
4981                         /* For each association */
4982                         SCTP_TCB_LOCK(stcb);
4983                         sctp_drain_mbufs(inp, stcb);
4984                         SCTP_TCB_UNLOCK(stcb);
4985                 }
4986                 SCTP_INP_RUNLOCK(inp);
4987         }
4988         SCTP_INP_INFO_RUNLOCK();
4989 }
4990
4991 int
4992 sctp_add_to_socket_q(struct sctp_inpcb *inp, struct sctp_tcb *stcb)
4993 {
4994         struct sctp_socket_q_list *sq;
4995
4996         /* write lock on INP assumed */
4997         if ((inp == NULL) || (stcb == NULL)) {
4998                 /* I am paranoid */
4999                 return (0);
5000         }
5001         sq = (struct sctp_socket_q_list *)SCTP_ZONE_GET(
5002             sctppcbinfo.ipi_zone_sockq);
5003         if (sq == NULL) {
5004                 /* out of sq structs */
5005                 return (0);
5006         }
5007         sctppcbinfo.ipi_count_sockq++;
5008         sctppcbinfo.ipi_gencnt_sockq++;
5009         if (stcb)
5010                 stcb->asoc.cnt_msg_on_sb++;
5011         sq->tcb = stcb;
5012         TAILQ_INSERT_TAIL(&inp->sctp_queue_list, sq, next_sq);
5013         return (1);
5014 }
5015
5016
5017 struct sctp_tcb *
5018 sctp_remove_from_socket_q(struct sctp_inpcb *inp)
5019 {
5020         struct sctp_tcb *stcb = NULL;
5021         struct sctp_socket_q_list *sq;
5022
5023         /* W-Lock on INP assumed held */
5024         sq = TAILQ_FIRST(&inp->sctp_queue_list);
5025         if (sq == NULL)
5026                 return (NULL);
5027
5028         stcb = sq->tcb;
5029         TAILQ_REMOVE(&inp->sctp_queue_list, sq, next_sq);
5030         SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_sockq, sq);
5031         sctppcbinfo.ipi_count_sockq--;
5032         sctppcbinfo.ipi_gencnt_sockq++;
5033         if (stcb) {
5034                 stcb->asoc.cnt_msg_on_sb--;
5035         }
5036         return (stcb);
5037 }
5038
5039 int
5040 sctp_initiate_iterator(asoc_func af, uint32_t pcb_state, uint32_t asoc_state,
5041                        void *argp, uint32_t argi, end_func ef,
5042                        struct sctp_inpcb *s_inp)
5043 {
5044         struct sctp_iterator *it=NULL;
5045         int s;
5046         if (af == NULL) {
5047                 return (-1);
5048         }
5049         MALLOC(it, struct sctp_iterator *, sizeof(struct sctp_iterator), M_PCB,
5050                M_WAITOK);
5051         if (it == NULL) {
5052                 return (ENOMEM);
5053         }
5054         memset(it, 0, sizeof(*it));
5055         it->function_toapply = af;
5056         it->function_atend = ef;
5057         it->pointer = argp;
5058         it->val = argi;
5059         it->pcb_flags = pcb_state;
5060         it->asoc_state = asoc_state;
5061         if (s_inp) {
5062                 it->inp = s_inp;
5063                 it->iterator_flags = SCTP_ITERATOR_DO_SINGLE_INP;
5064         } else {
5065                 SCTP_INP_INFO_RLOCK();
5066                 it->inp = LIST_FIRST(&sctppcbinfo.listhead);
5067                 SCTP_INP_INFO_RUNLOCK();
5068                 it->iterator_flags = SCTP_ITERATOR_DO_ALL_INP;
5069
5070         }
5071         /* Init the timer */
5072 #if defined(__FreeBSD__) && __FreeBSD_version >= 500000
5073         callout_init(&it->tmr.timer, 0);
5074 #else
5075         callout_init(&it->tmr.timer);
5076 #endif
5077         /* add to the list of all iterators */
5078         SCTP_INP_INFO_WLOCK();
5079         LIST_INSERT_HEAD(&sctppcbinfo.iteratorhead, it, sctp_nxt_itr);
5080         SCTP_INP_INFO_WUNLOCK();
5081 #if defined(__NetBSD__) || defined(__OpenBSD__)
5082         s = splsoftnet();
5083 #else
5084         s = splnet();
5085 #endif
5086         sctp_iterator_timer(it);
5087         splx(s);
5088         return (0);
5089 }
5090
5091
5092 /*
5093  * Callout/Timer routines for OS that doesn't have them
5094  */
5095 #ifdef _SCTP_NEEDS_CALLOUT_
5096 #ifndef __APPLE__
5097 extern int ticks;
5098 #endif
5099
5100 void
5101 callout_init(struct callout *c)
5102 {
5103         bzero(c, sizeof(*c));
5104 }
5105
5106 void
5107 callout_reset(struct callout *c, int to_ticks, void (*ftn)(void *), void *arg)
5108 {
5109         int s;
5110
5111         s = splhigh();
5112         if (c->c_flags & CALLOUT_PENDING)
5113                 callout_stop(c);
5114
5115         /*
5116          * We could spl down here and back up at the TAILQ_INSERT_TAIL,
5117          * but there's no point since doing this setup doesn't take much
5118          * time.
5119          */
5120         if (to_ticks <= 0)
5121                 to_ticks = 1;
5122
5123         c->c_arg = arg;
5124         c->c_flags = (CALLOUT_ACTIVE | CALLOUT_PENDING);
5125         c->c_func = ftn;
5126 #ifdef __APPLE__
5127         c->c_time = to_ticks;   /* just store the requested timeout */
5128         timeout(ftn, arg, to_ticks);
5129 #else
5130         c->c_time = ticks + to_ticks;
5131         TAILQ_INSERT_TAIL(&sctppcbinfo.callqueue, c, tqe);
5132 #endif
5133         splx(s);
5134 }
5135
5136 int
5137 callout_stop(struct callout *c)
5138 {
5139         int     s;
5140
5141         s = splhigh();
5142         /*
5143          * Don't attempt to delete a callout that's not on the queue.
5144          */
5145         if (!(c->c_flags & CALLOUT_PENDING)) {
5146                 c->c_flags &= ~CALLOUT_ACTIVE;
5147                 splx(s);
5148                 return (0);
5149         }
5150         c->c_flags &= ~(CALLOUT_ACTIVE | CALLOUT_PENDING| CALLOUT_FIRED);
5151 #ifdef __APPLE__
5152 /*      thread_call_cancel(c->c_call); */
5153         untimeout(c->c_func, c->c_arg);
5154 #else
5155         TAILQ_REMOVE(&sctppcbinfo.callqueue, c, tqe);
5156         c->c_func = NULL;
5157 #endif
5158         splx(s);
5159         return (1);
5160 }
5161
5162 #if !defined(__APPLE__)
5163 void
5164 sctp_fasttim(void)
5165 {
5166         struct callout *c, *n;
5167         struct calloutlist locallist;
5168         int inited = 0;
5169         int s;
5170         s = splhigh();
5171         /* run through and subtract and mark all callouts */
5172         c = TAILQ_FIRST(&sctppcbinfo.callqueue);
5173         while (c) {
5174                 n = TAILQ_NEXT(c, tqe);
5175                 if (c->c_time <= ticks) {
5176                         c->c_flags |= CALLOUT_FIRED;
5177                         c->c_time = 0;
5178                         TAILQ_REMOVE(&sctppcbinfo.callqueue, c, tqe);
5179                         if (inited == 0) {
5180                                 TAILQ_INIT(&locallist);
5181                                 inited = 1;
5182                         }
5183                         /* move off of main list */
5184                         TAILQ_INSERT_TAIL(&locallist, c, tqe);
5185                 }
5186                 c = n;
5187         }
5188         /* Now all the ones on the locallist must be called */
5189         if (inited) {
5190                 c = TAILQ_FIRST(&locallist);
5191                 while (c) {
5192                         /* remove it */
5193                         TAILQ_REMOVE(&locallist, c, tqe);
5194                         /* now validate that it did not get canceled */
5195                         if (c->c_flags & CALLOUT_FIRED) {
5196                                 c->c_flags &= ~CALLOUT_PENDING;
5197                                 splx(s);
5198                                 (*c->c_func)(c->c_arg);
5199                                 s = splhigh();
5200                         }
5201                         c = TAILQ_FIRST(&locallist);
5202                 }
5203         }
5204         splx(s);
5205 }
5206 #endif
5207 #endif /* _SCTP_NEEDS_CALLOUT_ */