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