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