1/*-
2 * Copyright (c) 2001-2008, by Cisco Systems, Inc. All rights reserved.
3 * Copyright (c) 2008-2012, by Randall Stewart. All rights reserved.
4 * Copyright (c) 2008-2012, by Michael Tuexen. All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions are met:
8 *
9 * a) Redistributions of source code must retain the above copyright notice,
10 *    this list of conditions and the following disclaimer.
11 *
12 * b) Redistributions in binary form must reproduce the above copyright
13 *    notice, this list of conditions and the following disclaimer in
14 *    the documentation and/or other materials provided with the distribution.
15 *
16 * c) Neither the name of Cisco Systems, Inc. nor the names of its
17 *    contributors may be used to endorse or promote products derived
18 *    from this software without specific prior written permission.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
22 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
24 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
30 * THE POSSIBILITY OF SUCH DAMAGE.
31 */
32
33#ifdef __FreeBSD__
34#include <sys/cdefs.h>
35__FBSDID("$FreeBSD: head/sys/netinet/sctp_pcb.c 271230 2014-09-07 18:05:37Z tuexen $");
36#endif
37
38#include <netinet/sctp_os.h>
39#ifdef __FreeBSD__
40#include <sys/proc.h>
41#endif
42#include <netinet/sctp_var.h>
43#include <netinet/sctp_sysctl.h>
44#include <netinet/sctp_pcb.h>
45#include <netinet/sctputil.h>
46#include <netinet/sctp.h>
47#include <netinet/sctp_header.h>
48#include <netinet/sctp_asconf.h>
49#include <netinet/sctp_output.h>
50#include <netinet/sctp_timer.h>
51#include <netinet/sctp_bsd_addr.h>
52#if defined(__FreeBSD__) && __FreeBSD_version >= 803000
53#include <netinet/sctp_dtrace_define.h>
54#endif
55#if defined(INET) || defined(INET6)
56#if !defined(__Userspace_os_Windows)
57#include <netinet/udp.h>
58#endif
59#endif
60#ifdef INET6
61#if defined(__Userspace__)
62#include "user_ip6_var.h"
63#else
64#include <netinet6/ip6_var.h>
65#endif
66#endif
67#if defined(__FreeBSD__)
68#include <sys/sched.h>
69#include <sys/smp.h>
70#include <sys/unistd.h>
71#endif
72#if defined(__Userspace__)
73#include <user_socketvar.h>
74#endif
75
76#if defined(__APPLE__)
77#define APPLE_FILE_NO 4
78#endif
79
80#if defined(__FreeBSD__) && __FreeBSD_version >= 801000
81VNET_DEFINE(struct sctp_base_info, system_base_info);
82#else
83struct sctp_base_info system_base_info;
84#endif
85
86#if defined(__Userspace__)
87#if defined(INET) || defined(INET6)
88struct ifaddrs *g_interfaces;
89#endif
90#endif
91/* FIX: we don't handle multiple link local scopes */
92/* "scopeless" replacement IN6_ARE_ADDR_EQUAL */
93#ifdef INET6
94int
95SCTP6_ARE_ADDR_EQUAL(struct sockaddr_in6 *a, struct sockaddr_in6 *b)
96{
97#ifdef SCTP_EMBEDDED_V6_SCOPE
98#if defined(__APPLE__)
99	struct in6_addr tmp_a, tmp_b;
100
101	tmp_a = a->sin6_addr;
102#if defined(APPLE_LEOPARD) || defined(APPLE_SNOWLEOPARD)
103	if (in6_embedscope(&tmp_a, a, NULL, NULL) != 0) {
104#else
105	if (in6_embedscope(&tmp_a, a, NULL, NULL, NULL) != 0) {
106#endif
107		return (0);
108	}
109	tmp_b = b->sin6_addr;
110#if defined(APPLE_LEOPARD) || defined(APPLE_SNOWLEOPARD)
111	if (in6_embedscope(&tmp_b, b, NULL, NULL) != 0) {
112#else
113	if (in6_embedscope(&tmp_b, b, NULL, NULL, NULL) != 0) {
114#endif
115		return (0);
116	}
117	return (IN6_ARE_ADDR_EQUAL(&tmp_a, &tmp_b));
118#elif defined(SCTP_KAME)
119	struct sockaddr_in6 tmp_a, tmp_b;
120
121	memcpy(&tmp_a, a, sizeof(struct sockaddr_in6));
122	if (sa6_embedscope(&tmp_a, MODULE_GLOBAL(ip6_use_defzone)) != 0) {
123		return (0);
124	}
125	memcpy(&tmp_b, b, sizeof(struct sockaddr_in6));
126	if (sa6_embedscope(&tmp_b, MODULE_GLOBAL(ip6_use_defzone)) != 0) {
127		return (0);
128	}
129	return (IN6_ARE_ADDR_EQUAL(&tmp_a.sin6_addr, &tmp_b.sin6_addr));
130#else
131	struct in6_addr tmp_a, tmp_b;
132
133	tmp_a = a->sin6_addr;
134	if (in6_embedscope(&tmp_a, a) != 0) {
135		return (0);
136	}
137	tmp_b = b->sin6_addr;
138	if (in6_embedscope(&tmp_b, b) != 0) {
139		return (0);
140	}
141	return (IN6_ARE_ADDR_EQUAL(&tmp_a, &tmp_b));
142#endif
143#else
144	return (IN6_ARE_ADDR_EQUAL(&(a->sin6_addr), &(b->sin6_addr)));
145#endif /* SCTP_EMBEDDED_V6_SCOPE */
146}
147#endif
148
149void
150sctp_fill_pcbinfo(struct sctp_pcbinfo *spcb)
151{
152	/*
153	 * We really don't need to lock this, but I will just because it
154	 * does not hurt.
155	 */
156	SCTP_INP_INFO_RLOCK();
157	spcb->ep_count = SCTP_BASE_INFO(ipi_count_ep);
158	spcb->asoc_count = SCTP_BASE_INFO(ipi_count_asoc);
159	spcb->laddr_count = SCTP_BASE_INFO(ipi_count_laddr);
160	spcb->raddr_count = SCTP_BASE_INFO(ipi_count_raddr);
161	spcb->chk_count = SCTP_BASE_INFO(ipi_count_chunk);
162	spcb->readq_count = SCTP_BASE_INFO(ipi_count_readq);
163	spcb->stream_oque = SCTP_BASE_INFO(ipi_count_strmoq);
164	spcb->free_chunks = SCTP_BASE_INFO(ipi_free_chunks);
165	SCTP_INP_INFO_RUNLOCK();
166}
167
168/*-
169 * Addresses are added to VRF's (Virtual Router's). For BSD we
170 * have only the default VRF 0. We maintain a hash list of
171 * VRF's. Each VRF has its own list of sctp_ifn's. Each of
172 * these has a list of addresses. When we add a new address
173 * to a VRF we lookup the ifn/ifn_index, if the ifn does
174 * not exist we create it and add it to the list of IFN's
175 * within the VRF. Once we have the sctp_ifn, we add the
176 * address to the list. So we look something like:
177 *
178 * hash-vrf-table
179 *   vrf-> ifn-> ifn -> ifn
180 *   vrf    |
181 *    ...   +--ifa-> ifa -> ifa
182 *   vrf
183 *
184 * We keep these separate lists since the SCTP subsystem will
185 * point to these from its source address selection nets structure.
186 * When an address is deleted it does not happen right away on
187 * the SCTP side, it gets scheduled. What we do when a
188 * delete happens is immediately remove the address from
189 * the master list and decrement the refcount. As our
190 * addip iterator works through and frees the src address
191 * selection pointing to the sctp_ifa, eventually the refcount
192 * will reach 0 and we will delete it. Note that it is assumed
193 * that any locking on system level ifn/ifa is done at the
194 * caller of these functions and these routines will only
195 * lock the SCTP structures as they add or delete things.
196 *
197 * Other notes on VRF concepts.
198 *  - An endpoint can be in multiple VRF's
199 *  - An association lives within a VRF and only one VRF.
200 *  - Any incoming packet we can deduce the VRF for by
201 *    looking at the mbuf/pak inbound (for BSD its VRF=0 :D)
202 *  - Any downward send call or connect call must supply the
203 *    VRF via ancillary data or via some sort of set default
204 *    VRF socket option call (again for BSD no brainer since
205 *    the VRF is always 0).
206 *  - An endpoint may add multiple VRF's to it.
207 *  - Listening sockets can accept associations in any
208 *    of the VRF's they are in but the assoc will end up
209 *    in only one VRF (gotten from the packet or connect/send).
210 *
211 */
212
213struct sctp_vrf *
214sctp_allocate_vrf(int vrf_id)
215{
216	struct sctp_vrf *vrf = NULL;
217	struct sctp_vrflist *bucket;
218
219	/* First allocate the VRF structure */
220	vrf = sctp_find_vrf(vrf_id);
221	if (vrf) {
222		/* Already allocated */
223		return (vrf);
224	}
225	SCTP_MALLOC(vrf, struct sctp_vrf *, sizeof(struct sctp_vrf),
226		    SCTP_M_VRF);
227	if (vrf == NULL) {
228		/* No memory */
229#ifdef INVARIANTS
230		panic("No memory for VRF:%d", vrf_id);
231#endif
232		return (NULL);
233	}
234	/* setup the VRF */
235	memset(vrf, 0, sizeof(struct sctp_vrf));
236	vrf->vrf_id = vrf_id;
237	LIST_INIT(&vrf->ifnlist);
238	vrf->total_ifa_count = 0;
239	vrf->refcount = 0;
240	/* now also setup table ids */
241	SCTP_INIT_VRF_TABLEID(vrf);
242	/* Init the HASH of addresses */
243	vrf->vrf_addr_hash = SCTP_HASH_INIT(SCTP_VRF_ADDR_HASH_SIZE,
244					    &vrf->vrf_addr_hashmark);
245	if (vrf->vrf_addr_hash == NULL) {
246		/* No memory */
247#ifdef INVARIANTS
248		panic("No memory for VRF:%d", vrf_id);
249#endif
250		SCTP_FREE(vrf, SCTP_M_VRF);
251		return (NULL);
252	}
253
254	/* Add it to the hash table */
255	bucket = &SCTP_BASE_INFO(sctp_vrfhash)[(vrf_id & SCTP_BASE_INFO(hashvrfmark))];
256	LIST_INSERT_HEAD(bucket, vrf, next_vrf);
257	atomic_add_int(&SCTP_BASE_INFO(ipi_count_vrfs), 1);
258	return (vrf);
259}
260
261
262struct sctp_ifn *
263sctp_find_ifn(void *ifn, uint32_t ifn_index)
264{
265	struct sctp_ifn *sctp_ifnp;
266	struct sctp_ifnlist *hash_ifn_head;
267
268	/* We assume the lock is held for the addresses
269	 * if that's wrong problems could occur :-)
270	 */
271	hash_ifn_head = &SCTP_BASE_INFO(vrf_ifn_hash)[(ifn_index & SCTP_BASE_INFO(vrf_ifn_hashmark))];
272	LIST_FOREACH(sctp_ifnp, hash_ifn_head, next_bucket) {
273		if (sctp_ifnp->ifn_index == ifn_index) {
274			return (sctp_ifnp);
275		}
276		if (sctp_ifnp->ifn_p && ifn && (sctp_ifnp->ifn_p == ifn)) {
277			return (sctp_ifnp);
278		}
279	}
280	return (NULL);
281}
282
283
284struct sctp_vrf *
285sctp_find_vrf(uint32_t vrf_id)
286{
287	struct sctp_vrflist *bucket;
288	struct sctp_vrf *liste;
289
290	bucket = &SCTP_BASE_INFO(sctp_vrfhash)[(vrf_id & SCTP_BASE_INFO(hashvrfmark))];
291	LIST_FOREACH(liste, bucket, next_vrf) {
292		if (vrf_id == liste->vrf_id) {
293			return (liste);
294		}
295	}
296	return (NULL);
297}
298
299
300void
301sctp_free_vrf(struct sctp_vrf *vrf)
302{
303	if (SCTP_DECREMENT_AND_CHECK_REFCOUNT(&vrf->refcount)) {
304                if (vrf->vrf_addr_hash) {
305                    SCTP_HASH_FREE(vrf->vrf_addr_hash, vrf->vrf_addr_hashmark);
306                    vrf->vrf_addr_hash = NULL;
307                }
308		/* We zero'd the count */
309		LIST_REMOVE(vrf, next_vrf);
310		SCTP_FREE(vrf, SCTP_M_VRF);
311		atomic_subtract_int(&SCTP_BASE_INFO(ipi_count_vrfs), 1);
312	}
313}
314
315
316void
317sctp_free_ifn(struct sctp_ifn *sctp_ifnp)
318{
319	if (SCTP_DECREMENT_AND_CHECK_REFCOUNT(&sctp_ifnp->refcount)) {
320		/* We zero'd the count */
321		if (sctp_ifnp->vrf) {
322			sctp_free_vrf(sctp_ifnp->vrf);
323		}
324		SCTP_FREE(sctp_ifnp, SCTP_M_IFN);
325		atomic_subtract_int(&SCTP_BASE_INFO(ipi_count_ifns), 1);
326	}
327}
328
329
330void
331sctp_update_ifn_mtu(uint32_t ifn_index, uint32_t mtu)
332{
333	struct sctp_ifn *sctp_ifnp;
334
335	sctp_ifnp = sctp_find_ifn((void *)NULL, ifn_index);
336	if (sctp_ifnp != NULL) {
337		sctp_ifnp->ifn_mtu = mtu;
338	}
339}
340
341
342void
343sctp_free_ifa(struct sctp_ifa *sctp_ifap)
344{
345	if (SCTP_DECREMENT_AND_CHECK_REFCOUNT(&sctp_ifap->refcount)) {
346		/* We zero'd the count */
347		if (sctp_ifap->ifn_p) {
348			sctp_free_ifn(sctp_ifap->ifn_p);
349		}
350		SCTP_FREE(sctp_ifap, SCTP_M_IFA);
351		atomic_subtract_int(&SCTP_BASE_INFO(ipi_count_ifas), 1);
352	}
353}
354
355
356static void
357sctp_delete_ifn(struct sctp_ifn *sctp_ifnp, int hold_addr_lock)
358{
359	struct sctp_ifn *found;
360
361	found = sctp_find_ifn(sctp_ifnp->ifn_p, sctp_ifnp->ifn_index);
362	if (found == NULL) {
363		/* Not in the list.. sorry */
364		return;
365	}
366	if (hold_addr_lock == 0)
367		SCTP_IPI_ADDR_WLOCK();
368	LIST_REMOVE(sctp_ifnp, next_bucket);
369	LIST_REMOVE(sctp_ifnp, next_ifn);
370	SCTP_DEREGISTER_INTERFACE(sctp_ifnp->ifn_index,
371				  sctp_ifnp->registered_af);
372	if (hold_addr_lock == 0)
373		SCTP_IPI_ADDR_WUNLOCK();
374	/* Take away the reference, and possibly free it */
375	sctp_free_ifn(sctp_ifnp);
376}
377
378
379void
380sctp_mark_ifa_addr_down(uint32_t vrf_id, struct sockaddr *addr,
381			const char *if_name, uint32_t ifn_index)
382{
383	struct sctp_vrf *vrf;
384	struct sctp_ifa *sctp_ifap;
385
386	SCTP_IPI_ADDR_RLOCK();
387	vrf = sctp_find_vrf(vrf_id);
388	if (vrf == NULL) {
389		SCTPDBG(SCTP_DEBUG_PCB4, "Can't find vrf_id 0x%x\n", vrf_id);
390		goto out;
391
392	}
393	sctp_ifap = sctp_find_ifa_by_addr(addr, vrf->vrf_id, SCTP_ADDR_LOCKED);
394	if (sctp_ifap == NULL) {
395		SCTPDBG(SCTP_DEBUG_PCB4, "Can't find sctp_ifap for address\n");
396		goto out;
397	}
398	if (sctp_ifap->ifn_p == NULL) {
399		SCTPDBG(SCTP_DEBUG_PCB4, "IFA has no IFN - can't mark unuseable\n");
400		goto out;
401	}
402	if (if_name) {
403		if (strncmp(if_name, sctp_ifap->ifn_p->ifn_name, SCTP_IFNAMSIZ) != 0) {
404			SCTPDBG(SCTP_DEBUG_PCB4, "IFN %s of IFA not the same as %s\n",
405				sctp_ifap->ifn_p->ifn_name, if_name);
406			goto out;
407		}
408	} else {
409		if (sctp_ifap->ifn_p->ifn_index != ifn_index) {
410			SCTPDBG(SCTP_DEBUG_PCB4, "IFA owned by ifn_index:%d down command for ifn_index:%d - ignored\n",
411				sctp_ifap->ifn_p->ifn_index, ifn_index);
412			goto out;
413		}
414	}
415
416	sctp_ifap->localifa_flags &= (~SCTP_ADDR_VALID);
417	sctp_ifap->localifa_flags |= SCTP_ADDR_IFA_UNUSEABLE;
418 out:
419	SCTP_IPI_ADDR_RUNLOCK();
420}
421
422
423void
424sctp_mark_ifa_addr_up(uint32_t vrf_id, struct sockaddr *addr,
425		      const char *if_name, uint32_t ifn_index)
426{
427	struct sctp_vrf *vrf;
428	struct sctp_ifa *sctp_ifap;
429
430	SCTP_IPI_ADDR_RLOCK();
431	vrf = sctp_find_vrf(vrf_id);
432	if (vrf == NULL) {
433		SCTPDBG(SCTP_DEBUG_PCB4, "Can't find vrf_id 0x%x\n", vrf_id);
434		goto out;
435
436	}
437	sctp_ifap = sctp_find_ifa_by_addr(addr, vrf->vrf_id, SCTP_ADDR_LOCKED);
438	if (sctp_ifap == NULL) {
439		SCTPDBG(SCTP_DEBUG_PCB4, "Can't find sctp_ifap for address\n");
440		goto out;
441	}
442	if (sctp_ifap->ifn_p == NULL) {
443		SCTPDBG(SCTP_DEBUG_PCB4, "IFA has no IFN - can't mark unuseable\n");
444		goto out;
445	}
446	if (if_name) {
447		if (strncmp(if_name, sctp_ifap->ifn_p->ifn_name, SCTP_IFNAMSIZ) != 0) {
448			SCTPDBG(SCTP_DEBUG_PCB4, "IFN %s of IFA not the same as %s\n",
449				sctp_ifap->ifn_p->ifn_name, if_name);
450			goto out;
451		}
452	} else {
453		if (sctp_ifap->ifn_p->ifn_index != ifn_index) {
454			SCTPDBG(SCTP_DEBUG_PCB4, "IFA owned by ifn_index:%d down command for ifn_index:%d - ignored\n",
455				sctp_ifap->ifn_p->ifn_index, ifn_index);
456			goto out;
457		}
458	}
459
460	sctp_ifap->localifa_flags &= (~SCTP_ADDR_IFA_UNUSEABLE);
461	sctp_ifap->localifa_flags |= SCTP_ADDR_VALID;
462 out:
463	SCTP_IPI_ADDR_RUNLOCK();
464}
465
466
467/*-
468 * Add an ifa to an ifn.
469 * Register the interface as necessary.
470 * NOTE: ADDR write lock MUST be held.
471 */
472static void
473sctp_add_ifa_to_ifn(struct sctp_ifn *sctp_ifnp, struct sctp_ifa *sctp_ifap)
474{
475	int ifa_af;
476
477	LIST_INSERT_HEAD(&sctp_ifnp->ifalist, sctp_ifap, next_ifa);
478	sctp_ifap->ifn_p = sctp_ifnp;
479	atomic_add_int(&sctp_ifap->ifn_p->refcount, 1);
480	/* update address counts */
481	sctp_ifnp->ifa_count++;
482	ifa_af = sctp_ifap->address.sa.sa_family;
483	switch (ifa_af) {
484#ifdef INET
485	case AF_INET:
486		sctp_ifnp->num_v4++;
487		break;
488#endif
489#ifdef INET6
490	case AF_INET6:
491		sctp_ifnp->num_v6++;
492		break;
493#endif
494	default:
495		break;
496	}
497	if (sctp_ifnp->ifa_count == 1) {
498		/* register the new interface */
499		SCTP_REGISTER_INTERFACE(sctp_ifnp->ifn_index, ifa_af);
500		sctp_ifnp->registered_af = ifa_af;
501	}
502}
503
504
505/*-
506 * Remove an ifa from its ifn.
507 * If no more addresses exist, remove the ifn too. Otherwise, re-register
508 * the interface based on the remaining address families left.
509 * NOTE: ADDR write lock MUST be held.
510 */
511static void
512sctp_remove_ifa_from_ifn(struct sctp_ifa *sctp_ifap)
513{
514	LIST_REMOVE(sctp_ifap, next_ifa);
515	if (sctp_ifap->ifn_p) {
516		/* update address counts */
517		sctp_ifap->ifn_p->ifa_count--;
518		switch (sctp_ifap->address.sa.sa_family) {
519#ifdef INET
520		case AF_INET:
521			sctp_ifap->ifn_p->num_v4--;
522			break;
523#endif
524#ifdef INET6
525		case AF_INET6:
526			sctp_ifap->ifn_p->num_v6--;
527			break;
528#endif
529		default:
530			break;
531		}
532
533		if (LIST_EMPTY(&sctp_ifap->ifn_p->ifalist)) {
534			/* remove the ifn, possibly freeing it */
535			sctp_delete_ifn(sctp_ifap->ifn_p, SCTP_ADDR_LOCKED);
536		} else {
537			/* re-register address family type, if needed */
538			if ((sctp_ifap->ifn_p->num_v6 == 0) &&
539			    (sctp_ifap->ifn_p->registered_af == AF_INET6)) {
540				SCTP_DEREGISTER_INTERFACE(sctp_ifap->ifn_p->ifn_index, AF_INET6);
541				SCTP_REGISTER_INTERFACE(sctp_ifap->ifn_p->ifn_index, AF_INET);
542				sctp_ifap->ifn_p->registered_af = AF_INET;
543			} else if ((sctp_ifap->ifn_p->num_v4 == 0) &&
544				   (sctp_ifap->ifn_p->registered_af == AF_INET)) {
545				SCTP_DEREGISTER_INTERFACE(sctp_ifap->ifn_p->ifn_index, AF_INET);
546				SCTP_REGISTER_INTERFACE(sctp_ifap->ifn_p->ifn_index, AF_INET6);
547				sctp_ifap->ifn_p->registered_af = AF_INET6;
548			}
549			/* free the ifn refcount */
550			sctp_free_ifn(sctp_ifap->ifn_p);
551		}
552		sctp_ifap->ifn_p = NULL;
553	}
554}
555
556
557struct sctp_ifa *
558sctp_add_addr_to_vrf(uint32_t vrf_id, void *ifn, uint32_t ifn_index,
559		     uint32_t ifn_type, const char *if_name, void *ifa,
560		     struct sockaddr *addr, uint32_t ifa_flags,
561		     int dynamic_add)
562{
563	struct sctp_vrf *vrf;
564	struct sctp_ifn *sctp_ifnp = NULL;
565	struct sctp_ifa *sctp_ifap = NULL;
566	struct sctp_ifalist *hash_addr_head;
567	struct sctp_ifnlist *hash_ifn_head;
568	uint32_t hash_of_addr;
569	int new_ifn_af = 0;
570
571#ifdef SCTP_DEBUG
572	SCTPDBG(SCTP_DEBUG_PCB4, "vrf_id 0x%x: adding address: ", vrf_id);
573	SCTPDBG_ADDR(SCTP_DEBUG_PCB4, addr);
574#endif
575	SCTP_IPI_ADDR_WLOCK();
576	sctp_ifnp = sctp_find_ifn(ifn, ifn_index);
577	if (sctp_ifnp) {
578		vrf = sctp_ifnp->vrf;
579	} else {
580		vrf = sctp_find_vrf(vrf_id);
581		if (vrf == NULL) {
582			vrf = sctp_allocate_vrf(vrf_id);
583			if (vrf == NULL) {
584				SCTP_IPI_ADDR_WUNLOCK();
585				return (NULL);
586			}
587		}
588	}
589	if (sctp_ifnp == NULL) {
590		/* build one and add it, can't hold lock
591		 * until after malloc done though.
592		 */
593		SCTP_IPI_ADDR_WUNLOCK();
594		SCTP_MALLOC(sctp_ifnp, struct sctp_ifn *,
595			    sizeof(struct sctp_ifn), SCTP_M_IFN);
596		if (sctp_ifnp == NULL) {
597#ifdef INVARIANTS
598			panic("No memory for IFN");
599#endif
600			return (NULL);
601		}
602		memset(sctp_ifnp, 0, sizeof(struct sctp_ifn));
603		sctp_ifnp->ifn_index = ifn_index;
604		sctp_ifnp->ifn_p = ifn;
605		sctp_ifnp->ifn_type = ifn_type;
606		sctp_ifnp->refcount = 0;
607		sctp_ifnp->vrf = vrf;
608		atomic_add_int(&vrf->refcount, 1);
609		sctp_ifnp->ifn_mtu = SCTP_GATHER_MTU_FROM_IFN_INFO(ifn, ifn_index, addr->sa_family);
610		if (if_name != NULL) {
611			snprintf(sctp_ifnp->ifn_name, SCTP_IFNAMSIZ, "%s", if_name);
612		} else {
613			snprintf(sctp_ifnp->ifn_name, SCTP_IFNAMSIZ, "%s", "unknown");
614		}
615		hash_ifn_head = &SCTP_BASE_INFO(vrf_ifn_hash)[(ifn_index & SCTP_BASE_INFO(vrf_ifn_hashmark))];
616		LIST_INIT(&sctp_ifnp->ifalist);
617		SCTP_IPI_ADDR_WLOCK();
618		LIST_INSERT_HEAD(hash_ifn_head, sctp_ifnp, next_bucket);
619		LIST_INSERT_HEAD(&vrf->ifnlist, sctp_ifnp, next_ifn);
620		atomic_add_int(&SCTP_BASE_INFO(ipi_count_ifns), 1);
621		new_ifn_af = 1;
622	}
623	sctp_ifap = sctp_find_ifa_by_addr(addr, vrf->vrf_id, SCTP_ADDR_LOCKED);
624	if (sctp_ifap) {
625		/* Hmm, it already exists? */
626		if ((sctp_ifap->ifn_p) &&
627		    (sctp_ifap->ifn_p->ifn_index == ifn_index)) {
628			SCTPDBG(SCTP_DEBUG_PCB4, "Using existing ifn %s (0x%x) for ifa %p\n",
629				sctp_ifap->ifn_p->ifn_name, ifn_index,
630				(void *)sctp_ifap);
631			if (new_ifn_af) {
632				/* Remove the created one that we don't want */
633				sctp_delete_ifn(sctp_ifnp, SCTP_ADDR_LOCKED);
634			}
635			if (sctp_ifap->localifa_flags & SCTP_BEING_DELETED) {
636				/* easy to solve, just switch back to active */
637				SCTPDBG(SCTP_DEBUG_PCB4, "Clearing deleted ifa flag\n");
638				sctp_ifap->localifa_flags = SCTP_ADDR_VALID;
639				sctp_ifap->ifn_p = sctp_ifnp;
640				atomic_add_int(&sctp_ifap->ifn_p->refcount, 1);
641			}
642		exit_stage_left:
643			SCTP_IPI_ADDR_WUNLOCK();
644			return (sctp_ifap);
645		} else {
646			if (sctp_ifap->ifn_p) {
647				/*
648				 * The last IFN gets the address, remove the
649				 * old one
650				 */
651				SCTPDBG(SCTP_DEBUG_PCB4, "Moving ifa %p from %s (0x%x) to %s (0x%x)\n",
652					(void *)sctp_ifap, sctp_ifap->ifn_p->ifn_name,
653					sctp_ifap->ifn_p->ifn_index, if_name,
654					ifn_index);
655				/* remove the address from the old ifn */
656				sctp_remove_ifa_from_ifn(sctp_ifap);
657				/* move the address over to the new ifn */
658				sctp_add_ifa_to_ifn(sctp_ifnp, sctp_ifap);
659				goto exit_stage_left;
660			} else {
661				/* repair ifnp which was NULL ? */
662				sctp_ifap->localifa_flags = SCTP_ADDR_VALID;
663				SCTPDBG(SCTP_DEBUG_PCB4, "Repairing ifn %p for ifa %p\n",
664					(void *)sctp_ifnp, (void *)sctp_ifap);
665				sctp_add_ifa_to_ifn(sctp_ifnp, sctp_ifap);
666			}
667			goto exit_stage_left;
668		}
669	}
670	SCTP_IPI_ADDR_WUNLOCK();
671	SCTP_MALLOC(sctp_ifap, struct sctp_ifa *, sizeof(struct sctp_ifa), SCTP_M_IFA);
672	if (sctp_ifap == NULL) {
673#ifdef INVARIANTS
674		panic("No memory for IFA");
675#endif
676		return (NULL);
677	}
678	memset(sctp_ifap, 0, sizeof(struct sctp_ifa));
679	sctp_ifap->ifn_p = sctp_ifnp;
680	atomic_add_int(&sctp_ifnp->refcount, 1);
681	sctp_ifap->vrf_id = vrf_id;
682	sctp_ifap->ifa = ifa;
683#ifdef HAVE_SA_LEN
684	memcpy(&sctp_ifap->address, addr, addr->sa_len);
685#else
686	switch (addr->sa_family) {
687#ifdef INET
688	case AF_INET:
689		memcpy(&sctp_ifap->address, addr, sizeof(struct sockaddr_in));
690		break;
691#endif
692#ifdef INET6
693	case AF_INET6:
694		memcpy(&sctp_ifap->address, addr, sizeof(struct sockaddr_in6));
695		break;
696#endif
697#if defined(__Userspace__)
698	case AF_CONN:
699		memcpy(&sctp_ifap->address, addr, sizeof(struct sockaddr_conn));
700		break;
701#endif
702	default:
703		/* TSNH */
704		break;
705	}
706#endif
707	sctp_ifap->localifa_flags = SCTP_ADDR_VALID | SCTP_ADDR_DEFER_USE;
708	sctp_ifap->flags = ifa_flags;
709	/* Set scope */
710	switch (sctp_ifap->address.sa.sa_family) {
711#ifdef INET
712	case AF_INET:
713	{
714		struct sockaddr_in *sin;
715
716		sin = &sctp_ifap->address.sin;
717		if (SCTP_IFN_IS_IFT_LOOP(sctp_ifap->ifn_p) ||
718		    (IN4_ISLOOPBACK_ADDRESS(&sin->sin_addr))) {
719			sctp_ifap->src_is_loop = 1;
720		}
721		if ((IN4_ISPRIVATE_ADDRESS(&sin->sin_addr))) {
722			sctp_ifap->src_is_priv = 1;
723		}
724		sctp_ifnp->num_v4++;
725		if (new_ifn_af)
726		    new_ifn_af = AF_INET;
727		break;
728	}
729#endif
730#ifdef INET6
731	case AF_INET6:
732	{
733		/* ok to use deprecated addresses? */
734		struct sockaddr_in6 *sin6;
735
736		sin6 = &sctp_ifap->address.sin6;
737		if (SCTP_IFN_IS_IFT_LOOP(sctp_ifap->ifn_p) ||
738		    (IN6_IS_ADDR_LOOPBACK(&sin6->sin6_addr))) {
739			sctp_ifap->src_is_loop = 1;
740		}
741		if (IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr)) {
742			sctp_ifap->src_is_priv = 1;
743		}
744		sctp_ifnp->num_v6++;
745		if (new_ifn_af)
746			new_ifn_af = AF_INET6;
747		break;
748	}
749#endif
750#if defined(__Userspace__)
751	case AF_CONN:
752		if (new_ifn_af)
753			new_ifn_af = AF_CONN;
754		break;
755#endif
756	default:
757		new_ifn_af = 0;
758		break;
759	}
760	hash_of_addr = sctp_get_ifa_hash_val(&sctp_ifap->address.sa);
761
762	if ((sctp_ifap->src_is_priv == 0) &&
763	    (sctp_ifap->src_is_loop == 0)) {
764		sctp_ifap->src_is_glob = 1;
765	}
766	SCTP_IPI_ADDR_WLOCK();
767	hash_addr_head = &vrf->vrf_addr_hash[(hash_of_addr & vrf->vrf_addr_hashmark)];
768	LIST_INSERT_HEAD(hash_addr_head, sctp_ifap, next_bucket);
769	sctp_ifap->refcount = 1;
770	LIST_INSERT_HEAD(&sctp_ifnp->ifalist, sctp_ifap, next_ifa);
771	sctp_ifnp->ifa_count++;
772	vrf->total_ifa_count++;
773	atomic_add_int(&SCTP_BASE_INFO(ipi_count_ifas), 1);
774	if (new_ifn_af) {
775		SCTP_REGISTER_INTERFACE(ifn_index, new_ifn_af);
776		sctp_ifnp->registered_af = new_ifn_af;
777	}
778	SCTP_IPI_ADDR_WUNLOCK();
779	if (dynamic_add) {
780		/* Bump up the refcount so that when the timer
781		 * completes it will drop back down.
782		 */
783		struct sctp_laddr *wi;
784
785		atomic_add_int(&sctp_ifap->refcount, 1);
786		wi = SCTP_ZONE_GET(SCTP_BASE_INFO(ipi_zone_laddr), struct sctp_laddr);
787		if (wi == NULL) {
788			/*
789			 * Gak, what can we do? We have lost an address
790			 * change can you say HOSED?
791			 */
792			SCTPDBG(SCTP_DEBUG_PCB4, "Lost an address change?\n");
793			/* Opps, must decrement the count */
794			sctp_del_addr_from_vrf(vrf_id, addr, ifn_index,
795					       if_name);
796			return (NULL);
797		}
798		SCTP_INCR_LADDR_COUNT();
799		bzero(wi, sizeof(*wi));
800		(void)SCTP_GETTIME_TIMEVAL(&wi->start_time);
801		wi->ifa = sctp_ifap;
802		wi->action = SCTP_ADD_IP_ADDRESS;
803
804		SCTP_WQ_ADDR_LOCK();
805		LIST_INSERT_HEAD(&SCTP_BASE_INFO(addr_wq), wi, sctp_nxt_addr);
806		SCTP_WQ_ADDR_UNLOCK();
807
808		sctp_timer_start(SCTP_TIMER_TYPE_ADDR_WQ,
809				 (struct sctp_inpcb *)NULL,
810				 (struct sctp_tcb *)NULL,
811				 (struct sctp_nets *)NULL);
812	} else {
813		/* it's ready for use */
814		sctp_ifap->localifa_flags &= ~SCTP_ADDR_DEFER_USE;
815	}
816	return (sctp_ifap);
817}
818
819void
820sctp_del_addr_from_vrf(uint32_t vrf_id, struct sockaddr *addr,
821		       uint32_t ifn_index, const char *if_name)
822{
823	struct sctp_vrf *vrf;
824	struct sctp_ifa *sctp_ifap = NULL;
825
826	SCTP_IPI_ADDR_WLOCK();
827	vrf = sctp_find_vrf(vrf_id);
828	if (vrf == NULL) {
829		SCTPDBG(SCTP_DEBUG_PCB4, "Can't find vrf_id 0x%x\n", vrf_id);
830		goto out_now;
831	}
832
833#ifdef SCTP_DEBUG
834	SCTPDBG(SCTP_DEBUG_PCB4, "vrf_id 0x%x: deleting address:", vrf_id);
835	SCTPDBG_ADDR(SCTP_DEBUG_PCB4, addr);
836#endif
837	sctp_ifap = sctp_find_ifa_by_addr(addr, vrf->vrf_id, SCTP_ADDR_LOCKED);
838	if (sctp_ifap) {
839		/* Validate the delete */
840		if (sctp_ifap->ifn_p) {
841			int valid = 0;
842			/*-
843			 * The name has priority over the ifn_index
844			 * if its given. We do this especially for
845			 * panda who might recycle indexes fast.
846			 */
847			if (if_name) {
848				if (strncmp(if_name, sctp_ifap->ifn_p->ifn_name, SCTP_IFNAMSIZ) == 0) {
849					/* They match its a correct delete */
850					valid = 1;
851				}
852			}
853			if (!valid) {
854				/* last ditch check ifn_index */
855				if (ifn_index == sctp_ifap->ifn_p->ifn_index) {
856					valid = 1;
857				}
858			}
859			if (!valid) {
860				SCTPDBG(SCTP_DEBUG_PCB4, "ifn:%d ifname:%s does not match addresses\n",
861					ifn_index, ((if_name == NULL) ? "NULL" : if_name));
862				SCTPDBG(SCTP_DEBUG_PCB4, "ifn:%d ifname:%s - ignoring delete\n",
863					sctp_ifap->ifn_p->ifn_index, sctp_ifap->ifn_p->ifn_name);
864				SCTP_IPI_ADDR_WUNLOCK();
865				return;
866			}
867		}
868		SCTPDBG(SCTP_DEBUG_PCB4, "Deleting ifa %p\n", (void *)sctp_ifap);
869		sctp_ifap->localifa_flags &= SCTP_ADDR_VALID;
870                /*
871		 * We don't set the flag. This means that the structure will
872		 * hang around in EP's that have bound specific to it until
873		 * they close. This gives us TCP like behavior if someone
874		 * removes an address (or for that matter adds it right back).
875		 */
876		/* sctp_ifap->localifa_flags |= SCTP_BEING_DELETED; */
877		vrf->total_ifa_count--;
878		LIST_REMOVE(sctp_ifap, next_bucket);
879		sctp_remove_ifa_from_ifn(sctp_ifap);
880	}
881#ifdef SCTP_DEBUG
882	else {
883		SCTPDBG(SCTP_DEBUG_PCB4, "Del Addr-ifn:%d Could not find address:",
884			ifn_index);
885		SCTPDBG_ADDR(SCTP_DEBUG_PCB1, addr);
886	}
887#endif
888
889 out_now:
890	SCTP_IPI_ADDR_WUNLOCK();
891	if (sctp_ifap) {
892		struct sctp_laddr *wi;
893
894		wi = SCTP_ZONE_GET(SCTP_BASE_INFO(ipi_zone_laddr), struct sctp_laddr);
895		if (wi == NULL) {
896			/*
897			 * Gak, what can we do? We have lost an address
898			 * change can you say HOSED?
899			 */
900			SCTPDBG(SCTP_DEBUG_PCB4, "Lost an address change?\n");
901
902			/* Oops, must decrement the count */
903			sctp_free_ifa(sctp_ifap);
904			return;
905		}
906		SCTP_INCR_LADDR_COUNT();
907		bzero(wi, sizeof(*wi));
908		(void)SCTP_GETTIME_TIMEVAL(&wi->start_time);
909		wi->ifa = sctp_ifap;
910		wi->action = SCTP_DEL_IP_ADDRESS;
911		SCTP_WQ_ADDR_LOCK();
912		/*
913		 * Should this really be a tailq? As it is we will process the
914		 * newest first :-0
915		 */
916		LIST_INSERT_HEAD(&SCTP_BASE_INFO(addr_wq), wi, sctp_nxt_addr);
917		SCTP_WQ_ADDR_UNLOCK();
918
919		sctp_timer_start(SCTP_TIMER_TYPE_ADDR_WQ,
920				 (struct sctp_inpcb *)NULL,
921				 (struct sctp_tcb *)NULL,
922				 (struct sctp_nets *)NULL);
923	}
924	return;
925}
926
927
928static int
929sctp_does_stcb_own_this_addr(struct sctp_tcb *stcb, struct sockaddr *to)
930{
931	int loopback_scope;
932#if defined(INET)
933	int ipv4_local_scope, ipv4_addr_legal;
934#endif
935#if defined(INET6)
936	int local_scope, site_scope, ipv6_addr_legal;
937#endif
938#if defined(__Userspace__)
939	int conn_addr_legal;
940#endif
941	struct sctp_vrf *vrf;
942	struct sctp_ifn *sctp_ifn;
943	struct sctp_ifa *sctp_ifa;
944
945	loopback_scope = stcb->asoc.scope.loopback_scope;
946#if defined(INET)
947	ipv4_local_scope = stcb->asoc.scope.ipv4_local_scope;
948	ipv4_addr_legal = stcb->asoc.scope.ipv4_addr_legal;
949#endif
950#if defined(INET6)
951	local_scope = stcb->asoc.scope.local_scope;
952	site_scope = stcb->asoc.scope.site_scope;
953	ipv6_addr_legal = stcb->asoc.scope.ipv6_addr_legal;
954#endif
955#if defined(__Userspace__)
956	conn_addr_legal = stcb->asoc.scope.conn_addr_legal;
957#endif
958
959	SCTP_IPI_ADDR_RLOCK();
960	vrf = sctp_find_vrf(stcb->asoc.vrf_id);
961	if (vrf == NULL) {
962		/* no vrf, no addresses */
963		SCTP_IPI_ADDR_RUNLOCK();
964		return (0);
965	}
966
967	if (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) {
968		LIST_FOREACH(sctp_ifn, &vrf->ifnlist, next_ifn) {
969			if ((loopback_scope == 0) &&
970			    SCTP_IFN_IS_IFT_LOOP(sctp_ifn)) {
971				continue;
972			}
973			LIST_FOREACH(sctp_ifa, &sctp_ifn->ifalist, next_ifa) {
974				if (sctp_is_addr_restricted(stcb, sctp_ifa) &&
975				    (!sctp_is_addr_pending(stcb, sctp_ifa))) {
976					/* We allow pending addresses, where we
977					 * have sent an asconf-add to be considered
978					 * valid.
979					 */
980					continue;
981				}
982				if (sctp_ifa->address.sa.sa_family != to->sa_family) {
983					continue;
984				}
985				switch (sctp_ifa->address.sa.sa_family) {
986#ifdef INET
987				case AF_INET:
988					if (ipv4_addr_legal) {
989						struct sockaddr_in *sin, *rsin;
990
991						sin = &sctp_ifa->address.sin;
992						rsin = (struct sockaddr_in *)to;
993						if ((ipv4_local_scope == 0) &&
994						    IN4_ISPRIVATE_ADDRESS(&sin->sin_addr)) {
995							continue;
996						}
997#if defined(__FreeBSD__)
998						if (prison_check_ip4(stcb->sctp_ep->ip_inp.inp.inp_cred,
999						                     &sin->sin_addr) != 0) {
1000							continue;
1001						}
1002#endif
1003						if (sin->sin_addr.s_addr == rsin->sin_addr.s_addr) {
1004							SCTP_IPI_ADDR_RUNLOCK();
1005							return (1);
1006						}
1007					}
1008					break;
1009#endif
1010#ifdef INET6
1011				case AF_INET6:
1012					if (ipv6_addr_legal) {
1013						struct sockaddr_in6 *sin6, *rsin6;
1014#if defined(SCTP_EMBEDDED_V6_SCOPE) && !defined(SCTP_KAME)
1015						struct sockaddr_in6 lsa6;
1016#endif
1017						sin6 = &sctp_ifa->address.sin6;
1018						rsin6 = (struct sockaddr_in6 *)to;
1019#if defined(__FreeBSD__)
1020						if (prison_check_ip6(stcb->sctp_ep->ip_inp.inp.inp_cred,
1021						                     &sin6->sin6_addr) != 0) {
1022							continue;
1023						}
1024#endif
1025						if (IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr)) {
1026							if (local_scope == 0)
1027								continue;
1028#if defined(SCTP_EMBEDDED_V6_SCOPE)
1029							if (sin6->sin6_scope_id == 0) {
1030#ifdef SCTP_KAME
1031								if (sa6_recoverscope(sin6) != 0)
1032									continue;
1033#else
1034								lsa6 = *sin6;
1035								if (in6_recoverscope(&lsa6,
1036								                     &lsa6.sin6_addr,
1037								                     NULL))
1038									continue;
1039								sin6 = &lsa6;
1040#endif /* SCTP_KAME */
1041							}
1042#endif /* SCTP_EMBEDDED_V6_SCOPE */
1043						}
1044						if ((site_scope == 0) &&
1045						    (IN6_IS_ADDR_SITELOCAL(&sin6->sin6_addr))) {
1046							continue;
1047						}
1048						if (SCTP6_ARE_ADDR_EQUAL(sin6, rsin6)) {
1049							SCTP_IPI_ADDR_RUNLOCK();
1050							return (1);
1051						}
1052					}
1053					break;
1054#endif
1055#if defined(__Userspace__)
1056				case AF_CONN:
1057					if (conn_addr_legal) {
1058						struct sockaddr_conn *sconn, *rsconn;
1059
1060						sconn = &sctp_ifa->address.sconn;
1061						rsconn = (struct sockaddr_conn *)to;
1062						if (sconn->sconn_addr == rsconn->sconn_addr) {
1063							SCTP_IPI_ADDR_RUNLOCK();
1064							return (1);
1065						}
1066					}
1067					break;
1068#endif
1069				default:
1070					/* TSNH */
1071					break;
1072				}
1073			}
1074		}
1075	} else {
1076		struct sctp_laddr *laddr;
1077
1078		LIST_FOREACH(laddr, &stcb->sctp_ep->sctp_addr_list, sctp_nxt_addr) {
1079			if (laddr->ifa->localifa_flags & SCTP_BEING_DELETED) {
1080				SCTPDBG(SCTP_DEBUG_PCB1, "ifa being deleted\n");
1081				continue;
1082			}
1083			if (sctp_is_addr_restricted(stcb, laddr->ifa) &&
1084			    (!sctp_is_addr_pending(stcb, laddr->ifa))) {
1085				/* We allow pending addresses, where we
1086				 * have sent an asconf-add to be considered
1087				 * valid.
1088				 */
1089				continue;
1090			}
1091			if (laddr->ifa->address.sa.sa_family != to->sa_family) {
1092				continue;
1093			}
1094			switch (to->sa_family) {
1095#ifdef INET
1096			case AF_INET:
1097			{
1098				struct sockaddr_in *sin, *rsin;
1099
1100				sin = &laddr->ifa->address.sin;
1101				rsin = (struct sockaddr_in *)to;
1102				if (sin->sin_addr.s_addr == rsin->sin_addr.s_addr) {
1103					SCTP_IPI_ADDR_RUNLOCK();
1104					return (1);
1105				}
1106				break;
1107			}
1108#endif
1109#ifdef INET6
1110			case AF_INET6:
1111			{
1112				struct sockaddr_in6 *sin6, *rsin6;
1113
1114				sin6 = &laddr->ifa->address.sin6;
1115				rsin6 = (struct sockaddr_in6 *)to;
1116				if (SCTP6_ARE_ADDR_EQUAL(sin6, rsin6)) {
1117					SCTP_IPI_ADDR_RUNLOCK();
1118					return (1);
1119				}
1120				break;
1121			}
1122
1123#endif
1124#if defined(__Userspace__)
1125			case AF_CONN:
1126			{
1127				struct sockaddr_conn *sconn, *rsconn;
1128
1129				sconn = &laddr->ifa->address.sconn;
1130				rsconn = (struct sockaddr_conn *)to;
1131				if (sconn->sconn_addr == rsconn->sconn_addr) {
1132					SCTP_IPI_ADDR_RUNLOCK();
1133					return (1);
1134				}
1135				break;
1136			}
1137#endif
1138			default:
1139				/* TSNH */
1140				break;
1141			}
1142
1143		}
1144	}
1145	SCTP_IPI_ADDR_RUNLOCK();
1146	return (0);
1147}
1148
1149
1150static struct sctp_tcb *
1151sctp_tcb_special_locate(struct sctp_inpcb **inp_p, struct sockaddr *from,
1152    struct sockaddr *to, struct sctp_nets **netp, uint32_t vrf_id)
1153{
1154	/**** ASSUMES THE CALLER holds the INP_INFO_RLOCK */
1155	/*
1156	 * If we support the TCP model, then we must now dig through to see
1157	 * if we can find our endpoint in the list of tcp ep's.
1158	 */
1159	uint16_t lport, rport;
1160	struct sctppcbhead *ephead;
1161	struct sctp_inpcb *inp;
1162	struct sctp_laddr *laddr;
1163	struct sctp_tcb *stcb;
1164	struct sctp_nets *net;
1165#ifdef SCTP_MVRF
1166	int fnd, i;
1167#endif
1168
1169	if ((to == NULL) || (from == NULL)) {
1170		return (NULL);
1171	}
1172
1173	switch (to->sa_family) {
1174#ifdef INET
1175	case AF_INET:
1176		if (from->sa_family == AF_INET) {
1177			lport = ((struct sockaddr_in *)to)->sin_port;
1178			rport = ((struct sockaddr_in *)from)->sin_port;
1179		} else {
1180			return (NULL);
1181		}
1182		break;
1183#endif
1184#ifdef INET6
1185	case AF_INET6:
1186		if (from->sa_family == AF_INET6) {
1187			lport = ((struct sockaddr_in6 *)to)->sin6_port;
1188			rport = ((struct sockaddr_in6 *)from)->sin6_port;
1189		} else {
1190			return (NULL);
1191		}
1192		break;
1193#endif
1194#if defined(__Userspace__)
1195	case AF_CONN:
1196		if (from->sa_family == AF_CONN) {
1197			lport = ((struct sockaddr_conn *)to)->sconn_port;
1198			rport = ((struct sockaddr_conn *)from)->sconn_port;
1199		} else {
1200			return (NULL);
1201		}
1202		break;
1203#endif
1204	default:
1205		return (NULL);
1206	}
1207	ephead = &SCTP_BASE_INFO(sctp_tcpephash)[SCTP_PCBHASH_ALLADDR((lport | rport), SCTP_BASE_INFO(hashtcpmark))];
1208	/*
1209	 * Ok now for each of the guys in this bucket we must look and see:
1210	 * - Does the remote port match. - Does there single association's
1211	 * addresses match this address (to). If so we update p_ep to point
1212	 * to this ep and return the tcb from it.
1213	 */
1214	LIST_FOREACH(inp, ephead, sctp_hash) {
1215		SCTP_INP_RLOCK(inp);
1216		if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) {
1217			SCTP_INP_RUNLOCK(inp);
1218			continue;
1219		}
1220		if (lport != inp->sctp_lport) {
1221			SCTP_INP_RUNLOCK(inp);
1222			continue;
1223		}
1224#if defined(__FreeBSD__)
1225		switch (to->sa_family) {
1226#ifdef INET
1227		case AF_INET:
1228		{
1229			struct sockaddr_in *sin;
1230
1231			sin = (struct sockaddr_in *)to;
1232			if (prison_check_ip4(inp->ip_inp.inp.inp_cred,
1233			                     &sin->sin_addr) != 0) {
1234				SCTP_INP_RUNLOCK(inp);
1235				continue;
1236			}
1237			break;
1238		}
1239#endif
1240#ifdef INET6
1241		case AF_INET6:
1242		{
1243			struct sockaddr_in6 *sin6;
1244
1245			sin6 = (struct sockaddr_in6 *)to;
1246			if (prison_check_ip6(inp->ip_inp.inp.inp_cred,
1247			                     &sin6->sin6_addr) != 0) {
1248				SCTP_INP_RUNLOCK(inp);
1249				continue;
1250			}
1251			break;
1252		}
1253#endif
1254		default:
1255			SCTP_INP_RUNLOCK(inp);
1256			continue;
1257		}
1258#endif
1259#ifdef SCTP_MVRF
1260		fnd = 0;
1261		for (i = 0; i < inp->num_vrfs; i++) {
1262			if (inp->m_vrf_ids[i] == vrf_id) {
1263				fnd = 1;
1264				break;
1265			}
1266		}
1267		if (fnd == 0) {
1268			SCTP_INP_RUNLOCK(inp);
1269			continue;
1270		}
1271#else
1272		if (inp->def_vrf_id != vrf_id) {
1273			SCTP_INP_RUNLOCK(inp);
1274			continue;
1275		}
1276#endif
1277		/* check to see if the ep has one of the addresses */
1278		if ((inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) == 0) {
1279			/* We are NOT bound all, so look further */
1280			int match = 0;
1281
1282			LIST_FOREACH(laddr, &inp->sctp_addr_list, sctp_nxt_addr) {
1283
1284				if (laddr->ifa == NULL) {
1285					SCTPDBG(SCTP_DEBUG_PCB1, "%s: NULL ifa\n", __FUNCTION__);
1286					continue;
1287				}
1288				if (laddr->ifa->localifa_flags & SCTP_BEING_DELETED) {
1289					SCTPDBG(SCTP_DEBUG_PCB1, "ifa being deleted\n");
1290					continue;
1291				}
1292				if (laddr->ifa->address.sa.sa_family ==
1293				    to->sa_family) {
1294					/* see if it matches */
1295#ifdef INET
1296					if (from->sa_family == AF_INET) {
1297						struct sockaddr_in *intf_addr, *sin;
1298
1299						intf_addr = &laddr->ifa->address.sin;
1300						sin = (struct sockaddr_in *)to;
1301						if (sin->sin_addr.s_addr ==
1302						    intf_addr->sin_addr.s_addr) {
1303							match = 1;
1304							break;
1305						}
1306					}
1307#endif
1308#ifdef INET6
1309					if (from->sa_family == AF_INET6) {
1310						struct sockaddr_in6 *intf_addr6;
1311						struct sockaddr_in6 *sin6;
1312
1313						sin6 = (struct sockaddr_in6 *)
1314						    to;
1315						intf_addr6 = &laddr->ifa->address.sin6;
1316
1317						if (SCTP6_ARE_ADDR_EQUAL(sin6,
1318						    intf_addr6)) {
1319							match = 1;
1320							break;
1321						}
1322					}
1323#endif
1324#if defined(__Userspace__)
1325					if (from->sa_family == AF_CONN) {
1326						struct sockaddr_conn *intf_addr, *sconn;
1327
1328						intf_addr = &laddr->ifa->address.sconn;
1329						sconn = (struct sockaddr_conn *)to;
1330						if (sconn->sconn_addr ==
1331						    intf_addr->sconn_addr) {
1332							match = 1;
1333							break;
1334						}
1335					}
1336#endif
1337				}
1338			}
1339			if (match == 0) {
1340				/* This endpoint does not have this address */
1341				SCTP_INP_RUNLOCK(inp);
1342				continue;
1343			}
1344		}
1345		/*
1346		 * Ok if we hit here the ep has the address, does it hold
1347		 * the tcb?
1348		 */
1349		/* XXX: Why don't we TAILQ_FOREACH through sctp_asoc_list? */
1350		stcb = LIST_FIRST(&inp->sctp_asoc_list);
1351		if (stcb == NULL) {
1352			SCTP_INP_RUNLOCK(inp);
1353			continue;
1354		}
1355		SCTP_TCB_LOCK(stcb);
1356		if (!sctp_does_stcb_own_this_addr(stcb, to)) {
1357			SCTP_TCB_UNLOCK(stcb);
1358			SCTP_INP_RUNLOCK(inp);
1359			continue;
1360		}
1361		if (stcb->rport != rport) {
1362			/* remote port does not match. */
1363			SCTP_TCB_UNLOCK(stcb);
1364			SCTP_INP_RUNLOCK(inp);
1365			continue;
1366		}
1367		if (stcb->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) {
1368			SCTP_TCB_UNLOCK(stcb);
1369			SCTP_INP_RUNLOCK(inp);
1370			continue;
1371		}
1372		if (!sctp_does_stcb_own_this_addr(stcb, to)) {
1373			SCTP_TCB_UNLOCK(stcb);
1374			SCTP_INP_RUNLOCK(inp);
1375			continue;
1376		}
1377		/* Does this TCB have a matching address? */
1378		TAILQ_FOREACH(net, &stcb->asoc.nets, sctp_next) {
1379
1380			if (net->ro._l_addr.sa.sa_family != from->sa_family) {
1381				/* not the same family, can't be a match */
1382				continue;
1383			}
1384			switch (from->sa_family) {
1385#ifdef INET
1386			case AF_INET:
1387			{
1388				struct sockaddr_in *sin, *rsin;
1389
1390				sin = (struct sockaddr_in *)&net->ro._l_addr;
1391				rsin = (struct sockaddr_in *)from;
1392				if (sin->sin_addr.s_addr ==
1393				    rsin->sin_addr.s_addr) {
1394					/* found it */
1395					if (netp != NULL) {
1396						*netp = net;
1397					}
1398					/* Update the endpoint pointer */
1399					*inp_p = inp;
1400					SCTP_INP_RUNLOCK(inp);
1401					return (stcb);
1402				}
1403				break;
1404			}
1405#endif
1406#ifdef INET6
1407			case AF_INET6:
1408			{
1409				struct sockaddr_in6 *sin6, *rsin6;
1410
1411				sin6 = (struct sockaddr_in6 *)&net->ro._l_addr;
1412				rsin6 = (struct sockaddr_in6 *)from;
1413				if (SCTP6_ARE_ADDR_EQUAL(sin6,
1414				    rsin6)) {
1415					/* found it */
1416					if (netp != NULL) {
1417						*netp = net;
1418					}
1419					/* Update the endpoint pointer */
1420					*inp_p = inp;
1421					SCTP_INP_RUNLOCK(inp);
1422					return (stcb);
1423				}
1424				break;
1425			}
1426#endif
1427#if defined(__Userspace__)
1428			case AF_CONN:
1429			{
1430				struct sockaddr_conn *sconn, *rsconn;
1431
1432				sconn = (struct sockaddr_conn *)&net->ro._l_addr;
1433				rsconn = (struct sockaddr_conn *)from;
1434				if (sconn->sconn_addr == rsconn->sconn_addr) {
1435					/* found it */
1436					if (netp != NULL) {
1437						*netp = net;
1438					}
1439					/* Update the endpoint pointer */
1440					*inp_p = inp;
1441					SCTP_INP_RUNLOCK(inp);
1442					return (stcb);
1443				}
1444				break;
1445			}
1446#endif
1447			default:
1448				/* TSNH */
1449				break;
1450			}
1451		}
1452		SCTP_TCB_UNLOCK(stcb);
1453		SCTP_INP_RUNLOCK(inp);
1454	}
1455	return (NULL);
1456}
1457
1458
1459/*
1460 * rules for use
1461 *
1462 * 1) If I return a NULL you must decrement any INP ref cnt. 2) If I find an
1463 * stcb, both will be locked (locked_tcb and stcb) but decrement will be done
1464 * (if locked == NULL). 3) Decrement happens on return ONLY if locked ==
1465 * NULL.
1466 */
1467
1468struct sctp_tcb *
1469sctp_findassociation_ep_addr(struct sctp_inpcb **inp_p, struct sockaddr *remote,
1470    struct sctp_nets **netp, struct sockaddr *local, struct sctp_tcb *locked_tcb)
1471{
1472	struct sctpasochead *head;
1473	struct sctp_inpcb *inp;
1474	struct sctp_tcb *stcb = NULL;
1475	struct sctp_nets *net;
1476	uint16_t rport;
1477
1478	inp = *inp_p;
1479	switch (remote->sa_family) {
1480#ifdef INET
1481	case AF_INET:
1482		rport = (((struct sockaddr_in *)remote)->sin_port);
1483		break;
1484#endif
1485#ifdef INET6
1486	case AF_INET6:
1487		rport = (((struct sockaddr_in6 *)remote)->sin6_port);
1488		break;
1489#endif
1490#if defined(__Userspace__)
1491	case AF_CONN:
1492		rport = (((struct sockaddr_in6 *)remote)->sin6_port);
1493		break;
1494#endif
1495	default:
1496		return (NULL);
1497	}
1498	if (locked_tcb) {
1499		/*
1500		 * UN-lock so we can do proper locking here this occurs when
1501		 * called from load_addresses_from_init.
1502		 */
1503		atomic_add_int(&locked_tcb->asoc.refcnt, 1);
1504		SCTP_TCB_UNLOCK(locked_tcb);
1505	}
1506	SCTP_INP_INFO_RLOCK();
1507	if ((inp->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE) ||
1508	    (inp->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL)) {
1509		/*-
1510		 * Now either this guy is our listener or it's the
1511		 * connector. If it is the one that issued the connect, then
1512		 * it's only chance is to be the first TCB in the list. If
1513		 * it is the acceptor, then do the special_lookup to hash
1514		 * and find the real inp.
1515		 */
1516		if ((inp->sctp_socket) && (inp->sctp_socket->so_qlimit)) {
1517			/* to is peer addr, from is my addr */
1518#ifndef SCTP_MVRF
1519			stcb = sctp_tcb_special_locate(inp_p, remote, local,
1520			    netp, inp->def_vrf_id);
1521			if ((stcb != NULL) && (locked_tcb == NULL)) {
1522				/* we have a locked tcb, lower refcount */
1523				SCTP_INP_DECR_REF(inp);
1524			}
1525			if ((locked_tcb != NULL) && (locked_tcb != stcb)) {
1526				SCTP_INP_RLOCK(locked_tcb->sctp_ep);
1527				SCTP_TCB_LOCK(locked_tcb);
1528				atomic_subtract_int(&locked_tcb->asoc.refcnt, 1);
1529				SCTP_INP_RUNLOCK(locked_tcb->sctp_ep);
1530			}
1531#else
1532			/*-
1533			 * MVRF is tricky, we must look in every VRF
1534			 * the endpoint has.
1535			 */
1536			int i;
1537
1538			for (i = 0; i < inp->num_vrfs; i++) {
1539				stcb = sctp_tcb_special_locate(inp_p, remote, local,
1540				                               netp, inp->m_vrf_ids[i]);
1541				if ((stcb != NULL) && (locked_tcb == NULL)) {
1542					/* we have a locked tcb, lower refcount */
1543					SCTP_INP_DECR_REF(inp);
1544					break;
1545				}
1546				if ((locked_tcb != NULL) && (locked_tcb != stcb)) {
1547					SCTP_INP_RLOCK(locked_tcb->sctp_ep);
1548					SCTP_TCB_LOCK(locked_tcb);
1549					atomic_subtract_int(&locked_tcb->asoc.refcnt, 1);
1550					SCTP_INP_RUNLOCK(locked_tcb->sctp_ep);
1551					break;
1552				}
1553			}
1554#endif
1555			SCTP_INP_INFO_RUNLOCK();
1556			return (stcb);
1557		} else {
1558			SCTP_INP_WLOCK(inp);
1559			if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) {
1560				goto null_return;
1561			}
1562			stcb = LIST_FIRST(&inp->sctp_asoc_list);
1563			if (stcb == NULL) {
1564				goto null_return;
1565			}
1566			SCTP_TCB_LOCK(stcb);
1567
1568			if (stcb->rport != rport) {
1569				/* remote port does not match. */
1570				SCTP_TCB_UNLOCK(stcb);
1571				goto null_return;
1572			}
1573			if (stcb->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) {
1574				SCTP_TCB_UNLOCK(stcb);
1575				goto null_return;
1576			}
1577			if (local && !sctp_does_stcb_own_this_addr(stcb, local)) {
1578				SCTP_TCB_UNLOCK(stcb);
1579				goto null_return;
1580			}
1581			/* now look at the list of remote addresses */
1582			TAILQ_FOREACH(net, &stcb->asoc.nets, sctp_next) {
1583#ifdef INVARIANTS
1584				if (net == (TAILQ_NEXT(net, sctp_next))) {
1585					panic("Corrupt net list");
1586				}
1587#endif
1588				if (net->ro._l_addr.sa.sa_family !=
1589				    remote->sa_family) {
1590					/* not the same family */
1591					continue;
1592				}
1593				switch (remote->sa_family) {
1594#ifdef INET
1595				case AF_INET:
1596				{
1597					struct sockaddr_in *sin, *rsin;
1598
1599					sin = (struct sockaddr_in *)
1600					    &net->ro._l_addr;
1601					rsin = (struct sockaddr_in *)remote;
1602					if (sin->sin_addr.s_addr ==
1603					    rsin->sin_addr.s_addr) {
1604						/* found it */
1605						if (netp != NULL) {
1606							*netp = net;
1607						}
1608						if (locked_tcb == NULL) {
1609							SCTP_INP_DECR_REF(inp);
1610						} else if (locked_tcb != stcb) {
1611							SCTP_TCB_LOCK(locked_tcb);
1612						}
1613						if (locked_tcb) {
1614							atomic_subtract_int(&locked_tcb->asoc.refcnt, 1);
1615						}
1616
1617						SCTP_INP_WUNLOCK(inp);
1618						SCTP_INP_INFO_RUNLOCK();
1619						return (stcb);
1620					}
1621					break;
1622				}
1623#endif
1624#ifdef INET6
1625				case AF_INET6:
1626				{
1627					struct sockaddr_in6 *sin6, *rsin6;
1628
1629					sin6 = (struct sockaddr_in6 *)&net->ro._l_addr;
1630					rsin6 = (struct sockaddr_in6 *)remote;
1631					if (SCTP6_ARE_ADDR_EQUAL(sin6,
1632					    rsin6)) {
1633						/* found it */
1634						if (netp != NULL) {
1635							*netp = net;
1636						}
1637						if (locked_tcb == NULL) {
1638							SCTP_INP_DECR_REF(inp);
1639						} else if (locked_tcb != stcb) {
1640							SCTP_TCB_LOCK(locked_tcb);
1641						}
1642						if (locked_tcb) {
1643							atomic_subtract_int(&locked_tcb->asoc.refcnt, 1);
1644						}
1645						SCTP_INP_WUNLOCK(inp);
1646						SCTP_INP_INFO_RUNLOCK();
1647						return (stcb);
1648					}
1649					break;
1650				}
1651#endif
1652#if defined(__Userspace__)
1653				case AF_CONN:
1654				{
1655					struct sockaddr_conn *sconn, *rsconn;
1656
1657					sconn = (struct sockaddr_conn *)&net->ro._l_addr;
1658					rsconn = (struct sockaddr_conn *)remote;
1659					if (sconn->sconn_addr == rsconn->sconn_addr) {
1660						/* found it */
1661						if (netp != NULL) {
1662							*netp = net;
1663						}
1664						if (locked_tcb == NULL) {
1665							SCTP_INP_DECR_REF(inp);
1666						} else if (locked_tcb != stcb) {
1667							SCTP_TCB_LOCK(locked_tcb);
1668						}
1669						if (locked_tcb) {
1670							atomic_subtract_int(&locked_tcb->asoc.refcnt, 1);
1671						}
1672						SCTP_INP_WUNLOCK(inp);
1673						SCTP_INP_INFO_RUNLOCK();
1674						return (stcb);
1675					}
1676					break;
1677				}
1678#endif
1679				default:
1680					/* TSNH */
1681					break;
1682				}
1683			}
1684			SCTP_TCB_UNLOCK(stcb);
1685		}
1686	} else {
1687		SCTP_INP_WLOCK(inp);
1688		if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) {
1689			goto null_return;
1690		}
1691		head = &inp->sctp_tcbhash[SCTP_PCBHASH_ALLADDR(rport,
1692		    inp->sctp_hashmark)];
1693		if (head == NULL) {
1694			goto null_return;
1695		}
1696		LIST_FOREACH(stcb, head, sctp_tcbhash) {
1697			if (stcb->rport != rport) {
1698				/* remote port does not match */
1699				continue;
1700			}
1701			SCTP_TCB_LOCK(stcb);
1702			if (stcb->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) {
1703				SCTP_TCB_UNLOCK(stcb);
1704				continue;
1705			}
1706			if (local && !sctp_does_stcb_own_this_addr(stcb, local)) {
1707				SCTP_TCB_UNLOCK(stcb);
1708				continue;
1709			}
1710			/* now look at the list of remote addresses */
1711			TAILQ_FOREACH(net, &stcb->asoc.nets, sctp_next) {
1712#ifdef INVARIANTS
1713				if (net == (TAILQ_NEXT(net, sctp_next))) {
1714					panic("Corrupt net list");
1715				}
1716#endif
1717				if (net->ro._l_addr.sa.sa_family !=
1718				    remote->sa_family) {
1719					/* not the same family */
1720					continue;
1721				}
1722				switch (remote->sa_family) {
1723#ifdef INET
1724				case AF_INET:
1725				{
1726					struct sockaddr_in *sin, *rsin;
1727
1728					sin = (struct sockaddr_in *)
1729					    &net->ro._l_addr;
1730					rsin = (struct sockaddr_in *)remote;
1731					if (sin->sin_addr.s_addr ==
1732					    rsin->sin_addr.s_addr) {
1733						/* found it */
1734						if (netp != NULL) {
1735							*netp = net;
1736						}
1737						if (locked_tcb == NULL) {
1738							SCTP_INP_DECR_REF(inp);
1739						} else if (locked_tcb != stcb) {
1740							SCTP_TCB_LOCK(locked_tcb);
1741						}
1742						if (locked_tcb) {
1743							atomic_subtract_int(&locked_tcb->asoc.refcnt, 1);
1744						}
1745						SCTP_INP_WUNLOCK(inp);
1746						SCTP_INP_INFO_RUNLOCK();
1747						return (stcb);
1748					}
1749					break;
1750				}
1751#endif
1752#ifdef INET6
1753				case AF_INET6:
1754				{
1755					struct sockaddr_in6 *sin6, *rsin6;
1756
1757					sin6 = (struct sockaddr_in6 *)
1758					    &net->ro._l_addr;
1759					rsin6 = (struct sockaddr_in6 *)remote;
1760					if (SCTP6_ARE_ADDR_EQUAL(sin6,
1761					    rsin6)) {
1762						/* found it */
1763						if (netp != NULL) {
1764							*netp = net;
1765						}
1766						if (locked_tcb == NULL) {
1767							SCTP_INP_DECR_REF(inp);
1768						} else if (locked_tcb != stcb) {
1769							SCTP_TCB_LOCK(locked_tcb);
1770						}
1771						if (locked_tcb) {
1772							atomic_subtract_int(&locked_tcb->asoc.refcnt, 1);
1773						}
1774						SCTP_INP_WUNLOCK(inp);
1775						SCTP_INP_INFO_RUNLOCK();
1776						return (stcb);
1777					}
1778					break;
1779				}
1780#endif
1781#if defined(__Userspace__)
1782				case AF_CONN:
1783				{
1784					struct sockaddr_conn *sconn, *rsconn;
1785
1786					sconn = (struct sockaddr_conn *)&net->ro._l_addr;
1787					rsconn = (struct sockaddr_conn *)remote;
1788					if (sconn->sconn_addr == rsconn->sconn_addr) {
1789						/* found it */
1790						if (netp != NULL) {
1791							*netp = net;
1792						}
1793						if (locked_tcb == NULL) {
1794							SCTP_INP_DECR_REF(inp);
1795						} else if (locked_tcb != stcb) {
1796							SCTP_TCB_LOCK(locked_tcb);
1797						}
1798						if (locked_tcb) {
1799							atomic_subtract_int(&locked_tcb->asoc.refcnt, 1);
1800						}
1801						SCTP_INP_WUNLOCK(inp);
1802						SCTP_INP_INFO_RUNLOCK();
1803						return (stcb);
1804					}
1805					break;
1806				}
1807#endif
1808				default:
1809					/* TSNH */
1810					break;
1811				}
1812			}
1813			SCTP_TCB_UNLOCK(stcb);
1814		}
1815	}
1816null_return:
1817	/* clean up for returning null */
1818	if (locked_tcb) {
1819		SCTP_TCB_LOCK(locked_tcb);
1820		atomic_subtract_int(&locked_tcb->asoc.refcnt, 1);
1821	}
1822	SCTP_INP_WUNLOCK(inp);
1823	SCTP_INP_INFO_RUNLOCK();
1824	/* not found */
1825	return (NULL);
1826}
1827
1828
1829/*
1830 * Find an association for a specific endpoint using the association id given
1831 * out in the COMM_UP notification
1832 */
1833struct sctp_tcb *
1834sctp_findasoc_ep_asocid_locked(struct sctp_inpcb *inp, sctp_assoc_t asoc_id, int want_lock)
1835{
1836	/*
1837	 * Use my the assoc_id to find a endpoint
1838	 */
1839	struct sctpasochead *head;
1840	struct sctp_tcb *stcb;
1841	uint32_t id;
1842
1843	if (inp == NULL) {
1844		SCTP_PRINTF("TSNH ep_associd\n");
1845		return (NULL);
1846	}
1847	if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) {
1848		SCTP_PRINTF("TSNH ep_associd0\n");
1849		return (NULL);
1850	}
1851	id = (uint32_t)asoc_id;
1852	head = &inp->sctp_asocidhash[SCTP_PCBHASH_ASOC(id, inp->hashasocidmark)];
1853	if (head == NULL) {
1854		/* invalid id TSNH */
1855		SCTP_PRINTF("TSNH ep_associd1\n");
1856		return (NULL);
1857	}
1858	LIST_FOREACH(stcb, head, sctp_tcbasocidhash) {
1859		if (stcb->asoc.assoc_id == id) {
1860			if (inp != stcb->sctp_ep) {
1861				/*
1862				 * some other guy has the same id active (id
1863				 * collision ??).
1864				 */
1865				SCTP_PRINTF("TSNH ep_associd2\n");
1866				continue;
1867			}
1868			if (stcb->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) {
1869				continue;
1870			}
1871			if (want_lock) {
1872				SCTP_TCB_LOCK(stcb);
1873			}
1874			return (stcb);
1875		}
1876	}
1877	return (NULL);
1878}
1879
1880
1881struct sctp_tcb *
1882sctp_findassociation_ep_asocid(struct sctp_inpcb *inp, sctp_assoc_t asoc_id, int want_lock)
1883{
1884	struct sctp_tcb *stcb;
1885
1886	SCTP_INP_RLOCK(inp);
1887	stcb = sctp_findasoc_ep_asocid_locked(inp, asoc_id, want_lock);
1888	SCTP_INP_RUNLOCK(inp);
1889	return (stcb);
1890}
1891
1892
1893/*
1894 * Endpoint probe expects that the INP_INFO is locked.
1895 */
1896static struct sctp_inpcb *
1897sctp_endpoint_probe(struct sockaddr *nam, struct sctppcbhead *head,
1898		    uint16_t lport, uint32_t vrf_id)
1899{
1900	struct sctp_inpcb *inp;
1901	struct sctp_laddr *laddr;
1902#ifdef INET
1903	struct sockaddr_in *sin;
1904#endif
1905#ifdef INET6
1906	struct sockaddr_in6 *sin6;
1907	struct sockaddr_in6 *intf_addr6;
1908#endif
1909#if defined(__Userspace__)
1910	struct sockaddr_conn *sconn;
1911#endif
1912#ifdef SCTP_MVRF
1913	int i;
1914#endif
1915	int  fnd;
1916
1917#ifdef INET
1918	sin = NULL;
1919#endif
1920#ifdef INET6
1921	sin6 = NULL;
1922#endif
1923#if defined(__Userspace__)
1924	sconn = NULL;
1925#endif
1926	switch (nam->sa_family) {
1927#ifdef INET
1928	case AF_INET:
1929		sin = (struct sockaddr_in *)nam;
1930		break;
1931#endif
1932#ifdef INET6
1933	case AF_INET6:
1934		sin6 = (struct sockaddr_in6 *)nam;
1935		break;
1936#endif
1937#if defined(__Userspace__)
1938	case AF_CONN:
1939		sconn = (struct sockaddr_conn *)nam;
1940		break;
1941#endif
1942	default:
1943		/* unsupported family */
1944		return (NULL);
1945	}
1946
1947	if (head == NULL)
1948		return (NULL);
1949
1950	LIST_FOREACH(inp, head, sctp_hash) {
1951		SCTP_INP_RLOCK(inp);
1952		if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) {
1953			SCTP_INP_RUNLOCK(inp);
1954			continue;
1955		}
1956		if ((inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) &&
1957		    (inp->sctp_lport == lport)) {
1958			/* got it */
1959			switch (nam->sa_family) {
1960#ifdef INET
1961			case AF_INET:
1962				if ((inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) &&
1963				    SCTP_IPV6_V6ONLY(inp)) {
1964					/* IPv4 on a IPv6 socket with ONLY IPv6 set */
1965					SCTP_INP_RUNLOCK(inp);
1966					continue;
1967				}
1968#if defined(__FreeBSD__)
1969				if (prison_check_ip4(inp->ip_inp.inp.inp_cred,
1970				                     &sin->sin_addr) != 0) {
1971					SCTP_INP_RUNLOCK(inp);
1972					continue;
1973				}
1974#endif
1975				break;
1976#endif
1977#ifdef INET6
1978			case AF_INET6:
1979				/* A V6 address and the endpoint is NOT bound V6 */
1980				if ((inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) == 0) {
1981					SCTP_INP_RUNLOCK(inp);
1982					continue;
1983				}
1984#if defined(__FreeBSD__)
1985				if (prison_check_ip6(inp->ip_inp.inp.inp_cred,
1986				                     &sin6->sin6_addr) != 0) {
1987					SCTP_INP_RUNLOCK(inp);
1988					continue;
1989				}
1990#endif
1991				break;
1992#endif
1993			default:
1994				break;
1995			}
1996			/* does a VRF id match? */
1997			fnd = 0;
1998#ifdef SCTP_MVRF
1999			for (i = 0; i < inp->num_vrfs; i++) {
2000				if (inp->m_vrf_ids[i] == vrf_id) {
2001					fnd = 1;
2002					break;
2003				}
2004			}
2005#else
2006			if (inp->def_vrf_id == vrf_id)
2007				fnd = 1;
2008#endif
2009
2010			SCTP_INP_RUNLOCK(inp);
2011			if (!fnd)
2012				continue;
2013			return (inp);
2014		}
2015		SCTP_INP_RUNLOCK(inp);
2016	}
2017	switch (nam->sa_family) {
2018#ifdef INET
2019	case AF_INET:
2020		if (sin->sin_addr.s_addr == INADDR_ANY) {
2021			/* Can't hunt for one that has no address specified */
2022			return (NULL);
2023		}
2024		break;
2025#endif
2026#ifdef INET6
2027	case AF_INET6:
2028		if (IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr)) {
2029			/* Can't hunt for one that has no address specified */
2030			return (NULL);
2031		}
2032		break;
2033#endif
2034#if defined(__Userspace__)
2035	case AF_CONN:
2036		if (sconn->sconn_addr == NULL) {
2037			return (NULL);
2038		}
2039		break;
2040#endif
2041	default:
2042		break;
2043	}
2044	/*
2045	 * ok, not bound to all so see if we can find a EP bound to this
2046	 * address.
2047	 */
2048	LIST_FOREACH(inp, head, sctp_hash) {
2049		SCTP_INP_RLOCK(inp);
2050		if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) {
2051			SCTP_INP_RUNLOCK(inp);
2052			continue;
2053		}
2054		if ((inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL)) {
2055			SCTP_INP_RUNLOCK(inp);
2056			continue;
2057		}
2058		/*
2059		 * Ok this could be a likely candidate, look at all of its
2060		 * addresses
2061		 */
2062		if (inp->sctp_lport != lport) {
2063			SCTP_INP_RUNLOCK(inp);
2064			continue;
2065		}
2066		/* does a VRF id match? */
2067		fnd = 0;
2068#ifdef SCTP_MVRF
2069		for (i = 0; i < inp->num_vrfs; i++) {
2070			if (inp->m_vrf_ids[i] == vrf_id) {
2071				fnd = 1;
2072				break;
2073			}
2074		}
2075#else
2076		if (inp->def_vrf_id == vrf_id)
2077			fnd = 1;
2078
2079#endif
2080		if (!fnd) {
2081			SCTP_INP_RUNLOCK(inp);
2082			continue;
2083		}
2084		LIST_FOREACH(laddr, &inp->sctp_addr_list, sctp_nxt_addr) {
2085			if (laddr->ifa == NULL) {
2086				SCTPDBG(SCTP_DEBUG_PCB1, "%s: NULL ifa\n",
2087					__FUNCTION__);
2088				continue;
2089			}
2090			SCTPDBG(SCTP_DEBUG_PCB1, "Ok laddr->ifa:%p is possible, ",
2091				(void *)laddr->ifa);
2092			if (laddr->ifa->localifa_flags & SCTP_BEING_DELETED) {
2093				SCTPDBG(SCTP_DEBUG_PCB1, "Huh IFA being deleted\n");
2094				continue;
2095			}
2096			if (laddr->ifa->address.sa.sa_family == nam->sa_family) {
2097				/* possible, see if it matches */
2098				switch (nam->sa_family) {
2099#ifdef INET
2100				case AF_INET:
2101#if defined(__APPLE__)
2102					if (sin == NULL) {
2103						/* TSNH */
2104						break;
2105					}
2106#endif
2107					if (sin->sin_addr.s_addr ==
2108					    laddr->ifa->address.sin.sin_addr.s_addr) {
2109						SCTP_INP_RUNLOCK(inp);
2110						return (inp);
2111					}
2112					break;
2113#endif
2114#ifdef INET6
2115				case AF_INET6:
2116					intf_addr6 = &laddr->ifa->address.sin6;
2117					if (SCTP6_ARE_ADDR_EQUAL(sin6,
2118					    intf_addr6)) {
2119						SCTP_INP_RUNLOCK(inp);
2120						return (inp);
2121					}
2122					break;
2123#endif
2124#if defined(__Userspace__)
2125				case AF_CONN:
2126					if (sconn->sconn_addr == laddr->ifa->address.sconn.sconn_addr) {
2127						SCTP_INP_RUNLOCK(inp);
2128						return (inp);
2129					}
2130					break;
2131#endif
2132				}
2133			}
2134		}
2135		SCTP_INP_RUNLOCK(inp);
2136	}
2137	return (NULL);
2138}
2139
2140
2141static struct sctp_inpcb *
2142sctp_isport_inuse(struct sctp_inpcb *inp, uint16_t lport, uint32_t vrf_id)
2143{
2144	struct sctppcbhead *head;
2145	struct sctp_inpcb *t_inp;
2146#ifdef SCTP_MVRF
2147	int i;
2148#endif
2149	int fnd;
2150
2151	head = &SCTP_BASE_INFO(sctp_ephash)[SCTP_PCBHASH_ALLADDR(lport,
2152	    SCTP_BASE_INFO(hashmark))];
2153	LIST_FOREACH(t_inp, head, sctp_hash) {
2154		if (t_inp->sctp_lport != lport) {
2155			continue;
2156		}
2157		/* is it in the VRF in question */
2158		fnd = 0;
2159#ifdef SCTP_MVRF
2160		for (i = 0; i < inp->num_vrfs; i++) {
2161			if (t_inp->m_vrf_ids[i] == vrf_id) {
2162				fnd = 1;
2163				break;
2164			}
2165		}
2166#else
2167		if (t_inp->def_vrf_id == vrf_id)
2168			fnd = 1;
2169#endif
2170		if (!fnd)
2171			continue;
2172
2173		/* This one is in use. */
2174		/* check the v6/v4 binding issue */
2175		if ((t_inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) &&
2176		    SCTP_IPV6_V6ONLY(t_inp)) {
2177			if (inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) {
2178				/* collision in V6 space */
2179				return (t_inp);
2180			} else {
2181				/* inp is BOUND_V4 no conflict */
2182				continue;
2183			}
2184		} else if (t_inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) {
2185			/* t_inp is bound v4 and v6, conflict always */
2186			return (t_inp);
2187		} else {
2188			/* t_inp is bound only V4 */
2189			if ((inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) &&
2190			    SCTP_IPV6_V6ONLY(inp)) {
2191				/* no conflict */
2192				continue;
2193			}
2194			/* else fall through to conflict */
2195		}
2196		return (t_inp);
2197	}
2198	return (NULL);
2199}
2200
2201
2202int
2203sctp_swap_inpcb_for_listen(struct sctp_inpcb *inp)
2204{
2205	/* For 1-2-1 with port reuse */
2206	struct sctppcbhead *head;
2207	struct sctp_inpcb *tinp;
2208
2209	if (sctp_is_feature_off(inp, SCTP_PCB_FLAGS_PORTREUSE)) {
2210		/* only works with port reuse on */
2211		return (-1);
2212	}
2213	if ((inp->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL) == 0) {
2214		return (0);
2215	}
2216	SCTP_INP_RUNLOCK(inp);
2217	head = &SCTP_BASE_INFO(sctp_ephash)[SCTP_PCBHASH_ALLADDR(inp->sctp_lport,
2218	                                    SCTP_BASE_INFO(hashmark))];
2219	/* Kick out all non-listeners to the TCP hash */
2220	LIST_FOREACH(tinp, head, sctp_hash) {
2221		if (tinp->sctp_lport != inp->sctp_lport) {
2222			continue;
2223		}
2224		if (tinp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) {
2225			continue;
2226		}
2227		if (tinp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE) {
2228			continue;
2229		}
2230		if (tinp->sctp_socket->so_qlimit) {
2231			continue;
2232		}
2233		SCTP_INP_WLOCK(tinp);
2234		LIST_REMOVE(tinp, sctp_hash);
2235		head = &SCTP_BASE_INFO(sctp_tcpephash)[SCTP_PCBHASH_ALLADDR(tinp->sctp_lport, SCTP_BASE_INFO(hashtcpmark))];
2236		tinp->sctp_flags |= SCTP_PCB_FLAGS_IN_TCPPOOL;
2237		LIST_INSERT_HEAD(head, tinp, sctp_hash);
2238		SCTP_INP_WUNLOCK(tinp);
2239	}
2240	SCTP_INP_WLOCK(inp);
2241	/* Pull from where he was */
2242	LIST_REMOVE(inp, sctp_hash);
2243	inp->sctp_flags &= ~SCTP_PCB_FLAGS_IN_TCPPOOL;
2244	head = &SCTP_BASE_INFO(sctp_ephash)[SCTP_PCBHASH_ALLADDR(inp->sctp_lport, SCTP_BASE_INFO(hashmark))];
2245	LIST_INSERT_HEAD(head, inp, sctp_hash);
2246	SCTP_INP_WUNLOCK(inp);
2247	SCTP_INP_RLOCK(inp);
2248	return (0);
2249}
2250
2251
2252struct sctp_inpcb *
2253sctp_pcb_findep(struct sockaddr *nam, int find_tcp_pool, int have_lock,
2254		uint32_t vrf_id)
2255{
2256	/*
2257	 * First we check the hash table to see if someone has this port
2258	 * bound with just the port.
2259	 */
2260	struct sctp_inpcb *inp;
2261	struct sctppcbhead *head;
2262	int lport;
2263	unsigned int i;
2264#ifdef INET
2265	struct sockaddr_in *sin;
2266#endif
2267#ifdef INET6
2268	struct sockaddr_in6 *sin6;
2269#endif
2270#if defined(__Userspace__)
2271	struct sockaddr_conn *sconn;
2272#endif
2273
2274	switch (nam->sa_family) {
2275#ifdef INET
2276	case AF_INET:
2277		sin = (struct sockaddr_in *)nam;
2278		lport = sin->sin_port;
2279		break;
2280#endif
2281#ifdef INET6
2282	case AF_INET6:
2283		sin6 = (struct sockaddr_in6 *)nam;
2284		lport = sin6->sin6_port;
2285		break;
2286#endif
2287#if defined(__Userspace__)
2288	case AF_CONN:
2289		sconn = (struct sockaddr_conn *)nam;
2290		lport = sconn->sconn_port;
2291		break;
2292#endif
2293	default:
2294		return (NULL);
2295	}
2296	/*
2297	 * I could cheat here and just cast to one of the types but we will
2298	 * do it right. It also provides the check against an Unsupported
2299	 * type too.
2300	 */
2301	/* Find the head of the ALLADDR chain */
2302	if (have_lock == 0) {
2303		SCTP_INP_INFO_RLOCK();
2304	}
2305	head = &SCTP_BASE_INFO(sctp_ephash)[SCTP_PCBHASH_ALLADDR(lport,
2306	    SCTP_BASE_INFO(hashmark))];
2307	inp = sctp_endpoint_probe(nam, head, lport, vrf_id);
2308
2309	/*
2310	 * If the TCP model exists it could be that the main listening
2311	 * endpoint is gone but there still exists a connected socket for this
2312	 * guy. If so we can return the first one that we find. This may NOT
2313	 * be the correct one so the caller should be wary on the returned INP.
2314	 * Currently the only caller that sets find_tcp_pool is in bindx where
2315	 * we are verifying that a user CAN bind the address. He either
2316	 * has bound it already, or someone else has, or its open to bind,
2317	 * so this is good enough.
2318	 */
2319	if (inp == NULL && find_tcp_pool) {
2320		for (i = 0; i < SCTP_BASE_INFO(hashtcpmark) + 1; i++) {
2321			head = &SCTP_BASE_INFO(sctp_tcpephash)[i];
2322			inp = sctp_endpoint_probe(nam, head, lport, vrf_id);
2323			if (inp) {
2324				break;
2325			}
2326		}
2327	}
2328	if (inp) {
2329		SCTP_INP_INCR_REF(inp);
2330	}
2331	if (have_lock == 0) {
2332		SCTP_INP_INFO_RUNLOCK();
2333	}
2334	return (inp);
2335}
2336
2337
2338/*
2339 * Find an association for an endpoint with the pointer to whom you want to
2340 * send to and the endpoint pointer. The address can be IPv4 or IPv6. We may
2341 * need to change the *to to some other struct like a mbuf...
2342 */
2343struct sctp_tcb *
2344sctp_findassociation_addr_sa(struct sockaddr *from, struct sockaddr *to,
2345    struct sctp_inpcb **inp_p, struct sctp_nets **netp, int find_tcp_pool,
2346    uint32_t vrf_id)
2347{
2348	struct sctp_inpcb *inp = NULL;
2349	struct sctp_tcb *stcb;
2350
2351	SCTP_INP_INFO_RLOCK();
2352	if (find_tcp_pool) {
2353		if (inp_p != NULL) {
2354			stcb = sctp_tcb_special_locate(inp_p, from, to, netp,
2355			                               vrf_id);
2356		} else {
2357			stcb = sctp_tcb_special_locate(&inp, from, to, netp,
2358			                               vrf_id);
2359		}
2360		if (stcb != NULL) {
2361			SCTP_INP_INFO_RUNLOCK();
2362			return (stcb);
2363		}
2364	}
2365	inp = sctp_pcb_findep(to, 0, 1, vrf_id);
2366	if (inp_p != NULL) {
2367		*inp_p = inp;
2368	}
2369	SCTP_INP_INFO_RUNLOCK();
2370	if (inp == NULL) {
2371		return (NULL);
2372	}
2373	/*
2374	 * ok, we have an endpoint, now lets find the assoc for it (if any)
2375	 * we now place the source address or from in the to of the find
2376	 * endpoint call. Since in reality this chain is used from the
2377	 * inbound packet side.
2378	 */
2379	if (inp_p != NULL) {
2380		stcb = sctp_findassociation_ep_addr(inp_p, from, netp, to,
2381		                                    NULL);
2382	} else {
2383		stcb = sctp_findassociation_ep_addr(&inp, from, netp, to,
2384		                                    NULL);
2385	}
2386	return (stcb);
2387}
2388
2389
2390/*
2391 * This routine will grub through the mbuf that is a INIT or INIT-ACK and
2392 * find all addresses that the sender has specified in any address list. Each
2393 * address will be used to lookup the TCB and see if one exits.
2394 */
2395static struct sctp_tcb *
2396sctp_findassociation_special_addr(struct mbuf *m, int offset,
2397    struct sctphdr *sh, struct sctp_inpcb **inp_p, struct sctp_nets **netp,
2398    struct sockaddr *dst)
2399{
2400	struct sctp_paramhdr *phdr, parm_buf;
2401#if defined(INET) || defined(INET6)
2402	struct sctp_tcb *stcb;
2403	uint16_t ptype;
2404#endif
2405	uint16_t plen;
2406#ifdef INET
2407	struct sockaddr_in sin4;
2408#endif
2409#ifdef INET6
2410	struct sockaddr_in6 sin6;
2411#endif
2412
2413#ifdef INET
2414	memset(&sin4, 0, sizeof(sin4));
2415#ifdef HAVE_SIN_LEN
2416	sin4.sin_len = sizeof(sin4);
2417#endif
2418	sin4.sin_family = AF_INET;
2419	sin4.sin_port = sh->src_port;
2420#endif
2421#ifdef INET6
2422	memset(&sin6, 0, sizeof(sin6));
2423#ifdef HAVE_SIN6_LEN
2424	sin6.sin6_len = sizeof(sin6);
2425#endif
2426	sin6.sin6_family = AF_INET6;
2427	sin6.sin6_port = sh->src_port;
2428#endif
2429
2430	offset += sizeof(struct sctp_init_chunk);
2431
2432	phdr = sctp_get_next_param(m, offset, &parm_buf, sizeof(parm_buf));
2433	while (phdr != NULL) {
2434		/* now we must see if we want the parameter */
2435#if defined(INET) || defined(INET6)
2436		ptype = ntohs(phdr->param_type);
2437#endif
2438		plen = ntohs(phdr->param_length);
2439		if (plen == 0) {
2440			break;
2441		}
2442#ifdef INET
2443		if (ptype == SCTP_IPV4_ADDRESS &&
2444		    plen == sizeof(struct sctp_ipv4addr_param)) {
2445			/* Get the rest of the address */
2446			struct sctp_ipv4addr_param ip4_parm, *p4;
2447
2448			phdr = sctp_get_next_param(m, offset,
2449			    (struct sctp_paramhdr *)&ip4_parm, min(plen, sizeof(ip4_parm)));
2450			if (phdr == NULL) {
2451				return (NULL);
2452			}
2453			p4 = (struct sctp_ipv4addr_param *)phdr;
2454			memcpy(&sin4.sin_addr, &p4->addr, sizeof(p4->addr));
2455			/* look it up */
2456			stcb = sctp_findassociation_ep_addr(inp_p,
2457			    (struct sockaddr *)&sin4, netp, dst, NULL);
2458			if (stcb != NULL) {
2459				return (stcb);
2460			}
2461		}
2462#endif
2463#ifdef INET6
2464		if (ptype == SCTP_IPV6_ADDRESS &&
2465		    plen == sizeof(struct sctp_ipv6addr_param)) {
2466			/* Get the rest of the address */
2467			struct sctp_ipv6addr_param ip6_parm, *p6;
2468
2469			phdr = sctp_get_next_param(m, offset,
2470			    (struct sctp_paramhdr *)&ip6_parm, min(plen,sizeof(ip6_parm)));
2471			if (phdr == NULL) {
2472				return (NULL);
2473			}
2474			p6 = (struct sctp_ipv6addr_param *)phdr;
2475			memcpy(&sin6.sin6_addr, &p6->addr, sizeof(p6->addr));
2476			/* look it up */
2477			stcb = sctp_findassociation_ep_addr(inp_p,
2478			    (struct sockaddr *)&sin6, netp, dst, NULL);
2479			if (stcb != NULL) {
2480				return (stcb);
2481			}
2482		}
2483#endif
2484		offset += SCTP_SIZE32(plen);
2485		phdr = sctp_get_next_param(m, offset, &parm_buf,
2486					   sizeof(parm_buf));
2487	}
2488	return (NULL);
2489}
2490
2491static struct sctp_tcb *
2492sctp_findassoc_by_vtag(struct sockaddr *from, struct sockaddr *to, uint32_t vtag,
2493		       struct sctp_inpcb **inp_p, struct sctp_nets **netp, uint16_t rport,
2494		       uint16_t lport, int skip_src_check, uint32_t vrf_id, uint32_t remote_tag)
2495{
2496	/*
2497	 * Use my vtag to hash. If we find it we then verify the source addr
2498	 * is in the assoc. If all goes well we save a bit on rec of a
2499	 * packet.
2500	 */
2501	struct sctpasochead *head;
2502	struct sctp_nets *net;
2503	struct sctp_tcb *stcb;
2504#ifdef SCTP_MVRF
2505	unsigned int i;
2506#endif
2507
2508	SCTP_INP_INFO_RLOCK();
2509	head = &SCTP_BASE_INFO(sctp_asochash)[SCTP_PCBHASH_ASOC(vtag,
2510	    SCTP_BASE_INFO(hashasocmark))];
2511	if (head == NULL) {
2512		/* invalid vtag */
2513		SCTP_INP_INFO_RUNLOCK();
2514		return (NULL);
2515	}
2516	LIST_FOREACH(stcb, head, sctp_asocs) {
2517		SCTP_INP_RLOCK(stcb->sctp_ep);
2518		if (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) {
2519			SCTP_INP_RUNLOCK(stcb->sctp_ep);
2520			continue;
2521		}
2522#ifdef SCTP_MVRF
2523		for (i = 0; i < stcb->sctp_ep->num_vrfs; i++) {
2524			if (stcb->sctp_ep->m_vrf_ids[i] == vrf_id) {
2525				break;
2526			}
2527		}
2528		if (i == stcb->sctp_ep->num_vrfs) {
2529			SCTP_INP_RUNLOCK(inp);
2530			continue;
2531		}
2532#else
2533		if (stcb->sctp_ep->def_vrf_id != vrf_id) {
2534			SCTP_INP_RUNLOCK(stcb->sctp_ep);
2535			continue;
2536		}
2537#endif
2538		SCTP_TCB_LOCK(stcb);
2539		SCTP_INP_RUNLOCK(stcb->sctp_ep);
2540		if (stcb->asoc.my_vtag == vtag) {
2541			/* candidate */
2542			if (stcb->rport != rport) {
2543				SCTP_TCB_UNLOCK(stcb);
2544				continue;
2545			}
2546			if (stcb->sctp_ep->sctp_lport != lport) {
2547				SCTP_TCB_UNLOCK(stcb);
2548				continue;
2549			}
2550			if (stcb->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) {
2551				SCTP_TCB_UNLOCK(stcb);
2552				continue;
2553			}
2554			/* RRS:Need toaddr check here */
2555			if (sctp_does_stcb_own_this_addr(stcb, to) == 0) {
2556			        /* Endpoint does not own this address */
2557				SCTP_TCB_UNLOCK(stcb);
2558				continue;
2559			}
2560			if (remote_tag) {
2561				/* If we have both vtags that's all we match on */
2562				if (stcb->asoc.peer_vtag == remote_tag) {
2563					/* If both tags match we consider it conclusive
2564					 * and check NO source/destination addresses
2565					 */
2566					goto conclusive;
2567				}
2568			}
2569			if (skip_src_check) {
2570			conclusive:
2571			        if (from) {
2572					*netp = sctp_findnet(stcb, from);
2573				} else {
2574					*netp = NULL;	/* unknown */
2575				}
2576				if (inp_p)
2577					*inp_p = stcb->sctp_ep;
2578				SCTP_INP_INFO_RUNLOCK();
2579				return (stcb);
2580			}
2581			net = sctp_findnet(stcb, from);
2582			if (net) {
2583				/* yep its him. */
2584				*netp = net;
2585				SCTP_STAT_INCR(sctps_vtagexpress);
2586				*inp_p = stcb->sctp_ep;
2587				SCTP_INP_INFO_RUNLOCK();
2588				return (stcb);
2589			} else {
2590				/*
2591				 * not him, this should only happen in rare
2592				 * cases so I peg it.
2593				 */
2594				SCTP_STAT_INCR(sctps_vtagbogus);
2595			}
2596		}
2597		SCTP_TCB_UNLOCK(stcb);
2598	}
2599	SCTP_INP_INFO_RUNLOCK();
2600	return (NULL);
2601}
2602
2603
2604/*
2605 * Find an association with the pointer to the inbound IP packet. This can be
2606 * a IPv4 or IPv6 packet.
2607 */
2608struct sctp_tcb *
2609sctp_findassociation_addr(struct mbuf *m, int offset,
2610    struct sockaddr *src, struct sockaddr *dst,
2611    struct sctphdr *sh, struct sctp_chunkhdr *ch,
2612    struct sctp_inpcb **inp_p, struct sctp_nets **netp, uint32_t vrf_id)
2613{
2614	int find_tcp_pool;
2615	struct sctp_tcb *stcb;
2616	struct sctp_inpcb *inp;
2617
2618	if (sh->v_tag) {
2619		/* we only go down this path if vtag is non-zero */
2620		stcb = sctp_findassoc_by_vtag(src, dst, ntohl(sh->v_tag),
2621		                              inp_p, netp, sh->src_port, sh->dest_port, 0, vrf_id, 0);
2622		if (stcb) {
2623			return (stcb);
2624		}
2625	}
2626
2627	find_tcp_pool = 0;
2628	if ((ch->chunk_type != SCTP_INITIATION) &&
2629	    (ch->chunk_type != SCTP_INITIATION_ACK) &&
2630	    (ch->chunk_type != SCTP_COOKIE_ACK) &&
2631	    (ch->chunk_type != SCTP_COOKIE_ECHO)) {
2632		/* Other chunk types go to the tcp pool. */
2633		find_tcp_pool = 1;
2634	}
2635	if (inp_p) {
2636		stcb = sctp_findassociation_addr_sa(src, dst, inp_p, netp,
2637		                                    find_tcp_pool, vrf_id);
2638		inp = *inp_p;
2639	} else {
2640		stcb = sctp_findassociation_addr_sa(src, dst, &inp, netp,
2641		                                    find_tcp_pool, vrf_id);
2642	}
2643	SCTPDBG(SCTP_DEBUG_PCB1, "stcb:%p inp:%p\n", (void *)stcb, (void *)inp);
2644	if (stcb == NULL && inp) {
2645		/* Found a EP but not this address */
2646		if ((ch->chunk_type == SCTP_INITIATION) ||
2647		    (ch->chunk_type == SCTP_INITIATION_ACK)) {
2648			/*-
2649			 * special hook, we do NOT return linp or an
2650			 * association that is linked to an existing
2651			 * association that is under the TCP pool (i.e. no
2652			 * listener exists). The endpoint finding routine
2653			 * will always find a listener before examining the
2654			 * TCP pool.
2655			 */
2656			if (inp->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL) {
2657				if (inp_p) {
2658					*inp_p = NULL;
2659				}
2660				return (NULL);
2661			}
2662			stcb = sctp_findassociation_special_addr(m,
2663			    offset, sh, &inp, netp, dst);
2664			if (inp_p != NULL) {
2665				*inp_p = inp;
2666			}
2667		}
2668	}
2669	SCTPDBG(SCTP_DEBUG_PCB1, "stcb is %p\n", (void *)stcb);
2670	return (stcb);
2671}
2672
2673/*
2674 * lookup an association by an ASCONF lookup address.
2675 * if the lookup address is 0.0.0.0 or ::0, use the vtag to do the lookup
2676 */
2677struct sctp_tcb *
2678sctp_findassociation_ep_asconf(struct mbuf *m, int offset,
2679			       struct sockaddr *dst, struct sctphdr *sh,
2680                               struct sctp_inpcb **inp_p, struct sctp_nets **netp, uint32_t vrf_id)
2681{
2682	struct sctp_tcb *stcb;
2683	union sctp_sockstore remote_store;
2684	struct sctp_paramhdr parm_buf, *phdr;
2685	int ptype;
2686	int zero_address = 0;
2687#ifdef INET
2688	struct sockaddr_in *sin;
2689#endif
2690#ifdef INET6
2691	struct sockaddr_in6 *sin6;
2692#endif
2693
2694	memset(&remote_store, 0, sizeof(remote_store));
2695	phdr = sctp_get_next_param(m, offset + sizeof(struct sctp_asconf_chunk),
2696				   &parm_buf, sizeof(struct sctp_paramhdr));
2697	if (phdr == NULL) {
2698		SCTPDBG(SCTP_DEBUG_INPUT3, "%s: failed to get asconf lookup addr\n",
2699			__FUNCTION__);
2700		return NULL;
2701	}
2702	ptype = (int)((uint32_t) ntohs(phdr->param_type));
2703	/* get the correlation address */
2704	switch (ptype) {
2705#ifdef INET6
2706	case SCTP_IPV6_ADDRESS:
2707	{
2708		/* ipv6 address param */
2709		struct sctp_ipv6addr_param *p6, p6_buf;
2710
2711		if (ntohs(phdr->param_length) != sizeof(struct sctp_ipv6addr_param)) {
2712			return NULL;
2713		}
2714		p6 = (struct sctp_ipv6addr_param *)sctp_get_next_param(m,
2715								       offset + sizeof(struct sctp_asconf_chunk),
2716								       &p6_buf.ph, sizeof(*p6));
2717		if (p6 == NULL) {
2718			SCTPDBG(SCTP_DEBUG_INPUT3, "%s: failed to get asconf v6 lookup addr\n",
2719				__FUNCTION__);
2720			return (NULL);
2721		}
2722		sin6 = &remote_store.sin6;
2723		sin6->sin6_family = AF_INET6;
2724#ifdef HAVE_SIN6_LEN
2725		sin6->sin6_len = sizeof(*sin6);
2726#endif
2727		sin6->sin6_port = sh->src_port;
2728		memcpy(&sin6->sin6_addr, &p6->addr, sizeof(struct in6_addr));
2729		if (IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr))
2730			zero_address = 1;
2731		break;
2732	}
2733#endif
2734#ifdef INET
2735	case SCTP_IPV4_ADDRESS:
2736	{
2737		/* ipv4 address param */
2738		struct sctp_ipv4addr_param *p4, p4_buf;
2739
2740		if (ntohs(phdr->param_length) != sizeof(struct sctp_ipv4addr_param)) {
2741			return NULL;
2742		}
2743		p4 = (struct sctp_ipv4addr_param *)sctp_get_next_param(m,
2744								       offset + sizeof(struct sctp_asconf_chunk),
2745								       &p4_buf.ph, sizeof(*p4));
2746		if (p4 == NULL) {
2747			SCTPDBG(SCTP_DEBUG_INPUT3, "%s: failed to get asconf v4 lookup addr\n",
2748				__FUNCTION__);
2749			return (NULL);
2750		}
2751		sin = &remote_store.sin;
2752		sin->sin_family = AF_INET;
2753#ifdef HAVE_SIN_LEN
2754		sin->sin_len = sizeof(*sin);
2755#endif
2756		sin->sin_port = sh->src_port;
2757		memcpy(&sin->sin_addr, &p4->addr, sizeof(struct in_addr));
2758		if (sin->sin_addr.s_addr == INADDR_ANY)
2759			zero_address = 1;
2760		break;
2761	}
2762#endif
2763	default:
2764		/* invalid address param type */
2765		return NULL;
2766	}
2767
2768	if (zero_address) {
2769	        stcb = sctp_findassoc_by_vtag(NULL, dst, ntohl(sh->v_tag), inp_p,
2770					      netp, sh->src_port, sh->dest_port, 1, vrf_id, 0);
2771		if (stcb != NULL) {
2772			SCTP_INP_DECR_REF(*inp_p);
2773		}
2774	} else {
2775		stcb = sctp_findassociation_ep_addr(inp_p,
2776		    &remote_store.sa, netp,
2777		    dst, NULL);
2778	}
2779	return (stcb);
2780}
2781
2782
2783/*
2784 * allocate a sctp_inpcb and setup a temporary binding to a port/all
2785 * addresses. This way if we don't get a bind we by default pick a ephemeral
2786 * port with all addresses bound.
2787 */
2788int
2789sctp_inpcb_alloc(struct socket *so, uint32_t vrf_id)
2790{
2791	/*
2792	 * we get called when a new endpoint starts up. We need to allocate
2793	 * the sctp_inpcb structure from the zone and init it. Mark it as
2794	 * unbound and find a port that we can use as an ephemeral with
2795	 * INADDR_ANY. If the user binds later no problem we can then add in
2796	 * the specific addresses. And setup the default parameters for the
2797	 * EP.
2798	 */
2799	int i, error;
2800	struct sctp_inpcb *inp;
2801	struct sctp_pcb *m;
2802	struct timeval time;
2803	sctp_sharedkey_t *null_key;
2804
2805	error = 0;
2806
2807	SCTP_INP_INFO_WLOCK();
2808	inp = SCTP_ZONE_GET(SCTP_BASE_INFO(ipi_zone_ep), struct sctp_inpcb);
2809	if (inp == NULL) {
2810		SCTP_PRINTF("Out of SCTP-INPCB structures - no resources\n");
2811		SCTP_INP_INFO_WUNLOCK();
2812		SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, ENOBUFS);
2813		return (ENOBUFS);
2814	}
2815	/* zap it */
2816	bzero(inp, sizeof(*inp));
2817
2818	/* bump generations */
2819#if defined(__APPLE__)
2820	inp->ip_inp.inp.inp_state = INPCB_STATE_INUSE;
2821#endif
2822	/* setup socket pointers */
2823	inp->sctp_socket = so;
2824	inp->ip_inp.inp.inp_socket = so;
2825#if defined(__FreeBSD__)
2826	inp->ip_inp.inp.inp_cred = crhold(so->so_cred);
2827#endif
2828#ifdef INET6
2829#if !defined(__Userspace__) && !defined(__Windows__)
2830	if (INP_SOCKAF(so) == AF_INET6) {
2831		if (MODULE_GLOBAL(ip6_auto_flowlabel)) {
2832			inp->ip_inp.inp.inp_flags |= IN6P_AUTOFLOWLABEL;
2833		}
2834		if (MODULE_GLOBAL(ip6_v6only)) {
2835			inp->ip_inp.inp.inp_flags |= IN6P_IPV6_V6ONLY;
2836		}
2837	}
2838#endif
2839#endif
2840	inp->sctp_associd_counter = 1;
2841	inp->partial_delivery_point = SCTP_SB_LIMIT_RCV(so) >> SCTP_PARTIAL_DELIVERY_SHIFT;
2842	inp->sctp_frag_point = SCTP_DEFAULT_MAXSEGMENT;
2843	inp->sctp_cmt_on_off = SCTP_BASE_SYSCTL(sctp_cmt_on_off);
2844	inp->ecn_supported = (uint8_t)SCTP_BASE_SYSCTL(sctp_ecn_enable);
2845	inp->prsctp_supported = (uint8_t)SCTP_BASE_SYSCTL(sctp_pr_enable);
2846	inp->auth_supported = (uint8_t)SCTP_BASE_SYSCTL(sctp_auth_enable);
2847	inp->asconf_supported = (uint8_t)SCTP_BASE_SYSCTL(sctp_asconf_enable);
2848	inp->reconfig_supported = (uint8_t)SCTP_BASE_SYSCTL(sctp_reconfig_enable);
2849	inp->nrsack_supported = (uint8_t)SCTP_BASE_SYSCTL(sctp_nrsack_enable);
2850	inp->pktdrop_supported = (uint8_t)SCTP_BASE_SYSCTL(sctp_pktdrop_enable);
2851#if defined(__Userspace__)
2852	inp->ulp_info = NULL;
2853	inp->recv_callback = NULL;
2854	inp->send_callback = NULL;
2855	inp->send_sb_threshold = 0;
2856#endif
2857	/* init the small hash table we use to track asocid <-> tcb */
2858	inp->sctp_asocidhash = SCTP_HASH_INIT(SCTP_STACK_VTAG_HASH_SIZE, &inp->hashasocidmark);
2859	if (inp->sctp_asocidhash == NULL) {
2860#if defined(__FreeBSD__)
2861		crfree(inp->ip_inp.inp.inp_cred);
2862#endif
2863		SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_ep), inp);
2864		SCTP_INP_INFO_WUNLOCK();
2865		return (ENOBUFS);
2866	}
2867#ifdef IPSEC
2868#if !(defined(__APPLE__))
2869	{
2870		struct inpcbpolicy *pcb_sp = NULL;
2871
2872		error = ipsec_init_policy(so, &pcb_sp);
2873		/* Arrange to share the policy */
2874		inp->ip_inp.inp.inp_sp = pcb_sp;
2875		((struct in6pcb *)(&inp->ip_inp.inp))->in6p_sp = pcb_sp;
2876	}
2877#else
2878	/* not sure what to do for openbsd here */
2879	error = 0;
2880#endif
2881	if (error != 0) {
2882#if defined(__FreeBSD__)
2883		crfree(inp->ip_inp.inp.inp_cred);
2884#endif
2885		SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_ep), inp);
2886		SCTP_INP_INFO_WUNLOCK();
2887		return error;
2888	}
2889#endif				/* IPSEC */
2890	SCTP_INCR_EP_COUNT();
2891	inp->ip_inp.inp.inp_ip_ttl = MODULE_GLOBAL(ip_defttl);
2892	SCTP_INP_INFO_WUNLOCK();
2893
2894	so->so_pcb = (caddr_t)inp;
2895
2896#if defined(__FreeBSD__) && __FreeBSD_version < 803000
2897	if ((SCTP_SO_TYPE(so) == SOCK_DGRAM) ||
2898	    (SCTP_SO_TYPE(so) == SOCK_SEQPACKET)) {
2899#else
2900	if (SCTP_SO_TYPE(so) == SOCK_SEQPACKET) {
2901#endif
2902		/* UDP style socket */
2903		inp->sctp_flags = (SCTP_PCB_FLAGS_UDPTYPE |
2904		    SCTP_PCB_FLAGS_UNBOUND);
2905		/* Be sure it is NON-BLOCKING IO for UDP */
2906		/* SCTP_SET_SO_NBIO(so); */
2907	} else if (SCTP_SO_TYPE(so) == SOCK_STREAM) {
2908		/* TCP style socket */
2909		inp->sctp_flags = (SCTP_PCB_FLAGS_TCPTYPE |
2910		    SCTP_PCB_FLAGS_UNBOUND);
2911		/* Be sure we have blocking IO by default */
2912		SCTP_CLEAR_SO_NBIO(so);
2913#if defined(__Panda__)
2914	} else if (SCTP_SO_TYPE(so) == SOCK_FASTSEQPACKET) {
2915		inp->sctp_flags = (SCTP_PCB_FLAGS_UDPTYPE |
2916		    SCTP_PCB_FLAGS_UNBOUND);
2917		sctp_feature_on(inp, SCTP_PCB_FLAGS_ZERO_COPY_ACTIVE);
2918	} else if (SCTP_SO_TYPE(so) == SOCK_FASTSTREAM) {
2919		inp->sctp_flags = (SCTP_PCB_FLAGS_TCPTYPE |
2920		    SCTP_PCB_FLAGS_UNBOUND);
2921		sctp_feature_on(inp, SCTP_PCB_FLAGS_ZERO_COPY_ACTIVE);
2922#endif
2923	} else {
2924		/*
2925		 * unsupported socket type (RAW, etc)- in case we missed it
2926		 * in protosw
2927		 */
2928		SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EOPNOTSUPP);
2929		so->so_pcb = NULL;
2930#if defined(__FreeBSD__)
2931		crfree(inp->ip_inp.inp.inp_cred);
2932#endif
2933		SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_ep), inp);
2934		return (EOPNOTSUPP);
2935	}
2936	if (SCTP_BASE_SYSCTL(sctp_default_frag_interleave) == SCTP_FRAG_LEVEL_1) {
2937		sctp_feature_on(inp, SCTP_PCB_FLAGS_FRAG_INTERLEAVE);
2938		sctp_feature_off(inp, SCTP_PCB_FLAGS_INTERLEAVE_STRMS);
2939	} else if (SCTP_BASE_SYSCTL(sctp_default_frag_interleave) == SCTP_FRAG_LEVEL_2) {
2940		sctp_feature_on(inp, SCTP_PCB_FLAGS_FRAG_INTERLEAVE);
2941		sctp_feature_on(inp, SCTP_PCB_FLAGS_INTERLEAVE_STRMS);
2942	} else if (SCTP_BASE_SYSCTL(sctp_default_frag_interleave) == SCTP_FRAG_LEVEL_0) {
2943		sctp_feature_off(inp, SCTP_PCB_FLAGS_FRAG_INTERLEAVE);
2944		sctp_feature_off(inp, SCTP_PCB_FLAGS_INTERLEAVE_STRMS);
2945	}
2946	inp->sctp_tcbhash = SCTP_HASH_INIT(SCTP_BASE_SYSCTL(sctp_pcbtblsize),
2947					   &inp->sctp_hashmark);
2948	if (inp->sctp_tcbhash == NULL) {
2949		SCTP_PRINTF("Out of SCTP-INPCB->hashinit - no resources\n");
2950		SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, ENOBUFS);
2951		so->so_pcb = NULL;
2952#if defined(__FreeBSD__)
2953		crfree(inp->ip_inp.inp.inp_cred);
2954#endif
2955		SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_ep), inp);
2956		return (ENOBUFS);
2957	}
2958#ifdef SCTP_MVRF
2959	inp->vrf_size = SCTP_DEFAULT_VRF_SIZE;
2960	SCTP_MALLOC(inp->m_vrf_ids, uint32_t *,
2961		    (sizeof(uint32_t) * inp->vrf_size), SCTP_M_MVRF);
2962	if (inp->m_vrf_ids == NULL) {
2963		SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, ENOBUFS);
2964		so->so_pcb = NULL;
2965		SCTP_HASH_FREE(inp->sctp_tcbhash, inp->sctp_hashmark);
2966#if defined(__FreeBSD__)
2967		crfree(inp->ip_inp.inp.inp_cred);
2968#endif
2969		SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_ep), inp);
2970		return (ENOBUFS);
2971	}
2972	inp->m_vrf_ids[0] = vrf_id;
2973	inp->num_vrfs = 1;
2974#endif
2975	inp->def_vrf_id = vrf_id;
2976
2977#if defined(__APPLE__)
2978#if defined(APPLE_LEOPARD) || defined(APPLE_SNOWLEOPARD)
2979	inp->ip_inp.inp.inpcb_mtx = lck_mtx_alloc_init(SCTP_BASE_INFO(sctbinfo).mtx_grp, SCTP_BASE_INFO(sctbinfo).mtx_attr);
2980	if (inp->ip_inp.inp.inpcb_mtx == NULL) {
2981		SCTP_PRINTF("in_pcballoc: can't alloc mutex! so=%p\n", (void *)so);
2982#ifdef SCTP_MVRF
2983		SCTP_FREE(inp->m_vrf_ids, SCTP_M_MVRF);
2984#endif
2985		SCTP_HASH_FREE(inp->sctp_tcbhash, inp->sctp_hashmark);
2986		so->so_pcb = NULL;
2987#if defined(__FreeBSD__)
2988		crfree(inp->ip_inp.inp.inp_cred);
2989#endif
2990		SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_ep), inp);
2991		SCTP_UNLOCK_EXC(SCTP_BASE_INFO(sctbinfo).ipi_lock);
2992		SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, ENOMEM);
2993		return (ENOMEM);
2994	}
2995#elif defined(APPLE_LION) || defined(APPLE_MOUNTAINLION)
2996	lck_mtx_init(&inp->ip_inp.inp.inpcb_mtx, SCTP_BASE_INFO(sctbinfo).mtx_grp, SCTP_BASE_INFO(sctbinfo).mtx_attr);
2997#else
2998	lck_mtx_init(&inp->ip_inp.inp.inpcb_mtx, SCTP_BASE_INFO(sctbinfo).ipi_lock_grp, SCTP_BASE_INFO(sctbinfo).ipi_lock_attr);
2999#endif
3000#endif
3001	SCTP_INP_INFO_WLOCK();
3002	SCTP_INP_LOCK_INIT(inp);
3003#if defined(__FreeBSD__)
3004	INP_LOCK_INIT(&inp->ip_inp.inp, "inp", "sctpinp");
3005#endif
3006	SCTP_INP_READ_INIT(inp);
3007	SCTP_ASOC_CREATE_LOCK_INIT(inp);
3008	/* lock the new ep */
3009	SCTP_INP_WLOCK(inp);
3010
3011	/* add it to the info area */
3012	LIST_INSERT_HEAD(&SCTP_BASE_INFO(listhead), inp, sctp_list);
3013#if defined(__APPLE__)
3014	inp->ip_inp.inp.inp_pcbinfo = &SCTP_BASE_INFO(sctbinfo);
3015#if defined(APPLE_LEOPARD) || defined(APPLE_SNOWLEOPARD) || defined(APPLE_LION) || defined(APPLE_MOUNTAINLION)
3016	LIST_INSERT_HEAD(SCTP_BASE_INFO(sctbinfo).listhead, &inp->ip_inp.inp, inp_list);
3017#else
3018	LIST_INSERT_HEAD(SCTP_BASE_INFO(sctbinfo).ipi_listhead, &inp->ip_inp.inp, inp_list);
3019#endif
3020#endif
3021	SCTP_INP_INFO_WUNLOCK();
3022
3023	TAILQ_INIT(&inp->read_queue);
3024	LIST_INIT(&inp->sctp_addr_list);
3025
3026	LIST_INIT(&inp->sctp_asoc_list);
3027
3028#ifdef SCTP_TRACK_FREED_ASOCS
3029	/* TEMP CODE */
3030	LIST_INIT(&inp->sctp_asoc_free_list);
3031#endif
3032	/* Init the timer structure for signature change */
3033	SCTP_OS_TIMER_INIT(&inp->sctp_ep.signature_change.timer);
3034	inp->sctp_ep.signature_change.type = SCTP_TIMER_TYPE_NEWCOOKIE;
3035
3036	/* now init the actual endpoint default data */
3037	m = &inp->sctp_ep;
3038
3039	/* setup the base timeout information */
3040	m->sctp_timeoutticks[SCTP_TIMER_SEND] = SEC_TO_TICKS(SCTP_SEND_SEC);	/* needed ? */
3041	m->sctp_timeoutticks[SCTP_TIMER_INIT] = SEC_TO_TICKS(SCTP_INIT_SEC);	/* needed ? */
3042	m->sctp_timeoutticks[SCTP_TIMER_RECV] = MSEC_TO_TICKS(SCTP_BASE_SYSCTL(sctp_delayed_sack_time_default));
3043	m->sctp_timeoutticks[SCTP_TIMER_HEARTBEAT] = MSEC_TO_TICKS(SCTP_BASE_SYSCTL(sctp_heartbeat_interval_default));
3044	m->sctp_timeoutticks[SCTP_TIMER_PMTU] = SEC_TO_TICKS(SCTP_BASE_SYSCTL(sctp_pmtu_raise_time_default));
3045	m->sctp_timeoutticks[SCTP_TIMER_MAXSHUTDOWN] = SEC_TO_TICKS(SCTP_BASE_SYSCTL(sctp_shutdown_guard_time_default));
3046	m->sctp_timeoutticks[SCTP_TIMER_SIGNATURE] = SEC_TO_TICKS(SCTP_BASE_SYSCTL(sctp_secret_lifetime_default));
3047	/* all max/min max are in ms */
3048	m->sctp_maxrto = SCTP_BASE_SYSCTL(sctp_rto_max_default);
3049	m->sctp_minrto = SCTP_BASE_SYSCTL(sctp_rto_min_default);
3050	m->initial_rto = SCTP_BASE_SYSCTL(sctp_rto_initial_default);
3051	m->initial_init_rto_max = SCTP_BASE_SYSCTL(sctp_init_rto_max_default);
3052	m->sctp_sack_freq = SCTP_BASE_SYSCTL(sctp_sack_freq_default);
3053	m->max_init_times = SCTP_BASE_SYSCTL(sctp_init_rtx_max_default);
3054	m->max_send_times = SCTP_BASE_SYSCTL(sctp_assoc_rtx_max_default);
3055	m->def_net_failure = SCTP_BASE_SYSCTL(sctp_path_rtx_max_default);
3056	m->def_net_pf_threshold = SCTP_BASE_SYSCTL(sctp_path_pf_threshold);
3057	m->sctp_sws_sender = SCTP_SWS_SENDER_DEF;
3058	m->sctp_sws_receiver = SCTP_SWS_RECEIVER_DEF;
3059	m->max_burst = SCTP_BASE_SYSCTL(sctp_max_burst_default);
3060	m->fr_max_burst = SCTP_BASE_SYSCTL(sctp_fr_max_burst_default);
3061
3062	m->sctp_default_cc_module = SCTP_BASE_SYSCTL(sctp_default_cc_module);
3063	m->sctp_default_ss_module = SCTP_BASE_SYSCTL(sctp_default_ss_module);
3064	m->max_open_streams_intome = SCTP_BASE_SYSCTL(sctp_nr_incoming_streams_default);
3065	/* number of streams to pre-open on a association */
3066	m->pre_open_stream_count = SCTP_BASE_SYSCTL(sctp_nr_outgoing_streams_default);
3067
3068	/* Add adaptation cookie */
3069	m->adaptation_layer_indicator = 0;
3070	m->adaptation_layer_indicator_provided = 0;
3071
3072	/* seed random number generator */
3073	m->random_counter = 1;
3074	m->store_at = SCTP_SIGNATURE_SIZE;
3075	SCTP_READ_RANDOM(m->random_numbers, sizeof(m->random_numbers));
3076	sctp_fill_random_store(m);
3077
3078	/* Minimum cookie size */
3079	m->size_of_a_cookie = (sizeof(struct sctp_init_msg) * 2) +
3080	    sizeof(struct sctp_state_cookie);
3081	m->size_of_a_cookie += SCTP_SIGNATURE_SIZE;
3082
3083	/* Setup the initial secret */
3084	(void)SCTP_GETTIME_TIMEVAL(&time);
3085	m->time_of_secret_change = time.tv_sec;
3086
3087	for (i = 0; i < SCTP_NUMBER_OF_SECRETS; i++) {
3088		m->secret_key[0][i] = sctp_select_initial_TSN(m);
3089	}
3090	sctp_timer_start(SCTP_TIMER_TYPE_NEWCOOKIE, inp, NULL, NULL);
3091
3092	/* How long is a cookie good for ? */
3093	m->def_cookie_life = MSEC_TO_TICKS(SCTP_BASE_SYSCTL(sctp_valid_cookie_life_default));
3094	/*
3095	 * Initialize authentication parameters
3096	 */
3097	m->local_hmacs = sctp_default_supported_hmaclist();
3098	m->local_auth_chunks = sctp_alloc_chunklist();
3099	if (inp->asconf_supported) {
3100		sctp_auth_add_chunk(SCTP_ASCONF, m->local_auth_chunks);
3101		sctp_auth_add_chunk(SCTP_ASCONF_ACK, m->local_auth_chunks);
3102	}
3103	m->default_dscp = 0;
3104#ifdef INET6
3105	m->default_flowlabel = 0;
3106#endif
3107	m->port = 0; /* encapsulation disabled by default */
3108	LIST_INIT(&m->shared_keys);
3109	/* add default NULL key as key id 0 */
3110	null_key = sctp_alloc_sharedkey();
3111	sctp_insert_sharedkey(&m->shared_keys, null_key);
3112	SCTP_INP_WUNLOCK(inp);
3113#ifdef SCTP_LOG_CLOSING
3114	sctp_log_closing(inp, NULL, 12);
3115#endif
3116	return (error);
3117}
3118
3119
3120void
3121sctp_move_pcb_and_assoc(struct sctp_inpcb *old_inp, struct sctp_inpcb *new_inp,
3122    struct sctp_tcb *stcb)
3123{
3124	struct sctp_nets *net;
3125	uint16_t lport, rport;
3126	struct sctppcbhead *head;
3127	struct sctp_laddr *laddr, *oladdr;
3128
3129	atomic_add_int(&stcb->asoc.refcnt, 1);
3130	SCTP_TCB_UNLOCK(stcb);
3131	SCTP_INP_INFO_WLOCK();
3132	SCTP_INP_WLOCK(old_inp);
3133	SCTP_INP_WLOCK(new_inp);
3134	SCTP_TCB_LOCK(stcb);
3135	atomic_subtract_int(&stcb->asoc.refcnt, 1);
3136
3137	new_inp->sctp_ep.time_of_secret_change =
3138	    old_inp->sctp_ep.time_of_secret_change;
3139	memcpy(new_inp->sctp_ep.secret_key, old_inp->sctp_ep.secret_key,
3140	    sizeof(old_inp->sctp_ep.secret_key));
3141	new_inp->sctp_ep.current_secret_number =
3142	    old_inp->sctp_ep.current_secret_number;
3143	new_inp->sctp_ep.last_secret_number =
3144	    old_inp->sctp_ep.last_secret_number;
3145	new_inp->sctp_ep.size_of_a_cookie = old_inp->sctp_ep.size_of_a_cookie;
3146
3147	/* make it so new data pours into the new socket */
3148	stcb->sctp_socket = new_inp->sctp_socket;
3149	stcb->sctp_ep = new_inp;
3150
3151	/* Copy the port across */
3152	lport = new_inp->sctp_lport = old_inp->sctp_lport;
3153	rport = stcb->rport;
3154	/* Pull the tcb from the old association */
3155	LIST_REMOVE(stcb, sctp_tcbhash);
3156	LIST_REMOVE(stcb, sctp_tcblist);
3157	if (stcb->asoc.in_asocid_hash) {
3158		LIST_REMOVE(stcb, sctp_tcbasocidhash);
3159	}
3160	/* Now insert the new_inp into the TCP connected hash */
3161	head = &SCTP_BASE_INFO(sctp_tcpephash)[SCTP_PCBHASH_ALLADDR((lport | rport), SCTP_BASE_INFO(hashtcpmark))];
3162
3163	LIST_INSERT_HEAD(head, new_inp, sctp_hash);
3164	/* Its safe to access */
3165	new_inp->sctp_flags &= ~SCTP_PCB_FLAGS_UNBOUND;
3166
3167	/* Now move the tcb into the endpoint list */
3168	LIST_INSERT_HEAD(&new_inp->sctp_asoc_list, stcb, sctp_tcblist);
3169	/*
3170	 * Question, do we even need to worry about the ep-hash since we
3171	 * only have one connection? Probably not :> so lets get rid of it
3172	 * and not suck up any kernel memory in that.
3173	 */
3174	if (stcb->asoc.in_asocid_hash) {
3175		struct sctpasochead *lhd;
3176		lhd = &new_inp->sctp_asocidhash[SCTP_PCBHASH_ASOC(stcb->asoc.assoc_id,
3177			new_inp->hashasocidmark)];
3178		LIST_INSERT_HEAD(lhd, stcb, sctp_tcbasocidhash);
3179	}
3180	/* Ok. Let's restart timer. */
3181	TAILQ_FOREACH(net, &stcb->asoc.nets, sctp_next) {
3182		sctp_timer_start(SCTP_TIMER_TYPE_PATHMTURAISE, new_inp,
3183		    stcb, net);
3184	}
3185
3186	SCTP_INP_INFO_WUNLOCK();
3187	if (new_inp->sctp_tcbhash != NULL) {
3188		SCTP_HASH_FREE(new_inp->sctp_tcbhash, new_inp->sctp_hashmark);
3189		new_inp->sctp_tcbhash = NULL;
3190	}
3191	if ((new_inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) == 0) {
3192		/* Subset bound, so copy in the laddr list from the old_inp */
3193		LIST_FOREACH(oladdr, &old_inp->sctp_addr_list, sctp_nxt_addr) {
3194			laddr = SCTP_ZONE_GET(SCTP_BASE_INFO(ipi_zone_laddr), struct sctp_laddr);
3195			if (laddr == NULL) {
3196				/*
3197				 * Gak, what can we do? This assoc is really
3198				 * HOSED. We probably should send an abort
3199				 * here.
3200				 */
3201				SCTPDBG(SCTP_DEBUG_PCB1, "Association hosed in TCP model, out of laddr memory\n");
3202				continue;
3203			}
3204			SCTP_INCR_LADDR_COUNT();
3205			bzero(laddr, sizeof(*laddr));
3206			(void)SCTP_GETTIME_TIMEVAL(&laddr->start_time);
3207			laddr->ifa = oladdr->ifa;
3208			atomic_add_int(&laddr->ifa->refcount, 1);
3209			LIST_INSERT_HEAD(&new_inp->sctp_addr_list, laddr,
3210			    sctp_nxt_addr);
3211			new_inp->laddr_count++;
3212			if (oladdr == stcb->asoc.last_used_address) {
3213				stcb->asoc.last_used_address = laddr;
3214			}
3215		}
3216	}
3217	/* Now any running timers need to be adjusted
3218	 * since we really don't care if they are running
3219	 * or not just blast in the new_inp into all of
3220	 * them.
3221	 */
3222
3223	stcb->asoc.dack_timer.ep = (void *)new_inp;
3224	stcb->asoc.asconf_timer.ep = (void *)new_inp;
3225	stcb->asoc.strreset_timer.ep = (void *)new_inp;
3226	stcb->asoc.shut_guard_timer.ep = (void *)new_inp;
3227	stcb->asoc.autoclose_timer.ep = (void *)new_inp;
3228	stcb->asoc.delayed_event_timer.ep = (void *)new_inp;
3229	stcb->asoc.delete_prim_timer.ep = (void *)new_inp;
3230	/* now what about the nets? */
3231	TAILQ_FOREACH(net, &stcb->asoc.nets, sctp_next) {
3232		net->pmtu_timer.ep = (void *)new_inp;
3233		net->hb_timer.ep = (void *)new_inp;
3234		net->rxt_timer.ep = (void *)new_inp;
3235	}
3236	SCTP_INP_WUNLOCK(new_inp);
3237	SCTP_INP_WUNLOCK(old_inp);
3238}
3239
3240
3241#if !(defined(__FreeBSD__) || defined(__APPLE__) || defined(__Userspace__))
3242/*
3243 * Don't know why, but without this there is an unknown reference when
3244 * compiling NetBSD... hmm
3245 */
3246extern void in6_sin6_2_sin(struct sockaddr_in *, struct sockaddr_in6 *sin6);
3247#endif
3248
3249
3250/* sctp_ifap is used to bypass normal local address validation checks */
3251int
3252#if defined(__FreeBSD__) && __FreeBSD_version >= 500000
3253sctp_inpcb_bind(struct socket *so, struct sockaddr *addr,
3254                struct sctp_ifa *sctp_ifap, struct thread *p)
3255#elif defined(__Windows__)
3256sctp_inpcb_bind(struct socket *so, struct sockaddr *addr,
3257                struct sctp_ifa *sctp_ifap, PKTHREAD p)
3258#else
3259sctp_inpcb_bind(struct socket *so, struct sockaddr *addr,
3260                struct sctp_ifa *sctp_ifap, struct proc *p)
3261#endif
3262{
3263	/* bind a ep to a socket address */
3264	struct sctppcbhead *head;
3265	struct sctp_inpcb *inp, *inp_tmp;
3266#if defined(INET) || (defined(INET6) && defined(__APPLE__)) || defined(__FreeBSD__) || defined(__APPLE__)
3267	struct inpcb *ip_inp;
3268#endif
3269	int port_reuse_active = 0;
3270	int bindall;
3271#ifdef SCTP_MVRF
3272	int i;
3273#endif
3274	uint16_t lport;
3275	int error;
3276	uint32_t vrf_id;
3277
3278	lport = 0;
3279	bindall = 1;
3280	inp = (struct sctp_inpcb *)so->so_pcb;
3281#if defined(INET) || (defined(INET6) && defined(__APPLE__)) || defined(__FreeBSD__) || defined(__APPLE__)
3282	ip_inp = (struct inpcb *)so->so_pcb;
3283#endif
3284#ifdef SCTP_DEBUG
3285	if (addr) {
3286		SCTPDBG(SCTP_DEBUG_PCB1, "Bind called port: %d\n",
3287			ntohs(((struct sockaddr_in *)addr)->sin_port));
3288		SCTPDBG(SCTP_DEBUG_PCB1, "Addr: ");
3289		SCTPDBG_ADDR(SCTP_DEBUG_PCB1, addr);
3290	}
3291#endif
3292	if ((inp->sctp_flags & SCTP_PCB_FLAGS_UNBOUND) == 0) {
3293		/* already did a bind, subsequent binds NOT allowed ! */
3294		SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
3295		return (EINVAL);
3296	}
3297#if defined(__FreeBSD__) && __FreeBSD_version >= 500000
3298#ifdef INVARIANTS
3299	if (p == NULL)
3300		panic("null proc/thread");
3301#endif
3302#endif
3303	if (addr != NULL) {
3304		switch (addr->sa_family) {
3305#ifdef INET
3306		case AF_INET:
3307		{
3308			struct sockaddr_in *sin;
3309
3310			/* IPV6_V6ONLY socket? */
3311			if (SCTP_IPV6_V6ONLY(ip_inp)) {
3312				SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
3313				return (EINVAL);
3314			}
3315#ifdef HAVE_SA_LEN
3316			if (addr->sa_len != sizeof(*sin)) {
3317				SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
3318				return (EINVAL);
3319			}
3320#endif
3321
3322			sin = (struct sockaddr_in *)addr;
3323			lport = sin->sin_port;
3324#if defined(__FreeBSD__) && __FreeBSD_version >= 800000
3325			/*
3326			 * For LOOPBACK the prison_local_ip4() call will transmute the ip address
3327			 * to the proper value.
3328			 */
3329			if (p && (error = prison_local_ip4(p->td_ucred, &sin->sin_addr)) != 0) {
3330				SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, error);
3331				return (error);
3332			}
3333#endif
3334			if (sin->sin_addr.s_addr != INADDR_ANY) {
3335				bindall = 0;
3336			}
3337			break;
3338		}
3339#endif
3340#ifdef INET6
3341		case AF_INET6:
3342		{
3343			/* Only for pure IPv6 Address. (No IPv4 Mapped!) */
3344			struct sockaddr_in6 *sin6;
3345
3346			sin6 = (struct sockaddr_in6 *)addr;
3347
3348#ifdef HAVE_SA_LEN
3349			if (addr->sa_len != sizeof(*sin6)) {
3350				SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
3351				return (EINVAL);
3352			}
3353#endif
3354			lport = sin6->sin6_port;
3355#if defined(__FreeBSD__) && __FreeBSD_version >= 800000
3356			/*
3357			 * For LOOPBACK the prison_local_ip6() call will transmute the ipv6 address
3358			 * to the proper value.
3359			 */
3360			if (p && (error = prison_local_ip6(p->td_ucred, &sin6->sin6_addr,
3361			    (SCTP_IPV6_V6ONLY(inp) != 0))) != 0) {
3362				SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, error);
3363				return (error);
3364			}
3365#endif
3366			if (!IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr)) {
3367				bindall = 0;
3368#ifdef SCTP_EMBEDDED_V6_SCOPE
3369				/* KAME hack: embed scopeid */
3370#if defined(SCTP_KAME)
3371				if (sa6_embedscope(sin6, MODULE_GLOBAL(ip6_use_defzone)) != 0) {
3372					SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
3373					return (EINVAL);
3374				}
3375#elif defined(__APPLE__)
3376#if defined(APPLE_LEOPARD) || defined(APPLE_SNOWLEOPARD)
3377				if (in6_embedscope(&sin6->sin6_addr, sin6, ip_inp, NULL) != 0) {
3378#else
3379				if (in6_embedscope(&sin6->sin6_addr, sin6, ip_inp, NULL, NULL) != 0) {
3380#endif
3381					SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
3382					return (EINVAL);
3383				}
3384#elif defined(__FreeBSD__)
3385				error = scope6_check_id(sin6, MODULE_GLOBAL(ip6_use_defzone));
3386				if (error != 0) {
3387					SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, error);
3388					return (error);
3389				}
3390#else
3391				if (in6_embedscope(&sin6->sin6_addr, sin6) != 0) {
3392					SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
3393					return (EINVAL);
3394				}
3395#endif
3396#endif /* SCTP_EMBEDDED_V6_SCOPE */
3397			}
3398#ifndef SCOPEDROUTING
3399			/* this must be cleared for ifa_ifwithaddr() */
3400			sin6->sin6_scope_id = 0;
3401#endif /* SCOPEDROUTING */
3402			break;
3403		}
3404#endif
3405#if defined(__Userspace__)
3406		case AF_CONN:
3407		{
3408			struct sockaddr_conn *sconn;
3409
3410#ifdef HAVE_SA_LEN
3411			if (addr->sa_len != sizeof(struct sockaddr_conn)) {
3412				SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
3413				return (EINVAL);
3414			}
3415#endif
3416			sconn = (struct sockaddr_conn *)addr;
3417			lport = sconn->sconn_port;
3418			if (sconn->sconn_addr != NULL) {
3419				bindall = 0;
3420			}
3421			break;
3422		}
3423#endif
3424		default:
3425			SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EAFNOSUPPORT);
3426			return (EAFNOSUPPORT);
3427		}
3428	}
3429	SCTP_INP_INFO_WLOCK();
3430	SCTP_INP_WLOCK(inp);
3431	/* Setup a vrf_id to be the default for the non-bind-all case. */
3432	vrf_id = inp->def_vrf_id;
3433
3434	/* increase our count due to the unlock we do */
3435	SCTP_INP_INCR_REF(inp);
3436	if (lport) {
3437		/*
3438		 * Did the caller specify a port? if so we must see if an ep
3439		 * already has this one bound.
3440		 */
3441		/* got to be root to get at low ports */
3442#if !defined(__Windows__)
3443		if (ntohs(lport) < IPPORT_RESERVED) {
3444			if (p && (error =
3445#ifdef __FreeBSD__
3446#if __FreeBSD_version > 602000
3447				  priv_check(p, PRIV_NETINET_RESERVEDPORT)
3448#elif __FreeBSD_version >= 500000
3449				  suser_cred(p->td_ucred, 0)
3450#else
3451				  suser(p)
3452#endif
3453#elif defined(__APPLE__)
3454				  suser(p->p_ucred, &p->p_acflag)
3455#elif defined(__Userspace__) /* must be true to use raw socket */
3456				  1
3457#else
3458				  suser(p, 0)
3459#endif
3460				    )) {
3461				SCTP_INP_DECR_REF(inp);
3462				SCTP_INP_WUNLOCK(inp);
3463				SCTP_INP_INFO_WUNLOCK();
3464				return (error);
3465			}
3466#if defined(__Panda__)
3467			if (!SCTP_IS_PRIVILEDGED(so)) {
3468				SCTP_INP_DECR_REF(inp);
3469				SCTP_INP_WUNLOCK(inp);
3470				SCTP_INP_INFO_WUNLOCK();
3471				SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EACCES);
3472				return (EACCES);
3473			}
3474#endif
3475		}
3476#endif /* __Windows__ */
3477		SCTP_INP_WUNLOCK(inp);
3478		if (bindall) {
3479#ifdef SCTP_MVRF
3480			for (i = 0; i < inp->num_vrfs; i++) {
3481				vrf_id = inp->m_vrf_ids[i];
3482#else
3483				vrf_id = inp->def_vrf_id;
3484#endif
3485				inp_tmp = sctp_pcb_findep(addr, 0, 1, vrf_id);
3486				if (inp_tmp != NULL) {
3487					/*
3488					 * lock guy returned and lower count
3489					 * note that we are not bound so
3490					 * inp_tmp should NEVER be inp. And
3491					 * it is this inp (inp_tmp) that gets
3492					 * the reference bump, so we must
3493					 * lower it.
3494					 */
3495					SCTP_INP_DECR_REF(inp_tmp);
3496					/* unlock info */
3497					if ((sctp_is_feature_on(inp, SCTP_PCB_FLAGS_PORTREUSE)) &&
3498					    (sctp_is_feature_on(inp_tmp, SCTP_PCB_FLAGS_PORTREUSE))) {
3499						/* Ok, must be one-2-one and allowing port re-use */
3500						port_reuse_active = 1;
3501						goto continue_anyway;
3502					}
3503					SCTP_INP_DECR_REF(inp);
3504					SCTP_INP_INFO_WUNLOCK();
3505					SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EADDRINUSE);
3506					return (EADDRINUSE);
3507				}
3508#ifdef SCTP_MVRF
3509			}
3510#endif
3511		} else {
3512			inp_tmp = sctp_pcb_findep(addr, 0, 1, vrf_id);
3513			if (inp_tmp != NULL) {
3514				/*
3515				 * lock guy returned and lower count note
3516				 * that we are not bound so inp_tmp should
3517				 * NEVER be inp. And it is this inp (inp_tmp)
3518				 * that gets the reference bump, so we must
3519				 * lower it.
3520				 */
3521				SCTP_INP_DECR_REF(inp_tmp);
3522				/* unlock info */
3523				if ((sctp_is_feature_on(inp, SCTP_PCB_FLAGS_PORTREUSE)) &&
3524				    (sctp_is_feature_on(inp_tmp, SCTP_PCB_FLAGS_PORTREUSE))) {
3525					/* Ok, must be one-2-one and allowing port re-use */
3526					port_reuse_active = 1;
3527					goto continue_anyway;
3528				}
3529				SCTP_INP_DECR_REF(inp);
3530				SCTP_INP_INFO_WUNLOCK();
3531				SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EADDRINUSE);
3532				return (EADDRINUSE);
3533			}
3534		}
3535	continue_anyway:
3536		SCTP_INP_WLOCK(inp);
3537		if (bindall) {
3538			/* verify that no lport is not used by a singleton */
3539			if ((port_reuse_active == 0) &&
3540			    (inp_tmp = sctp_isport_inuse(inp, lport, vrf_id))) {
3541				/* Sorry someone already has this one bound */
3542				if ((sctp_is_feature_on(inp, SCTP_PCB_FLAGS_PORTREUSE)) &&
3543				    (sctp_is_feature_on(inp_tmp, SCTP_PCB_FLAGS_PORTREUSE))) {
3544					port_reuse_active = 1;
3545				} else {
3546					SCTP_INP_DECR_REF(inp);
3547					SCTP_INP_WUNLOCK(inp);
3548					SCTP_INP_INFO_WUNLOCK();
3549					SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EADDRINUSE);
3550					return (EADDRINUSE);
3551				}
3552			}
3553		}
3554	} else {
3555		uint16_t first, last, candidate;
3556		uint16_t count;
3557		int done;
3558
3559#if defined(__Windows__)
3560		first = 1;
3561		last = 0xffff;
3562#else
3563#if defined(__Userspace__)
3564		/* TODO ensure uid is 0, etc... */
3565#elif defined(__FreeBSD__) || defined(__APPLE__)
3566		if (ip_inp->inp_flags & INP_HIGHPORT) {
3567			first = MODULE_GLOBAL(ipport_hifirstauto);
3568			last = MODULE_GLOBAL(ipport_hilastauto);
3569		} else if (ip_inp->inp_flags & INP_LOWPORT) {
3570			if (p && (error =
3571#ifdef __FreeBSD__
3572#if __FreeBSD_version > 602000
3573				  priv_check(p, PRIV_NETINET_RESERVEDPORT)
3574#elif __FreeBSD_version >= 500000
3575				  suser_cred(p->td_ucred, 0)
3576#else
3577				  suser(p)
3578#endif
3579#elif defined(__APPLE__)
3580				  suser(p->p_ucred, &p->p_acflag)
3581#else
3582				  suser(p, 0)
3583#endif
3584				    )) {
3585				SCTP_INP_DECR_REF(inp);
3586				SCTP_INP_WUNLOCK(inp);
3587				SCTP_INP_INFO_WUNLOCK();
3588				SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, error);
3589				return (error);
3590			}
3591			first = MODULE_GLOBAL(ipport_lowfirstauto);
3592			last = MODULE_GLOBAL(ipport_lowlastauto);
3593		} else {
3594#endif
3595			first = MODULE_GLOBAL(ipport_firstauto);
3596			last = MODULE_GLOBAL(ipport_lastauto);
3597#if defined(__FreeBSD__) || defined(__APPLE__)
3598		}
3599#endif
3600#endif /* __Windows__ */
3601		if (first > last) {
3602			uint16_t temp;
3603
3604			temp = first;
3605			first = last;
3606			last = temp;
3607		}
3608		count = last - first + 1; /* number of candidates */
3609		candidate = first + sctp_select_initial_TSN(&inp->sctp_ep) % (count);
3610
3611		done = 0;
3612		while (!done) {
3613#ifdef SCTP_MVRF
3614			for (i = 0; i < inp->num_vrfs; i++) {
3615				if (sctp_isport_inuse(inp, htons(candidate), inp->m_vrf_ids[i]) != NULL) {
3616					break;
3617				}
3618			}
3619			if (i == inp->num_vrfs) {
3620				done = 1;
3621			}
3622#else
3623			if (sctp_isport_inuse(inp, htons(candidate), inp->def_vrf_id) == NULL) {
3624				done = 1;
3625			}
3626#endif
3627			if (!done) {
3628				if (--count == 0) {
3629					SCTP_INP_DECR_REF(inp);
3630					SCTP_INP_WUNLOCK(inp);
3631					SCTP_INP_INFO_WUNLOCK();
3632					SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EADDRINUSE);
3633					return (EADDRINUSE);
3634				}
3635				if (candidate == last)
3636					candidate = first;
3637				else
3638					candidate = candidate + 1;
3639			}
3640		}
3641		lport = htons(candidate);
3642	}
3643	SCTP_INP_DECR_REF(inp);
3644	if (inp->sctp_flags & (SCTP_PCB_FLAGS_SOCKET_GONE |
3645			       SCTP_PCB_FLAGS_SOCKET_ALLGONE)) {
3646		/*
3647		 * this really should not happen. The guy did a non-blocking
3648		 * bind and then did a close at the same time.
3649		 */
3650		SCTP_INP_WUNLOCK(inp);
3651		SCTP_INP_INFO_WUNLOCK();
3652		SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
3653		return (EINVAL);
3654	}
3655	/* ok we look clear to give out this port, so lets setup the binding */
3656	if (bindall) {
3657		/* binding to all addresses, so just set in the proper flags */
3658		inp->sctp_flags |= SCTP_PCB_FLAGS_BOUNDALL;
3659		/* set the automatic addr changes from kernel flag */
3660		if (SCTP_BASE_SYSCTL(sctp_auto_asconf) == 0) {
3661			sctp_feature_off(inp, SCTP_PCB_FLAGS_DO_ASCONF);
3662			sctp_feature_off(inp, SCTP_PCB_FLAGS_AUTO_ASCONF);
3663		} else {
3664			sctp_feature_on(inp, SCTP_PCB_FLAGS_DO_ASCONF);
3665			sctp_feature_on(inp, SCTP_PCB_FLAGS_AUTO_ASCONF);
3666		}
3667		if (SCTP_BASE_SYSCTL(sctp_multiple_asconfs) == 0) {
3668			sctp_feature_off(inp, SCTP_PCB_FLAGS_MULTIPLE_ASCONFS);
3669		} else {
3670			sctp_feature_on(inp, SCTP_PCB_FLAGS_MULTIPLE_ASCONFS);
3671		}
3672		/* set the automatic mobility_base from kernel
3673		   flag (by micchie)
3674		*/
3675		if (SCTP_BASE_SYSCTL(sctp_mobility_base) == 0) {
3676			sctp_mobility_feature_off(inp, SCTP_MOBILITY_BASE);
3677			sctp_mobility_feature_off(inp, SCTP_MOBILITY_PRIM_DELETED);
3678		} else {
3679			sctp_mobility_feature_on(inp, SCTP_MOBILITY_BASE);
3680			sctp_mobility_feature_off(inp, SCTP_MOBILITY_PRIM_DELETED);
3681		}
3682		/* set the automatic mobility_fasthandoff from kernel
3683		   flag (by micchie)
3684		*/
3685		if (SCTP_BASE_SYSCTL(sctp_mobility_fasthandoff) == 0) {
3686			sctp_mobility_feature_off(inp, SCTP_MOBILITY_FASTHANDOFF);
3687			sctp_mobility_feature_off(inp, SCTP_MOBILITY_PRIM_DELETED);
3688		} else {
3689			sctp_mobility_feature_on(inp, SCTP_MOBILITY_FASTHANDOFF);
3690			sctp_mobility_feature_off(inp, SCTP_MOBILITY_PRIM_DELETED);
3691		}
3692	} else {
3693		/*
3694		 * bind specific, make sure flags is off and add a new
3695		 * address structure to the sctp_addr_list inside the ep
3696		 * structure.
3697		 *
3698		 * We will need to allocate one and insert it at the head. The
3699		 * socketopt call can just insert new addresses in there as
3700		 * well. It will also have to do the embed scope kame hack
3701		 * too (before adding).
3702		 */
3703		struct sctp_ifa *ifa;
3704		union sctp_sockstore store;
3705
3706		memset(&store, 0, sizeof(store));
3707		switch (addr->sa_family) {
3708#ifdef INET
3709		case AF_INET:
3710			memcpy(&store.sin, addr, sizeof(struct sockaddr_in));
3711			store.sin.sin_port = 0;
3712			break;
3713#endif
3714#ifdef INET6
3715		case AF_INET6:
3716			memcpy(&store.sin6, addr, sizeof(struct sockaddr_in6));
3717			store.sin6.sin6_port = 0;
3718			break;
3719#endif
3720#if defined(__Userspace__)
3721		case AF_CONN:
3722			memcpy(&store.sconn, addr, sizeof(struct sockaddr_conn));
3723			store.sconn.sconn_port = 0;
3724			break;
3725#endif
3726		default:
3727			break;
3728		}
3729		/*
3730		 * first find the interface with the bound address need to
3731		 * zero out the port to find the address! yuck! can't do
3732		 * this earlier since need port for sctp_pcb_findep()
3733		 */
3734		if (sctp_ifap != NULL) {
3735			ifa = sctp_ifap;
3736		} else {
3737			/* Note for BSD we hit here always other
3738			 * O/S's will pass things in via the
3739			 * sctp_ifap argument (Panda).
3740			 */
3741			ifa = sctp_find_ifa_by_addr(&store.sa,
3742						    vrf_id, SCTP_ADDR_NOT_LOCKED);
3743		}
3744		if (ifa == NULL) {
3745			/* Can't find an interface with that address */
3746			SCTP_INP_WUNLOCK(inp);
3747			SCTP_INP_INFO_WUNLOCK();
3748			SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EADDRNOTAVAIL);
3749			return (EADDRNOTAVAIL);
3750		}
3751#ifdef INET6
3752		if (addr->sa_family == AF_INET6) {
3753			/* GAK, more FIXME IFA lock? */
3754			if (ifa->localifa_flags & SCTP_ADDR_IFA_UNUSEABLE) {
3755				/* Can't bind a non-existent addr. */
3756				SCTP_INP_WUNLOCK(inp);
3757				SCTP_INP_INFO_WUNLOCK();
3758				SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
3759				return (EINVAL);
3760			}
3761		}
3762#endif
3763		/* we're not bound all */
3764		inp->sctp_flags &= ~SCTP_PCB_FLAGS_BOUNDALL;
3765		/* allow bindx() to send ASCONF's for binding changes */
3766		sctp_feature_on(inp, SCTP_PCB_FLAGS_DO_ASCONF);
3767		/* clear automatic addr changes from kernel flag */
3768		sctp_feature_off(inp, SCTP_PCB_FLAGS_AUTO_ASCONF);
3769
3770		/* add this address to the endpoint list */
3771		error = sctp_insert_laddr(&inp->sctp_addr_list, ifa, 0);
3772		if (error != 0) {
3773			SCTP_INP_WUNLOCK(inp);
3774			SCTP_INP_INFO_WUNLOCK();
3775			return (error);
3776		}
3777		inp->laddr_count++;
3778	}
3779	/* find the bucket */
3780	if (port_reuse_active) {
3781		/* Put it into tcp 1-2-1 hash */
3782		head = &SCTP_BASE_INFO(sctp_tcpephash)[SCTP_PCBHASH_ALLADDR(lport, SCTP_BASE_INFO(hashtcpmark))];
3783		inp->sctp_flags |= SCTP_PCB_FLAGS_IN_TCPPOOL;
3784	} else {
3785		head = &SCTP_BASE_INFO(sctp_ephash)[SCTP_PCBHASH_ALLADDR(lport, SCTP_BASE_INFO(hashmark))];
3786	}
3787	/* put it in the bucket */
3788	LIST_INSERT_HEAD(head, inp, sctp_hash);
3789	SCTPDBG(SCTP_DEBUG_PCB1, "Main hash to bind at head:%p, bound port:%d - in tcp_pool=%d\n",
3790		(void *)head, ntohs(lport), port_reuse_active);
3791	/* set in the port */
3792	inp->sctp_lport = lport;
3793
3794	/* turn off just the unbound flag */
3795	inp->sctp_flags &= ~SCTP_PCB_FLAGS_UNBOUND;
3796	SCTP_INP_WUNLOCK(inp);
3797	SCTP_INP_INFO_WUNLOCK();
3798	return (0);
3799}
3800
3801
3802static void
3803sctp_iterator_inp_being_freed(struct sctp_inpcb *inp)
3804{
3805	struct sctp_iterator *it, *nit;
3806
3807	/*
3808	 * We enter with the only the ITERATOR_LOCK in place and a write
3809	 * lock on the inp_info stuff.
3810	 */
3811	it = sctp_it_ctl.cur_it;
3812#if defined(__FreeBSD__) && __FreeBSD_version >= 801000
3813	if (it && (it->vn != curvnet)) {
3814		/* Its not looking at our VNET */
3815		return;
3816	}
3817#endif
3818	if (it && (it->inp == inp)) {
3819		/*
3820		 * This is tricky and we hold the iterator lock,
3821		 * but when it returns and gets the lock (when we
3822		 * release it) the iterator will try to operate on
3823		 * inp. We need to stop that from happening. But
3824		 * of course the iterator has a reference on the
3825		 * stcb and inp. We can mark it and it will stop.
3826		 *
3827		 * If its a single iterator situation, we
3828		 * set the end iterator flag. Otherwise
3829		 * we set the iterator to go to the next inp.
3830		 *
3831		 */
3832		if (it->iterator_flags & SCTP_ITERATOR_DO_SINGLE_INP) {
3833			sctp_it_ctl.iterator_flags |= SCTP_ITERATOR_STOP_CUR_IT;
3834		} else {
3835			sctp_it_ctl.iterator_flags |= SCTP_ITERATOR_STOP_CUR_INP;
3836		}
3837	}
3838	/* Now go through and remove any single reference to
3839	 * our inp that may be still pending on the list
3840	 */
3841	SCTP_IPI_ITERATOR_WQ_LOCK();
3842	TAILQ_FOREACH_SAFE(it, &sctp_it_ctl.iteratorhead, sctp_nxt_itr, nit) {
3843#if defined(__FreeBSD__) && __FreeBSD_version >= 801000
3844		if (it->vn != curvnet) {
3845			continue;
3846		}
3847#endif
3848		if (it->inp == inp) {
3849			/* This one points to me is it inp specific? */
3850			if (it->iterator_flags & SCTP_ITERATOR_DO_SINGLE_INP) {
3851				/* Remove and free this one */
3852				TAILQ_REMOVE(&sctp_it_ctl.iteratorhead,
3853				    it, sctp_nxt_itr);
3854				if (it->function_atend != NULL) {
3855					(*it->function_atend) (it->pointer, it->val);
3856				}
3857				SCTP_FREE(it, SCTP_M_ITER);
3858			} else {
3859				it->inp = LIST_NEXT(it->inp, sctp_list);
3860				if (it->inp) {
3861					SCTP_INP_INCR_REF(it->inp);
3862				}
3863			}
3864			/* When its put in the refcnt is incremented so decr it */
3865			SCTP_INP_DECR_REF(inp);
3866		}
3867	}
3868	SCTP_IPI_ITERATOR_WQ_UNLOCK();
3869}
3870
3871/* release sctp_inpcb unbind the port */
3872void
3873sctp_inpcb_free(struct sctp_inpcb *inp, int immediate, int from)
3874{
3875	/*
3876	 * Here we free a endpoint. We must find it (if it is in the Hash
3877	 * table) and remove it from there. Then we must also find it in the
3878	 * overall list and remove it from there. After all removals are
3879	 * complete then any timer has to be stopped. Then start the actual
3880	 * freeing. a) Any local lists. b) Any associations. c) The hash of
3881	 * all associations. d) finally the ep itself.
3882	 */
3883	struct sctp_tcb *asoc, *nasoc;
3884	struct sctp_laddr *laddr, *nladdr;
3885	struct inpcb *ip_pcb;
3886	struct socket *so;
3887	int being_refed = 0;
3888	struct sctp_queued_to_read *sq, *nsq;
3889#if !defined(__Panda__) && !defined(__Userspace__)
3890#if !defined(__FreeBSD__) || __FreeBSD_version < 500000
3891	sctp_rtentry_t *rt;
3892#endif
3893#endif
3894	int cnt;
3895	sctp_sharedkey_t *shared_key, *nshared_key;
3896
3897
3898#if defined(__APPLE__)
3899	sctp_lock_assert(SCTP_INP_SO(inp));
3900#endif
3901#ifdef SCTP_LOG_CLOSING
3902	sctp_log_closing(inp, NULL, 0);
3903#endif
3904	SCTP_ITERATOR_LOCK();
3905	/* mark any iterators on the list or being processed */
3906	sctp_iterator_inp_being_freed(inp);
3907	SCTP_ITERATOR_UNLOCK();
3908	so = inp->sctp_socket;
3909	if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) {
3910		/* been here before.. eeks.. get out of here */
3911		SCTP_PRINTF("This conflict in free SHOULD not be happening! from %d, imm %d\n", from, immediate);
3912#ifdef SCTP_LOG_CLOSING
3913		sctp_log_closing(inp, NULL, 1);
3914#endif
3915		return;
3916	}
3917	SCTP_ASOC_CREATE_LOCK(inp);
3918	SCTP_INP_INFO_WLOCK();
3919
3920	SCTP_INP_WLOCK(inp);
3921	if (from == SCTP_CALLED_AFTER_CMPSET_OFCLOSE) {
3922		inp->sctp_flags &= ~SCTP_PCB_FLAGS_CLOSE_IP;
3923		/* socket is gone, so no more wakeups allowed */
3924		inp->sctp_flags |= SCTP_PCB_FLAGS_DONT_WAKE;
3925		inp->sctp_flags &= ~SCTP_PCB_FLAGS_WAKEINPUT;
3926		inp->sctp_flags &= ~SCTP_PCB_FLAGS_WAKEOUTPUT;
3927
3928	}
3929	/* First time through we have the socket lock, after that no more. */
3930	sctp_timer_stop(SCTP_TIMER_TYPE_NEWCOOKIE, inp, NULL, NULL,
3931			SCTP_FROM_SCTP_PCB+SCTP_LOC_1);
3932
3933	if (inp->control) {
3934		sctp_m_freem(inp->control);
3935		inp->control = NULL;
3936	}
3937	if (inp->pkt) {
3938		sctp_m_freem(inp->pkt);
3939		inp->pkt = NULL;
3940	}
3941	ip_pcb = &inp->ip_inp.inp;	/* we could just cast the main pointer
3942					 * here but I will be nice :> (i.e.
3943					 * ip_pcb = ep;) */
3944	if (immediate == SCTP_FREE_SHOULD_USE_GRACEFUL_CLOSE) {
3945		int cnt_in_sd;
3946
3947		cnt_in_sd = 0;
3948		LIST_FOREACH_SAFE(asoc, &inp->sctp_asoc_list, sctp_tcblist, nasoc) {
3949			SCTP_TCB_LOCK(asoc);
3950			if (asoc->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) {
3951				/* Skip guys being freed */
3952				cnt_in_sd++;
3953				if (asoc->asoc.state & SCTP_STATE_IN_ACCEPT_QUEUE) {
3954					/*
3955					 * Special case - we did not start a kill
3956					 * timer on the asoc due to it was not
3957					 * closed. So go ahead and start it now.
3958					 */
3959					asoc->asoc.state &= ~SCTP_STATE_IN_ACCEPT_QUEUE;
3960					sctp_timer_start(SCTP_TIMER_TYPE_ASOCKILL, inp, asoc, NULL);
3961				}
3962				SCTP_TCB_UNLOCK(asoc);
3963				continue;
3964			}
3965			if (((SCTP_GET_STATE(&asoc->asoc) == SCTP_STATE_COOKIE_WAIT) ||
3966			    (SCTP_GET_STATE(&asoc->asoc) == SCTP_STATE_COOKIE_ECHOED)) &&
3967			    (asoc->asoc.total_output_queue_size == 0)) {
3968				/* If we have data in queue, we don't want to just
3969				 * free since the app may have done, send()/close
3970				 * or connect/send/close. And it wants the data
3971				 * to get across first.
3972				 */
3973				/* Just abandon things in the front states */
3974				if (sctp_free_assoc(inp, asoc, SCTP_PCBFREE_NOFORCE,
3975						   SCTP_FROM_SCTP_PCB+SCTP_LOC_2) == 0) {
3976					cnt_in_sd++;
3977				}
3978				continue;
3979			}
3980			/* Disconnect the socket please */
3981			asoc->sctp_socket = NULL;
3982			asoc->asoc.state |= SCTP_STATE_CLOSED_SOCKET;
3983			if ((asoc->asoc.size_on_reasm_queue > 0) ||
3984			    (asoc->asoc.control_pdapi) ||
3985			    (asoc->asoc.size_on_all_streams > 0) ||
3986			    (so && (so->so_rcv.sb_cc > 0))) {
3987				/* Left with Data unread */
3988				struct mbuf *op_err;
3989
3990				op_err = sctp_generate_cause(SCTP_CAUSE_USER_INITIATED_ABT, "");
3991				asoc->sctp_ep->last_abort_code = SCTP_FROM_SCTP_PCB+SCTP_LOC_3;
3992				sctp_send_abort_tcb(asoc, op_err, SCTP_SO_LOCKED);
3993				SCTP_STAT_INCR_COUNTER32(sctps_aborted);
3994				if ((SCTP_GET_STATE(&asoc->asoc) == SCTP_STATE_OPEN) ||
3995				    (SCTP_GET_STATE(&asoc->asoc) == SCTP_STATE_SHUTDOWN_RECEIVED)) {
3996					SCTP_STAT_DECR_GAUGE32(sctps_currestab);
3997				}
3998				if (sctp_free_assoc(inp, asoc,
3999						    SCTP_PCBFREE_NOFORCE, SCTP_FROM_SCTP_PCB+SCTP_LOC_4) == 0) {
4000					cnt_in_sd++;
4001				}
4002				continue;
4003			} else if (TAILQ_EMPTY(&asoc->asoc.send_queue) &&
4004			           TAILQ_EMPTY(&asoc->asoc.sent_queue) &&
4005			           (asoc->asoc.stream_queue_cnt == 0)) {
4006				if (asoc->asoc.locked_on_sending) {
4007					goto abort_anyway;
4008				}
4009				if ((SCTP_GET_STATE(&asoc->asoc) != SCTP_STATE_SHUTDOWN_SENT) &&
4010				    (SCTP_GET_STATE(&asoc->asoc) != SCTP_STATE_SHUTDOWN_ACK_SENT)) {
4011					struct sctp_nets *netp;
4012
4013					/*
4014					 * there is nothing queued to send,
4015					 * so I send shutdown
4016					 */
4017					if ((SCTP_GET_STATE(&asoc->asoc) == SCTP_STATE_OPEN) ||
4018					    (SCTP_GET_STATE(&asoc->asoc) == SCTP_STATE_SHUTDOWN_RECEIVED)) {
4019						SCTP_STAT_DECR_GAUGE32(sctps_currestab);
4020					}
4021					SCTP_SET_STATE(&asoc->asoc, SCTP_STATE_SHUTDOWN_SENT);
4022					SCTP_CLEAR_SUBSTATE(&asoc->asoc, SCTP_STATE_SHUTDOWN_PENDING);
4023					sctp_stop_timers_for_shutdown(asoc);
4024					if (asoc->asoc.alternate) {
4025						netp = asoc->asoc.alternate;
4026					} else {
4027						netp = asoc->asoc.primary_destination;
4028					}
4029					sctp_send_shutdown(asoc, netp);
4030					sctp_timer_start(SCTP_TIMER_TYPE_SHUTDOWN, asoc->sctp_ep, asoc,
4031					    netp);
4032					sctp_timer_start(SCTP_TIMER_TYPE_SHUTDOWNGUARD, asoc->sctp_ep, asoc,
4033					    asoc->asoc.primary_destination);
4034					sctp_chunk_output(inp, asoc, SCTP_OUTPUT_FROM_SHUT_TMR, SCTP_SO_LOCKED);
4035				}
4036			} else {
4037				/* mark into shutdown pending */
4038				struct sctp_stream_queue_pending *sp;
4039
4040				asoc->asoc.state |= SCTP_STATE_SHUTDOWN_PENDING;
4041				sctp_timer_start(SCTP_TIMER_TYPE_SHUTDOWNGUARD, asoc->sctp_ep, asoc,
4042						 asoc->asoc.primary_destination);
4043				if (asoc->asoc.locked_on_sending) {
4044					sp = TAILQ_LAST(&((asoc->asoc.locked_on_sending)->outqueue),
4045						sctp_streamhead);
4046					if (sp == NULL) {
4047						SCTP_PRINTF("Error, sp is NULL, locked on sending is %p strm:%d\n",
4048						       (void *)asoc->asoc.locked_on_sending,
4049						       asoc->asoc.locked_on_sending->stream_no);
4050					} else {
4051						if ((sp->length == 0) && (sp->msg_is_complete == 0))
4052							asoc->asoc.state |= SCTP_STATE_PARTIAL_MSG_LEFT;
4053					}
4054				}
4055				if (TAILQ_EMPTY(&asoc->asoc.send_queue) &&
4056				    TAILQ_EMPTY(&asoc->asoc.sent_queue) &&
4057				    (asoc->asoc.state & SCTP_STATE_PARTIAL_MSG_LEFT)) {
4058					struct mbuf *op_err;
4059				abort_anyway:
4060					op_err = sctp_generate_cause(SCTP_CAUSE_USER_INITIATED_ABT, "");
4061					asoc->sctp_ep->last_abort_code = SCTP_FROM_SCTP_PCB+SCTP_LOC_5;
4062					sctp_send_abort_tcb(asoc, op_err, SCTP_SO_LOCKED);
4063					SCTP_STAT_INCR_COUNTER32(sctps_aborted);
4064					if ((SCTP_GET_STATE(&asoc->asoc) == SCTP_STATE_OPEN) ||
4065					    (SCTP_GET_STATE(&asoc->asoc) == SCTP_STATE_SHUTDOWN_RECEIVED)) {
4066						SCTP_STAT_DECR_GAUGE32(sctps_currestab);
4067					}
4068					if (sctp_free_assoc(inp, asoc,
4069							    SCTP_PCBFREE_NOFORCE,
4070							    SCTP_FROM_SCTP_PCB+SCTP_LOC_6) == 0) {
4071						cnt_in_sd++;
4072					}
4073					continue;
4074				} else {
4075					sctp_chunk_output(inp, asoc, SCTP_OUTPUT_FROM_CLOSING, SCTP_SO_LOCKED);
4076				}
4077			}
4078			cnt_in_sd++;
4079			SCTP_TCB_UNLOCK(asoc);
4080		}
4081		/* now is there some left in our SHUTDOWN state? */
4082		if (cnt_in_sd) {
4083#ifdef SCTP_LOG_CLOSING
4084			sctp_log_closing(inp, NULL, 2);
4085#endif
4086			inp->sctp_socket = NULL;
4087			SCTP_INP_WUNLOCK(inp);
4088			SCTP_ASOC_CREATE_UNLOCK(inp);
4089			SCTP_INP_INFO_WUNLOCK();
4090			return;
4091		}
4092	}
4093	inp->sctp_socket = NULL;
4094	if ((inp->sctp_flags & SCTP_PCB_FLAGS_UNBOUND) !=
4095	    SCTP_PCB_FLAGS_UNBOUND) {
4096		/*
4097		 * ok, this guy has been bound. It's port is
4098		 * somewhere in the SCTP_BASE_INFO(hash table). Remove
4099		 * it!
4100		 */
4101		LIST_REMOVE(inp, sctp_hash);
4102		inp->sctp_flags |= SCTP_PCB_FLAGS_UNBOUND;
4103	}
4104
4105	/* If there is a timer running to kill us,
4106	 * forget it, since it may have a contest
4107	 * on the INP lock.. which would cause us
4108	 * to die ...
4109	 */
4110	cnt = 0;
4111	LIST_FOREACH_SAFE(asoc, &inp->sctp_asoc_list, sctp_tcblist, nasoc) {
4112		SCTP_TCB_LOCK(asoc);
4113		if (asoc->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) {
4114			if (asoc->asoc.state & SCTP_STATE_IN_ACCEPT_QUEUE) {
4115				asoc->asoc.state &= ~SCTP_STATE_IN_ACCEPT_QUEUE;
4116				sctp_timer_start(SCTP_TIMER_TYPE_ASOCKILL, inp, asoc, NULL);
4117			}
4118		        cnt++;
4119			SCTP_TCB_UNLOCK(asoc);
4120			continue;
4121		}
4122		/* Free associations that are NOT killing us */
4123		if ((SCTP_GET_STATE(&asoc->asoc) != SCTP_STATE_COOKIE_WAIT) &&
4124		    ((asoc->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) == 0)) {
4125			struct mbuf *op_err;
4126
4127			op_err = sctp_generate_cause(SCTP_CAUSE_USER_INITIATED_ABT, "");
4128			asoc->sctp_ep->last_abort_code = SCTP_FROM_SCTP_PCB+SCTP_LOC_7;
4129			sctp_send_abort_tcb(asoc, op_err, SCTP_SO_LOCKED);
4130			SCTP_STAT_INCR_COUNTER32(sctps_aborted);
4131		} else if (asoc->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) {
4132			cnt++;
4133			SCTP_TCB_UNLOCK(asoc);
4134			continue;
4135		}
4136		if ((SCTP_GET_STATE(&asoc->asoc) == SCTP_STATE_OPEN) ||
4137		    (SCTP_GET_STATE(&asoc->asoc) == SCTP_STATE_SHUTDOWN_RECEIVED)) {
4138			SCTP_STAT_DECR_GAUGE32(sctps_currestab);
4139		}
4140		if (sctp_free_assoc(inp, asoc, SCTP_PCBFREE_FORCE, SCTP_FROM_SCTP_PCB+SCTP_LOC_8) == 0) {
4141			cnt++;
4142		}
4143	}
4144	if (cnt) {
4145		/* Ok we have someone out there that will kill us */
4146		(void)SCTP_OS_TIMER_STOP(&inp->sctp_ep.signature_change.timer);
4147#ifdef SCTP_LOG_CLOSING
4148		sctp_log_closing(inp, NULL, 3);
4149#endif
4150		SCTP_INP_WUNLOCK(inp);
4151		SCTP_ASOC_CREATE_UNLOCK(inp);
4152		SCTP_INP_INFO_WUNLOCK();
4153		return;
4154	}
4155	if (SCTP_INP_LOCK_CONTENDED(inp))
4156		being_refed++;
4157	if (SCTP_INP_READ_CONTENDED(inp))
4158		being_refed++;
4159	if (SCTP_ASOC_CREATE_LOCK_CONTENDED(inp))
4160		being_refed++;
4161
4162	if ((inp->refcount) ||
4163	    (being_refed) ||
4164	    (inp->sctp_flags & SCTP_PCB_FLAGS_CLOSE_IP)) {
4165		(void)SCTP_OS_TIMER_STOP(&inp->sctp_ep.signature_change.timer);
4166#ifdef SCTP_LOG_CLOSING
4167		sctp_log_closing(inp, NULL, 4);
4168#endif
4169		sctp_timer_start(SCTP_TIMER_TYPE_INPKILL, inp, NULL, NULL);
4170		SCTP_INP_WUNLOCK(inp);
4171		SCTP_ASOC_CREATE_UNLOCK(inp);
4172		SCTP_INP_INFO_WUNLOCK();
4173		return;
4174	}
4175	inp->sctp_ep.signature_change.type = 0;
4176	inp->sctp_flags |= SCTP_PCB_FLAGS_SOCKET_ALLGONE;
4177	/* Remove it from the list .. last thing we need a
4178	 * lock for.
4179	 */
4180	LIST_REMOVE(inp, sctp_list);
4181	SCTP_INP_WUNLOCK(inp);
4182	SCTP_ASOC_CREATE_UNLOCK(inp);
4183	SCTP_INP_INFO_WUNLOCK();
4184	/* Now we release all locks. Since this INP
4185	 * cannot be found anymore except possibly by the
4186	 * kill timer that might be running. We call
4187	 * the drain function here. It should hit the case
4188	 * were it sees the ACTIVE flag cleared and exit
4189	 * out freeing us to proceed and destroy everything.
4190	 */
4191	if (from != SCTP_CALLED_FROM_INPKILL_TIMER) {
4192		(void)SCTP_OS_TIMER_STOP_DRAIN(&inp->sctp_ep.signature_change.timer);
4193	} else {
4194		/* Probably un-needed */
4195		(void)SCTP_OS_TIMER_STOP(&inp->sctp_ep.signature_change.timer);
4196	}
4197
4198#ifdef SCTP_LOG_CLOSING
4199	sctp_log_closing(inp, NULL, 5);
4200#endif
4201
4202#if !(defined(__Panda__) || defined(__Windows__) || defined(__Userspace__))
4203#if !defined(__FreeBSD__) || __FreeBSD_version < 500000
4204	rt = ip_pcb->inp_route.ro_rt;
4205#endif
4206#endif
4207
4208#if defined(__Panda__)
4209	if (inp->pak_to_read) {
4210		(void)SCTP_OS_TIMER_STOP(&inp->sctp_ep.zero_copy_timer.timer);
4211		SCTP_RELEASE_PKT(inp->pak_to_read);
4212		inp->pak_to_read = NULL;
4213	}
4214	if (inp->pak_to_read_sendq) {
4215		(void)SCTP_OS_TIMER_STOP(&inp->sctp_ep.zero_copy_sendq_timer.timer);
4216		SCTP_RELEASE_PKT(inp->pak_to_read_sendq);
4217		inp->pak_to_read_sendq = NULL;
4218	}
4219#endif
4220	if ((inp->sctp_asocidhash) != NULL) {
4221		SCTP_HASH_FREE(inp->sctp_asocidhash, inp->hashasocidmark);
4222		inp->sctp_asocidhash = NULL;
4223	}
4224	/*sa_ignore FREED_MEMORY*/
4225	TAILQ_FOREACH_SAFE(sq, &inp->read_queue, next, nsq) {
4226		/* Its only abandoned if it had data left */
4227		if (sq->length)
4228			SCTP_STAT_INCR(sctps_left_abandon);
4229
4230		TAILQ_REMOVE(&inp->read_queue, sq, next);
4231		sctp_free_remote_addr(sq->whoFrom);
4232		if (so)
4233			so->so_rcv.sb_cc -= sq->length;
4234		if (sq->data) {
4235			sctp_m_freem(sq->data);
4236			sq->data = NULL;
4237		}
4238		/*
4239		 * no need to free the net count, since at this point all
4240		 * assoc's are gone.
4241		 */
4242		SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_readq), sq);
4243		SCTP_DECR_READQ_COUNT();
4244	}
4245	/* Now the sctp_pcb things */
4246	/*
4247	 * free each asoc if it is not already closed/free. we can't use the
4248	 * macro here since le_next will get freed as part of the
4249	 * sctp_free_assoc() call.
4250	 */
4251	if (so) {
4252#ifdef IPSEC
4253		ipsec_delete_pcbpolicy(ip_pcb);
4254#endif				/* IPSEC */
4255
4256		/* Unlocks not needed since the socket is gone now */
4257	}
4258#ifndef __Panda__
4259	if (ip_pcb->inp_options) {
4260		(void)sctp_m_free(ip_pcb->inp_options);
4261		ip_pcb->inp_options = 0;
4262	}
4263#endif
4264
4265#if !(defined(__Panda__) || defined(__Windows__) || defined(__Userspace__))
4266#if !defined(__FreeBSD__) || __FreeBSD_version < 500000
4267	if (rt) {
4268		RTFREE(rt);
4269		ip_pcb->inp_route.ro_rt = 0;
4270	}
4271#endif
4272#if defined(__FreeBSD__) && __FreeBSD_version < 803000
4273#ifdef INET
4274	if (ip_pcb->inp_moptions) {
4275		inp_freemoptions(ip_pcb->inp_moptions);
4276		ip_pcb->inp_moptions = 0;
4277	}
4278#endif
4279#endif
4280#endif
4281
4282#ifdef INET6
4283#if !(defined(__Panda__) || defined(__Windows__) || defined(__Userspace__))
4284#if defined(__FreeBSD__) || defined(__APPLE__)
4285	if (ip_pcb->inp_vflag & INP_IPV6) {
4286#else
4287	if (inp->inp_vflag & INP_IPV6) {
4288#endif
4289		struct in6pcb *in6p;
4290
4291		in6p = (struct in6pcb *)inp;
4292		ip6_freepcbopts(in6p->in6p_outputopts);
4293	}
4294#endif
4295#endif				/* INET6 */
4296#if !(defined(__FreeBSD__) || defined(__APPLE__) || defined(__Windows__) || defined(__Userspace__))
4297	inp->inp_vflag = 0;
4298#else
4299	ip_pcb->inp_vflag = 0;
4300#endif
4301	/* free up authentication fields */
4302	if (inp->sctp_ep.local_auth_chunks != NULL)
4303		sctp_free_chunklist(inp->sctp_ep.local_auth_chunks);
4304	if (inp->sctp_ep.local_hmacs != NULL)
4305		sctp_free_hmaclist(inp->sctp_ep.local_hmacs);
4306
4307	LIST_FOREACH_SAFE(shared_key, &inp->sctp_ep.shared_keys, next, nshared_key) {
4308		LIST_REMOVE(shared_key, next);
4309		sctp_free_sharedkey(shared_key);
4310		/*sa_ignore FREED_MEMORY*/
4311	}
4312
4313#if defined(__APPLE__)
4314	inp->ip_inp.inp.inp_state = INPCB_STATE_DEAD;
4315	if (in_pcb_checkstate(&inp->ip_inp.inp, WNT_STOPUSING, 1) != WNT_STOPUSING) {
4316#ifdef INVARIANTS
4317		panic("sctp_inpcb_free inp = %p couldn't set to STOPUSING\n", (void *)inp);
4318#else
4319		SCTP_PRINTF("sctp_inpcb_free inp = %p couldn't set to STOPUSING\n", (void *)inp);
4320#endif
4321	}
4322	inp->ip_inp.inp.inp_socket->so_flags |= SOF_PCBCLEARING;
4323#endif
4324	/*
4325	 * if we have an address list the following will free the list of
4326	 * ifaddr's that are set into this ep. Again macro limitations here,
4327	 * since the LIST_FOREACH could be a bad idea.
4328	 */
4329	LIST_FOREACH_SAFE(laddr, &inp->sctp_addr_list, sctp_nxt_addr, nladdr) {
4330		sctp_remove_laddr(laddr);
4331	}
4332
4333#ifdef SCTP_TRACK_FREED_ASOCS
4334	/* TEMP CODE */
4335	LIST_FOREACH_SAFE(asoc, &inp->sctp_asoc_free_list, sctp_tcblist, nasoc) {
4336		LIST_REMOVE(asoc, sctp_tcblist);
4337		SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_asoc), asoc);
4338		SCTP_DECR_ASOC_COUNT();
4339	}
4340	/* *** END TEMP CODE ****/
4341#endif
4342#ifdef SCTP_MVRF
4343	SCTP_FREE(inp->m_vrf_ids, SCTP_M_MVRF);
4344#endif
4345	/* Now lets see about freeing the EP hash table. */
4346	if (inp->sctp_tcbhash != NULL) {
4347		SCTP_HASH_FREE(inp->sctp_tcbhash, inp->sctp_hashmark);
4348		inp->sctp_tcbhash = NULL;
4349	}
4350	/* Now we must put the ep memory back into the zone pool */
4351#if defined(__FreeBSD__)
4352	crfree(inp->ip_inp.inp.inp_cred);
4353	INP_LOCK_DESTROY(&inp->ip_inp.inp);
4354#endif
4355	SCTP_INP_LOCK_DESTROY(inp);
4356	SCTP_INP_READ_DESTROY(inp);
4357	SCTP_ASOC_CREATE_LOCK_DESTROY(inp);
4358#if !defined(__APPLE__)
4359	SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_ep), inp);
4360	SCTP_DECR_EP_COUNT();
4361#else
4362	/* For Tiger, we will do this later... */
4363#endif
4364}
4365
4366
4367struct sctp_nets *
4368sctp_findnet(struct sctp_tcb *stcb, struct sockaddr *addr)
4369{
4370	struct sctp_nets *net;
4371	/* locate the address */
4372	TAILQ_FOREACH(net, &stcb->asoc.nets, sctp_next) {
4373		if (sctp_cmpaddr(addr, (struct sockaddr *)&net->ro._l_addr))
4374			return (net);
4375	}
4376	return (NULL);
4377}
4378
4379
4380int
4381sctp_is_address_on_local_host(struct sockaddr *addr, uint32_t vrf_id)
4382{
4383#ifdef __Panda__
4384	return (0);
4385#else
4386	struct sctp_ifa *sctp_ifa;
4387	sctp_ifa = sctp_find_ifa_by_addr(addr, vrf_id, SCTP_ADDR_NOT_LOCKED);
4388	if (sctp_ifa) {
4389		return (1);
4390	} else {
4391		return (0);
4392	}
4393#endif
4394}
4395
4396/*
4397 * add's a remote endpoint address, done with the INIT/INIT-ACK as well as
4398 * when a ASCONF arrives that adds it. It will also initialize all the cwnd
4399 * stats of stuff.
4400 */
4401int
4402sctp_add_remote_addr(struct sctp_tcb *stcb, struct sockaddr *newaddr,
4403    struct sctp_nets **netp, int set_scope, int from)
4404{
4405	/*
4406	 * The following is redundant to the same lines in the
4407	 * sctp_aloc_assoc() but is needed since others call the add
4408	 * address function
4409	 */
4410	struct sctp_nets *net, *netfirst;
4411	int addr_inscope;
4412
4413	SCTPDBG(SCTP_DEBUG_PCB1, "Adding an address (from:%d) to the peer: ",
4414		from);
4415	SCTPDBG_ADDR(SCTP_DEBUG_PCB1, newaddr);
4416
4417	netfirst = sctp_findnet(stcb, newaddr);
4418	if (netfirst) {
4419		/*
4420		 * Lie and return ok, we don't want to make the association
4421		 * go away for this behavior. It will happen in the TCP
4422		 * model in a connected socket. It does not reach the hash
4423		 * table until after the association is built so it can't be
4424		 * found. Mark as reachable, since the initial creation will
4425		 * have been cleared and the NOT_IN_ASSOC flag will have
4426		 * been added... and we don't want to end up removing it
4427		 * back out.
4428		 */
4429		if (netfirst->dest_state & SCTP_ADDR_UNCONFIRMED) {
4430			netfirst->dest_state = (SCTP_ADDR_REACHABLE |
4431			    SCTP_ADDR_UNCONFIRMED);
4432		} else {
4433			netfirst->dest_state = SCTP_ADDR_REACHABLE;
4434		}
4435
4436		return (0);
4437	}
4438	addr_inscope = 1;
4439	switch (newaddr->sa_family) {
4440#ifdef INET
4441	case AF_INET:
4442	{
4443		struct sockaddr_in *sin;
4444
4445		sin = (struct sockaddr_in *)newaddr;
4446		if (sin->sin_addr.s_addr == 0) {
4447			/* Invalid address */
4448			return (-1);
4449		}
4450		/* zero out the bzero area */
4451		memset(&sin->sin_zero, 0, sizeof(sin->sin_zero));
4452
4453		/* assure len is set */
4454#ifdef HAVE_SIN_LEN
4455		sin->sin_len = sizeof(struct sockaddr_in);
4456#endif
4457		if (set_scope) {
4458#ifdef SCTP_DONT_DO_PRIVADDR_SCOPE
4459			stcb->asoc.scope.ipv4_local_scope = 1;
4460#else
4461			if (IN4_ISPRIVATE_ADDRESS(&sin->sin_addr)) {
4462				stcb->asoc.scope.ipv4_local_scope = 1;
4463			}
4464#endif				/* SCTP_DONT_DO_PRIVADDR_SCOPE */
4465		} else {
4466			/* Validate the address is in scope */
4467			if ((IN4_ISPRIVATE_ADDRESS(&sin->sin_addr)) &&
4468			    (stcb->asoc.scope.ipv4_local_scope == 0)) {
4469				addr_inscope = 0;
4470			}
4471		}
4472		break;
4473	}
4474#endif
4475#ifdef INET6
4476	case AF_INET6:
4477	{
4478		struct sockaddr_in6 *sin6;
4479
4480		sin6 = (struct sockaddr_in6 *)newaddr;
4481		if (IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr)) {
4482			/* Invalid address */
4483			return (-1);
4484		}
4485		/* assure len is set */
4486#ifdef HAVE_SIN6_LEN
4487		sin6->sin6_len = sizeof(struct sockaddr_in6);
4488#endif
4489		if (set_scope) {
4490			if (sctp_is_address_on_local_host(newaddr, stcb->asoc.vrf_id)) {
4491				stcb->asoc.scope.loopback_scope = 1;
4492				stcb->asoc.scope.local_scope = 0;
4493				stcb->asoc.scope.ipv4_local_scope = 1;
4494				stcb->asoc.scope.site_scope = 1;
4495			} else if (IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr)) {
4496				/*
4497				 * If the new destination is a LINK_LOCAL we
4498				 * must have common site scope. Don't set
4499				 * the local scope since we may not share
4500				 * all links, only loopback can do this.
4501				 * Links on the local network would also be
4502				 * on our private network for v4 too.
4503				 */
4504				stcb->asoc.scope.ipv4_local_scope = 1;
4505				stcb->asoc.scope.site_scope = 1;
4506			} else if (IN6_IS_ADDR_SITELOCAL(&sin6->sin6_addr)) {
4507				/*
4508				 * If the new destination is SITE_LOCAL then
4509				 * we must have site scope in common.
4510				 */
4511				stcb->asoc.scope.site_scope = 1;
4512			}
4513		} else {
4514			/* Validate the address is in scope */
4515			if (IN6_IS_ADDR_LOOPBACK(&sin6->sin6_addr) &&
4516			    (stcb->asoc.scope.loopback_scope == 0)) {
4517				addr_inscope = 0;
4518			} else if (IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr) &&
4519			    (stcb->asoc.scope.local_scope == 0)) {
4520				addr_inscope = 0;
4521			} else if (IN6_IS_ADDR_SITELOCAL(&sin6->sin6_addr) &&
4522			    (stcb->asoc.scope.site_scope == 0)) {
4523				addr_inscope = 0;
4524			}
4525		}
4526		break;
4527	}
4528#endif
4529#if defined(__Userspace__)
4530	case AF_CONN:
4531	{
4532		struct sockaddr_conn *sconn;
4533
4534		sconn = (struct sockaddr_conn *)newaddr;
4535		if (sconn->sconn_addr == NULL) {
4536			/* Invalid address */
4537			return (-1);
4538		}
4539#ifdef HAVE_SCONN_LEN
4540		sconn->sconn_len = sizeof(struct sockaddr_conn);
4541#endif
4542		break;
4543	}
4544#endif
4545	default:
4546		/* not supported family type */
4547		return (-1);
4548	}
4549	net = SCTP_ZONE_GET(SCTP_BASE_INFO(ipi_zone_net), struct sctp_nets);
4550	if (net == NULL) {
4551		return (-1);
4552	}
4553	SCTP_INCR_RADDR_COUNT();
4554	bzero(net, sizeof(struct sctp_nets));
4555	(void)SCTP_GETTIME_TIMEVAL(&net->start_time);
4556#ifdef HAVE_SA_LEN
4557	memcpy(&net->ro._l_addr, newaddr, newaddr->sa_len);
4558#endif
4559	switch (newaddr->sa_family) {
4560#ifdef INET
4561	case AF_INET:
4562#ifndef HAVE_SA_LEN
4563		memcpy(&net->ro._l_addr, newaddr, sizeof(struct sockaddr_in));
4564#endif
4565		((struct sockaddr_in *)&net->ro._l_addr)->sin_port = stcb->rport;
4566		break;
4567#endif
4568#ifdef INET6
4569	case AF_INET6:
4570#ifndef HAVE_SA_LEN
4571		memcpy(&net->ro._l_addr, newaddr, sizeof(struct sockaddr_in6));
4572#endif
4573		((struct sockaddr_in6 *)&net->ro._l_addr)->sin6_port = stcb->rport;
4574		break;
4575#endif
4576#if defined(__Userspace__)
4577	case AF_CONN:
4578#ifndef HAVE_SA_LEN
4579		memcpy(&net->ro._l_addr, newaddr, sizeof(struct sockaddr_conn));
4580#endif
4581		((struct sockaddr_conn *)&net->ro._l_addr)->sconn_port = stcb->rport;
4582		break;
4583#endif
4584	default:
4585		break;
4586	}
4587	net->addr_is_local = sctp_is_address_on_local_host(newaddr, stcb->asoc.vrf_id);
4588	if (net->addr_is_local && ((set_scope || (from == SCTP_ADDR_IS_CONFIRMED)))) {
4589		stcb->asoc.scope.loopback_scope = 1;
4590		stcb->asoc.scope.ipv4_local_scope = 1;
4591		stcb->asoc.scope.local_scope = 0;
4592		stcb->asoc.scope.site_scope = 1;
4593		addr_inscope = 1;
4594	}
4595	net->failure_threshold = stcb->asoc.def_net_failure;
4596	net->pf_threshold = stcb->asoc.def_net_pf_threshold;
4597	if (addr_inscope == 0) {
4598		net->dest_state = (SCTP_ADDR_REACHABLE |
4599		    SCTP_ADDR_OUT_OF_SCOPE);
4600	} else {
4601		if (from == SCTP_ADDR_IS_CONFIRMED)
4602			/* SCTP_ADDR_IS_CONFIRMED is passed by connect_x */
4603			net->dest_state = SCTP_ADDR_REACHABLE;
4604		else
4605			net->dest_state = SCTP_ADDR_REACHABLE |
4606			    SCTP_ADDR_UNCONFIRMED;
4607	}
4608	/* We set this to 0, the timer code knows that
4609	 * this means its an initial value
4610	 */
4611	net->rto_needed = 1;
4612	net->RTO = 0;
4613	net->RTO_measured = 0;
4614	stcb->asoc.numnets++;
4615	net->ref_count = 1;
4616	net->cwr_window_tsn = net->last_cwr_tsn = stcb->asoc.sending_seq - 1;
4617	net->port = stcb->asoc.port;
4618	net->dscp = stcb->asoc.default_dscp;
4619#ifdef INET6
4620	net->flowlabel = stcb->asoc.default_flowlabel;
4621#endif
4622	if (sctp_stcb_is_feature_on(stcb->sctp_ep, stcb, SCTP_PCB_FLAGS_DONOT_HEARTBEAT)) {
4623		net->dest_state |= SCTP_ADDR_NOHB;
4624	} else {
4625		net->dest_state &= ~SCTP_ADDR_NOHB;
4626	}
4627	if (sctp_stcb_is_feature_on(stcb->sctp_ep, stcb, SCTP_PCB_FLAGS_DO_NOT_PMTUD)) {
4628		net->dest_state |= SCTP_ADDR_NO_PMTUD;
4629	} else {
4630		net->dest_state &= ~SCTP_ADDR_NO_PMTUD;
4631	}
4632	net->heart_beat_delay = stcb->asoc.heart_beat_delay;
4633	/* Init the timer structure */
4634	SCTP_OS_TIMER_INIT(&net->rxt_timer.timer);
4635	SCTP_OS_TIMER_INIT(&net->pmtu_timer.timer);
4636	SCTP_OS_TIMER_INIT(&net->hb_timer.timer);
4637
4638	/* Now generate a route for this guy */
4639#ifdef INET6
4640#ifdef SCTP_EMBEDDED_V6_SCOPE
4641	/* KAME hack: embed scopeid */
4642	if (newaddr->sa_family == AF_INET6) {
4643		struct sockaddr_in6 *sin6;
4644
4645		sin6 = (struct sockaddr_in6 *)&net->ro._l_addr;
4646#if defined(__APPLE__)
4647#if defined(APPLE_LEOPARD) || defined(APPLE_SNOWLEOPARD)
4648		(void)in6_embedscope(&sin6->sin6_addr, sin6, &stcb->sctp_ep->ip_inp.inp, NULL);
4649#else
4650		(void)in6_embedscope(&sin6->sin6_addr, sin6, &stcb->sctp_ep->ip_inp.inp, NULL, NULL);
4651#endif
4652#elif defined(SCTP_KAME)
4653		(void)sa6_embedscope(sin6, MODULE_GLOBAL(ip6_use_defzone));
4654#else
4655		(void)in6_embedscope(&sin6->sin6_addr, sin6);
4656#endif
4657#ifndef SCOPEDROUTING
4658		sin6->sin6_scope_id = 0;
4659#endif
4660	}
4661#endif /* SCTP_EMBEDDED_V6_SCOPE */
4662#endif
4663	SCTP_RTALLOC((sctp_route_t *)&net->ro, stcb->asoc.vrf_id);
4664
4665#if defined(__Userspace__)
4666	net->src_addr_selected = 0;
4667#else
4668	if (SCTP_ROUTE_HAS_VALID_IFN(&net->ro)) {
4669		/* Get source address */
4670		net->ro._s_addr = sctp_source_address_selection(stcb->sctp_ep,
4671								stcb,
4672								(sctp_route_t *)&net->ro,
4673								net,
4674								0,
4675								stcb->asoc.vrf_id);
4676		if (net->ro._s_addr != NULL) {
4677			net->src_addr_selected = 1;
4678			/* Now get the interface MTU */
4679			if (net->ro._s_addr->ifn_p != NULL) {
4680				net->mtu = SCTP_GATHER_MTU_FROM_INTFC(net->ro._s_addr->ifn_p);
4681			}
4682		} else {
4683			net->src_addr_selected = 0;
4684		}
4685		if (net->mtu > 0) {
4686			uint32_t rmtu;
4687
4688			rmtu = SCTP_GATHER_MTU_FROM_ROUTE(net->ro._s_addr, &net->ro._l_addr.sa, net->ro.ro_rt);
4689			if (rmtu == 0) {
4690				/* Start things off to match mtu of interface please. */
4691				SCTP_SET_MTU_OF_ROUTE(&net->ro._l_addr.sa,
4692						      net->ro.ro_rt, net->mtu);
4693			} else {
4694				/* we take the route mtu over the interface, since
4695				 * the route may be leading out the loopback, or
4696				 * a different interface.
4697				 */
4698				net->mtu = rmtu;
4699			}
4700		}
4701	} else {
4702		net->src_addr_selected = 0;
4703	}
4704#endif
4705	if (net->mtu == 0) {
4706		switch (newaddr->sa_family) {
4707#ifdef INET
4708		case AF_INET:
4709			net->mtu = SCTP_DEFAULT_MTU;
4710			break;
4711#endif
4712#ifdef INET6
4713		case AF_INET6:
4714			net->mtu = 1280;
4715			break;
4716#endif
4717#if defined(__Userspace__)
4718		case AF_CONN:
4719			net->mtu = 1280;
4720			break;
4721#endif
4722		default:
4723			break;
4724		}
4725	}
4726#if defined(INET) || defined(INET6)
4727	if (net->port) {
4728		net->mtu -= (uint32_t)sizeof(struct udphdr);
4729	}
4730#endif
4731	if (from == SCTP_ALLOC_ASOC) {
4732		stcb->asoc.smallest_mtu = net->mtu;
4733	}
4734	if (stcb->asoc.smallest_mtu > net->mtu) {
4735		stcb->asoc.smallest_mtu = net->mtu;
4736	}
4737#ifdef INET6
4738#ifdef SCTP_EMBEDDED_V6_SCOPE
4739	if (newaddr->sa_family == AF_INET6) {
4740		struct sockaddr_in6 *sin6;
4741
4742		sin6 = (struct sockaddr_in6 *)&net->ro._l_addr;
4743#ifdef SCTP_KAME
4744		(void)sa6_recoverscope(sin6);
4745#else
4746		(void)in6_recoverscope(sin6, &sin6->sin6_addr, NULL);
4747#endif /* SCTP_KAME */
4748	}
4749#endif /* SCTP_EMBEDDED_V6_SCOPE */
4750#endif
4751
4752	/* JRS - Use the congestion control given in the CC module */
4753	if (stcb->asoc.cc_functions.sctp_set_initial_cc_param != NULL)
4754		(*stcb->asoc.cc_functions.sctp_set_initial_cc_param)(stcb, net);
4755
4756	/*
4757	 * CMT: CUC algo - set find_pseudo_cumack to TRUE (1) at beginning
4758	 * of assoc (2005/06/27, iyengar@cis.udel.edu)
4759	 */
4760	net->find_pseudo_cumack = 1;
4761	net->find_rtx_pseudo_cumack = 1;
4762#if defined(__FreeBSD__)
4763	/* Choose an initial flowid. */
4764	net->flowid = stcb->asoc.my_vtag ^
4765	              ntohs(stcb->rport) ^
4766	              ntohs(stcb->sctp_ep->sctp_lport);
4767#ifdef INVARIANTS
4768	net->flowidset = 1;
4769#endif
4770#endif
4771	if (netp) {
4772		*netp = net;
4773	}
4774	netfirst = TAILQ_FIRST(&stcb->asoc.nets);
4775	if (net->ro.ro_rt == NULL) {
4776		/* Since we have no route put it at the back */
4777		TAILQ_INSERT_TAIL(&stcb->asoc.nets, net, sctp_next);
4778	} else if (netfirst == NULL) {
4779		/* We are the first one in the pool. */
4780		TAILQ_INSERT_HEAD(&stcb->asoc.nets, net, sctp_next);
4781	} else if (netfirst->ro.ro_rt == NULL) {
4782		/*
4783		 * First one has NO route. Place this one ahead of the first
4784		 * one.
4785		 */
4786		TAILQ_INSERT_HEAD(&stcb->asoc.nets, net, sctp_next);
4787#ifndef __Panda__
4788	} else if (net->ro.ro_rt->rt_ifp != netfirst->ro.ro_rt->rt_ifp) {
4789		/*
4790		 * This one has a different interface than the one at the
4791		 * top of the list. Place it ahead.
4792		 */
4793		TAILQ_INSERT_HEAD(&stcb->asoc.nets, net, sctp_next);
4794#endif
4795	} else {
4796		/*
4797		 * Ok we have the same interface as the first one. Move
4798		 * forward until we find either a) one with a NULL route...
4799		 * insert ahead of that b) one with a different ifp.. insert
4800		 * after that. c) end of the list.. insert at the tail.
4801		 */
4802		struct sctp_nets *netlook;
4803
4804		do {
4805			netlook = TAILQ_NEXT(netfirst, sctp_next);
4806			if (netlook == NULL) {
4807				/* End of the list */
4808				TAILQ_INSERT_TAIL(&stcb->asoc.nets, net, sctp_next);
4809				break;
4810			} else if (netlook->ro.ro_rt == NULL) {
4811				/* next one has NO route */
4812				TAILQ_INSERT_BEFORE(netfirst, net, sctp_next);
4813				break;
4814			}
4815#ifndef __Panda__
4816			else if (netlook->ro.ro_rt->rt_ifp != net->ro.ro_rt->rt_ifp)
4817#else
4818			else
4819#endif
4820			{
4821				TAILQ_INSERT_AFTER(&stcb->asoc.nets, netlook,
4822						   net, sctp_next);
4823				break;
4824			}
4825#ifndef __Panda__
4826			/* Shift forward */
4827			netfirst = netlook;
4828#endif
4829		} while (netlook != NULL);
4830	}
4831
4832	/* got to have a primary set */
4833	if (stcb->asoc.primary_destination == 0) {
4834		stcb->asoc.primary_destination = net;
4835	} else if ((stcb->asoc.primary_destination->ro.ro_rt == NULL) &&
4836		    (net->ro.ro_rt) &&
4837	    ((net->dest_state & SCTP_ADDR_UNCONFIRMED) == 0)) {
4838		/* No route to current primary adopt new primary */
4839		stcb->asoc.primary_destination = net;
4840	}
4841	/* Validate primary is first */
4842	net = TAILQ_FIRST(&stcb->asoc.nets);
4843	if ((net != stcb->asoc.primary_destination) &&
4844	    (stcb->asoc.primary_destination)) {
4845		/* first one on the list is NOT the primary
4846		 * sctp_cmpaddr() is much more efficient if
4847		 * the primary is the first on the list, make it
4848		 * so.
4849		 */
4850		TAILQ_REMOVE(&stcb->asoc.nets,
4851			     stcb->asoc.primary_destination, sctp_next);
4852		TAILQ_INSERT_HEAD(&stcb->asoc.nets,
4853				  stcb->asoc.primary_destination, sctp_next);
4854	}
4855	return (0);
4856}
4857
4858
4859static uint32_t
4860sctp_aloc_a_assoc_id(struct sctp_inpcb *inp, struct sctp_tcb *stcb)
4861{
4862	uint32_t id;
4863	struct sctpasochead *head;
4864	struct sctp_tcb *lstcb;
4865
4866	SCTP_INP_WLOCK(inp);
4867 try_again:
4868	if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) {
4869		/* TSNH */
4870		SCTP_INP_WUNLOCK(inp);
4871		return (0);
4872	}
4873	/*
4874	 * We don't allow assoc id to be one of SCTP_FUTURE_ASSOC,
4875	 * SCTP_CURRENT_ASSOC and SCTP_ALL_ASSOC.
4876	 */
4877	if (inp->sctp_associd_counter <= SCTP_ALL_ASSOC) {
4878		inp->sctp_associd_counter = SCTP_ALL_ASSOC + 1;
4879	}
4880	id = inp->sctp_associd_counter;
4881	inp->sctp_associd_counter++;
4882	lstcb = sctp_findasoc_ep_asocid_locked(inp, (sctp_assoc_t)id, 0);
4883	if (lstcb) {
4884		goto try_again;
4885	}
4886	head = &inp->sctp_asocidhash[SCTP_PCBHASH_ASOC(id, inp->hashasocidmark)];
4887	LIST_INSERT_HEAD(head, stcb, sctp_tcbasocidhash);
4888	stcb->asoc.in_asocid_hash = 1;
4889	SCTP_INP_WUNLOCK(inp);
4890	return id;
4891}
4892
4893/*
4894 * allocate an association and add it to the endpoint. The caller must be
4895 * careful to add all additional addresses once they are know right away or
4896 * else the assoc will be may experience a blackout scenario.
4897 */
4898struct sctp_tcb *
4899sctp_aloc_assoc(struct sctp_inpcb *inp, struct sockaddr *firstaddr,
4900		int *error, uint32_t override_tag, uint32_t vrf_id,
4901#if defined(__FreeBSD__) && __FreeBSD_version >= 500000
4902		struct thread *p
4903#elif defined(__Windows__)
4904		PKTHREAD p
4905#else
4906#if defined(__Userspace__)
4907                /*  __Userspace__ NULL proc is going to be passed here. See sctp_lower_sosend */
4908#endif
4909		struct proc *p
4910#endif
4911)
4912{
4913	/* note the p argument is only valid in unbound sockets */
4914
4915	struct sctp_tcb *stcb;
4916	struct sctp_association *asoc;
4917	struct sctpasochead *head;
4918	uint16_t rport;
4919	int err;
4920
4921	/*
4922	 * Assumption made here: Caller has done a
4923	 * sctp_findassociation_ep_addr(ep, addr's); to make sure the
4924	 * address does not exist already.
4925	 */
4926	if (SCTP_BASE_INFO(ipi_count_asoc) >= SCTP_MAX_NUM_OF_ASOC) {
4927		/* Hit max assoc, sorry no more */
4928		SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, ENOBUFS);
4929		*error = ENOBUFS;
4930		return (NULL);
4931	}
4932	if (firstaddr == NULL) {
4933		SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
4934		*error = EINVAL;
4935		return (NULL);
4936	}
4937	SCTP_INP_RLOCK(inp);
4938	if ((inp->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL) &&
4939	    ((sctp_is_feature_off(inp, SCTP_PCB_FLAGS_PORTREUSE)) ||
4940	     (inp->sctp_flags & SCTP_PCB_FLAGS_CONNECTED))) {
4941		/*
4942		 * If its in the TCP pool, its NOT allowed to create an
4943		 * association. The parent listener needs to call
4944		 * sctp_aloc_assoc.. or the one-2-many socket. If a peeled
4945		 * off, or connected one does this.. its an error.
4946		 */
4947		SCTP_INP_RUNLOCK(inp);
4948		SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
4949		*error = EINVAL;
4950		return (NULL);
4951	}
4952	if ((inp->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL) ||
4953	    (inp->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE)) {
4954		if ((inp->sctp_flags & SCTP_PCB_FLAGS_WAS_CONNECTED) ||
4955		    (inp->sctp_flags & SCTP_PCB_FLAGS_WAS_ABORTED)) {
4956			SCTP_INP_RUNLOCK(inp);
4957			SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
4958			*error = EINVAL;
4959			return (NULL);
4960		}
4961	}
4962	SCTPDBG(SCTP_DEBUG_PCB3, "Allocate an association for peer:");
4963#ifdef SCTP_DEBUG
4964	if (firstaddr) {
4965		SCTPDBG_ADDR(SCTP_DEBUG_PCB3, firstaddr);
4966		switch (firstaddr->sa_family) {
4967#ifdef INET
4968		case AF_INET:
4969			SCTPDBG(SCTP_DEBUG_PCB3, "Port:%d\n",
4970			        ntohs(((struct sockaddr_in *)firstaddr)->sin_port));
4971			break;
4972#endif
4973#ifdef INET6
4974		case AF_INET6:
4975			SCTPDBG(SCTP_DEBUG_PCB3, "Port:%d\n",
4976			        ntohs(((struct sockaddr_in6 *)firstaddr)->sin6_port));
4977			break;
4978#endif
4979#if defined(__Userspace__)
4980		case AF_CONN:
4981			SCTPDBG(SCTP_DEBUG_PCB3, "Port:%d\n",
4982			        ntohs(((struct sockaddr_conn *)firstaddr)->sconn_port));
4983			break;
4984#endif
4985		default:
4986			break;
4987		}
4988	} else {
4989		SCTPDBG(SCTP_DEBUG_PCB3,"None\n");
4990	}
4991#endif				/* SCTP_DEBUG */
4992	switch (firstaddr->sa_family) {
4993#ifdef INET
4994	case AF_INET:
4995	{
4996		struct sockaddr_in *sin;
4997
4998		sin = (struct sockaddr_in *)firstaddr;
4999		if ((ntohs(sin->sin_port) == 0) ||
5000		    (sin->sin_addr.s_addr == INADDR_ANY) ||
5001		    (sin->sin_addr.s_addr == INADDR_BROADCAST) ||
5002		    IN_MULTICAST(ntohl(sin->sin_addr.s_addr))) {
5003			/* Invalid address */
5004			SCTP_INP_RUNLOCK(inp);
5005			SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
5006			*error = EINVAL;
5007			return (NULL);
5008		}
5009		rport = sin->sin_port;
5010		break;
5011	}
5012#endif
5013#ifdef INET6
5014	case AF_INET6:
5015	{
5016		struct sockaddr_in6 *sin6;
5017
5018		sin6 = (struct sockaddr_in6 *)firstaddr;
5019		if ((ntohs(sin6->sin6_port) == 0) ||
5020		    IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr) ||
5021		    IN6_IS_ADDR_MULTICAST(&sin6->sin6_addr)) {
5022			/* Invalid address */
5023			SCTP_INP_RUNLOCK(inp);
5024			SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
5025			*error = EINVAL;
5026			return (NULL);
5027		}
5028		rport = sin6->sin6_port;
5029		break;
5030	}
5031#endif
5032#if defined(__Userspace__)
5033	case AF_CONN:
5034	{
5035		struct sockaddr_conn *sconn;
5036
5037		sconn = (struct sockaddr_conn *)firstaddr;
5038		if ((ntohs(sconn->sconn_port) == 0) ||
5039		    (sconn->sconn_addr == NULL)) {
5040			/* Invalid address */
5041			SCTP_INP_RUNLOCK(inp);
5042			SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
5043			*error = EINVAL;
5044			return (NULL);
5045		}
5046		rport = sconn->sconn_port;
5047		break;
5048	}
5049#endif
5050	default:
5051		/* not supported family type */
5052		SCTP_INP_RUNLOCK(inp);
5053		SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
5054		*error = EINVAL;
5055		return (NULL);
5056	}
5057	SCTP_INP_RUNLOCK(inp);
5058	if (inp->sctp_flags & SCTP_PCB_FLAGS_UNBOUND) {
5059		/*
5060		 * If you have not performed a bind, then we need to do the
5061		 * ephemeral bind for you.
5062		 */
5063		if ((err = sctp_inpcb_bind(inp->sctp_socket,
5064		    (struct sockaddr *)NULL,
5065		    (struct sctp_ifa *)NULL,
5066#ifndef __Panda__
5067					   p
5068#else
5069					   (struct proc *)NULL
5070#endif
5071		    ))) {
5072			/* bind error, probably perm */
5073			*error = err;
5074			return (NULL);
5075		}
5076	}
5077	stcb = SCTP_ZONE_GET(SCTP_BASE_INFO(ipi_zone_asoc), struct sctp_tcb);
5078	if (stcb == NULL) {
5079		/* out of memory? */
5080		SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, ENOMEM);
5081		*error = ENOMEM;
5082		return (NULL);
5083	}
5084	SCTP_INCR_ASOC_COUNT();
5085
5086	bzero(stcb, sizeof(*stcb));
5087	asoc = &stcb->asoc;
5088
5089	asoc->assoc_id = sctp_aloc_a_assoc_id(inp, stcb);
5090	SCTP_TCB_LOCK_INIT(stcb);
5091	SCTP_TCB_SEND_LOCK_INIT(stcb);
5092	stcb->rport = rport;
5093	/* setup back pointer's */
5094	stcb->sctp_ep = inp;
5095	stcb->sctp_socket = inp->sctp_socket;
5096	if ((err = sctp_init_asoc(inp, stcb, override_tag, vrf_id))) {
5097		/* failed */
5098		SCTP_TCB_LOCK_DESTROY(stcb);
5099		SCTP_TCB_SEND_LOCK_DESTROY(stcb);
5100		LIST_REMOVE(stcb, sctp_tcbasocidhash);
5101		SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_asoc), stcb);
5102		SCTP_DECR_ASOC_COUNT();
5103		*error = err;
5104		return (NULL);
5105	}
5106	/* and the port */
5107	SCTP_INP_INFO_WLOCK();
5108	SCTP_INP_WLOCK(inp);
5109	if (inp->sctp_flags & (SCTP_PCB_FLAGS_SOCKET_GONE | SCTP_PCB_FLAGS_SOCKET_ALLGONE)) {
5110		/* inpcb freed while alloc going on */
5111		SCTP_TCB_LOCK_DESTROY(stcb);
5112		SCTP_TCB_SEND_LOCK_DESTROY(stcb);
5113		LIST_REMOVE(stcb, sctp_tcbasocidhash);
5114		SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_asoc), stcb);
5115		SCTP_INP_WUNLOCK(inp);
5116		SCTP_INP_INFO_WUNLOCK();
5117		SCTP_DECR_ASOC_COUNT();
5118		SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
5119		*error = EINVAL;
5120		return (NULL);
5121	}
5122	SCTP_TCB_LOCK(stcb);
5123
5124	/* now that my_vtag is set, add it to the hash */
5125	head = &SCTP_BASE_INFO(sctp_asochash)[SCTP_PCBHASH_ASOC(stcb->asoc.my_vtag, SCTP_BASE_INFO(hashasocmark))];
5126	/* put it in the bucket in the vtag hash of assoc's for the system */
5127	LIST_INSERT_HEAD(head, stcb, sctp_asocs);
5128	SCTP_INP_INFO_WUNLOCK();
5129
5130	if ((err = sctp_add_remote_addr(stcb, firstaddr, NULL, SCTP_DO_SETSCOPE, SCTP_ALLOC_ASOC))) {
5131		/* failure.. memory error? */
5132		if (asoc->strmout) {
5133			SCTP_FREE(asoc->strmout, SCTP_M_STRMO);
5134			asoc->strmout = NULL;
5135		}
5136		if (asoc->mapping_array) {
5137			SCTP_FREE(asoc->mapping_array, SCTP_M_MAP);
5138			asoc->mapping_array = NULL;
5139		}
5140		if (asoc->nr_mapping_array) {
5141			SCTP_FREE(asoc->nr_mapping_array, SCTP_M_MAP);
5142			asoc->nr_mapping_array = NULL;
5143		}
5144		SCTP_DECR_ASOC_COUNT();
5145		SCTP_TCB_UNLOCK(stcb);
5146		SCTP_TCB_LOCK_DESTROY(stcb);
5147		SCTP_TCB_SEND_LOCK_DESTROY(stcb);
5148		LIST_REMOVE(stcb, sctp_tcbasocidhash);
5149		SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_asoc), stcb);
5150		SCTP_INP_WUNLOCK(inp);
5151		SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, ENOBUFS);
5152		*error = ENOBUFS;
5153		return (NULL);
5154	}
5155	/* Init all the timers */
5156	SCTP_OS_TIMER_INIT(&asoc->dack_timer.timer);
5157	SCTP_OS_TIMER_INIT(&asoc->strreset_timer.timer);
5158	SCTP_OS_TIMER_INIT(&asoc->asconf_timer.timer);
5159	SCTP_OS_TIMER_INIT(&asoc->shut_guard_timer.timer);
5160	SCTP_OS_TIMER_INIT(&asoc->autoclose_timer.timer);
5161	SCTP_OS_TIMER_INIT(&asoc->delayed_event_timer.timer);
5162	SCTP_OS_TIMER_INIT(&asoc->delete_prim_timer.timer);
5163
5164	LIST_INSERT_HEAD(&inp->sctp_asoc_list, stcb, sctp_tcblist);
5165	/* now file the port under the hash as well */
5166	if (inp->sctp_tcbhash != NULL) {
5167		head = &inp->sctp_tcbhash[SCTP_PCBHASH_ALLADDR(stcb->rport,
5168		    inp->sctp_hashmark)];
5169		LIST_INSERT_HEAD(head, stcb, sctp_tcbhash);
5170	}
5171	SCTP_INP_WUNLOCK(inp);
5172	SCTPDBG(SCTP_DEBUG_PCB1, "Association %p now allocated\n", (void *)stcb);
5173	return (stcb);
5174}
5175
5176
5177void
5178sctp_remove_net(struct sctp_tcb *stcb, struct sctp_nets *net)
5179{
5180	struct sctp_association *asoc;
5181
5182	asoc = &stcb->asoc;
5183	asoc->numnets--;
5184	TAILQ_REMOVE(&asoc->nets, net, sctp_next);
5185	if (net == asoc->primary_destination) {
5186		/* Reset primary */
5187		struct sctp_nets *lnet;
5188
5189		lnet = TAILQ_FIRST(&asoc->nets);
5190		/* Mobility adaptation
5191		   Ideally, if deleted destination is the primary, it becomes
5192		   a fast retransmission trigger by the subsequent SET PRIMARY.
5193		   (by micchie)
5194		 */
5195		if (sctp_is_mobility_feature_on(stcb->sctp_ep,
5196		                                SCTP_MOBILITY_BASE) ||
5197		    sctp_is_mobility_feature_on(stcb->sctp_ep,
5198		                                SCTP_MOBILITY_FASTHANDOFF)) {
5199			SCTPDBG(SCTP_DEBUG_ASCONF1, "remove_net: primary dst is deleting\n");
5200			if (asoc->deleted_primary != NULL) {
5201				SCTPDBG(SCTP_DEBUG_ASCONF1, "remove_net: deleted primary may be already stored\n");
5202				goto out;
5203			}
5204			asoc->deleted_primary = net;
5205			atomic_add_int(&net->ref_count, 1);
5206			memset(&net->lastsa, 0, sizeof(net->lastsa));
5207			memset(&net->lastsv, 0, sizeof(net->lastsv));
5208			sctp_mobility_feature_on(stcb->sctp_ep,
5209						 SCTP_MOBILITY_PRIM_DELETED);
5210			sctp_timer_start(SCTP_TIMER_TYPE_PRIM_DELETED,
5211					 stcb->sctp_ep, stcb, NULL);
5212		}
5213out:
5214		/* Try to find a confirmed primary */
5215		asoc->primary_destination = sctp_find_alternate_net(stcb, lnet, 0);
5216	}
5217	if (net == asoc->last_data_chunk_from) {
5218		/* Reset primary */
5219		asoc->last_data_chunk_from = TAILQ_FIRST(&asoc->nets);
5220	}
5221	if (net == asoc->last_control_chunk_from) {
5222		/* Clear net */
5223		asoc->last_control_chunk_from = NULL;
5224	}
5225	if (net == stcb->asoc.alternate) {
5226		sctp_free_remote_addr(stcb->asoc.alternate);
5227		stcb->asoc.alternate = NULL;
5228	}
5229	sctp_free_remote_addr(net);
5230}
5231
5232/*
5233 * remove a remote endpoint address from an association, it will fail if the
5234 * address does not exist.
5235 */
5236int
5237sctp_del_remote_addr(struct sctp_tcb *stcb, struct sockaddr *remaddr)
5238{
5239	/*
5240	 * Here we need to remove a remote address. This is quite simple, we
5241	 * first find it in the list of address for the association
5242	 * (tasoc->asoc.nets) and then if it is there, we do a LIST_REMOVE
5243	 * on that item. Note we do not allow it to be removed if there are
5244	 * no other addresses.
5245	 */
5246	struct sctp_association *asoc;
5247	struct sctp_nets *net, *nnet;
5248
5249	asoc = &stcb->asoc;
5250
5251	/* locate the address */
5252	TAILQ_FOREACH_SAFE(net, &asoc->nets, sctp_next, nnet) {
5253		if (net->ro._l_addr.sa.sa_family != remaddr->sa_family) {
5254			continue;
5255		}
5256		if (sctp_cmpaddr((struct sockaddr *)&net->ro._l_addr,
5257		    remaddr)) {
5258			/* we found the guy */
5259			if (asoc->numnets < 2) {
5260				/* Must have at LEAST two remote addresses */
5261				return (-1);
5262			} else {
5263				sctp_remove_net(stcb, net);
5264				return (0);
5265			}
5266		}
5267	}
5268	/* not found. */
5269	return (-2);
5270}
5271
5272void
5273sctp_delete_from_timewait(uint32_t tag, uint16_t lport, uint16_t rport)
5274{
5275	struct sctpvtaghead *chain;
5276	struct sctp_tagblock *twait_block;
5277	int found = 0;
5278	int i;
5279
5280	chain = &SCTP_BASE_INFO(vtag_timewait)[(tag % SCTP_STACK_VTAG_HASH_SIZE)];
5281	LIST_FOREACH(twait_block, chain, sctp_nxt_tagblock) {
5282		for (i = 0; i < SCTP_NUMBER_IN_VTAG_BLOCK; i++) {
5283		  if ((twait_block->vtag_block[i].v_tag == tag) &&
5284		      (twait_block->vtag_block[i].lport == lport) &&
5285		      (twait_block->vtag_block[i].rport == rport)) {
5286				twait_block->vtag_block[i].tv_sec_at_expire = 0;
5287				twait_block->vtag_block[i].v_tag = 0;
5288				twait_block->vtag_block[i].lport = 0;
5289				twait_block->vtag_block[i].rport = 0;
5290				found = 1;
5291				break;
5292			}
5293		}
5294		if (found)
5295			break;
5296	}
5297}
5298
5299int
5300sctp_is_in_timewait(uint32_t tag, uint16_t lport, uint16_t rport)
5301{
5302	struct sctpvtaghead *chain;
5303	struct sctp_tagblock *twait_block;
5304	int found = 0;
5305	int i;
5306
5307	SCTP_INP_INFO_WLOCK();
5308	chain = &SCTP_BASE_INFO(vtag_timewait)[(tag % SCTP_STACK_VTAG_HASH_SIZE)];
5309	LIST_FOREACH(twait_block, chain, sctp_nxt_tagblock) {
5310		for (i = 0; i < SCTP_NUMBER_IN_VTAG_BLOCK; i++) {
5311			if ((twait_block->vtag_block[i].v_tag == tag)  &&
5312			    (twait_block->vtag_block[i].lport == lport)  &&
5313			    (twait_block->vtag_block[i].rport == rport)) {
5314				found = 1;
5315				break;
5316			}
5317		}
5318		if (found)
5319			break;
5320	}
5321	SCTP_INP_INFO_WUNLOCK();
5322	return (found);
5323}
5324
5325
5326void
5327sctp_add_vtag_to_timewait(uint32_t tag, uint32_t time, uint16_t lport, uint16_t rport)
5328{
5329	struct sctpvtaghead *chain;
5330	struct sctp_tagblock *twait_block;
5331	struct timeval now;
5332	int set, i;
5333
5334	if (time == 0) {
5335		/* Its disabled */
5336		return;
5337	}
5338	(void)SCTP_GETTIME_TIMEVAL(&now);
5339	chain = &SCTP_BASE_INFO(vtag_timewait)[(tag % SCTP_STACK_VTAG_HASH_SIZE)];
5340	set = 0;
5341	LIST_FOREACH(twait_block, chain, sctp_nxt_tagblock) {
5342		/* Block(s) present, lets find space, and expire on the fly */
5343		for (i = 0; i < SCTP_NUMBER_IN_VTAG_BLOCK; i++) {
5344			if ((twait_block->vtag_block[i].v_tag == 0) &&
5345			    !set) {
5346				twait_block->vtag_block[i].tv_sec_at_expire =
5347					now.tv_sec + time;
5348				twait_block->vtag_block[i].v_tag = tag;
5349				twait_block->vtag_block[i].lport = lport;
5350				twait_block->vtag_block[i].rport = rport;
5351				set = 1;
5352			} else if ((twait_block->vtag_block[i].v_tag) &&
5353				    ((long)twait_block->vtag_block[i].tv_sec_at_expire < now.tv_sec)) {
5354				/* Audit expires this guy */
5355				twait_block->vtag_block[i].tv_sec_at_expire = 0;
5356				twait_block->vtag_block[i].v_tag = 0;
5357				twait_block->vtag_block[i].lport = 0;
5358				twait_block->vtag_block[i].rport = 0;
5359				if (set == 0) {
5360					/* Reuse it for my new tag */
5361					twait_block->vtag_block[i].tv_sec_at_expire = now.tv_sec + time;
5362					twait_block->vtag_block[i].v_tag = tag;
5363					twait_block->vtag_block[i].lport = lport;
5364					twait_block->vtag_block[i].rport = rport;
5365					set = 1;
5366				}
5367			}
5368		}
5369		if (set) {
5370			/*
5371			 * We only do up to the block where we can
5372			 * place our tag for audits
5373			 */
5374			break;
5375		}
5376	}
5377	/* Need to add a new block to chain */
5378	if (!set) {
5379		SCTP_MALLOC(twait_block, struct sctp_tagblock *,
5380		    sizeof(struct sctp_tagblock), SCTP_M_TIMW);
5381		if (twait_block == NULL) {
5382#ifdef INVARIANTS
5383			panic("Can not alloc tagblock");
5384#endif
5385			return;
5386		}
5387		memset(twait_block, 0, sizeof(struct sctp_tagblock));
5388		LIST_INSERT_HEAD(chain, twait_block, sctp_nxt_tagblock);
5389		twait_block->vtag_block[0].tv_sec_at_expire = now.tv_sec + time;
5390		twait_block->vtag_block[0].v_tag = tag;
5391		twait_block->vtag_block[0].lport = lport;
5392		twait_block->vtag_block[0].rport = rport;
5393	}
5394}
5395
5396
5397#ifdef __Panda__
5398void panda_wakeup_socket(struct socket *so);
5399#endif
5400
5401/*-
5402 * Free the association after un-hashing the remote port. This
5403 * function ALWAYS returns holding NO LOCK on the stcb. It DOES
5404 * expect that the input to this function IS a locked TCB.
5405 * It will return 0, if it did NOT destroy the association (instead
5406 * it unlocks it. It will return NON-zero if it either destroyed the
5407 * association OR the association is already destroyed.
5408 */
5409int
5410sctp_free_assoc(struct sctp_inpcb *inp, struct sctp_tcb *stcb, int from_inpcbfree, int from_location)
5411{
5412	int i;
5413	struct sctp_association *asoc;
5414	struct sctp_nets *net, *nnet;
5415	struct sctp_laddr *laddr, *naddr;
5416	struct sctp_tmit_chunk *chk, *nchk;
5417	struct sctp_asconf_addr *aparam, *naparam;
5418	struct sctp_asconf_ack *aack, *naack;
5419	struct sctp_stream_reset_list *strrst, *nstrrst;
5420	struct sctp_queued_to_read *sq, *nsq;
5421	struct sctp_stream_queue_pending *sp, *nsp;
5422	sctp_sharedkey_t *shared_key, *nshared_key;
5423	struct socket *so;
5424
5425	/* first, lets purge the entry from the hash table. */
5426#if defined(__APPLE__)
5427	sctp_lock_assert(SCTP_INP_SO(inp));
5428#endif
5429
5430#ifdef SCTP_LOG_CLOSING
5431	sctp_log_closing(inp, stcb, 6);
5432#endif
5433	if (stcb->asoc.state == 0) {
5434#ifdef SCTP_LOG_CLOSING
5435		sctp_log_closing(inp, NULL, 7);
5436#endif
5437		/* there is no asoc, really TSNH :-0 */
5438		return (1);
5439	}
5440	if (stcb->asoc.alternate) {
5441		sctp_free_remote_addr(stcb->asoc.alternate);
5442		stcb->asoc.alternate = NULL;
5443	}
5444#if !defined(__APPLE__) /* TEMP: moved to below */
5445        /* TEMP CODE */
5446	if (stcb->freed_from_where == 0) {
5447		/* Only record the first place free happened from */
5448		stcb->freed_from_where = from_location;
5449	}
5450        /* TEMP CODE */
5451#endif
5452
5453	asoc = &stcb->asoc;
5454	if ((inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) ||
5455	    (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE))
5456		/* nothing around */
5457		so = NULL;
5458	else
5459		so = inp->sctp_socket;
5460
5461	/*
5462	 * We used timer based freeing if a reader or writer is in the way.
5463	 * So we first check if we are actually being called from a timer,
5464	 * if so we abort early if a reader or writer is still in the way.
5465	 */
5466	if ((stcb->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) &&
5467	    (from_inpcbfree == SCTP_NORMAL_PROC)) {
5468		/*
5469		 * is it the timer driving us? if so are the reader/writers
5470		 * gone?
5471		 */
5472		if (stcb->asoc.refcnt) {
5473			/* nope, reader or writer in the way */
5474			sctp_timer_start(SCTP_TIMER_TYPE_ASOCKILL, inp, stcb, NULL);
5475			/* no asoc destroyed */
5476			SCTP_TCB_UNLOCK(stcb);
5477#ifdef SCTP_LOG_CLOSING
5478			sctp_log_closing(inp, stcb, 8);
5479#endif
5480			return (0);
5481		}
5482	}
5483	/* now clean up any other timers */
5484	(void)SCTP_OS_TIMER_STOP(&asoc->dack_timer.timer);
5485	asoc->dack_timer.self = NULL;
5486	(void)SCTP_OS_TIMER_STOP(&asoc->strreset_timer.timer);
5487	/*-
5488	 * For stream reset we don't blast this unless
5489	 * it is a str-reset timer, it might be the
5490	 * free-asoc timer which we DON'T want to
5491	 * disturb.
5492	 */
5493	if (asoc->strreset_timer.type == SCTP_TIMER_TYPE_STRRESET)
5494		asoc->strreset_timer.self = NULL;
5495	(void)SCTP_OS_TIMER_STOP(&asoc->asconf_timer.timer);
5496	asoc->asconf_timer.self = NULL;
5497	(void)SCTP_OS_TIMER_STOP(&asoc->autoclose_timer.timer);
5498	asoc->autoclose_timer.self = NULL;
5499	(void)SCTP_OS_TIMER_STOP(&asoc->shut_guard_timer.timer);
5500	asoc->shut_guard_timer.self = NULL;
5501	(void)SCTP_OS_TIMER_STOP(&asoc->delayed_event_timer.timer);
5502	asoc->delayed_event_timer.self = NULL;
5503	/* Mobility adaptation */
5504	(void)SCTP_OS_TIMER_STOP(&asoc->delete_prim_timer.timer);
5505	asoc->delete_prim_timer.self = NULL;
5506	TAILQ_FOREACH(net, &asoc->nets, sctp_next) {
5507		(void)SCTP_OS_TIMER_STOP(&net->rxt_timer.timer);
5508		net->rxt_timer.self = NULL;
5509		(void)SCTP_OS_TIMER_STOP(&net->pmtu_timer.timer);
5510		net->pmtu_timer.self = NULL;
5511		(void)SCTP_OS_TIMER_STOP(&net->hb_timer.timer);
5512		net->hb_timer.self = NULL;
5513	}
5514	/* Now the read queue needs to be cleaned up (only once) */
5515	if ((stcb->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) == 0) {
5516		stcb->asoc.state |= SCTP_STATE_ABOUT_TO_BE_FREED;
5517		SCTP_INP_READ_LOCK(inp);
5518		TAILQ_FOREACH(sq, &inp->read_queue, next) {
5519			if (sq->stcb == stcb) {
5520				sq->do_not_ref_stcb = 1;
5521				sq->sinfo_cumtsn = stcb->asoc.cumulative_tsn;
5522				/* If there is no end, there never
5523				 * will be now.
5524				 */
5525				if (sq->end_added == 0) {
5526					/* Held for PD-API clear that. */
5527					sq->pdapi_aborted = 1;
5528					sq->held_length = 0;
5529					if (sctp_stcb_is_feature_on(inp, stcb, SCTP_PCB_FLAGS_PDAPIEVNT) && (so != NULL)) {
5530						/*
5531						 * Need to add a PD-API aborted indication.
5532						 * Setting the control_pdapi assures that it will
5533						 * be added right after this msg.
5534						 */
5535						uint32_t strseq;
5536						stcb->asoc.control_pdapi = sq;
5537						strseq = (sq->sinfo_stream << 16) | sq->sinfo_ssn;
5538						sctp_ulp_notify(SCTP_NOTIFY_PARTIAL_DELVIERY_INDICATION,
5539						                stcb,
5540						                SCTP_PARTIAL_DELIVERY_ABORTED,
5541						                (void *)&strseq,
5542						                SCTP_SO_LOCKED);
5543						stcb->asoc.control_pdapi = NULL;
5544					}
5545				}
5546				/* Add an end to wake them */
5547				sq->end_added = 1;
5548			}
5549		}
5550		SCTP_INP_READ_UNLOCK(inp);
5551		if (stcb->block_entry) {
5552			SCTP_LTRACE_ERR_RET(inp, stcb, NULL, SCTP_FROM_SCTP_PCB, ECONNRESET);
5553			stcb->block_entry->error = ECONNRESET;
5554			stcb->block_entry = NULL;
5555		}
5556	}
5557	if ((stcb->asoc.refcnt) || (stcb->asoc.state & SCTP_STATE_IN_ACCEPT_QUEUE)) {
5558		/* Someone holds a reference OR the socket is unaccepted yet.
5559		*/
5560		if ((stcb->asoc.refcnt)  ||
5561		    (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) ||
5562		    (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE)) {
5563			stcb->asoc.state &= ~SCTP_STATE_IN_ACCEPT_QUEUE;
5564			sctp_timer_start(SCTP_TIMER_TYPE_ASOCKILL, inp, stcb, NULL);
5565		}
5566		SCTP_TCB_UNLOCK(stcb);
5567		if ((inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) ||
5568		    (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE))
5569			/* nothing around */
5570			so = NULL;
5571		if (so) {
5572			/* Wake any reader/writers */
5573			sctp_sorwakeup(inp, so);
5574			sctp_sowwakeup(inp, so);
5575		}
5576
5577#ifdef SCTP_LOG_CLOSING
5578		sctp_log_closing(inp, stcb, 9);
5579#endif
5580		/* no asoc destroyed */
5581		return (0);
5582	}
5583#ifdef SCTP_LOG_CLOSING
5584	sctp_log_closing(inp, stcb, 10);
5585#endif
5586	/* When I reach here, no others want
5587	 * to kill the assoc yet.. and I own
5588	 * the lock. Now its possible an abort
5589	 * comes in when I do the lock exchange
5590	 * below to grab all the locks to do
5591	 * the final take out. to prevent this
5592	 * we increment the count, which will
5593	 * start a timer and blow out above thus
5594	 * assuring us that we hold exclusive
5595	 * killing of the asoc. Note that
5596	 * after getting back the TCB lock
5597	 * we will go ahead and increment the
5598	 * counter back up and stop any timer
5599	 * a passing stranger may have started :-S
5600	 */
5601	if (from_inpcbfree == SCTP_NORMAL_PROC) {
5602		atomic_add_int(&stcb->asoc.refcnt, 1);
5603
5604		SCTP_TCB_UNLOCK(stcb);
5605		SCTP_INP_INFO_WLOCK();
5606		SCTP_INP_WLOCK(inp);
5607		SCTP_TCB_LOCK(stcb);
5608	}
5609	/* Double check the GONE flag */
5610	if ((inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) ||
5611	    (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE))
5612		/* nothing around */
5613		so = NULL;
5614
5615	if ((inp->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE) ||
5616	    (inp->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL)) {
5617		/*
5618		 * For TCP type we need special handling when we are
5619		 * connected. We also include the peel'ed off ones to.
5620		 */
5621		if (inp->sctp_flags & SCTP_PCB_FLAGS_CONNECTED) {
5622			inp->sctp_flags &= ~SCTP_PCB_FLAGS_CONNECTED;
5623			inp->sctp_flags |= SCTP_PCB_FLAGS_WAS_CONNECTED;
5624			if (so) {
5625				SOCK_LOCK(so);
5626				if (so->so_rcv.sb_cc == 0) {
5627					so->so_state &= ~(SS_ISCONNECTING |
5628							  SS_ISDISCONNECTING |
5629							  SS_ISCONFIRMING |
5630							  SS_ISCONNECTED);
5631				}
5632#if defined(__APPLE__)
5633				socantrcvmore(so);
5634#else
5635				socantrcvmore_locked(so);
5636#endif
5637				sctp_sowwakeup(inp, so);
5638				sctp_sorwakeup(inp, so);
5639				SCTP_SOWAKEUP(so);
5640			}
5641		}
5642	}
5643
5644	/* Make it invalid too, that way if its
5645	 * about to run it will abort and return.
5646	 */
5647	/* re-increment the lock */
5648	if (from_inpcbfree == SCTP_NORMAL_PROC) {
5649		atomic_add_int(&stcb->asoc.refcnt, -1);
5650	}
5651	if (stcb->asoc.refcnt) {
5652		stcb->asoc.state &= ~SCTP_STATE_IN_ACCEPT_QUEUE;
5653		sctp_timer_start(SCTP_TIMER_TYPE_ASOCKILL, inp, stcb, NULL);
5654		if (from_inpcbfree == SCTP_NORMAL_PROC) {
5655			SCTP_INP_INFO_WUNLOCK();
5656			SCTP_INP_WUNLOCK(inp);
5657		}
5658		SCTP_TCB_UNLOCK(stcb);
5659		return (0);
5660	}
5661	asoc->state = 0;
5662	if (inp->sctp_tcbhash) {
5663		LIST_REMOVE(stcb, sctp_tcbhash);
5664	}
5665	if (stcb->asoc.in_asocid_hash) {
5666		LIST_REMOVE(stcb, sctp_tcbasocidhash);
5667	}
5668	/* Now lets remove it from the list of ALL associations in the EP */
5669	LIST_REMOVE(stcb, sctp_tcblist);
5670	if (from_inpcbfree == SCTP_NORMAL_PROC) {
5671		SCTP_INP_INCR_REF(inp);
5672		SCTP_INP_WUNLOCK(inp);
5673	}
5674	/* pull from vtag hash */
5675	LIST_REMOVE(stcb, sctp_asocs);
5676	sctp_add_vtag_to_timewait(asoc->my_vtag, SCTP_BASE_SYSCTL(sctp_vtag_time_wait),
5677				  inp->sctp_lport, stcb->rport);
5678
5679	/* Now restop the timers to be sure
5680	 * this is paranoia at is finest!
5681	 */
5682	(void)SCTP_OS_TIMER_STOP(&asoc->strreset_timer.timer);
5683	(void)SCTP_OS_TIMER_STOP(&asoc->dack_timer.timer);
5684	(void)SCTP_OS_TIMER_STOP(&asoc->strreset_timer.timer);
5685	(void)SCTP_OS_TIMER_STOP(&asoc->asconf_timer.timer);
5686	(void)SCTP_OS_TIMER_STOP(&asoc->shut_guard_timer.timer);
5687	(void)SCTP_OS_TIMER_STOP(&asoc->autoclose_timer.timer);
5688	(void)SCTP_OS_TIMER_STOP(&asoc->delayed_event_timer.timer);
5689	TAILQ_FOREACH(net, &asoc->nets, sctp_next) {
5690		(void)SCTP_OS_TIMER_STOP(&net->rxt_timer.timer);
5691		(void)SCTP_OS_TIMER_STOP(&net->pmtu_timer.timer);
5692		(void)SCTP_OS_TIMER_STOP(&net->hb_timer.timer);
5693	}
5694
5695	asoc->strreset_timer.type = SCTP_TIMER_TYPE_NONE;
5696	/*
5697	 * The chunk lists and such SHOULD be empty but we check them just
5698	 * in case.
5699	 */
5700	/* anything on the wheel needs to be removed */
5701	for (i = 0; i < asoc->streamoutcnt; i++) {
5702		struct sctp_stream_out *outs;
5703
5704		outs = &asoc->strmout[i];
5705		/* now clean up any chunks here */
5706		TAILQ_FOREACH_SAFE(sp, &outs->outqueue, next, nsp) {
5707			TAILQ_REMOVE(&outs->outqueue, sp, next);
5708			sctp_free_spbufspace(stcb, asoc, sp);
5709			if (sp->data) {
5710				if (so) {
5711					/* Still an open socket - report */
5712					sctp_ulp_notify(SCTP_NOTIFY_SPECIAL_SP_FAIL, stcb,
5713					                0, (void *)sp, SCTP_SO_LOCKED);
5714				}
5715				if (sp->data) {
5716					sctp_m_freem(sp->data);
5717					sp->data = NULL;
5718					sp->tail_mbuf = NULL;
5719					sp->length = 0;
5720				}
5721			}
5722			if (sp->net) {
5723				sctp_free_remote_addr(sp->net);
5724				sp->net = NULL;
5725			}
5726			sctp_free_a_strmoq(stcb, sp, SCTP_SO_LOCKED);
5727		}
5728	}
5729	/*sa_ignore FREED_MEMORY*/
5730	TAILQ_FOREACH_SAFE(strrst, &asoc->resetHead, next_resp, nstrrst) {
5731		TAILQ_REMOVE(&asoc->resetHead, strrst, next_resp);
5732		SCTP_FREE(strrst, SCTP_M_STRESET);
5733	}
5734	TAILQ_FOREACH_SAFE(sq, &asoc->pending_reply_queue, next, nsq) {
5735		TAILQ_REMOVE(&asoc->pending_reply_queue, sq, next);
5736		if (sq->data) {
5737			sctp_m_freem(sq->data);
5738			sq->data = NULL;
5739		}
5740		sctp_free_remote_addr(sq->whoFrom);
5741		sq->whoFrom = NULL;
5742		sq->stcb = NULL;
5743		/* Free the ctl entry */
5744		SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_readq), sq);
5745		SCTP_DECR_READQ_COUNT();
5746		/*sa_ignore FREED_MEMORY*/
5747	}
5748	TAILQ_FOREACH_SAFE(chk, &asoc->free_chunks, sctp_next, nchk) {
5749		TAILQ_REMOVE(&asoc->free_chunks, chk, sctp_next);
5750		if (chk->data) {
5751			sctp_m_freem(chk->data);
5752			chk->data = NULL;
5753		}
5754		if (chk->holds_key_ref)
5755			sctp_auth_key_release(stcb, chk->auth_keyid, SCTP_SO_LOCKED);
5756		SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_chunk), chk);
5757		SCTP_DECR_CHK_COUNT();
5758		atomic_subtract_int(&SCTP_BASE_INFO(ipi_free_chunks), 1);
5759		asoc->free_chunk_cnt--;
5760		/*sa_ignore FREED_MEMORY*/
5761	}
5762	/* pending send queue SHOULD be empty */
5763	TAILQ_FOREACH_SAFE(chk, &asoc->send_queue, sctp_next, nchk) {
5764		if (asoc->strmout[chk->rec.data.stream_number].chunks_on_queues > 0) {
5765			asoc->strmout[chk->rec.data.stream_number].chunks_on_queues--;
5766#ifdef INVARIANTS
5767		} else {
5768			panic("No chunks on the queues for sid %u.", chk->rec.data.stream_number);
5769#endif
5770		}
5771		TAILQ_REMOVE(&asoc->send_queue, chk, sctp_next);
5772		if (chk->data) {
5773			if (so) {
5774				/* Still a socket? */
5775				sctp_ulp_notify(SCTP_NOTIFY_UNSENT_DG_FAIL, stcb,
5776				                0, chk, SCTP_SO_LOCKED);
5777			}
5778			if (chk->data) {
5779				sctp_m_freem(chk->data);
5780				chk->data = NULL;
5781			}
5782		}
5783		if (chk->holds_key_ref)
5784			sctp_auth_key_release(stcb, chk->auth_keyid, SCTP_SO_LOCKED);
5785		if (chk->whoTo) {
5786			sctp_free_remote_addr(chk->whoTo);
5787			chk->whoTo = NULL;
5788		}
5789		SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_chunk), chk);
5790		SCTP_DECR_CHK_COUNT();
5791		/*sa_ignore FREED_MEMORY*/
5792	}
5793	/* sent queue SHOULD be empty */
5794	TAILQ_FOREACH_SAFE(chk, &asoc->sent_queue, sctp_next, nchk) {
5795		if (chk->sent != SCTP_DATAGRAM_NR_ACKED) {
5796			if (asoc->strmout[chk->rec.data.stream_number].chunks_on_queues > 0) {
5797				asoc->strmout[chk->rec.data.stream_number].chunks_on_queues--;
5798#ifdef INVARIANTS
5799			} else {
5800				panic("No chunks on the queues for sid %u.", chk->rec.data.stream_number);
5801#endif
5802			}
5803		}
5804		TAILQ_REMOVE(&asoc->sent_queue, chk, sctp_next);
5805		if (chk->data) {
5806			if (so) {
5807				/* Still a socket? */
5808				sctp_ulp_notify(SCTP_NOTIFY_SENT_DG_FAIL, stcb,
5809				                0, chk, SCTP_SO_LOCKED);
5810			}
5811			if (chk->data) {
5812				sctp_m_freem(chk->data);
5813				chk->data = NULL;
5814			}
5815		}
5816		if (chk->holds_key_ref)
5817			sctp_auth_key_release(stcb, chk->auth_keyid, SCTP_SO_LOCKED);
5818		sctp_free_remote_addr(chk->whoTo);
5819		SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_chunk), chk);
5820		SCTP_DECR_CHK_COUNT();
5821		/*sa_ignore FREED_MEMORY*/
5822	}
5823#ifdef INVARIANTS
5824	for (i = 0; i < stcb->asoc.streamoutcnt; i++) {
5825		if (stcb->asoc.strmout[i].chunks_on_queues > 0) {
5826			panic("%u chunks left for stream %u.", stcb->asoc.strmout[i].chunks_on_queues, i);
5827		}
5828	}
5829#endif
5830	/* control queue MAY not be empty */
5831	TAILQ_FOREACH_SAFE(chk, &asoc->control_send_queue, sctp_next, nchk) {
5832		TAILQ_REMOVE(&asoc->control_send_queue, chk, sctp_next);
5833		if (chk->data) {
5834			sctp_m_freem(chk->data);
5835			chk->data = NULL;
5836		}
5837		if (chk->holds_key_ref)
5838			sctp_auth_key_release(stcb, chk->auth_keyid, SCTP_SO_LOCKED);
5839		sctp_free_remote_addr(chk->whoTo);
5840		SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_chunk), chk);
5841		SCTP_DECR_CHK_COUNT();
5842		/*sa_ignore FREED_MEMORY*/
5843	}
5844	/* ASCONF queue MAY not be empty */
5845	TAILQ_FOREACH_SAFE(chk, &asoc->asconf_send_queue, sctp_next, nchk) {
5846		TAILQ_REMOVE(&asoc->asconf_send_queue, chk, sctp_next);
5847		if (chk->data) {
5848			sctp_m_freem(chk->data);
5849			chk->data = NULL;
5850		}
5851		if (chk->holds_key_ref)
5852			sctp_auth_key_release(stcb, chk->auth_keyid, SCTP_SO_LOCKED);
5853		sctp_free_remote_addr(chk->whoTo);
5854		SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_chunk), chk);
5855		SCTP_DECR_CHK_COUNT();
5856		/*sa_ignore FREED_MEMORY*/
5857	}
5858	TAILQ_FOREACH_SAFE(chk, &asoc->reasmqueue, sctp_next, nchk) {
5859		TAILQ_REMOVE(&asoc->reasmqueue, chk, sctp_next);
5860		if (chk->data) {
5861			sctp_m_freem(chk->data);
5862			chk->data = NULL;
5863		}
5864		if (chk->holds_key_ref)
5865			sctp_auth_key_release(stcb, chk->auth_keyid, SCTP_SO_LOCKED);
5866		sctp_free_remote_addr(chk->whoTo);
5867		SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_chunk), chk);
5868		SCTP_DECR_CHK_COUNT();
5869		/*sa_ignore FREED_MEMORY*/
5870	}
5871
5872	if (asoc->mapping_array) {
5873		SCTP_FREE(asoc->mapping_array, SCTP_M_MAP);
5874		asoc->mapping_array = NULL;
5875	}
5876	if (asoc->nr_mapping_array) {
5877		SCTP_FREE(asoc->nr_mapping_array, SCTP_M_MAP);
5878		asoc->nr_mapping_array = NULL;
5879	}
5880	/* the stream outs */
5881	if (asoc->strmout) {
5882		SCTP_FREE(asoc->strmout, SCTP_M_STRMO);
5883		asoc->strmout = NULL;
5884	}
5885	asoc->strm_realoutsize = asoc->streamoutcnt = 0;
5886	if (asoc->strmin) {
5887		struct sctp_queued_to_read *ctl, *nctl;
5888
5889		for (i = 0; i < asoc->streamincnt; i++) {
5890			TAILQ_FOREACH_SAFE(ctl, &asoc->strmin[i].inqueue, next, nctl) {
5891				TAILQ_REMOVE(&asoc->strmin[i].inqueue, ctl, next);
5892				sctp_free_remote_addr(ctl->whoFrom);
5893				if (ctl->data) {
5894					sctp_m_freem(ctl->data);
5895					ctl->data = NULL;
5896				}
5897				/*
5898				 * We don't free the address here
5899				 * since all the net's were freed
5900				 * above.
5901				 */
5902				SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_readq), ctl);
5903				SCTP_DECR_READQ_COUNT();
5904			}
5905		}
5906		SCTP_FREE(asoc->strmin, SCTP_M_STRMI);
5907		asoc->strmin = NULL;
5908	}
5909	asoc->streamincnt = 0;
5910	TAILQ_FOREACH_SAFE(net, &asoc->nets, sctp_next, nnet) {
5911#ifdef INVARIANTS
5912		if (SCTP_BASE_INFO(ipi_count_raddr) == 0) {
5913			panic("no net's left alloc'ed, or list points to itself");
5914		}
5915#endif
5916		TAILQ_REMOVE(&asoc->nets, net, sctp_next);
5917		sctp_free_remote_addr(net);
5918	}
5919	LIST_FOREACH_SAFE(laddr, &asoc->sctp_restricted_addrs, sctp_nxt_addr, naddr) {
5920		/*sa_ignore FREED_MEMORY*/
5921		sctp_remove_laddr(laddr);
5922	}
5923
5924	/* pending asconf (address) parameters */
5925	TAILQ_FOREACH_SAFE(aparam, &asoc->asconf_queue, next, naparam) {
5926		/*sa_ignore FREED_MEMORY*/
5927		TAILQ_REMOVE(&asoc->asconf_queue, aparam, next);
5928		SCTP_FREE(aparam,SCTP_M_ASC_ADDR);
5929	}
5930	TAILQ_FOREACH_SAFE(aack, &asoc->asconf_ack_sent, next, naack) {
5931		/*sa_ignore FREED_MEMORY*/
5932		TAILQ_REMOVE(&asoc->asconf_ack_sent, aack, next);
5933		if (aack->data != NULL) {
5934			sctp_m_freem(aack->data);
5935		}
5936		SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_asconf_ack), aack);
5937	}
5938	/* clean up auth stuff */
5939	if (asoc->local_hmacs)
5940		sctp_free_hmaclist(asoc->local_hmacs);
5941	if (asoc->peer_hmacs)
5942		sctp_free_hmaclist(asoc->peer_hmacs);
5943
5944	if (asoc->local_auth_chunks)
5945		sctp_free_chunklist(asoc->local_auth_chunks);
5946	if (asoc->peer_auth_chunks)
5947		sctp_free_chunklist(asoc->peer_auth_chunks);
5948
5949	sctp_free_authinfo(&asoc->authinfo);
5950
5951	LIST_FOREACH_SAFE(shared_key, &asoc->shared_keys, next, nshared_key) {
5952		LIST_REMOVE(shared_key, next);
5953		sctp_free_sharedkey(shared_key);
5954		/*sa_ignore FREED_MEMORY*/
5955	}
5956
5957	/* Insert new items here :> */
5958
5959	/* Get rid of LOCK */
5960	SCTP_TCB_UNLOCK(stcb);
5961	SCTP_TCB_LOCK_DESTROY(stcb);
5962	SCTP_TCB_SEND_LOCK_DESTROY(stcb);
5963	if (from_inpcbfree == SCTP_NORMAL_PROC) {
5964		SCTP_INP_INFO_WUNLOCK();
5965		SCTP_INP_RLOCK(inp);
5966	}
5967#if defined(__APPLE__) /* TEMP CODE */
5968	stcb->freed_from_where = from_location;
5969#endif
5970#ifdef SCTP_TRACK_FREED_ASOCS
5971	if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE) {
5972		/* now clean up the tasoc itself */
5973		SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_asoc), stcb);
5974		SCTP_DECR_ASOC_COUNT();
5975	} else {
5976		LIST_INSERT_HEAD(&inp->sctp_asoc_free_list, stcb, sctp_tcblist);
5977	}
5978#else
5979	SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_asoc), stcb);
5980	SCTP_DECR_ASOC_COUNT();
5981#endif
5982	if (from_inpcbfree == SCTP_NORMAL_PROC) {
5983		if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE) {
5984			/* If its NOT the inp_free calling us AND
5985			 * sctp_close as been called, we
5986			 * call back...
5987			 */
5988			SCTP_INP_RUNLOCK(inp);
5989			/* This will start the kill timer (if we are
5990			 * the last one) since we hold an increment yet. But
5991			 * this is the only safe way to do this
5992			 * since otherwise if the socket closes
5993			 * at the same time we are here we might
5994			 * collide in the cleanup.
5995			 */
5996			sctp_inpcb_free(inp,
5997					SCTP_FREE_SHOULD_USE_GRACEFUL_CLOSE,
5998					SCTP_CALLED_DIRECTLY_NOCMPSET);
5999			SCTP_INP_DECR_REF(inp);
6000			goto out_of;
6001		} else {
6002			/* The socket is still open. */
6003			SCTP_INP_DECR_REF(inp);
6004		}
6005	}
6006	if (from_inpcbfree == SCTP_NORMAL_PROC) {
6007		SCTP_INP_RUNLOCK(inp);
6008	}
6009 out_of:
6010	/* destroyed the asoc */
6011#ifdef SCTP_LOG_CLOSING
6012	sctp_log_closing(inp, NULL, 11);
6013#endif
6014	return (1);
6015}
6016
6017
6018
6019/*
6020 * determine if a destination is "reachable" based upon the addresses bound
6021 * to the current endpoint (e.g. only v4 or v6 currently bound)
6022 */
6023/*
6024 * FIX: if we allow assoc-level bindx(), then this needs to be fixed to use
6025 * assoc level v4/v6 flags, as the assoc *may* not have the same address
6026 * types bound as its endpoint
6027 */
6028int
6029sctp_destination_is_reachable(struct sctp_tcb *stcb, struct sockaddr *destaddr)
6030{
6031	struct sctp_inpcb *inp;
6032	int answer;
6033
6034	/*
6035	 * No locks here, the TCB, in all cases is already locked and an
6036	 * assoc is up. There is either a INP lock by the caller applied (in
6037	 * asconf case when deleting an address) or NOT in the HB case,
6038	 * however if HB then the INP increment is up and the INP will not
6039	 * be removed (on top of the fact that we have a TCB lock). So we
6040	 * only want to read the sctp_flags, which is either bound-all or
6041	 * not.. no protection needed since once an assoc is up you can't be
6042	 * changing your binding.
6043	 */
6044	inp = stcb->sctp_ep;
6045	if (inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) {
6046		/* if bound all, destination is not restricted */
6047		/*
6048		 * RRS: Question during lock work: Is this correct? If you
6049		 * are bound-all you still might need to obey the V4--V6
6050		 * flags??? IMO this bound-all stuff needs to be removed!
6051		 */
6052		return (1);
6053	}
6054	/* NOTE: all "scope" checks are done when local addresses are added */
6055	switch (destaddr->sa_family) {
6056#ifdef INET6
6057	case AF_INET6:
6058#if !(defined(__FreeBSD__) || defined(__APPLE__) || defined(__Windows__) || defined(__Userspace__))
6059		answer = inp->inp_vflag & INP_IPV6;
6060#else
6061		answer = inp->ip_inp.inp.inp_vflag & INP_IPV6;
6062#endif
6063		break;
6064#endif
6065#ifdef INET
6066	case AF_INET:
6067#if !(defined(__FreeBSD__) || defined(__APPLE__) || defined(__Windows__) || defined(__Userspace__))
6068		answer = inp->inp_vflag & INP_IPV4;
6069#else
6070		answer = inp->ip_inp.inp.inp_vflag & INP_IPV4;
6071#endif
6072		break;
6073#endif
6074#if defined(__Userspace__)
6075	case AF_CONN:
6076		answer = inp->ip_inp.inp.inp_vflag & INP_CONN;
6077		break;
6078#endif
6079	default:
6080		/* invalid family, so it's unreachable */
6081		answer = 0;
6082		break;
6083	}
6084	return (answer);
6085}
6086
6087/*
6088 * update the inp_vflags on an endpoint
6089 */
6090static void
6091sctp_update_ep_vflag(struct sctp_inpcb *inp)
6092{
6093	struct sctp_laddr *laddr;
6094
6095	/* first clear the flag */
6096#if !(defined(__FreeBSD__) || defined(__APPLE__) || defined(__Windows__) || defined(__Userspace__))
6097	inp->inp_vflag = 0;
6098#else
6099	inp->ip_inp.inp.inp_vflag = 0;
6100#endif
6101	/* set the flag based on addresses on the ep list */
6102	LIST_FOREACH(laddr, &inp->sctp_addr_list, sctp_nxt_addr) {
6103		if (laddr->ifa == NULL) {
6104			SCTPDBG(SCTP_DEBUG_PCB1, "%s: NULL ifa\n",
6105				__FUNCTION__);
6106			continue;
6107		}
6108
6109		if (laddr->ifa->localifa_flags & SCTP_BEING_DELETED) {
6110			continue;
6111		}
6112		switch (laddr->ifa->address.sa.sa_family) {
6113#ifdef INET6
6114		case AF_INET6:
6115#if !(defined(__FreeBSD__) || defined(__APPLE__) || defined(__Windows__) || defined(__Userspace__))
6116			inp->inp_vflag |= INP_IPV6;
6117#else
6118			inp->ip_inp.inp.inp_vflag |= INP_IPV6;
6119#endif
6120			break;
6121#endif
6122#ifdef INET
6123		case AF_INET:
6124#if !(defined(__FreeBSD__) || defined(__APPLE__) || defined(__Windows__) || defined(__Userspace__))
6125			inp->inp_vflag |= INP_IPV4;
6126#else
6127			inp->ip_inp.inp.inp_vflag |= INP_IPV4;
6128#endif
6129			break;
6130#endif
6131#if defined(__Userspace__)
6132		case AF_CONN:
6133			inp->ip_inp.inp.inp_vflag |= INP_CONN;
6134			break;
6135#endif
6136		default:
6137			break;
6138		}
6139	}
6140}
6141
6142/*
6143 * Add the address to the endpoint local address list There is nothing to be
6144 * done if we are bound to all addresses
6145 */
6146void
6147sctp_add_local_addr_ep(struct sctp_inpcb *inp, struct sctp_ifa *ifa, uint32_t action)
6148{
6149	struct sctp_laddr *laddr;
6150	int fnd, error = 0;
6151
6152	fnd = 0;
6153
6154	if (inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) {
6155		/* You are already bound to all. You have it already */
6156		return;
6157	}
6158#ifdef INET6
6159	if (ifa->address.sa.sa_family == AF_INET6) {
6160		if (ifa->localifa_flags & SCTP_ADDR_IFA_UNUSEABLE) {
6161			/* Can't bind a non-useable addr. */
6162			return;
6163		}
6164	}
6165#endif
6166	/* first, is it already present? */
6167	LIST_FOREACH(laddr, &inp->sctp_addr_list, sctp_nxt_addr) {
6168		if (laddr->ifa == ifa) {
6169			fnd = 1;
6170			break;
6171		}
6172	}
6173
6174	if (fnd == 0) {
6175		/* Not in the ep list */
6176		error = sctp_insert_laddr(&inp->sctp_addr_list, ifa, action);
6177		if (error != 0)
6178			return;
6179		inp->laddr_count++;
6180		/* update inp_vflag flags */
6181		switch (ifa->address.sa.sa_family) {
6182#ifdef INET6
6183		case AF_INET6:
6184#if !(defined(__FreeBSD__) || defined(__APPLE__) || defined(__Windows__) || defined(__Userspace__))
6185			inp->inp_vflag |= INP_IPV6;
6186#else
6187			inp->ip_inp.inp.inp_vflag |= INP_IPV6;
6188#endif
6189			break;
6190#endif
6191#ifdef INET
6192		case AF_INET:
6193#if !(defined(__FreeBSD__) || defined(__APPLE__) || defined(__Windows__) || defined(__Userspace__))
6194			inp->inp_vflag |= INP_IPV4;
6195#else
6196			inp->ip_inp.inp.inp_vflag |= INP_IPV4;
6197#endif
6198			break;
6199#endif
6200#if defined(__Userspace__)
6201		case AF_CONN:
6202			inp->ip_inp.inp.inp_vflag |= INP_CONN;
6203			break;
6204#endif
6205		default:
6206			break;
6207		}
6208	}
6209	return;
6210}
6211
6212
6213/*
6214 * select a new (hopefully reachable) destination net (should only be used
6215 * when we deleted an ep addr that is the only usable source address to reach
6216 * the destination net)
6217 */
6218static void
6219sctp_select_primary_destination(struct sctp_tcb *stcb)
6220{
6221	struct sctp_nets *net;
6222
6223	TAILQ_FOREACH(net, &stcb->asoc.nets, sctp_next) {
6224		/* for now, we'll just pick the first reachable one we find */
6225		if (net->dest_state & SCTP_ADDR_UNCONFIRMED)
6226			continue;
6227		if (sctp_destination_is_reachable(stcb,
6228		    (struct sockaddr *)&net->ro._l_addr)) {
6229			/* found a reachable destination */
6230			stcb->asoc.primary_destination = net;
6231		}
6232	}
6233	/* I can't there from here! ...we're gonna die shortly... */
6234}
6235
6236
6237/*
6238 * Delete the address from the endpoint local address list There is nothing
6239 * to be done if we are bound to all addresses
6240 */
6241void
6242sctp_del_local_addr_ep(struct sctp_inpcb *inp, struct sctp_ifa *ifa)
6243{
6244	struct sctp_laddr *laddr;
6245	int fnd;
6246
6247	fnd = 0;
6248	if (inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) {
6249		/* You are already bound to all. You have it already */
6250		return;
6251	}
6252	LIST_FOREACH(laddr, &inp->sctp_addr_list, sctp_nxt_addr) {
6253		if (laddr->ifa == ifa) {
6254			fnd = 1;
6255			break;
6256		}
6257	}
6258	if (fnd && (inp->laddr_count < 2)) {
6259		/* can't delete unless there are at LEAST 2 addresses */
6260		return;
6261	}
6262	if (fnd) {
6263		/*
6264		 * clean up any use of this address go through our
6265		 * associations and clear any last_used_address that match
6266		 * this one for each assoc, see if a new primary_destination
6267		 * is needed
6268		 */
6269		struct sctp_tcb *stcb;
6270
6271		/* clean up "next_addr_touse" */
6272		if (inp->next_addr_touse == laddr)
6273			/* delete this address */
6274			inp->next_addr_touse = NULL;
6275
6276		/* clean up "last_used_address" */
6277		LIST_FOREACH(stcb, &inp->sctp_asoc_list, sctp_tcblist) {
6278			struct sctp_nets *net;
6279			SCTP_TCB_LOCK(stcb);
6280			if (stcb->asoc.last_used_address == laddr)
6281				/* delete this address */
6282				stcb->asoc.last_used_address = NULL;
6283			/* Now spin through all the nets and purge any ref to laddr */
6284			TAILQ_FOREACH(net, &stcb->asoc.nets, sctp_next) {
6285				if (net->ro._s_addr &&
6286				    (net->ro._s_addr->ifa == laddr->ifa)) {
6287					/* Yep, purge src address selected */
6288					sctp_rtentry_t *rt;
6289
6290					/* delete this address if cached */
6291					rt = net->ro.ro_rt;
6292					if (rt != NULL) {
6293						RTFREE(rt);
6294						net->ro.ro_rt = NULL;
6295					}
6296					sctp_free_ifa(net->ro._s_addr);
6297					net->ro._s_addr = NULL;
6298					net->src_addr_selected = 0;
6299				}
6300			}
6301			SCTP_TCB_UNLOCK(stcb);
6302		}		/* for each tcb */
6303		/* remove it from the ep list */
6304		sctp_remove_laddr(laddr);
6305		inp->laddr_count--;
6306		/* update inp_vflag flags */
6307		sctp_update_ep_vflag(inp);
6308	}
6309	return;
6310}
6311
6312/*
6313 * Add the address to the TCB local address restricted list.
6314 * This is a "pending" address list (eg. addresses waiting for an
6315 * ASCONF-ACK response) and cannot be used as a valid source address.
6316 */
6317void
6318sctp_add_local_addr_restricted(struct sctp_tcb *stcb, struct sctp_ifa *ifa)
6319{
6320	struct sctp_laddr *laddr;
6321	struct sctpladdr *list;
6322
6323	/*
6324	 * Assumes TCB is locked.. and possibly the INP. May need to
6325	 * confirm/fix that if we need it and is not the case.
6326	 */
6327	list = &stcb->asoc.sctp_restricted_addrs;
6328
6329#ifdef INET6
6330	if (ifa->address.sa.sa_family == AF_INET6) {
6331		if (ifa->localifa_flags & SCTP_ADDR_IFA_UNUSEABLE) {
6332			/* Can't bind a non-existent addr. */
6333			return;
6334		}
6335	}
6336#endif
6337	/* does the address already exist? */
6338	LIST_FOREACH(laddr, list, sctp_nxt_addr) {
6339		if (laddr->ifa == ifa) {
6340			return;
6341		}
6342	}
6343
6344	/* add to the list */
6345	(void)sctp_insert_laddr(list, ifa, 0);
6346	return;
6347}
6348
6349/*
6350 * insert an laddr entry with the given ifa for the desired list
6351 */
6352int
6353sctp_insert_laddr(struct sctpladdr *list, struct sctp_ifa *ifa, uint32_t act)
6354{
6355	struct sctp_laddr *laddr;
6356
6357	laddr = SCTP_ZONE_GET(SCTP_BASE_INFO(ipi_zone_laddr), struct sctp_laddr);
6358	if (laddr == NULL) {
6359		/* out of memory? */
6360		SCTP_LTRACE_ERR_RET(NULL, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
6361		return (EINVAL);
6362	}
6363	SCTP_INCR_LADDR_COUNT();
6364	bzero(laddr, sizeof(*laddr));
6365	(void)SCTP_GETTIME_TIMEVAL(&laddr->start_time);
6366	laddr->ifa = ifa;
6367	laddr->action = act;
6368	atomic_add_int(&ifa->refcount, 1);
6369	/* insert it */
6370	LIST_INSERT_HEAD(list, laddr, sctp_nxt_addr);
6371
6372	return (0);
6373}
6374
6375/*
6376 * Remove an laddr entry from the local address list (on an assoc)
6377 */
6378void
6379sctp_remove_laddr(struct sctp_laddr *laddr)
6380{
6381
6382	/* remove from the list */
6383	LIST_REMOVE(laddr, sctp_nxt_addr);
6384	sctp_free_ifa(laddr->ifa);
6385	SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_laddr), laddr);
6386	SCTP_DECR_LADDR_COUNT();
6387}
6388
6389/*
6390 * Remove a local address from the TCB local address restricted list
6391 */
6392void
6393sctp_del_local_addr_restricted(struct sctp_tcb *stcb, struct sctp_ifa *ifa)
6394{
6395	struct sctp_inpcb *inp;
6396	struct sctp_laddr *laddr;
6397
6398	/*
6399	 * This is called by asconf work. It is assumed that a) The TCB is
6400	 * locked and b) The INP is locked. This is true in as much as I can
6401	 * trace through the entry asconf code where I did these locks.
6402	 * Again, the ASCONF code is a bit different in that it does lock
6403	 * the INP during its work often times. This must be since we don't
6404	 * want other proc's looking up things while what they are looking
6405	 * up is changing :-D
6406	 */
6407
6408	inp = stcb->sctp_ep;
6409	/* if subset bound and don't allow ASCONF's, can't delete last */
6410	if (((inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) == 0) &&
6411	    sctp_is_feature_off(inp, SCTP_PCB_FLAGS_DO_ASCONF)) {
6412		if (stcb->sctp_ep->laddr_count < 2) {
6413			/* can't delete last address */
6414			return;
6415		}
6416	}
6417	LIST_FOREACH(laddr, &stcb->asoc.sctp_restricted_addrs, sctp_nxt_addr) {
6418		/* remove the address if it exists */
6419		if (laddr->ifa == NULL)
6420			continue;
6421		if (laddr->ifa == ifa) {
6422			sctp_remove_laddr(laddr);
6423			return;
6424		}
6425	}
6426
6427	/* address not found! */
6428	return;
6429}
6430
6431#if defined(__FreeBSD__)
6432/*
6433 * Temporarily remove for __APPLE__ until we use the Tiger equivalents
6434 */
6435/* sysctl */
6436static int sctp_max_number_of_assoc = SCTP_MAX_NUM_OF_ASOC;
6437static int sctp_scale_up_for_address = SCTP_SCALE_FOR_ADDR;
6438#endif				/* FreeBSD || APPLE */
6439
6440
6441
6442#if defined(__FreeBSD__) && defined(SCTP_MCORE_INPUT) && defined(SMP)
6443struct sctp_mcore_ctrl *sctp_mcore_workers = NULL;
6444int *sctp_cpuarry = NULL;
6445void
6446sctp_queue_to_mcore(struct mbuf *m, int off, int cpu_to_use)
6447{
6448	/* Queue a packet to a processor for the specified core */
6449	struct sctp_mcore_queue *qent;
6450	struct sctp_mcore_ctrl *wkq;
6451	int need_wake = 0;
6452	if (sctp_mcore_workers == NULL) {
6453		/* Something went way bad during setup */
6454		sctp_input_with_port(m, off, 0);
6455		return;
6456	}
6457	SCTP_MALLOC(qent, struct sctp_mcore_queue *,
6458		    (sizeof(struct sctp_mcore_queue)),
6459		    SCTP_M_MCORE);
6460	if (qent == NULL) {
6461		/* This is trouble  */
6462		sctp_input_with_port(m, off, 0);
6463		return;
6464	}
6465#if defined(__FreeBSD__) && __FreeBSD_version >= 801000
6466	qent->vn = curvnet;
6467#endif
6468	qent->m = m;
6469	qent->off = off;
6470	qent->v6 = 0;
6471	wkq = &sctp_mcore_workers[cpu_to_use];
6472	SCTP_MCORE_QLOCK(wkq);
6473
6474	TAILQ_INSERT_TAIL(&wkq->que, qent, next);
6475	if (wkq->running == 0) {
6476		need_wake = 1;
6477	}
6478	SCTP_MCORE_QUNLOCK(wkq);
6479	if (need_wake) {
6480		wakeup(&wkq->running);
6481	}
6482}
6483
6484static void
6485sctp_mcore_thread(void *arg)
6486{
6487
6488	struct sctp_mcore_ctrl *wkq;
6489	struct sctp_mcore_queue *qent;
6490
6491	wkq = (struct sctp_mcore_ctrl *)arg;
6492	struct mbuf *m;
6493	int off, v6;
6494
6495	/* Wait for first tickle */
6496	SCTP_MCORE_LOCK(wkq);
6497	wkq->running = 0;
6498	msleep(&wkq->running,
6499	       &wkq->core_mtx,
6500	       0, "wait for pkt", 0);
6501	SCTP_MCORE_UNLOCK(wkq);
6502
6503	/* Bind to our cpu */
6504	thread_lock(curthread);
6505	sched_bind(curthread, wkq->cpuid);
6506	thread_unlock(curthread);
6507
6508	/* Now lets start working */
6509	SCTP_MCORE_LOCK(wkq);
6510	/* Now grab lock and go */
6511	for (;;) {
6512		SCTP_MCORE_QLOCK(wkq);
6513	skip_sleep:
6514		wkq->running = 1;
6515		qent = TAILQ_FIRST(&wkq->que);
6516		if (qent) {
6517			TAILQ_REMOVE(&wkq->que, qent, next);
6518			SCTP_MCORE_QUNLOCK(wkq);
6519#if defined(__FreeBSD__) && __FreeBSD_version >= 801000
6520			CURVNET_SET(qent->vn);
6521#endif
6522			m = qent->m;
6523			off = qent->off;
6524			v6 = qent->v6;
6525			SCTP_FREE(qent, SCTP_M_MCORE);
6526			if (v6 == 0) {
6527				sctp_input_with_port(m, off, 0);
6528			} else {
6529				SCTP_PRINTF("V6 not yet supported\n");
6530				sctp_m_freem(m);
6531			}
6532#if defined(__FreeBSD__) && __FreeBSD_version >= 801000
6533			CURVNET_RESTORE();
6534#endif
6535			SCTP_MCORE_QLOCK(wkq);
6536		}
6537		wkq->running = 0;
6538		if (!TAILQ_EMPTY(&wkq->que)) {
6539			goto skip_sleep;
6540		}
6541		SCTP_MCORE_QUNLOCK(wkq);
6542		msleep(&wkq->running,
6543		       &wkq->core_mtx,
6544		       0, "wait for pkt", 0);
6545	}
6546}
6547
6548static void
6549sctp_startup_mcore_threads(void)
6550{
6551	int i, cpu;
6552
6553	if (mp_ncpus == 1)
6554		return;
6555
6556	if (sctp_mcore_workers != NULL) {
6557		/* Already been here in some previous
6558		 * vnet?
6559		 */
6560		return;
6561	}
6562	SCTP_MALLOC(sctp_mcore_workers, struct sctp_mcore_ctrl *,
6563		    ((mp_maxid+1) * sizeof(struct sctp_mcore_ctrl)),
6564		    SCTP_M_MCORE);
6565	if (sctp_mcore_workers == NULL) {
6566		/* TSNH I hope */
6567		return;
6568	}
6569	memset(sctp_mcore_workers, 0 , ((mp_maxid+1) *
6570					sizeof(struct sctp_mcore_ctrl)));
6571	/* Init the structures */
6572	for (i = 0; i<=mp_maxid; i++) {
6573		TAILQ_INIT(&sctp_mcore_workers[i].que);
6574		SCTP_MCORE_LOCK_INIT(&sctp_mcore_workers[i]);
6575		SCTP_MCORE_QLOCK_INIT(&sctp_mcore_workers[i]);
6576		sctp_mcore_workers[i].cpuid = i;
6577	}
6578	if (sctp_cpuarry == NULL) {
6579		SCTP_MALLOC(sctp_cpuarry, int *,
6580			    (mp_ncpus * sizeof(int)),
6581			    SCTP_M_MCORE);
6582		i = 0;
6583		CPU_FOREACH(cpu) {
6584			sctp_cpuarry[i] = cpu;
6585			i++;
6586		}
6587	}
6588
6589	/* Now start them all */
6590	CPU_FOREACH(cpu) {
6591#if __FreeBSD_version <= 701000
6592		(void)kthread_create(sctp_mcore_thread,
6593				     (void *)&sctp_mcore_workers[cpu],
6594				     &sctp_mcore_workers[cpu].thread_proc,
6595				     RFPROC,
6596				     SCTP_KTHREAD_PAGES,
6597				     SCTP_MCORE_NAME);
6598
6599#else
6600		(void)kproc_create(sctp_mcore_thread,
6601				   (void *)&sctp_mcore_workers[cpu],
6602				   &sctp_mcore_workers[cpu].thread_proc,
6603				   RFPROC,
6604				   SCTP_KTHREAD_PAGES,
6605				   SCTP_MCORE_NAME);
6606#endif
6607
6608	}
6609}
6610#endif
6611#if defined(__FreeBSD__) && __FreeBSD_cc_version >= 1200000
6612static struct mbuf *
6613sctp_netisr_hdlr(struct mbuf *m, uintptr_t source)
6614{
6615	struct ip *ip;
6616	struct sctphdr *sh;
6617	int offset;
6618	uint32_t flowid, tag;
6619
6620	/*
6621	 * No flow id built by lower layers fix it so we
6622	 * create one.
6623	 */
6624	ip = mtod(m, struct ip *);
6625	offset = (ip->ip_hl << 2) + sizeof(struct sctphdr);
6626	if (SCTP_BUF_LEN(m) < offset) {
6627		if ((m = m_pullup(m, offset)) == NULL) {
6628			SCTP_STAT_INCR(sctps_hdrops);
6629			return (NULL);
6630		}
6631		ip = mtod(m, struct ip *);
6632	}
6633	sh = (struct sctphdr *)((caddr_t)ip + (ip->ip_hl << 2));
6634	tag = htonl(sh->v_tag);
6635	flowid = tag ^ ntohs(sh->dest_port) ^ ntohs(sh->src_port);
6636	m->m_pkthdr.flowid = flowid;
6637	m->m_flags |= M_FLOWID;
6638	return (m);
6639}
6640#endif
6641
6642void
6643sctp_pcb_init()
6644{
6645	/*
6646	 * SCTP initialization for the PCB structures should be called by
6647	 * the sctp_init() funciton.
6648	 */
6649	int i;
6650	struct timeval tv;
6651
6652	if (SCTP_BASE_VAR(sctp_pcb_initialized) != 0) {
6653		/* error I was called twice */
6654		return;
6655	}
6656	SCTP_BASE_VAR(sctp_pcb_initialized) = 1;
6657
6658#if defined(SCTP_LOCAL_TRACE_BUF)
6659#if defined(__Windows__)
6660	if (SCTP_BASE_SYSCTL(sctp_log) != NULL) {
6661		bzero(SCTP_BASE_SYSCTL(sctp_log), sizeof(struct sctp_log));
6662	}
6663#else
6664	bzero(&SCTP_BASE_SYSCTL(sctp_log), sizeof(struct sctp_log));
6665#endif
6666#endif
6667#if defined(__FreeBSD__) && defined(SMP) && defined(SCTP_USE_PERCPU_STAT)
6668	SCTP_MALLOC(SCTP_BASE_STATS, struct sctpstat *,
6669		    ((mp_maxid+1) * sizeof(struct sctpstat)),
6670		    SCTP_M_MCORE);
6671#endif
6672	(void)SCTP_GETTIME_TIMEVAL(&tv);
6673#if defined(__FreeBSD__) && defined(SMP) && defined(SCTP_USE_PERCPU_STAT)
6674	bzero(SCTP_BASE_STATS, (sizeof(struct sctpstat) * (mp_maxid+1)));
6675	SCTP_BASE_STATS[PCPU_GET(cpuid)].sctps_discontinuitytime.tv_sec = (uint32_t)tv.tv_sec;
6676	SCTP_BASE_STATS[PCPU_GET(cpuid)].sctps_discontinuitytime.tv_usec = (uint32_t)tv.tv_usec;
6677#else
6678	bzero(&SCTP_BASE_STATS, sizeof(struct sctpstat));
6679	SCTP_BASE_STAT(sctps_discontinuitytime).tv_sec = (uint32_t)tv.tv_sec;
6680	SCTP_BASE_STAT(sctps_discontinuitytime).tv_usec = (uint32_t)tv.tv_usec;
6681#endif
6682	/* init the empty list of (All) Endpoints */
6683	LIST_INIT(&SCTP_BASE_INFO(listhead));
6684#if defined(__APPLE__)
6685	LIST_INIT(&SCTP_BASE_INFO(inplisthead));
6686#if defined(APPLE_LEOPARD) || defined(APPLE_SNOWLEOPARD) || defined(APPLE_LION) || defined(APPLE_MOUNTAINLION)
6687	SCTP_BASE_INFO(sctbinfo).listhead = &SCTP_BASE_INFO(inplisthead);
6688	SCTP_BASE_INFO(sctbinfo).mtx_grp_attr = lck_grp_attr_alloc_init();
6689	lck_grp_attr_setdefault(SCTP_BASE_INFO(sctbinfo).mtx_grp_attr);
6690	SCTP_BASE_INFO(sctbinfo).mtx_grp = lck_grp_alloc_init("sctppcb", SCTP_BASE_INFO(sctbinfo).mtx_grp_attr);
6691	SCTP_BASE_INFO(sctbinfo).mtx_attr = lck_attr_alloc_init();
6692	lck_attr_setdefault(SCTP_BASE_INFO(sctbinfo).mtx_attr);
6693#else
6694	SCTP_BASE_INFO(sctbinfo).ipi_listhead = &SCTP_BASE_INFO(inplisthead);
6695	SCTP_BASE_INFO(sctbinfo).ipi_lock_grp_attr = lck_grp_attr_alloc_init();
6696	lck_grp_attr_setdefault(SCTP_BASE_INFO(sctbinfo).ipi_lock_grp_attr);
6697	SCTP_BASE_INFO(sctbinfo).ipi_lock_grp = lck_grp_alloc_init("sctppcb", SCTP_BASE_INFO(sctbinfo).ipi_lock_grp_attr);
6698	SCTP_BASE_INFO(sctbinfo).ipi_lock_attr = lck_attr_alloc_init();
6699	lck_attr_setdefault(SCTP_BASE_INFO(sctbinfo).ipi_lock_attr);
6700#endif
6701#if !defined(APPLE_LEOPARD) && !defined(APPLE_SNOWLEOPARD) && !defined(APPLE_LION) && !defined(APPLE_MOUNTAINLION)
6702	SCTP_BASE_INFO(sctbinfo).ipi_gc = sctp_gc;
6703	in_pcbinfo_attach(&SCTP_BASE_INFO(sctbinfo));
6704#endif
6705#endif
6706
6707
6708	/* init the hash table of endpoints */
6709#if defined(__FreeBSD__)
6710#if defined(__FreeBSD_cc_version) && __FreeBSD_cc_version >= 440000
6711	TUNABLE_INT_FETCH("net.inet.sctp.tcbhashsize", &SCTP_BASE_SYSCTL(sctp_hashtblsize));
6712	TUNABLE_INT_FETCH("net.inet.sctp.pcbhashsize", &SCTP_BASE_SYSCTL(sctp_pcbtblsize));
6713	TUNABLE_INT_FETCH("net.inet.sctp.chunkscale", &SCTP_BASE_SYSCTL(sctp_chunkscale));
6714#else
6715	TUNABLE_INT_FETCH("net.inet.sctp.tcbhashsize", SCTP_TCBHASHSIZE,
6716			  SCTP_BASE_SYSCTL(sctp_hashtblsize));
6717	TUNABLE_INT_FETCH("net.inet.sctp.pcbhashsize", SCTP_PCBHASHSIZE,
6718			  SCTP_BASE_SYSCTL(sctp_pcbtblsize));
6719	TUNABLE_INT_FETCH("net.inet.sctp.chunkscale", SCTP_CHUNKQUEUE_SCALE,
6720			  SCTP_BASE_SYSCTL(sctp_chunkscale));
6721#endif
6722#endif
6723	SCTP_BASE_INFO(sctp_asochash) = SCTP_HASH_INIT((SCTP_BASE_SYSCTL(sctp_hashtblsize) * 31),
6724						       &SCTP_BASE_INFO(hashasocmark));
6725	SCTP_BASE_INFO(sctp_ephash) = SCTP_HASH_INIT(SCTP_BASE_SYSCTL(sctp_hashtblsize),
6726						     &SCTP_BASE_INFO(hashmark));
6727	SCTP_BASE_INFO(sctp_tcpephash) = SCTP_HASH_INIT(SCTP_BASE_SYSCTL(sctp_hashtblsize),
6728							&SCTP_BASE_INFO(hashtcpmark));
6729	SCTP_BASE_INFO(hashtblsize) = SCTP_BASE_SYSCTL(sctp_hashtblsize);
6730
6731
6732	SCTP_BASE_INFO(sctp_vrfhash) = SCTP_HASH_INIT(SCTP_SIZE_OF_VRF_HASH,
6733						      &SCTP_BASE_INFO(hashvrfmark));
6734
6735	SCTP_BASE_INFO(vrf_ifn_hash) = SCTP_HASH_INIT(SCTP_VRF_IFN_HASH_SIZE,
6736						      &SCTP_BASE_INFO(vrf_ifn_hashmark));
6737	/* init the zones */
6738	/*
6739	 * FIX ME: Should check for NULL returns, but if it does fail we are
6740	 * doomed to panic anyways... add later maybe.
6741	 */
6742	SCTP_ZONE_INIT(SCTP_BASE_INFO(ipi_zone_ep), "sctp_ep",
6743		       sizeof(struct sctp_inpcb), maxsockets);
6744
6745	SCTP_ZONE_INIT(SCTP_BASE_INFO(ipi_zone_asoc), "sctp_asoc",
6746		       sizeof(struct sctp_tcb), sctp_max_number_of_assoc);
6747
6748	SCTP_ZONE_INIT(SCTP_BASE_INFO(ipi_zone_laddr), "sctp_laddr",
6749		       sizeof(struct sctp_laddr),
6750		       (sctp_max_number_of_assoc * sctp_scale_up_for_address));
6751
6752	SCTP_ZONE_INIT(SCTP_BASE_INFO(ipi_zone_net), "sctp_raddr",
6753		       sizeof(struct sctp_nets),
6754		       (sctp_max_number_of_assoc * sctp_scale_up_for_address));
6755
6756	SCTP_ZONE_INIT(SCTP_BASE_INFO(ipi_zone_chunk), "sctp_chunk",
6757		       sizeof(struct sctp_tmit_chunk),
6758		       (sctp_max_number_of_assoc * SCTP_BASE_SYSCTL(sctp_chunkscale)));
6759
6760	SCTP_ZONE_INIT(SCTP_BASE_INFO(ipi_zone_readq), "sctp_readq",
6761		       sizeof(struct sctp_queued_to_read),
6762		       (sctp_max_number_of_assoc * SCTP_BASE_SYSCTL(sctp_chunkscale)));
6763
6764	SCTP_ZONE_INIT(SCTP_BASE_INFO(ipi_zone_strmoq), "sctp_stream_msg_out",
6765		       sizeof(struct sctp_stream_queue_pending),
6766		       (sctp_max_number_of_assoc * SCTP_BASE_SYSCTL(sctp_chunkscale)));
6767
6768	SCTP_ZONE_INIT(SCTP_BASE_INFO(ipi_zone_asconf), "sctp_asconf",
6769		       sizeof(struct sctp_asconf),
6770		       (sctp_max_number_of_assoc * SCTP_BASE_SYSCTL(sctp_chunkscale)));
6771
6772	SCTP_ZONE_INIT(SCTP_BASE_INFO(ipi_zone_asconf_ack), "sctp_asconf_ack",
6773		       sizeof(struct sctp_asconf_ack),
6774		       (sctp_max_number_of_assoc * SCTP_BASE_SYSCTL(sctp_chunkscale)));
6775
6776
6777	/* Master Lock INIT for info structure */
6778	SCTP_INP_INFO_LOCK_INIT();
6779	SCTP_STATLOG_INIT_LOCK();
6780
6781	SCTP_IPI_COUNT_INIT();
6782	SCTP_IPI_ADDR_INIT();
6783#ifdef SCTP_PACKET_LOGGING
6784	SCTP_IP_PKTLOG_INIT();
6785#endif
6786	LIST_INIT(&SCTP_BASE_INFO(addr_wq));
6787
6788	SCTP_WQ_ADDR_INIT();
6789	/* not sure if we need all the counts */
6790	SCTP_BASE_INFO(ipi_count_ep) = 0;
6791	/* assoc/tcb zone info */
6792	SCTP_BASE_INFO(ipi_count_asoc) = 0;
6793	/* local addrlist zone info */
6794	SCTP_BASE_INFO(ipi_count_laddr) = 0;
6795	/* remote addrlist zone info */
6796	SCTP_BASE_INFO(ipi_count_raddr) = 0;
6797	/* chunk info */
6798	SCTP_BASE_INFO(ipi_count_chunk) = 0;
6799
6800	/* socket queue zone info */
6801	SCTP_BASE_INFO(ipi_count_readq) = 0;
6802
6803	/* stream out queue cont */
6804	SCTP_BASE_INFO(ipi_count_strmoq) = 0;
6805
6806	SCTP_BASE_INFO(ipi_free_strmoq) = 0;
6807	SCTP_BASE_INFO(ipi_free_chunks) = 0;
6808
6809	SCTP_OS_TIMER_INIT(&SCTP_BASE_INFO(addr_wq_timer.timer));
6810
6811	/* Init the TIMEWAIT list */
6812	for (i = 0; i < SCTP_STACK_VTAG_HASH_SIZE; i++) {
6813		LIST_INIT(&SCTP_BASE_INFO(vtag_timewait)[i]);
6814	}
6815#if defined(SCTP_PROCESS_LEVEL_LOCKS)
6816#if defined(__Userspace_os_Windows)
6817	InitializeConditionVariable(&sctp_it_ctl.iterator_wakeup);
6818#else
6819	(void)pthread_cond_init(&sctp_it_ctl.iterator_wakeup, NULL);
6820#endif
6821#endif
6822	sctp_startup_iterator();
6823
6824#if defined(__FreeBSD__) && defined(SCTP_MCORE_INPUT) && defined(SMP)
6825	sctp_startup_mcore_threads();
6826#endif
6827
6828#ifndef __Panda__
6829	/*
6830	 * INIT the default VRF which for BSD is the only one, other O/S's
6831	 * may have more. But initially they must start with one and then
6832	 * add the VRF's as addresses are added.
6833	 */
6834	sctp_init_vrf_list(SCTP_DEFAULT_VRF);
6835#endif
6836#if defined(__FreeBSD__) && __FreeBSD_cc_version >= 1200000
6837	if (ip_register_flow_handler(sctp_netisr_hdlr, IPPROTO_SCTP)) {
6838		SCTP_PRINTF("***SCTP- Error can't register netisr handler***\n");
6839	}
6840#endif
6841#if defined(_SCTP_NEEDS_CALLOUT_) || defined(_USER_SCTP_NEEDS_CALLOUT_)
6842	/* allocate the lock for the callout/timer queue */
6843	SCTP_TIMERQ_LOCK_INIT();
6844	TAILQ_INIT(&SCTP_BASE_INFO(callqueue));
6845#endif
6846#if defined(__Userspace__)
6847	mbuf_init(NULL);
6848	atomic_init();
6849#if defined(INET) || defined(INET6)
6850	recv_thread_init();
6851#endif
6852#endif
6853}
6854
6855/*
6856 * Assumes that the SCTP_BASE_INFO() lock is NOT held.
6857 */
6858void
6859sctp_pcb_finish(void)
6860{
6861	struct sctp_vrflist *vrf_bucket;
6862	struct sctp_vrf *vrf, *nvrf;
6863	struct sctp_ifn *ifn, *nifn;
6864	struct sctp_ifa *ifa, *nifa;
6865	struct sctpvtaghead *chain;
6866	struct sctp_tagblock *twait_block, *prev_twait_block;
6867	struct sctp_laddr *wi, *nwi;
6868	int i;
6869	struct sctp_iterator *it, *nit;
6870
6871#if !defined(__FreeBSD__)
6872	/* Notify the iterator to exit. */
6873	SCTP_IPI_ITERATOR_WQ_LOCK();
6874	sctp_it_ctl.iterator_flags |= SCTP_ITERATOR_MUST_EXIT;
6875	sctp_wakeup_iterator();
6876	SCTP_IPI_ITERATOR_WQ_UNLOCK();
6877#endif
6878#if defined(__APPLE__)
6879#if !defined(APPLE_LEOPARD) && !defined(APPLE_SNOWLEOPARD) && !defined(APPLE_LION) && !defined(APPLE_MOUNTAINLION)
6880	in_pcbinfo_detach(&SCTP_BASE_INFO(sctbinfo));
6881#endif
6882	SCTP_IPI_ITERATOR_WQ_LOCK();
6883	do {
6884		msleep(&sctp_it_ctl.iterator_flags,
6885		       sctp_it_ctl.ipi_iterator_wq_mtx,
6886		       0, "waiting_for_work", 0);
6887	} while ((sctp_it_ctl.iterator_flags & SCTP_ITERATOR_EXITED) == 0);
6888	thread_deallocate(sctp_it_ctl.thread_proc);
6889	SCTP_IPI_ITERATOR_WQ_UNLOCK();
6890#endif
6891#if defined(__Windows__)
6892	if (sctp_it_ctl.iterator_thread_obj != NULL) {
6893		NTSTATUS status = STATUS_SUCCESS;
6894
6895		KeSetEvent(&sctp_it_ctl.iterator_wakeup[1], IO_NO_INCREMENT, FALSE);
6896		status = KeWaitForSingleObject(sctp_it_ctl.iterator_thread_obj,
6897					       Executive,
6898					       KernelMode,
6899					       FALSE,
6900					       NULL);
6901		ObDereferenceObject(sctp_it_ctl.iterator_thread_obj);
6902	}
6903#endif
6904#if defined(__Userspace__)
6905	if (sctp_it_ctl.thread_proc) {
6906#if defined(__Userspace_os_Windows)
6907		WaitForSingleObject(sctp_it_ctl.thread_proc, INFINITE);
6908		CloseHandle(sctp_it_ctl.thread_proc);
6909		sctp_it_ctl.thread_proc = NULL;
6910#else
6911		pthread_join(sctp_it_ctl.thread_proc, NULL);
6912		sctp_it_ctl.thread_proc = 0;
6913#endif
6914	}
6915#endif
6916#if defined(SCTP_PROCESS_LEVEL_LOCKS)
6917#if defined(__Userspace_os_Windows)
6918	DeleteConditionVariable(&sctp_it_ctl.iterator_wakeup);
6919#else
6920	pthread_cond_destroy(&sctp_it_ctl.iterator_wakeup);
6921#endif
6922#endif
6923	/* In FreeBSD the iterator thread never exits
6924	 * but we do clean up.
6925	 * The only way FreeBSD reaches here is if we have VRF's
6926	 * but we still add the ifdef to make it compile on old versions.
6927	 */
6928	SCTP_IPI_ITERATOR_WQ_LOCK();
6929	TAILQ_FOREACH_SAFE(it, &sctp_it_ctl.iteratorhead, sctp_nxt_itr, nit) {
6930#if defined(__FreeBSD__) && __FreeBSD_version >= 801000
6931		if (it->vn != curvnet) {
6932			continue;
6933		}
6934#endif
6935		TAILQ_REMOVE(&sctp_it_ctl.iteratorhead, it, sctp_nxt_itr);
6936		if (it->function_atend != NULL) {
6937			(*it->function_atend) (it->pointer, it->val);
6938		}
6939		SCTP_FREE(it,SCTP_M_ITER);
6940	}
6941	SCTP_IPI_ITERATOR_WQ_UNLOCK();
6942#if defined(__FreeBSD__) && __FreeBSD_version >= 801000
6943	SCTP_ITERATOR_LOCK();
6944	if ((sctp_it_ctl.cur_it) &&
6945	    (sctp_it_ctl.cur_it->vn == curvnet)) {
6946		sctp_it_ctl.iterator_flags |= SCTP_ITERATOR_STOP_CUR_IT;
6947	}
6948	SCTP_ITERATOR_UNLOCK();
6949#endif
6950#if !defined(__FreeBSD__)
6951	SCTP_IPI_ITERATOR_WQ_DESTROY();
6952	SCTP_ITERATOR_LOCK_DESTROY();
6953#endif
6954	SCTP_OS_TIMER_STOP(&SCTP_BASE_INFO(addr_wq_timer.timer));
6955	SCTP_WQ_ADDR_LOCK();
6956	LIST_FOREACH_SAFE(wi, &SCTP_BASE_INFO(addr_wq), sctp_nxt_addr, nwi) {
6957		LIST_REMOVE(wi, sctp_nxt_addr);
6958		SCTP_DECR_LADDR_COUNT();
6959		if (wi->action == SCTP_DEL_IP_ADDRESS) {
6960			SCTP_FREE(wi->ifa, SCTP_M_IFA);
6961		}
6962		SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_laddr), wi);
6963	}
6964	SCTP_WQ_ADDR_UNLOCK();
6965
6966	/*
6967	 * free the vrf/ifn/ifa lists and hashes (be sure address monitor
6968	 * is destroyed first).
6969	 */
6970	vrf_bucket = &SCTP_BASE_INFO(sctp_vrfhash)[(SCTP_DEFAULT_VRFID & SCTP_BASE_INFO(hashvrfmark))];
6971	LIST_FOREACH_SAFE(vrf, vrf_bucket, next_vrf, nvrf) {
6972		LIST_FOREACH_SAFE(ifn, &vrf->ifnlist, next_ifn, nifn) {
6973			LIST_FOREACH_SAFE(ifa, &ifn->ifalist, next_ifa, nifa) {
6974				/* free the ifa */
6975				LIST_REMOVE(ifa, next_bucket);
6976				LIST_REMOVE(ifa, next_ifa);
6977				SCTP_FREE(ifa, SCTP_M_IFA);
6978			}
6979			/* free the ifn */
6980			LIST_REMOVE(ifn, next_bucket);
6981			LIST_REMOVE(ifn, next_ifn);
6982			SCTP_FREE(ifn, SCTP_M_IFN);
6983		}
6984		SCTP_HASH_FREE(vrf->vrf_addr_hash, vrf->vrf_addr_hashmark);
6985		/* free the vrf */
6986		LIST_REMOVE(vrf, next_vrf);
6987		SCTP_FREE(vrf, SCTP_M_VRF);
6988	}
6989	/* free the vrf hashes */
6990	SCTP_HASH_FREE(SCTP_BASE_INFO(sctp_vrfhash), SCTP_BASE_INFO(hashvrfmark));
6991	SCTP_HASH_FREE(SCTP_BASE_INFO(vrf_ifn_hash), SCTP_BASE_INFO(vrf_ifn_hashmark));
6992#if defined(__Userspace__) && !defined(__Userspace_os_Windows)
6993	/* free memory allocated by getifaddrs call */
6994#if defined(INET) || defined(INET6)
6995	freeifaddrs(g_interfaces);
6996#endif
6997#endif
6998
6999	/* free the TIMEWAIT list elements malloc'd in the function
7000	 * sctp_add_vtag_to_timewait()...
7001	 */
7002	for (i = 0; i < SCTP_STACK_VTAG_HASH_SIZE; i++) {
7003		chain = &SCTP_BASE_INFO(vtag_timewait)[i];
7004		if (!LIST_EMPTY(chain)) {
7005			prev_twait_block = NULL;
7006			LIST_FOREACH(twait_block, chain, sctp_nxt_tagblock) {
7007				if (prev_twait_block) {
7008					SCTP_FREE(prev_twait_block, SCTP_M_TIMW);
7009				}
7010				prev_twait_block = twait_block;
7011			}
7012			SCTP_FREE(prev_twait_block, SCTP_M_TIMW);
7013		}
7014	}
7015
7016	/* free the locks and mutexes */
7017#if defined(__APPLE__)
7018	SCTP_TIMERQ_LOCK_DESTROY();
7019#endif
7020#ifdef SCTP_PACKET_LOGGING
7021	SCTP_IP_PKTLOG_DESTROY();
7022#endif
7023	SCTP_IPI_ADDR_DESTROY();
7024#if defined(__APPLE__)
7025	SCTP_IPI_COUNT_DESTROY();
7026#endif
7027	SCTP_STATLOG_DESTROY();
7028	SCTP_INP_INFO_LOCK_DESTROY();
7029
7030	SCTP_WQ_ADDR_DESTROY();
7031
7032#if defined(__APPLE__)
7033#if defined(APPLE_LEOPARD) || defined(APPLE_SNOWLEOPARD) || defined(APPLE_LION) || defined(APPLE_MOUNTAINLION)
7034	lck_grp_attr_free(SCTP_BASE_INFO(sctbinfo).mtx_grp_attr);
7035	lck_grp_free(SCTP_BASE_INFO(sctbinfo).mtx_grp);
7036	lck_attr_free(SCTP_BASE_INFO(sctbinfo).mtx_attr);
7037#else
7038	lck_grp_attr_free(SCTP_BASE_INFO(sctbinfo).ipi_lock_grp_attr);
7039	lck_grp_free(SCTP_BASE_INFO(sctbinfo).ipi_lock_grp);
7040	lck_attr_free(SCTP_BASE_INFO(sctbinfo).ipi_lock_attr);
7041#endif
7042#endif
7043#if defined(__Userspace__)
7044	SCTP_TIMERQ_LOCK_DESTROY();
7045	SCTP_ZONE_DESTROY(zone_mbuf);
7046	SCTP_ZONE_DESTROY(zone_clust);
7047	SCTP_ZONE_DESTROY(zone_ext_refcnt);
7048#endif
7049#if defined(__Windows__) || defined(__FreeBSD__) || defined(__Userspace__)
7050	SCTP_ZONE_DESTROY(SCTP_BASE_INFO(ipi_zone_ep));
7051	SCTP_ZONE_DESTROY(SCTP_BASE_INFO(ipi_zone_asoc));
7052	SCTP_ZONE_DESTROY(SCTP_BASE_INFO(ipi_zone_laddr));
7053	SCTP_ZONE_DESTROY(SCTP_BASE_INFO(ipi_zone_net));
7054	SCTP_ZONE_DESTROY(SCTP_BASE_INFO(ipi_zone_chunk));
7055	SCTP_ZONE_DESTROY(SCTP_BASE_INFO(ipi_zone_readq));
7056	SCTP_ZONE_DESTROY(SCTP_BASE_INFO(ipi_zone_strmoq));
7057	SCTP_ZONE_DESTROY(SCTP_BASE_INFO(ipi_zone_asconf));
7058	SCTP_ZONE_DESTROY(SCTP_BASE_INFO(ipi_zone_asconf_ack));
7059#endif
7060	/* Get rid of other stuff to */
7061	if (SCTP_BASE_INFO(sctp_asochash) != NULL)
7062		SCTP_HASH_FREE(SCTP_BASE_INFO(sctp_asochash), SCTP_BASE_INFO(hashasocmark));
7063	if (SCTP_BASE_INFO(sctp_ephash) != NULL)
7064		SCTP_HASH_FREE(SCTP_BASE_INFO(sctp_ephash), SCTP_BASE_INFO(hashmark));
7065	if (SCTP_BASE_INFO(sctp_tcpephash) != NULL)
7066		SCTP_HASH_FREE(SCTP_BASE_INFO(sctp_tcpephash), SCTP_BASE_INFO(hashtcpmark));
7067#if defined(__FreeBSD__) && defined(SMP) && defined(SCTP_USE_PERCPU_STAT)
7068	SCTP_FREE(SCTP_BASE_STATS, SCTP_M_MCORE);
7069#endif
7070}
7071
7072
7073int
7074sctp_load_addresses_from_init(struct sctp_tcb *stcb, struct mbuf *m,
7075                              int offset, int limit,
7076                              struct sockaddr *src, struct sockaddr *dst,
7077                              struct sockaddr *altsa)
7078{
7079	/*
7080	 * grub through the INIT pulling addresses and loading them to the
7081	 * nets structure in the asoc. The from address in the mbuf should
7082	 * also be loaded (if it is not already). This routine can be called
7083	 * with either INIT or INIT-ACK's as long as the m points to the IP
7084	 * packet and the offset points to the beginning of the parameters.
7085	 */
7086	struct sctp_inpcb *inp;
7087	struct sctp_nets *net, *nnet, *net_tmp;
7088	struct sctp_paramhdr *phdr, parm_buf;
7089	struct sctp_tcb *stcb_tmp;
7090	uint16_t ptype, plen;
7091	struct sockaddr *sa;
7092	uint8_t random_store[SCTP_PARAM_BUFFER_SIZE];
7093	struct sctp_auth_random *p_random = NULL;
7094	uint16_t random_len = 0;
7095	uint8_t hmacs_store[SCTP_PARAM_BUFFER_SIZE];
7096	struct sctp_auth_hmac_algo *hmacs = NULL;
7097	uint16_t hmacs_len = 0;
7098	uint8_t saw_asconf = 0;
7099	uint8_t saw_asconf_ack = 0;
7100	uint8_t chunks_store[SCTP_PARAM_BUFFER_SIZE];
7101	struct sctp_auth_chunk_list *chunks = NULL;
7102	uint16_t num_chunks = 0;
7103	sctp_key_t *new_key;
7104	uint32_t keylen;
7105	int got_random = 0, got_hmacs = 0, got_chklist = 0;
7106	uint8_t peer_supports_ecn;
7107	uint8_t peer_supports_prsctp;
7108	uint8_t peer_supports_auth;
7109	uint8_t peer_supports_asconf;
7110	uint8_t peer_supports_asconf_ack;
7111	uint8_t peer_supports_reconfig;
7112	uint8_t peer_supports_nrsack;
7113	uint8_t peer_supports_pktdrop;
7114#ifdef INET
7115	struct sockaddr_in sin;
7116#endif
7117#ifdef INET6
7118	struct sockaddr_in6 sin6;
7119#endif
7120
7121	/* First get the destination address setup too. */
7122#ifdef INET
7123	memset(&sin, 0, sizeof(sin));
7124	sin.sin_family = AF_INET;
7125#ifdef HAVE_SIN_LEN
7126	sin.sin_len = sizeof(sin);
7127#endif
7128	sin.sin_port = stcb->rport;
7129#endif
7130#ifdef INET6
7131	memset(&sin6, 0, sizeof(sin6));
7132	sin6.sin6_family = AF_INET6;
7133#ifdef HAVE_SIN6_LEN
7134	sin6.sin6_len = sizeof(struct sockaddr_in6);
7135#endif
7136	sin6.sin6_port = stcb->rport;
7137#endif
7138	if (altsa) {
7139		sa = altsa;
7140	} else {
7141		sa = src;
7142	}
7143	peer_supports_ecn = 0;
7144	peer_supports_prsctp = 0;
7145	peer_supports_auth = 0;
7146	peer_supports_asconf = 0;
7147	peer_supports_reconfig = 0;
7148	peer_supports_nrsack = 0;
7149	peer_supports_pktdrop = 0;
7150	TAILQ_FOREACH(net, &stcb->asoc.nets, sctp_next) {
7151		/* mark all addresses that we have currently on the list */
7152		net->dest_state |= SCTP_ADDR_NOT_IN_ASSOC;
7153	}
7154	/* does the source address already exist? if so skip it */
7155	inp = stcb->sctp_ep;
7156	atomic_add_int(&stcb->asoc.refcnt, 1);
7157	stcb_tmp = sctp_findassociation_ep_addr(&inp, sa, &net_tmp, dst, stcb);
7158	atomic_add_int(&stcb->asoc.refcnt, -1);
7159
7160	if ((stcb_tmp == NULL && inp == stcb->sctp_ep) || inp == NULL) {
7161		/* we must add the source address */
7162		/* no scope set here since we have a tcb already. */
7163		switch (sa->sa_family) {
7164#ifdef INET
7165		case AF_INET:
7166			if (stcb->asoc.scope.ipv4_addr_legal) {
7167				if (sctp_add_remote_addr(stcb, sa, NULL, SCTP_DONOT_SETSCOPE, SCTP_LOAD_ADDR_2)) {
7168					return (-1);
7169				}
7170			}
7171			break;
7172#endif
7173#ifdef INET6
7174		case AF_INET6:
7175			if (stcb->asoc.scope.ipv6_addr_legal) {
7176				if (sctp_add_remote_addr(stcb, sa, NULL, SCTP_DONOT_SETSCOPE, SCTP_LOAD_ADDR_3)) {
7177					return (-2);
7178				}
7179			}
7180			break;
7181#endif
7182#if defined(__Userspace__)
7183		case AF_CONN:
7184			if (stcb->asoc.scope.conn_addr_legal) {
7185				if (sctp_add_remote_addr(stcb, sa, NULL, SCTP_DONOT_SETSCOPE, SCTP_LOAD_ADDR_3)) {
7186					return (-2);
7187				}
7188			}
7189			break;
7190#endif
7191		default:
7192			break;
7193		}
7194	} else {
7195		if (net_tmp != NULL && stcb_tmp == stcb) {
7196			net_tmp->dest_state &= ~SCTP_ADDR_NOT_IN_ASSOC;
7197		} else if (stcb_tmp != stcb) {
7198			/* It belongs to another association? */
7199			if (stcb_tmp)
7200				SCTP_TCB_UNLOCK(stcb_tmp);
7201			return (-3);
7202		}
7203	}
7204	if (stcb->asoc.state == 0) {
7205		/* the assoc was freed? */
7206		return (-4);
7207	}
7208	/* now we must go through each of the params. */
7209	phdr = sctp_get_next_param(m, offset, &parm_buf, sizeof(parm_buf));
7210	while (phdr) {
7211		ptype = ntohs(phdr->param_type);
7212		plen = ntohs(phdr->param_length);
7213		/*
7214		 * SCTP_PRINTF("ptype => %0x, plen => %d\n", (uint32_t)ptype,
7215		 * (int)plen);
7216		 */
7217		if (offset + plen > limit) {
7218			break;
7219		}
7220		if (plen == 0) {
7221			break;
7222		}
7223#ifdef INET
7224		if (ptype == SCTP_IPV4_ADDRESS) {
7225			if (stcb->asoc.scope.ipv4_addr_legal) {
7226				struct sctp_ipv4addr_param *p4, p4_buf;
7227
7228				/* ok get the v4 address and check/add */
7229				phdr = sctp_get_next_param(m, offset,
7230							   (struct sctp_paramhdr *)&p4_buf,
7231							   sizeof(p4_buf));
7232				if (plen != sizeof(struct sctp_ipv4addr_param) ||
7233				    phdr == NULL) {
7234					return (-5);
7235				}
7236				p4 = (struct sctp_ipv4addr_param *)phdr;
7237				sin.sin_addr.s_addr = p4->addr;
7238				if (IN_MULTICAST(ntohl(sin.sin_addr.s_addr))) {
7239					/* Skip multi-cast addresses */
7240					goto next_param;
7241				}
7242				if ((sin.sin_addr.s_addr == INADDR_BROADCAST) ||
7243				    (sin.sin_addr.s_addr == INADDR_ANY)) {
7244					goto next_param;
7245				}
7246				sa = (struct sockaddr *)&sin;
7247				inp = stcb->sctp_ep;
7248				atomic_add_int(&stcb->asoc.refcnt, 1);
7249				stcb_tmp = sctp_findassociation_ep_addr(&inp, sa, &net,
7250									dst, stcb);
7251				atomic_add_int(&stcb->asoc.refcnt, -1);
7252
7253				if ((stcb_tmp == NULL && inp == stcb->sctp_ep) ||
7254				    inp == NULL) {
7255					/* we must add the source address */
7256					/*
7257					 * no scope set since we have a tcb
7258					 * already
7259					 */
7260
7261					/*
7262					 * we must validate the state again
7263					 * here
7264					 */
7265				add_it_now:
7266					if (stcb->asoc.state == 0) {
7267						/* the assoc was freed? */
7268						return (-7);
7269					}
7270					if (sctp_add_remote_addr(stcb, sa, NULL, SCTP_DONOT_SETSCOPE, SCTP_LOAD_ADDR_4)) {
7271						return (-8);
7272					}
7273				} else if (stcb_tmp == stcb) {
7274					if (stcb->asoc.state == 0) {
7275						/* the assoc was freed? */
7276						return (-10);
7277					}
7278					if (net != NULL) {
7279						/* clear flag */
7280						net->dest_state &=
7281							~SCTP_ADDR_NOT_IN_ASSOC;
7282					}
7283				} else {
7284					/*
7285					 * strange, address is in another
7286					 * assoc? straighten out locks.
7287					 */
7288					if (stcb_tmp) {
7289						if (SCTP_GET_STATE(&stcb_tmp->asoc) & SCTP_STATE_COOKIE_WAIT) {
7290							/* in setup state we abort this guy */
7291							sctp_abort_an_association(stcb_tmp->sctp_ep,
7292										  stcb_tmp, NULL, SCTP_SO_NOT_LOCKED);
7293							goto add_it_now;
7294						}
7295						SCTP_TCB_UNLOCK(stcb_tmp);
7296					}
7297
7298					if (stcb->asoc.state == 0) {
7299						/* the assoc was freed? */
7300						return (-12);
7301					}
7302					return (-13);
7303				}
7304			}
7305		} else
7306#endif
7307#ifdef INET6
7308		if (ptype == SCTP_IPV6_ADDRESS) {
7309			if (stcb->asoc.scope.ipv6_addr_legal) {
7310				/* ok get the v6 address and check/add */
7311				struct sctp_ipv6addr_param *p6, p6_buf;
7312
7313				phdr = sctp_get_next_param(m, offset,
7314							   (struct sctp_paramhdr *)&p6_buf,
7315							   sizeof(p6_buf));
7316				if (plen != sizeof(struct sctp_ipv6addr_param) ||
7317				    phdr == NULL) {
7318					return (-14);
7319				}
7320				p6 = (struct sctp_ipv6addr_param *)phdr;
7321				memcpy((caddr_t)&sin6.sin6_addr, p6->addr,
7322				       sizeof(p6->addr));
7323				if (IN6_IS_ADDR_MULTICAST(&sin6.sin6_addr)) {
7324					/* Skip multi-cast addresses */
7325					goto next_param;
7326				}
7327				if (IN6_IS_ADDR_LINKLOCAL(&sin6.sin6_addr)) {
7328					/* Link local make no sense without scope */
7329					goto next_param;
7330				}
7331				sa = (struct sockaddr *)&sin6;
7332				inp = stcb->sctp_ep;
7333				atomic_add_int(&stcb->asoc.refcnt, 1);
7334				stcb_tmp = sctp_findassociation_ep_addr(&inp, sa, &net,
7335									dst, stcb);
7336				atomic_add_int(&stcb->asoc.refcnt, -1);
7337				if (stcb_tmp == NULL &&
7338				    (inp == stcb->sctp_ep || inp == NULL)) {
7339					/*
7340					 * we must validate the state again
7341					 * here
7342					 */
7343				add_it_now6:
7344					if (stcb->asoc.state == 0) {
7345						/* the assoc was freed? */
7346						return (-16);
7347					}
7348					/*
7349					 * we must add the address, no scope
7350					 * set
7351					 */
7352					if (sctp_add_remote_addr(stcb, sa, NULL, SCTP_DONOT_SETSCOPE, SCTP_LOAD_ADDR_5)) {
7353						return (-17);
7354					}
7355				} else if (stcb_tmp == stcb) {
7356					/*
7357					 * we must validate the state again
7358					 * here
7359					 */
7360					if (stcb->asoc.state == 0) {
7361						/* the assoc was freed? */
7362						return (-19);
7363					}
7364					if (net != NULL) {
7365						/* clear flag */
7366						net->dest_state &=
7367							~SCTP_ADDR_NOT_IN_ASSOC;
7368					}
7369				} else {
7370					/*
7371					 * strange, address is in another
7372					 * assoc? straighten out locks.
7373					 */
7374					if (stcb_tmp)
7375						if (SCTP_GET_STATE(&stcb_tmp->asoc) & SCTP_STATE_COOKIE_WAIT) {
7376							/* in setup state we abort this guy */
7377							sctp_abort_an_association(stcb_tmp->sctp_ep,
7378										  stcb_tmp, NULL, SCTP_SO_NOT_LOCKED);
7379							goto add_it_now6;
7380						}
7381					SCTP_TCB_UNLOCK(stcb_tmp);
7382
7383					if (stcb->asoc.state == 0) {
7384						/* the assoc was freed? */
7385						return (-21);
7386					}
7387					return (-22);
7388				}
7389			}
7390		} else
7391#endif
7392		if (ptype == SCTP_ECN_CAPABLE) {
7393			peer_supports_ecn = 1;
7394		} else if (ptype == SCTP_ULP_ADAPTATION) {
7395			if (stcb->asoc.state != SCTP_STATE_OPEN) {
7396				struct sctp_adaptation_layer_indication ai, *aip;
7397
7398				phdr = sctp_get_next_param(m, offset,
7399							   (struct sctp_paramhdr *)&ai, sizeof(ai));
7400				aip = (struct sctp_adaptation_layer_indication *)phdr;
7401				if (aip) {
7402					stcb->asoc.peers_adaptation = ntohl(aip->indication);
7403					stcb->asoc.adaptation_needed = 1;
7404				}
7405			}
7406		} else if (ptype == SCTP_SET_PRIM_ADDR) {
7407			struct sctp_asconf_addr_param lstore, *fee;
7408			int lptype;
7409			struct sockaddr *lsa = NULL;
7410#ifdef INET
7411			struct sctp_asconf_addrv4_param *fii;
7412#endif
7413
7414			if (stcb->asoc.asconf_supported == 0) {
7415				return (-100);
7416			}
7417			if (plen > sizeof(lstore)) {
7418				return (-23);
7419			}
7420			phdr = sctp_get_next_param(m, offset,
7421						   (struct sctp_paramhdr *)&lstore,
7422						   min(plen,sizeof(lstore)));
7423			if (phdr == NULL) {
7424				return (-24);
7425			}
7426			fee = (struct sctp_asconf_addr_param *)phdr;
7427			lptype = ntohs(fee->addrp.ph.param_type);
7428			switch (lptype) {
7429#ifdef INET
7430			case SCTP_IPV4_ADDRESS:
7431				if (plen !=
7432				    sizeof(struct sctp_asconf_addrv4_param)) {
7433					SCTP_PRINTF("Sizeof setprim in init/init ack not %d but %d - ignored\n",
7434						    (int)sizeof(struct sctp_asconf_addrv4_param),
7435						    plen);
7436				} else {
7437					fii = (struct sctp_asconf_addrv4_param *)fee;
7438					sin.sin_addr.s_addr = fii->addrp.addr;
7439					lsa = (struct sockaddr *)&sin;
7440				}
7441				break;
7442#endif
7443#ifdef INET6
7444			case SCTP_IPV6_ADDRESS:
7445				if (plen !=
7446				    sizeof(struct sctp_asconf_addr_param)) {
7447					SCTP_PRINTF("Sizeof setprim (v6) in init/init ack not %d but %d - ignored\n",
7448						    (int)sizeof(struct sctp_asconf_addr_param),
7449						    plen);
7450				} else {
7451					memcpy(sin6.sin6_addr.s6_addr,
7452					       fee->addrp.addr,
7453					       sizeof(fee->addrp.addr));
7454					lsa = (struct sockaddr *)&sin6;
7455				}
7456				break;
7457#endif
7458			default:
7459				break;
7460			}
7461			if (lsa) {
7462				(void)sctp_set_primary_addr(stcb, sa, NULL);
7463			}
7464		} else if (ptype == SCTP_HAS_NAT_SUPPORT) {
7465			stcb->asoc.peer_supports_nat = 1;
7466		} else if (ptype == SCTP_PRSCTP_SUPPORTED) {
7467			/* Peer supports pr-sctp */
7468			peer_supports_prsctp = 1;
7469		} else if (ptype == SCTP_SUPPORTED_CHUNK_EXT) {
7470			/* A supported extension chunk */
7471			struct sctp_supported_chunk_types_param *pr_supported;
7472			uint8_t local_store[SCTP_PARAM_BUFFER_SIZE];
7473			int num_ent, i;
7474
7475			phdr = sctp_get_next_param(m, offset,
7476						   (struct sctp_paramhdr *)&local_store, min(sizeof(local_store),plen));
7477			if (phdr == NULL) {
7478				return (-25);
7479			}
7480			pr_supported = (struct sctp_supported_chunk_types_param *)phdr;
7481			num_ent = plen - sizeof(struct sctp_paramhdr);
7482			for (i = 0; i < num_ent; i++) {
7483				switch (pr_supported->chunk_types[i]) {
7484				case SCTP_ASCONF:
7485					peer_supports_asconf = 1;
7486				case SCTP_ASCONF_ACK:
7487					peer_supports_asconf_ack = 1;
7488					break;
7489				case SCTP_FORWARD_CUM_TSN:
7490					peer_supports_prsctp = 1;
7491					break;
7492				case SCTP_PACKET_DROPPED:
7493					peer_supports_pktdrop = 1;
7494					break;
7495				case SCTP_NR_SELECTIVE_ACK:
7496					peer_supports_nrsack = 1;
7497					break;
7498				case SCTP_STREAM_RESET:
7499					peer_supports_reconfig = 1;
7500					break;
7501				case SCTP_AUTHENTICATION:
7502					peer_supports_auth = 1;
7503					break;
7504				default:
7505					/* one I have not learned yet */
7506					break;
7507
7508				}
7509			}
7510		} else if (ptype == SCTP_RANDOM) {
7511			if (plen > sizeof(random_store))
7512				break;
7513			if (got_random) {
7514				/* already processed a RANDOM */
7515				goto next_param;
7516			}
7517			phdr = sctp_get_next_param(m, offset,
7518						   (struct sctp_paramhdr *)random_store,
7519						   min(sizeof(random_store),plen));
7520			if (phdr == NULL)
7521				return (-26);
7522			p_random = (struct sctp_auth_random *)phdr;
7523			random_len = plen - sizeof(*p_random);
7524			/* enforce the random length */
7525			if (random_len != SCTP_AUTH_RANDOM_SIZE_REQUIRED) {
7526				SCTPDBG(SCTP_DEBUG_AUTH1, "SCTP: invalid RANDOM len\n");
7527				return (-27);
7528			}
7529			got_random = 1;
7530		} else if (ptype == SCTP_HMAC_LIST) {
7531			int num_hmacs;
7532			int i;
7533
7534			if (plen > sizeof(hmacs_store))
7535				break;
7536			if (got_hmacs) {
7537				/* already processed a HMAC list */
7538				goto next_param;
7539			}
7540			phdr = sctp_get_next_param(m, offset,
7541						   (struct sctp_paramhdr *)hmacs_store,
7542						   min(plen,sizeof(hmacs_store)));
7543			if (phdr == NULL)
7544				return (-28);
7545			hmacs = (struct sctp_auth_hmac_algo *)phdr;
7546			hmacs_len = plen - sizeof(*hmacs);
7547			num_hmacs = hmacs_len / sizeof(hmacs->hmac_ids[0]);
7548			/* validate the hmac list */
7549			if (sctp_verify_hmac_param(hmacs, num_hmacs)) {
7550				return (-29);
7551			}
7552			if (stcb->asoc.peer_hmacs != NULL)
7553				sctp_free_hmaclist(stcb->asoc.peer_hmacs);
7554			stcb->asoc.peer_hmacs = sctp_alloc_hmaclist(num_hmacs);
7555			if (stcb->asoc.peer_hmacs != NULL) {
7556				for (i = 0; i < num_hmacs; i++) {
7557					(void)sctp_auth_add_hmacid(stcb->asoc.peer_hmacs,
7558								   ntohs(hmacs->hmac_ids[i]));
7559				}
7560			}
7561			got_hmacs = 1;
7562		} else if (ptype == SCTP_CHUNK_LIST) {
7563			int i;
7564
7565			if (plen > sizeof(chunks_store))
7566				break;
7567			if (got_chklist) {
7568				/* already processed a Chunks list */
7569				goto next_param;
7570			}
7571			phdr = sctp_get_next_param(m, offset,
7572						   (struct sctp_paramhdr *)chunks_store,
7573						   min(plen,sizeof(chunks_store)));
7574			if (phdr == NULL)
7575				return (-30);
7576			chunks = (struct sctp_auth_chunk_list *)phdr;
7577			num_chunks = plen - sizeof(*chunks);
7578			if (stcb->asoc.peer_auth_chunks != NULL)
7579				sctp_clear_chunklist(stcb->asoc.peer_auth_chunks);
7580			else
7581				stcb->asoc.peer_auth_chunks = sctp_alloc_chunklist();
7582			for (i = 0; i < num_chunks; i++) {
7583				(void)sctp_auth_add_chunk(chunks->chunk_types[i],
7584							  stcb->asoc.peer_auth_chunks);
7585				/* record asconf/asconf-ack if listed */
7586				if (chunks->chunk_types[i] == SCTP_ASCONF)
7587					saw_asconf = 1;
7588				if (chunks->chunk_types[i] == SCTP_ASCONF_ACK)
7589					saw_asconf_ack = 1;
7590
7591			}
7592			got_chklist = 1;
7593		} else if ((ptype == SCTP_HEARTBEAT_INFO) ||
7594			   (ptype == SCTP_STATE_COOKIE) ||
7595			   (ptype == SCTP_UNRECOG_PARAM) ||
7596			   (ptype == SCTP_COOKIE_PRESERVE) ||
7597			   (ptype == SCTP_SUPPORTED_ADDRTYPE) ||
7598			   (ptype == SCTP_ADD_IP_ADDRESS) ||
7599			   (ptype == SCTP_DEL_IP_ADDRESS) ||
7600			   (ptype == SCTP_ERROR_CAUSE_IND) ||
7601			   (ptype == SCTP_SUCCESS_REPORT)) {
7602			/* don't care */ ;
7603		} else {
7604			if ((ptype & 0x8000) == 0x0000) {
7605				/*
7606				 * must stop processing the rest of the
7607				 * param's. Any report bits were handled
7608				 * with the call to
7609				 * sctp_arethere_unrecognized_parameters()
7610				 * when the INIT or INIT-ACK was first seen.
7611				 */
7612				break;
7613			}
7614		}
7615
7616	next_param:
7617		offset += SCTP_SIZE32(plen);
7618		if (offset >= limit) {
7619			break;
7620		}
7621		phdr = sctp_get_next_param(m, offset, &parm_buf,
7622					   sizeof(parm_buf));
7623	}
7624	/* Now check to see if we need to purge any addresses */
7625	TAILQ_FOREACH_SAFE(net, &stcb->asoc.nets, sctp_next, nnet) {
7626		if ((net->dest_state & SCTP_ADDR_NOT_IN_ASSOC) ==
7627		    SCTP_ADDR_NOT_IN_ASSOC) {
7628			/* This address has been removed from the asoc */
7629			/* remove and free it */
7630			stcb->asoc.numnets--;
7631			TAILQ_REMOVE(&stcb->asoc.nets, net, sctp_next);
7632			sctp_free_remote_addr(net);
7633			if (net == stcb->asoc.primary_destination) {
7634				stcb->asoc.primary_destination = NULL;
7635				sctp_select_primary_destination(stcb);
7636			}
7637		}
7638	}
7639	if ((stcb->asoc.ecn_supported == 1) &&
7640	    (peer_supports_ecn == 0)) {
7641		stcb->asoc.ecn_supported = 0;
7642	}
7643	if ((stcb->asoc.prsctp_supported == 1) &&
7644	    (peer_supports_prsctp == 0)) {
7645		stcb->asoc.prsctp_supported = 0;
7646	}
7647	if ((stcb->asoc.auth_supported == 1) &&
7648	    ((peer_supports_auth == 0) ||
7649	     (got_random == 0) || (got_hmacs == 0))) {
7650		stcb->asoc.auth_supported = 0;
7651	}
7652	if ((stcb->asoc.asconf_supported == 1) &&
7653	    ((peer_supports_asconf == 0) || (peer_supports_asconf_ack == 0) ||
7654	     (stcb->asoc.auth_supported == 0) ||
7655	     (saw_asconf == 0) || (saw_asconf_ack == 0))) {
7656		stcb->asoc.asconf_supported = 0;
7657	}
7658	if ((stcb->asoc.reconfig_supported == 1) &&
7659	    (peer_supports_reconfig == 0)) {
7660		stcb->asoc.reconfig_supported = 0;
7661	}
7662	if ((stcb->asoc.nrsack_supported == 1) &&
7663	    (peer_supports_nrsack == 0)) {
7664		stcb->asoc.nrsack_supported = 0;
7665	}
7666	if ((stcb->asoc.pktdrop_supported == 1) &&
7667	    (peer_supports_pktdrop == 0)){
7668		stcb->asoc.pktdrop_supported = 0;
7669	}
7670	/* validate authentication required parameters */
7671	if ((peer_supports_auth == 0) && (got_chklist == 1)) {
7672		/* peer does not support auth but sent a chunks list? */
7673		return (-31);
7674	}
7675	if ((peer_supports_asconf == 1) && (peer_supports_auth == 0)) {
7676		/* peer supports asconf but not auth? */
7677		return (-32);
7678	} else if ((peer_supports_asconf == 1) &&
7679	           (peer_supports_auth == 1) &&
7680		   ((saw_asconf == 0) || (saw_asconf_ack == 0))) {
7681		return (-33);
7682	}
7683	/* concatenate the full random key */
7684	keylen = sizeof(*p_random) + random_len + sizeof(*hmacs) + hmacs_len;
7685	if (chunks != NULL) {
7686		keylen += sizeof(*chunks) + num_chunks;
7687	}
7688	new_key = sctp_alloc_key(keylen);
7689	if (new_key != NULL) {
7690		/* copy in the RANDOM */
7691		if (p_random != NULL) {
7692			keylen = sizeof(*p_random) + random_len;
7693			bcopy(p_random, new_key->key, keylen);
7694		}
7695		/* append in the AUTH chunks */
7696		if (chunks != NULL) {
7697			bcopy(chunks, new_key->key + keylen,
7698			      sizeof(*chunks) + num_chunks);
7699			keylen += sizeof(*chunks) + num_chunks;
7700		}
7701		/* append in the HMACs */
7702		if (hmacs != NULL) {
7703			bcopy(hmacs, new_key->key + keylen,
7704			      sizeof(*hmacs) + hmacs_len);
7705		}
7706	} else {
7707		/* failed to get memory for the key */
7708		return (-34);
7709	}
7710	if (stcb->asoc.authinfo.peer_random != NULL)
7711		sctp_free_key(stcb->asoc.authinfo.peer_random);
7712	stcb->asoc.authinfo.peer_random = new_key;
7713	sctp_clear_cachedkeys(stcb, stcb->asoc.authinfo.assoc_keyid);
7714	sctp_clear_cachedkeys(stcb, stcb->asoc.authinfo.recv_keyid);
7715
7716	return (0);
7717}
7718
7719int
7720sctp_set_primary_addr(struct sctp_tcb *stcb, struct sockaddr *sa,
7721		      struct sctp_nets *net)
7722{
7723	/* make sure the requested primary address exists in the assoc */
7724	if (net == NULL && sa)
7725		net = sctp_findnet(stcb, sa);
7726
7727	if (net == NULL) {
7728		/* didn't find the requested primary address! */
7729		return (-1);
7730	} else {
7731		/* set the primary address */
7732		if (net->dest_state & SCTP_ADDR_UNCONFIRMED) {
7733			/* Must be confirmed, so queue to set */
7734			net->dest_state |= SCTP_ADDR_REQ_PRIMARY;
7735			return (0);
7736		}
7737		stcb->asoc.primary_destination = net;
7738		if (!(net->dest_state & SCTP_ADDR_PF) && (stcb->asoc.alternate)) {
7739			sctp_free_remote_addr(stcb->asoc.alternate);
7740			stcb->asoc.alternate = NULL;
7741		}
7742		net = TAILQ_FIRST(&stcb->asoc.nets);
7743		if (net != stcb->asoc.primary_destination) {
7744			/* first one on the list is NOT the primary
7745			 * sctp_cmpaddr() is much more efficient if
7746			 * the primary is the first on the list, make it
7747			 * so.
7748			 */
7749			TAILQ_REMOVE(&stcb->asoc.nets, stcb->asoc.primary_destination, sctp_next);
7750			TAILQ_INSERT_HEAD(&stcb->asoc.nets, stcb->asoc.primary_destination, sctp_next);
7751		}
7752		return (0);
7753	}
7754}
7755
7756int
7757sctp_is_vtag_good(uint32_t tag, uint16_t lport, uint16_t rport, struct timeval *now)
7758{
7759	/*
7760	 * This function serves two purposes. It will see if a TAG can be
7761	 * re-used and return 1 for yes it is ok and 0 for don't use that
7762	 * tag. A secondary function it will do is purge out old tags that
7763	 * can be removed.
7764	 */
7765	struct sctpvtaghead *chain;
7766	struct sctp_tagblock *twait_block;
7767	struct sctpasochead *head;
7768	struct sctp_tcb *stcb;
7769	int i;
7770
7771	SCTP_INP_INFO_RLOCK();
7772	head = &SCTP_BASE_INFO(sctp_asochash)[SCTP_PCBHASH_ASOC(tag,
7773								SCTP_BASE_INFO(hashasocmark))];
7774	if (head == NULL) {
7775		/* invalid vtag */
7776		goto skip_vtag_check;
7777	}
7778	LIST_FOREACH(stcb, head, sctp_asocs) {
7779		/* We choose not to lock anything here. TCB's can't be
7780		 * removed since we have the read lock, so they can't
7781		 * be freed on us, same thing for the INP. I may
7782		 * be wrong with this assumption, but we will go
7783		 * with it for now :-)
7784		 */
7785		if (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) {
7786			continue;
7787		}
7788		if (stcb->asoc.my_vtag == tag) {
7789			/* candidate */
7790			if (stcb->rport != rport) {
7791				continue;
7792			}
7793			if (stcb->sctp_ep->sctp_lport != lport) {
7794				continue;
7795			}
7796			/* Its a used tag set */
7797			SCTP_INP_INFO_RUNLOCK();
7798			return (0);
7799		}
7800	}
7801skip_vtag_check:
7802
7803	chain = &SCTP_BASE_INFO(vtag_timewait)[(tag % SCTP_STACK_VTAG_HASH_SIZE)];
7804	/* Now what about timed wait ? */
7805	LIST_FOREACH(twait_block, chain, sctp_nxt_tagblock) {
7806		/*
7807		 * Block(s) are present, lets see if we have this tag in the
7808		 * list
7809		 */
7810		for (i = 0; i < SCTP_NUMBER_IN_VTAG_BLOCK; i++) {
7811			if (twait_block->vtag_block[i].v_tag == 0) {
7812				/* not used */
7813				continue;
7814			} else if ((long)twait_block->vtag_block[i].tv_sec_at_expire  <
7815				   now->tv_sec) {
7816				/* Audit expires this guy */
7817				twait_block->vtag_block[i].tv_sec_at_expire = 0;
7818				twait_block->vtag_block[i].v_tag = 0;
7819				twait_block->vtag_block[i].lport = 0;
7820				twait_block->vtag_block[i].rport = 0;
7821			} else if ((twait_block->vtag_block[i].v_tag == tag) &&
7822				   (twait_block->vtag_block[i].lport == lport) &&
7823				   (twait_block->vtag_block[i].rport == rport)) {
7824				/* Bad tag, sorry :< */
7825				SCTP_INP_INFO_RUNLOCK();
7826				return (0);
7827			}
7828		}
7829	}
7830	SCTP_INP_INFO_RUNLOCK();
7831	return (1);
7832}
7833
7834static void
7835sctp_drain_mbufs(struct sctp_tcb *stcb)
7836{
7837	/*
7838	 * We must hunt this association for MBUF's past the cumack (i.e.
7839	 * out of order data that we can renege on).
7840	 */
7841	struct sctp_association *asoc;
7842	struct sctp_tmit_chunk *chk, *nchk;
7843	uint32_t cumulative_tsn_p1;
7844	struct sctp_queued_to_read *ctl, *nctl;
7845	int cnt, strmat;
7846	uint32_t gap, i;
7847	int fnd = 0;
7848
7849	/* We look for anything larger than the cum-ack + 1 */
7850
7851	asoc = &stcb->asoc;
7852	if (asoc->cumulative_tsn == asoc->highest_tsn_inside_map) {
7853		/* none we can reneg on. */
7854		return;
7855	}
7856	SCTP_STAT_INCR(sctps_protocol_drains_done);
7857	cumulative_tsn_p1 = asoc->cumulative_tsn + 1;
7858	cnt = 0;
7859	/* First look in the re-assembly queue */
7860	TAILQ_FOREACH_SAFE(chk, &asoc->reasmqueue, sctp_next, nchk) {
7861		if (SCTP_TSN_GT(chk->rec.data.TSN_seq, cumulative_tsn_p1)) {
7862			/* Yep it is above cum-ack */
7863			cnt++;
7864			SCTP_CALC_TSN_TO_GAP(gap, chk->rec.data.TSN_seq, asoc->mapping_array_base_tsn);
7865			asoc->size_on_reasm_queue = sctp_sbspace_sub(asoc->size_on_reasm_queue, chk->send_size);
7866			sctp_ucount_decr(asoc->cnt_on_reasm_queue);
7867			SCTP_UNSET_TSN_PRESENT(asoc->mapping_array, gap);
7868			TAILQ_REMOVE(&asoc->reasmqueue, chk, sctp_next);
7869			if (chk->data) {
7870				sctp_m_freem(chk->data);
7871				chk->data = NULL;
7872			}
7873			sctp_free_a_chunk(stcb, chk, SCTP_SO_NOT_LOCKED);
7874		}
7875	}
7876	/* Ok that was fun, now we will drain all the inbound streams? */
7877	for (strmat = 0; strmat < asoc->streamincnt; strmat++) {
7878		TAILQ_FOREACH_SAFE(ctl, &asoc->strmin[strmat].inqueue, next, nctl) {
7879			if (SCTP_TSN_GT(ctl->sinfo_tsn, cumulative_tsn_p1)) {
7880				/* Yep it is above cum-ack */
7881				cnt++;
7882				SCTP_CALC_TSN_TO_GAP(gap, ctl->sinfo_tsn, asoc->mapping_array_base_tsn);
7883				asoc->size_on_all_streams = sctp_sbspace_sub(asoc->size_on_all_streams, ctl->length);
7884				sctp_ucount_decr(asoc->cnt_on_all_streams);
7885				SCTP_UNSET_TSN_PRESENT(asoc->mapping_array, gap);
7886				TAILQ_REMOVE(&asoc->strmin[strmat].inqueue, ctl, next);
7887				if (ctl->data) {
7888					sctp_m_freem(ctl->data);
7889					ctl->data = NULL;
7890				}
7891				sctp_free_remote_addr(ctl->whoFrom);
7892				SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_readq), ctl);
7893				SCTP_DECR_READQ_COUNT();
7894			}
7895		}
7896	}
7897	if (cnt) {
7898		/* We must back down to see what the new highest is */
7899		for (i = asoc->highest_tsn_inside_map; SCTP_TSN_GE(i, asoc->mapping_array_base_tsn); i--) {
7900			SCTP_CALC_TSN_TO_GAP(gap, i, asoc->mapping_array_base_tsn);
7901			if (SCTP_IS_TSN_PRESENT(asoc->mapping_array, gap)) {
7902				asoc->highest_tsn_inside_map = i;
7903				fnd = 1;
7904				break;
7905			}
7906		}
7907		if (!fnd) {
7908			asoc->highest_tsn_inside_map = asoc->mapping_array_base_tsn - 1;
7909		}
7910
7911		/*
7912		 * Question, should we go through the delivery queue? The only
7913		 * reason things are on here is the app not reading OR a p-d-api up.
7914		 * An attacker COULD send enough in to initiate the PD-API and then
7915		 * send a bunch of stuff to other streams... these would wind up on
7916		 * the delivery queue.. and then we would not get to them. But in
7917		 * order to do this I then have to back-track and un-deliver
7918		 * sequence numbers in streams.. el-yucko. I think for now we will
7919		 * NOT look at the delivery queue and leave it to be something to
7920		 * consider later. An alternative would be to abort the P-D-API with
7921		 * a notification and then deliver the data.... Or another method
7922		 * might be to keep track of how many times the situation occurs and
7923		 * if we see a possible attack underway just abort the association.
7924		 */
7925#ifdef SCTP_DEBUG
7926		SCTPDBG(SCTP_DEBUG_PCB1, "Freed %d chunks from reneg harvest\n", cnt);
7927#endif
7928		/*
7929		 * Now do we need to find a new
7930		 * asoc->highest_tsn_inside_map?
7931		 */
7932		asoc->last_revoke_count = cnt;
7933		(void)SCTP_OS_TIMER_STOP(&stcb->asoc.dack_timer.timer);
7934		/*sa_ignore NO_NULL_CHK*/
7935		sctp_send_sack(stcb, SCTP_SO_NOT_LOCKED);
7936		sctp_chunk_output(stcb->sctp_ep, stcb, SCTP_OUTPUT_FROM_DRAIN, SCTP_SO_NOT_LOCKED);
7937	}
7938	/*
7939	 * Another issue, in un-setting the TSN's in the mapping array we
7940	 * DID NOT adjust the highest_tsn marker.  This will cause one of two
7941	 * things to occur. It may cause us to do extra work in checking for
7942	 * our mapping array movement. More importantly it may cause us to
7943	 * SACK every datagram. This may not be a bad thing though since we
7944	 * will recover once we get our cum-ack above and all this stuff we
7945	 * dumped recovered.
7946	 */
7947}
7948
7949void
7950sctp_drain()
7951{
7952	/*
7953	 * We must walk the PCB lists for ALL associations here. The system
7954	 * is LOW on MBUF's and needs help. This is where reneging will
7955	 * occur. We really hope this does NOT happen!
7956	 */
7957#if defined(__FreeBSD__) && __FreeBSD_version >= 801000
7958	VNET_ITERATOR_DECL(vnet_iter);
7959#else
7960	struct sctp_inpcb *inp;
7961	struct sctp_tcb *stcb;
7962
7963	SCTP_STAT_INCR(sctps_protocol_drain_calls);
7964	if (SCTP_BASE_SYSCTL(sctp_do_drain) == 0) {
7965		return;
7966	}
7967#endif
7968#if defined(__FreeBSD__) && __FreeBSD_version >= 801000
7969	VNET_LIST_RLOCK_NOSLEEP();
7970	VNET_FOREACH(vnet_iter) {
7971		CURVNET_SET(vnet_iter);
7972		struct sctp_inpcb *inp;
7973		struct sctp_tcb *stcb;
7974#endif
7975
7976#if defined(__FreeBSD__) && __FreeBSD_version >= 801000
7977		SCTP_STAT_INCR(sctps_protocol_drain_calls);
7978		if (SCTP_BASE_SYSCTL(sctp_do_drain) == 0) {
7979#ifdef VIMAGE
7980			continue;
7981#else
7982			return;
7983#endif
7984		}
7985#endif
7986		SCTP_INP_INFO_RLOCK();
7987		LIST_FOREACH(inp, &SCTP_BASE_INFO(listhead), sctp_list) {
7988			/* For each endpoint */
7989			SCTP_INP_RLOCK(inp);
7990			LIST_FOREACH(stcb, &inp->sctp_asoc_list, sctp_tcblist) {
7991				/* For each association */
7992				SCTP_TCB_LOCK(stcb);
7993				sctp_drain_mbufs(stcb);
7994				SCTP_TCB_UNLOCK(stcb);
7995			}
7996			SCTP_INP_RUNLOCK(inp);
7997		}
7998		SCTP_INP_INFO_RUNLOCK();
7999#if defined(__FreeBSD__) && __FreeBSD_version >= 801000
8000		CURVNET_RESTORE();
8001	}
8002	VNET_LIST_RUNLOCK_NOSLEEP();
8003#endif
8004}
8005
8006/*
8007 * start a new iterator
8008 * iterates through all endpoints and associations based on the pcb_state
8009 * flags and asoc_state.  "af" (mandatory) is executed for all matching
8010 * assocs and "ef" (optional) is executed when the iterator completes.
8011 * "inpf" (optional) is executed for each new endpoint as it is being
8012 * iterated through. inpe (optional) is called when the inp completes
8013 * its way through all the stcbs.
8014 */
8015int
8016sctp_initiate_iterator(inp_func inpf,
8017		       asoc_func af,
8018		       inp_func inpe,
8019		       uint32_t pcb_state,
8020		       uint32_t pcb_features,
8021		       uint32_t asoc_state,
8022		       void *argp,
8023		       uint32_t argi,
8024		       end_func ef,
8025		       struct sctp_inpcb *s_inp,
8026		       uint8_t chunk_output_off)
8027{
8028	struct sctp_iterator *it = NULL;
8029
8030	if (af == NULL) {
8031		return (-1);
8032	}
8033	SCTP_MALLOC(it, struct sctp_iterator *, sizeof(struct sctp_iterator),
8034		    SCTP_M_ITER);
8035	if (it == NULL) {
8036		SCTP_LTRACE_ERR_RET(NULL, NULL, NULL, SCTP_FROM_SCTP_PCB, ENOMEM);
8037		return (ENOMEM);
8038	}
8039	memset(it, 0, sizeof(*it));
8040	it->function_assoc = af;
8041	it->function_inp = inpf;
8042	if (inpf)
8043		it->done_current_ep = 0;
8044	else
8045		it->done_current_ep = 1;
8046	it->function_atend = ef;
8047	it->pointer = argp;
8048	it->val = argi;
8049	it->pcb_flags = pcb_state;
8050	it->pcb_features = pcb_features;
8051	it->asoc_state = asoc_state;
8052	it->function_inp_end = inpe;
8053	it->no_chunk_output = chunk_output_off;
8054#if defined(__FreeBSD__) && __FreeBSD_version >= 801000
8055	it->vn = curvnet;
8056#endif
8057	if (s_inp) {
8058		/* Assume lock is held here */
8059		it->inp = s_inp;
8060		SCTP_INP_INCR_REF(it->inp);
8061		it->iterator_flags = SCTP_ITERATOR_DO_SINGLE_INP;
8062	} else {
8063		SCTP_INP_INFO_RLOCK();
8064		it->inp = LIST_FIRST(&SCTP_BASE_INFO(listhead));
8065		if (it->inp) {
8066			SCTP_INP_INCR_REF(it->inp);
8067		}
8068		SCTP_INP_INFO_RUNLOCK();
8069		it->iterator_flags = SCTP_ITERATOR_DO_ALL_INP;
8070
8071	}
8072	SCTP_IPI_ITERATOR_WQ_LOCK();
8073
8074	TAILQ_INSERT_TAIL(&sctp_it_ctl.iteratorhead, it, sctp_nxt_itr);
8075	if (sctp_it_ctl.iterator_running == 0) {
8076		sctp_wakeup_iterator();
8077	}
8078	SCTP_IPI_ITERATOR_WQ_UNLOCK();
8079	/* sa_ignore MEMLEAK {memory is put on the tailq for the iterator} */
8080	return (0);
8081}
8082