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