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