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