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