1 /*        $NetBSD: sctp_output.c,v 1.38 2025/04/14 16:43:01 andvar Exp $ */
2 /*        $KAME: sctp_output.c,v 1.48 2005/06/16 18:29:24 jinmei Exp $          */
3 
4 /*
5  * Copyright (C) 2002, 2003, 2004 Cisco Systems Inc,
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the project nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32 #include <sys/cdefs.h>
33 __KERNEL_RCSID(0, "$NetBSD: sctp_output.c,v 1.38 2025/04/14 16:43:01 andvar Exp $");
34 
35 #ifdef _KERNEL_OPT
36 #include "opt_ipsec.h"
37 #include "opt_inet.h"
38 #include "opt_sctp.h"
39 #endif /* _KERNEL_OPT */
40 
41 #include <sys/param.h>
42 #include <sys/systm.h>
43 #include <sys/malloc.h>
44 #include <sys/mbuf.h>
45 #include <sys/domain.h>
46 #include <sys/protosw.h>
47 #include <sys/socket.h>
48 #include <sys/socketvar.h>
49 #include <sys/proc.h>
50 #include <sys/kernel.h>
51 #include <sys/sysctl.h>
52 #include <sys/resourcevar.h>
53 #include <sys/uio.h>
54 #ifdef INET6
55 #include <sys/domain.h>
56 #endif
57 
58 #include <machine/limits.h>
59 #include <machine/cpu.h>
60 
61 #include <net/if.h>
62 #include <net/if_types.h>
63 
64 #include <net/route.h>
65 
66 #include <netinet/in.h>
67 #include <netinet/in_systm.h>
68 #include <netinet/ip.h>
69 #include <netinet/in_pcb.h>
70 #include <netinet/in_var.h>
71 #include <netinet/ip_var.h>
72 
73 #ifdef INET6
74 #include <netinet/ip6.h>
75 #include <netinet6/ip6_var.h>
76 #include <netinet6/scope6_var.h>
77 #include <netinet6/nd6.h>
78 
79 #include <netinet6/in6_pcb.h>
80 
81 #include <netinet/icmp6.h>
82 
83 #endif /* INET6 */
84 
85 #if defined(HAVE_NRL_INPCB) || defined(__FreeBSD__)
86 #ifndef in6pcb
87 #define in6pcb                inpcb
88 #endif
89 #endif
90 
91 #include <netinet/sctp_pcb.h>
92 
93 #ifdef IPSEC
94 #include <netipsec/ipsec.h>
95 #include <netipsec/key.h>
96 #endif /* IPSEC */
97 
98 #include <netinet/sctp_var.h>
99 #include <netinet/sctp_header.h>
100 #include <netinet/sctputil.h>
101 #include <netinet/sctp_pcb.h>
102 #include <netinet/sctp_output.h>
103 #include <netinet/sctp_uio.h>
104 #include <netinet/sctputil.h>
105 #include <netinet/sctp_hashdriver.h>
106 #include <netinet/sctp_timer.h>
107 #include <netinet/sctp_asconf.h>
108 #include <netinet/sctp_indata.h>
109 
110 #ifdef SCTP_DEBUG
111 extern uint32_t sctp_debug_on;
112 #endif
113 
114 extern int sctp_peer_chunk_oh;
115 
116 static int
sctp_find_cmsg(int c_type,void * data,struct mbuf * control,int cpsize)117 sctp_find_cmsg(int c_type, void *data, struct mbuf *control, int cpsize)
118 {
119           struct cmsghdr cmh;
120           int tlen, at;
121 
122           tlen = control->m_len;
123           at = 0;
124           /*
125            * Independent of how many mbufs, find the c_type inside the control
126            * structure and copy out the data.
127            */
128           while (at < tlen) {
129                     if ((tlen-at) < (int)CMSG_ALIGN(sizeof(cmh))) {
130                               /* not enough room for one more we are done. */
131                               return (0);
132                     }
133                     m_copydata(control, at, sizeof(cmh), (void *)&cmh);
134                     if ((cmh.cmsg_len + at) > tlen) {
135                               /*
136                                * this is real messed up since there is not enough
137                                * data here to cover the cmsg header. We are done.
138                                */
139                               return (0);
140                     }
141                     if ((cmh.cmsg_level == IPPROTO_SCTP) &&
142                         (c_type == cmh.cmsg_type)) {
143                               /* found the one we want, copy it out */
144                               at += CMSG_ALIGN(sizeof(struct cmsghdr));
145                               if ((int)(cmh.cmsg_len - CMSG_ALIGN(sizeof(struct cmsghdr))) < cpsize) {
146                                         /*
147                                          * space of cmsg_len after header not
148                                          * big enough
149                                          */
150                                         return (0);
151                               }
152                               m_copydata(control, at, cpsize, data);
153                               return (1);
154                      } else {
155                               at += CMSG_ALIGN(cmh.cmsg_len);
156                               if (cmh.cmsg_len == 0) {
157                                         break;
158                               }
159                     }
160           }
161           /* not found */
162           return (0);
163 }
164 
165 static struct mbuf *
sctp_add_addr_to_mbuf(struct mbuf * m,struct ifaddr * ifa)166 sctp_add_addr_to_mbuf(struct mbuf *m, struct ifaddr *ifa)
167 {
168           struct sctp_paramhdr *parmh;
169           struct mbuf *mret;
170           int len;
171           if (ifa->ifa_addr->sa_family == AF_INET) {
172                     len = sizeof(struct sctp_ipv4addr_param);
173           } else if (ifa->ifa_addr->sa_family == AF_INET6) {
174                     len = sizeof(struct sctp_ipv6addr_param);
175           } else {
176                     /* unknown type */
177                     return (m);
178           }
179 
180           if (M_TRAILINGSPACE(m) >= len) {
181                     /* easy side we just drop it on the end */
182                     parmh = (struct sctp_paramhdr *)(m->m_data + m->m_len);
183                     mret = m;
184           } else {
185                     /* Need more space */
186                     mret = m;
187                     while (mret->m_next != NULL) {
188                               mret = mret->m_next;
189                     }
190                     MGET(mret->m_next, M_DONTWAIT, MT_DATA);
191                     if (mret->m_next == NULL) {
192                               /* We are hosed, can't add more addresses */
193                               return (m);
194                     }
195                     mret = mret->m_next;
196                     parmh = mtod(mret, struct sctp_paramhdr *);
197           }
198           /* now add the parameter */
199           if (ifa->ifa_addr->sa_family == AF_INET) {
200                     struct sctp_ipv4addr_param *ipv4p;
201                     struct sockaddr_in *sin;
202                     sin = (struct sockaddr_in *)ifa->ifa_addr;
203                     ipv4p = (struct sctp_ipv4addr_param *)parmh;
204                     parmh->param_type = htons(SCTP_IPV4_ADDRESS);
205                     parmh->param_length = htons(len);
206                     ipv4p->addr = sin->sin_addr.s_addr;
207                     mret->m_len += len;
208           } else if (ifa->ifa_addr->sa_family == AF_INET6) {
209                     struct sctp_ipv6addr_param *ipv6p;
210                     struct sockaddr_in6 *sin6;
211                     sin6 = (struct sockaddr_in6 *)ifa->ifa_addr;
212                     ipv6p = (struct sctp_ipv6addr_param *)parmh;
213                     parmh->param_type = htons(SCTP_IPV6_ADDRESS);
214                     parmh->param_length = htons(len);
215                     memcpy(ipv6p->addr, &sin6->sin6_addr,
216                         sizeof(ipv6p->addr));
217                     /* clear embedded scope in the address */
218                     in6_clearscope((struct in6_addr *)ipv6p->addr);
219                     mret->m_len += len;
220           } else {
221                     return (m);
222           }
223           return (mret);
224 }
225 
226 
227 
228 static struct mbuf *
sctp_add_cookie(struct sctp_inpcb * inp,struct mbuf * init,int init_offset,struct mbuf * initack,int initack_offset,struct sctp_state_cookie * stc_in)229 sctp_add_cookie(struct sctp_inpcb *inp, struct mbuf *init, int init_offset,
230     struct mbuf *initack, int initack_offset, struct sctp_state_cookie *stc_in)
231 {
232           struct mbuf *copy_init, *copy_initack, *m_at, *sig, *mret;
233           struct sctp_state_cookie *stc;
234           struct sctp_paramhdr *ph;
235           uint8_t *signature;
236           int sig_offset;
237           uint16_t cookie_sz;
238 
239           mret = NULL;
240 
241           MGET(mret, M_DONTWAIT, MT_DATA);
242           if (mret == NULL) {
243                     return (NULL);
244           }
245           copy_init = sctp_m_copym(init, init_offset, M_COPYALL, M_DONTWAIT);
246           if (copy_init == NULL) {
247                     sctp_m_freem(mret);
248                     return (NULL);
249           }
250           copy_initack = sctp_m_copym(initack, initack_offset, M_COPYALL,
251               M_DONTWAIT);
252           if (copy_initack == NULL) {
253                     sctp_m_freem(mret);
254                     sctp_m_freem(copy_init);
255                     return (NULL);
256           }
257           /* easy side we just drop it on the end */
258           ph = mtod(mret, struct sctp_paramhdr *);
259           mret->m_len = sizeof(struct sctp_state_cookie) +
260               sizeof(struct sctp_paramhdr);
261           stc = (struct sctp_state_cookie *)((vaddr_t)ph +
262               sizeof(struct sctp_paramhdr));
263           ph->param_type = htons(SCTP_STATE_COOKIE);
264           ph->param_length = 0;         /* fill in at the end */
265           /* Fill in the stc cookie data */
266           *stc = *stc_in;
267 
268           /* tack the INIT and then the INIT-ACK onto the chain */
269           cookie_sz = 0;
270           m_at = mret;
271           for (m_at = mret; m_at; m_at = m_at->m_next) {
272                     cookie_sz += m_at->m_len;
273                     if (m_at->m_next == NULL) {
274                               m_at->m_next = copy_init;
275                               break;
276                     }
277           }
278 
279           for (m_at = copy_init; m_at; m_at = m_at->m_next) {
280                     cookie_sz += m_at->m_len;
281                     if (m_at->m_next == NULL) {
282                               m_at->m_next = copy_initack;
283                               break;
284                     }
285           }
286 
287           for (m_at = copy_initack; m_at; m_at = m_at->m_next) {
288                     cookie_sz += m_at->m_len;
289                     if (m_at->m_next == NULL) {
290                               break;
291                     }
292           }
293           MGET(sig, M_DONTWAIT, MT_DATA);
294           if (sig == NULL) {
295                     /* no space */
296                     sctp_m_freem(mret);
297                     sctp_m_freem(copy_init);
298                     sctp_m_freem(copy_initack);
299                     return (NULL);
300           }
301           sig->m_len = 0;
302           m_at->m_next = sig;
303           sig_offset = 0;
304           signature = (uint8_t *)(mtod(sig, vaddr_t) + sig_offset);
305           /* Time to sign the cookie */
306           sctp_hash_digest_m((char *)inp->sctp_ep.secret_key[
307               (int)(inp->sctp_ep.current_secret_number)],
308               SCTP_SECRET_SIZE, mret, sizeof(struct sctp_paramhdr),
309               (uint8_t *)signature);
310           sig->m_len += SCTP_SIGNATURE_SIZE;
311           cookie_sz += SCTP_SIGNATURE_SIZE;
312 
313           ph->param_length = htons(cookie_sz);
314           return (mret);
315 }
316 
317 
318 static struct sockaddr_in *
sctp_is_v4_ifa_addr_prefered(struct ifaddr * ifa,uint8_t loopscope,uint8_t ipv4_scope,uint8_t * sin_loop,uint8_t * sin_local)319 sctp_is_v4_ifa_addr_prefered (struct ifaddr *ifa, uint8_t loopscope, uint8_t ipv4_scope, uint8_t *sin_loop, uint8_t *sin_local)
320 {
321           struct sockaddr_in *sin;
322           /*
323            * Here we determine if its a prefered address. A
324            * prefered address means it is the same scope or
325            * higher scope then the destination.
326            *  L = loopback, P = private, G = global
327            * -----------------------------------------
328            *  src    |      dest     |    result
329            *-----------------------------------------
330            *   L     |       L       |    yes
331            *-----------------------------------------
332            *   P     |       L       |    yes
333            *-----------------------------------------
334            *   G     |       L       |    yes
335            *-----------------------------------------
336            *   L     |       P       |    no
337            *-----------------------------------------
338            *   P     |       P       |    yes
339            *-----------------------------------------
340            *   G     |       P       |    no
341            *-----------------------------------------
342            *   L     |       G       |    no
343            *-----------------------------------------
344            *   P     |       G       |    no
345            *-----------------------------------------
346            *   G     |       G       |    yes
347            *-----------------------------------------
348            */
349 
350           if (ifa->ifa_addr->sa_family != AF_INET) {
351                     /* forget non-v4 */
352                     return (NULL);
353           }
354           /* Ok the address may be ok */
355           sin = (struct sockaddr_in *)ifa->ifa_addr;
356           if (sin->sin_addr.s_addr == 0) {
357                     return (NULL);
358           }
359           *sin_local = *sin_loop = 0;
360           if ((ifa->ifa_ifp->if_type == IFT_LOOP) ||
361               (IN4_ISLOOPBACK_ADDRESS(&sin->sin_addr))) {
362                     *sin_loop = 1;
363                     *sin_local = 1;
364           }
365           if ((IN4_ISPRIVATE_ADDRESS(&sin->sin_addr))) {
366                     *sin_local = 1;
367           }
368           if (!loopscope && *sin_loop) {
369                     /* Its a loopback address and we don't have loop scope */
370                     return (NULL);
371           }
372           if (!ipv4_scope && *sin_local) {
373                     /* Its a private address, and we don't have private address scope */
374                     return (NULL);
375           }
376           if (((ipv4_scope == 0) && (loopscope == 0)) && (*sin_local)) {
377                     /* its a global src and a private dest */
378                     return (NULL);
379           }
380           /* its a prefered address */
381           return (sin);
382 }
383 
384 static struct sockaddr_in *
sctp_is_v4_ifa_addr_acceptable(struct ifaddr * ifa,uint8_t loopscope,uint8_t ipv4_scope,uint8_t * sin_loop,uint8_t * sin_local)385 sctp_is_v4_ifa_addr_acceptable (struct ifaddr *ifa, uint8_t loopscope, uint8_t ipv4_scope, uint8_t *sin_loop, uint8_t *sin_local)
386 {
387           struct sockaddr_in *sin;
388           /*
389            * Here we determine if its a acceptable address. A
390            * acceptable address means it is the same scope or
391            * higher scope but we can allow for NAT which means
392            * its ok to have a global dest and a private src.
393            *
394            *  L = loopback, P = private, G = global
395            * -----------------------------------------
396            *  src    |      dest     |    result
397            *-----------------------------------------
398            *   L     |       L       |    yes
399            *-----------------------------------------
400            *   P     |       L       |    yes
401            *-----------------------------------------
402            *   G     |       L       |    yes
403            *-----------------------------------------
404            *   L     |       P       |    no
405            *-----------------------------------------
406            *   P     |       P       |    yes
407            *-----------------------------------------
408            *   G     |       P       |    yes - probably this won't work.
409            *-----------------------------------------
410            *   L     |       G       |    no
411            *-----------------------------------------
412            *   P     |       G       |    yes
413            *-----------------------------------------
414            *   G     |       G       |    yes
415            *-----------------------------------------
416            */
417 
418           if (ifa->ifa_addr->sa_family != AF_INET) {
419                     /* forget non-v4 */
420                     return (NULL);
421           }
422           /* Ok the address may be ok */
423           sin = (struct sockaddr_in *)ifa->ifa_addr;
424           if (sin->sin_addr.s_addr == 0) {
425                     return (NULL);
426           }
427           *sin_local = *sin_loop = 0;
428           if ((ifa->ifa_ifp->if_type == IFT_LOOP) ||
429               (IN4_ISLOOPBACK_ADDRESS(&sin->sin_addr))) {
430                     *sin_loop = 1;
431                     *sin_local = 1;
432           }
433           if ((IN4_ISPRIVATE_ADDRESS(&sin->sin_addr))) {
434                     *sin_local = 1;
435           }
436           if (!loopscope && *sin_loop) {
437                     /* Its a loopback address and we don't have loop scope */
438                     return (NULL);
439           }
440           /* its an acceptable address */
441           return (sin);
442 }
443 
444 /*
445  * This treats the address list on the ep as a restricted list
446  * (negative list). If a the passed address is listed, then
447  * the address is NOT allowed on the association.
448  */
449 int
sctp_is_addr_restricted(struct sctp_tcb * stcb,struct sockaddr * addr)450 sctp_is_addr_restricted(struct sctp_tcb *stcb, struct sockaddr *addr)
451 {
452           struct sctp_laddr *laddr;
453 #ifdef SCTP_DEBUG
454           int cnt=0;
455 #endif
456           if (stcb == NULL) {
457                     /* There are no restrictions, no TCB :-) */
458                     return (0);
459           }
460 #ifdef SCTP_DEBUG
461           LIST_FOREACH(laddr, &stcb->asoc.sctp_local_addr_list, sctp_nxt_addr) {
462                     cnt++;
463           }
464           if (sctp_debug_on & SCTP_DEBUG_OUTPUT4) {
465                     printf("There are %d addresses on the restricted list\n", cnt);
466           }
467           cnt = 0;
468 #endif
469           LIST_FOREACH(laddr, &stcb->asoc.sctp_local_addr_list, sctp_nxt_addr) {
470                     if (laddr->ifa == NULL) {
471 #ifdef SCTP_DEBUG
472                               if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
473                                         printf("Help I have fallen and I can't get up!\n");
474                               }
475 #endif
476                               continue;
477                     }
478 #ifdef SCTP_DEBUG
479                     if (sctp_debug_on & SCTP_DEBUG_OUTPUT4) {
480                               cnt++;
481                               printf("Restricted address[%d]:", cnt);
482                               sctp_print_address(laddr->ifa->ifa_addr);
483                     }
484 #endif
485                     if (sctp_cmpaddr(addr, laddr->ifa->ifa_addr) == 1) {
486                               /* Yes it is on the list */
487                               return (1);
488                     }
489           }
490           return (0);
491 }
492 
493 static int
sctp_is_addr_in_ep(struct sctp_inpcb * inp,struct ifaddr * ifa)494 sctp_is_addr_in_ep(struct sctp_inpcb *inp, struct ifaddr *ifa)
495 {
496           struct sctp_laddr *laddr;
497 
498           if (ifa == NULL)
499                     return (0);
500           LIST_FOREACH(laddr, &inp->sctp_addr_list, sctp_nxt_addr) {
501                     if (laddr->ifa == NULL) {
502 #ifdef SCTP_DEBUG
503                               if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
504                                         printf("Help I have fallen and I can't get up!\n");
505                               }
506 #endif
507                               continue;
508                     }
509                     if (laddr->ifa->ifa_addr == NULL)
510                               continue;
511                     if (laddr->ifa == ifa)
512                               /* same pointer */
513                               return (1);
514                     if (laddr->ifa->ifa_addr->sa_family != ifa->ifa_addr->sa_family) {
515                               /* skip non compatible address comparison */
516                               continue;
517                     }
518                     if (sctp_cmpaddr(ifa->ifa_addr, laddr->ifa->ifa_addr) == 1) {
519                               /* Yes it is restricted */
520                               return (1);
521                     }
522           }
523           return (0);
524 }
525 
526 
527 
528 static struct in_addr
sctp_choose_v4_boundspecific_inp(struct sctp_inpcb * inp,struct rtentry * rt,uint8_t ipv4_scope,uint8_t loopscope)529 sctp_choose_v4_boundspecific_inp(struct sctp_inpcb *inp,
530                                          struct rtentry *rt,
531                                          uint8_t ipv4_scope,
532                                          uint8_t loopscope)
533 {
534           struct in_addr ans;
535           struct sctp_laddr *laddr;
536           struct sockaddr_in *sin;
537           struct ifnet *ifn;
538           struct ifaddr *ifa;
539           uint8_t sin_loop, sin_local;
540 
541           /* first question, is the ifn we will emit on
542            * in our list, if so, we want that one.
543            */
544           ifn = rt->rt_ifp;
545           if (ifn) {
546                     /* is a prefered one on the interface we route out? */
547                     IFADDR_READER_FOREACH(ifa, ifn) {
548                               sin = sctp_is_v4_ifa_addr_prefered (ifa, loopscope, ipv4_scope, &sin_loop, &sin_local);
549                               if (sin == NULL)
550                                         continue;
551                               if (sctp_is_addr_in_ep(inp, ifa)) {
552                                         return (sin->sin_addr);
553                               }
554                     }
555                     /* is an acceptable one on the interface we route out? */
556                     IFADDR_READER_FOREACH(ifa, ifn) {
557                               sin = sctp_is_v4_ifa_addr_acceptable (ifa, loopscope, ipv4_scope, &sin_loop, &sin_local);
558                               if (sin == NULL)
559                                         continue;
560                               if (sctp_is_addr_in_ep(inp, ifa)) {
561                                         return (sin->sin_addr);
562                               }
563                     }
564           }
565           /* ok, what about a prefered address in the inp */
566           for (laddr = LIST_FIRST(&inp->sctp_addr_list);
567                laddr && (laddr != inp->next_addr_touse);
568                laddr = LIST_NEXT(laddr, sctp_nxt_addr)) {
569                     if (laddr->ifa == NULL) {
570                               /* address has been removed */
571                               continue;
572                     }
573                     sin = sctp_is_v4_ifa_addr_prefered (laddr->ifa, loopscope, ipv4_scope, &sin_loop, &sin_local);
574                     if (sin == NULL)
575                               continue;
576                     return (sin->sin_addr);
577 
578           }
579           /* ok, what about an acceptable address in the inp */
580           for (laddr = LIST_FIRST(&inp->sctp_addr_list);
581                laddr && (laddr != inp->next_addr_touse);
582                laddr = LIST_NEXT(laddr, sctp_nxt_addr)) {
583                     if (laddr->ifa == NULL) {
584                               /* address has been removed */
585                               continue;
586                     }
587                     sin = sctp_is_v4_ifa_addr_acceptable (laddr->ifa, loopscope, ipv4_scope, &sin_loop, &sin_local);
588                     if (sin == NULL)
589                               continue;
590                     return (sin->sin_addr);
591 
592           }
593 
594           /* no address bound can be a source for the destination we are in trouble */
595 #ifdef SCTP_DEBUG
596           if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
597                     printf("Src address selection for EP, no acceptable src address found for address\n");
598           }
599 #endif
600           memset(&ans, 0, sizeof(ans));
601           return (ans);
602 }
603 
604 
605 
606 static struct in_addr
sctp_choose_v4_boundspecific_stcb(struct sctp_inpcb * inp,struct sctp_tcb * stcb,struct sctp_nets * net,struct rtentry * rt,uint8_t ipv4_scope,uint8_t loopscope,int non_asoc_addr_ok)607 sctp_choose_v4_boundspecific_stcb(struct sctp_inpcb *inp,
608                                           struct sctp_tcb *stcb,
609                                           struct sctp_nets *net,
610                                           struct rtentry *rt,
611                                         uint8_t ipv4_scope,
612                                           uint8_t loopscope,
613                                           int non_asoc_addr_ok)
614 {
615           /*
616            * Here we have two cases, bound all asconf
617            * allowed. bound all asconf not allowed.
618            *
619            */
620           struct sctp_laddr *laddr, *starting_point;
621           struct in_addr ans;
622           struct ifnet *ifn;
623           struct ifaddr *ifa;
624           uint8_t sin_loop, sin_local, start_at_beginning=0;
625           struct sockaddr_in *sin;
626 
627           /* first question, is the ifn we will emit on
628            * in our list, if so, we want that one.
629            */
630           ifn = rt->rt_ifp;
631 
632           if (inp->sctp_flags & SCTP_PCB_FLAGS_DO_ASCONF) {
633                     /*
634                      * Here we use the list of addresses on the endpoint. Then
635                      * the addresses listed on the "restricted" list is just that,
636                      * address that have not been added and can't be used (unless
637                      * the non_asoc_addr_ok is set).
638                      */
639 #ifdef SCTP_DEBUG
640                     if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
641                               printf("Have a STCB - asconf allowed, not bound all have a netgative list\n");
642                     }
643 #endif
644                     /* first question, is the ifn we will emit on
645                      * in our list, if so, we want that one.
646                      */
647                     if (ifn) {
648                               /* first try for a preferred address on the ep */
649                               IFADDR_READER_FOREACH(ifa, ifn) {
650                                         if (sctp_is_addr_in_ep(inp, ifa)) {
651                                                   sin = sctp_is_v4_ifa_addr_prefered (ifa, loopscope, ipv4_scope, &sin_loop, &sin_local);
652                                                   if (sin == NULL)
653                                                             continue;
654                                                   if ((non_asoc_addr_ok == 0) &&
655                                                       (sctp_is_addr_restricted(stcb, (struct sockaddr *)sin))) {
656                                                             /* on the no-no list */
657                                                             continue;
658                                                   }
659                                                   return (sin->sin_addr);
660                                         }
661                               }
662                               /* next try for an acceptable address on the ep */
663                               IFADDR_READER_FOREACH(ifa, ifn) {
664                                         if (sctp_is_addr_in_ep(inp, ifa)) {
665                                                   sin = sctp_is_v4_ifa_addr_acceptable (ifa, loopscope, ipv4_scope, &sin_loop, &sin_local);
666                                                   if (sin == NULL)
667                                                             continue;
668                                                   if ((non_asoc_addr_ok == 0) &&
669                                                       (sctp_is_addr_restricted(stcb, (struct sockaddr *)sin))) {
670                                                             /* on the no-no list */
671                                                             continue;
672                                                   }
673                                                   return (sin->sin_addr);
674                                         }
675                               }
676 
677                     }
678                     /* if we can't find one like that then we must
679                      * look at all addresses bound to pick one at
680                      * first prefereable then secondly acceptable.
681                      */
682                     starting_point = stcb->asoc.last_used_address;
683           sctpv4_from_the_top:
684                     if (stcb->asoc.last_used_address == NULL) {
685                               start_at_beginning=1;
686                               stcb->asoc.last_used_address = LIST_FIRST(&inp->sctp_addr_list);
687                     }
688                     /* search beginning with the last used address */
689                     for (laddr = stcb->asoc.last_used_address; laddr;
690                          laddr = LIST_NEXT(laddr, sctp_nxt_addr)) {
691                               if (laddr->ifa == NULL) {
692                                         /* address has been removed */
693                                         continue;
694                               }
695                               sin = sctp_is_v4_ifa_addr_prefered (laddr->ifa, loopscope, ipv4_scope, &sin_loop, &sin_local);
696                               if (sin == NULL)
697                                         continue;
698                               if ((non_asoc_addr_ok == 0) &&
699                                   (sctp_is_addr_restricted(stcb, (struct sockaddr *)sin))) {
700                                         /* on the no-no list */
701                                         continue;
702                               }
703                               return (sin->sin_addr);
704 
705                     }
706                     if (start_at_beginning == 0) {
707                               stcb->asoc.last_used_address = NULL;
708                               goto sctpv4_from_the_top;
709                     }
710                     /* now try for any higher scope than the destination */
711                     stcb->asoc.last_used_address = starting_point;
712                     start_at_beginning = 0;
713           sctpv4_from_the_top2:
714                     if (stcb->asoc.last_used_address == NULL) {
715                               start_at_beginning=1;
716                               stcb->asoc.last_used_address = LIST_FIRST(&inp->sctp_addr_list);
717                     }
718                     /* search beginning with the last used address */
719                     for (laddr = stcb->asoc.last_used_address; laddr;
720                          laddr = LIST_NEXT(laddr, sctp_nxt_addr)) {
721                               if (laddr->ifa == NULL) {
722                                         /* address has been removed */
723                                         continue;
724                               }
725                               sin = sctp_is_v4_ifa_addr_acceptable (laddr->ifa, loopscope, ipv4_scope, &sin_loop, &sin_local);
726                               if (sin == NULL)
727                                         continue;
728                               if ((non_asoc_addr_ok == 0) &&
729                                   (sctp_is_addr_restricted(stcb, (struct sockaddr *)sin))) {
730                                         /* on the no-no list */
731                                         continue;
732                               }
733                               return (sin->sin_addr);
734                     }
735                     if (start_at_beginning == 0) {
736                               stcb->asoc.last_used_address = NULL;
737                               goto sctpv4_from_the_top2;
738                     }
739           } else {
740                     /*
741                      * Here we have an address list on the association, thats the
742                      * only valid source addresses that we can use.
743                      */
744 #ifdef SCTP_DEBUG
745                     if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
746                               printf("Have a STCB - no asconf allowed, not bound all have a positive list\n");
747                     }
748 #endif
749                     /* First look at all addresses for one that is on
750                      * the interface we route out
751                      */
752                     LIST_FOREACH(laddr, &stcb->asoc.sctp_local_addr_list,
753                                    sctp_nxt_addr) {
754                               if (laddr->ifa == NULL) {
755                                         /* address has been removed */
756                                         continue;
757                               }
758                               sin = sctp_is_v4_ifa_addr_prefered (laddr->ifa, loopscope, ipv4_scope, &sin_loop, &sin_local);
759                               if (sin == NULL)
760                                         continue;
761                               /* first question, is laddr->ifa an address associated with the emit interface */
762                               if (ifn) {
763                                         IFADDR_READER_FOREACH(ifa, ifn) {
764                                                   if (laddr->ifa == ifa) {
765                                                             sin = (struct sockaddr_in *)laddr->ifa->ifa_addr;
766                                                             return (sin->sin_addr);
767                                                   }
768                                                   if (sctp_cmpaddr(ifa->ifa_addr, laddr->ifa->ifa_addr) == 1) {
769                                                             sin = (struct sockaddr_in *)laddr->ifa->ifa_addr;
770                                                             return (sin->sin_addr);
771                                                   }
772                                         }
773                               }
774                     }
775                     /* what about an acceptable one on the interface? */
776                     LIST_FOREACH(laddr, &stcb->asoc.sctp_local_addr_list,
777                                    sctp_nxt_addr) {
778                               if (laddr->ifa == NULL) {
779                                         /* address has been removed */
780                                         continue;
781                               }
782                               sin = sctp_is_v4_ifa_addr_acceptable (laddr->ifa, loopscope, ipv4_scope, &sin_loop, &sin_local);
783                               if (sin == NULL)
784                                         continue;
785                               /* first question, is laddr->ifa an address associated with the emit interface */
786                               if (ifn) {
787                                         IFADDR_READER_FOREACH(ifa, ifn) {
788                                                   if (laddr->ifa == ifa) {
789                                                             sin = (struct sockaddr_in *)laddr->ifa->ifa_addr;
790                                                             return (sin->sin_addr);
791                                                   }
792                                                   if (sctp_cmpaddr(ifa->ifa_addr, laddr->ifa->ifa_addr) == 1) {
793                                                             sin = (struct sockaddr_in *)laddr->ifa->ifa_addr;
794                                                             return (sin->sin_addr);
795                                                   }
796                                         }
797                               }
798                     }
799                     /* ok, next one that is preferable in general */
800                     LIST_FOREACH(laddr, &stcb->asoc.sctp_local_addr_list,
801                                    sctp_nxt_addr) {
802                               if (laddr->ifa == NULL) {
803                                         /* address has been removed */
804                                         continue;
805                               }
806                               sin = sctp_is_v4_ifa_addr_prefered (laddr->ifa, loopscope, ipv4_scope, &sin_loop, &sin_local);
807                               if (sin == NULL)
808                                         continue;
809                               return (sin->sin_addr);
810                     }
811 
812                     /* last, what about one that is acceptable */
813                     LIST_FOREACH(laddr, &stcb->asoc.sctp_local_addr_list,
814                                    sctp_nxt_addr) {
815                               if (laddr->ifa == NULL) {
816                                         /* address has been removed */
817                                         continue;
818                               }
819                               sin = sctp_is_v4_ifa_addr_acceptable (laddr->ifa, loopscope, ipv4_scope, &sin_loop, &sin_local);
820                               if (sin == NULL)
821                                         continue;
822                               return (sin->sin_addr);
823                     }
824           }
825           memset(&ans, 0, sizeof(ans));
826           return (ans);
827 }
828 
829 static struct sockaddr_in *
sctp_select_v4_nth_prefered_addr_from_ifn_boundall(struct ifnet * ifn,struct sctp_tcb * stcb,int non_asoc_addr_ok,uint8_t loopscope,uint8_t ipv4_scope,int cur_addr_num)830 sctp_select_v4_nth_prefered_addr_from_ifn_boundall (struct ifnet *ifn, struct sctp_tcb *stcb, int non_asoc_addr_ok,
831                                                                 uint8_t loopscope, uint8_t ipv4_scope, int cur_addr_num)
832 {
833           struct ifaddr *ifa;
834           struct sockaddr_in *sin;
835           uint8_t sin_loop, sin_local;
836           int num_eligible_addr = 0;
837           IFADDR_READER_FOREACH(ifa, ifn) {
838                     sin = sctp_is_v4_ifa_addr_prefered (ifa, loopscope, ipv4_scope, &sin_loop, &sin_local);
839                     if (sin == NULL)
840                               continue;
841                     if (stcb) {
842                               if ((non_asoc_addr_ok == 0) && sctp_is_addr_restricted(stcb, (struct sockaddr *)sin)) {
843                                         /* It is restricted for some reason.. probably
844                                          * not yet added.
845                                          */
846                                         continue;
847                               }
848                     }
849                     if (cur_addr_num == num_eligible_addr) {
850                               return (sin);
851                     }
852           }
853           return (NULL);
854 }
855 
856 
857 static int
sctp_count_v4_num_prefered_boundall(struct ifnet * ifn,struct sctp_tcb * stcb,int non_asoc_addr_ok,uint8_t loopscope,uint8_t ipv4_scope,uint8_t * sin_loop,uint8_t * sin_local)858 sctp_count_v4_num_prefered_boundall (struct ifnet *ifn, struct sctp_tcb *stcb, int non_asoc_addr_ok,
859                                              uint8_t loopscope, uint8_t ipv4_scope, uint8_t *sin_loop, uint8_t *sin_local)
860 {
861           struct ifaddr *ifa;
862           struct sockaddr_in *sin;
863           int num_eligible_addr = 0;
864 
865           IFADDR_READER_FOREACH(ifa, ifn) {
866                     sin = sctp_is_v4_ifa_addr_prefered (ifa, loopscope, ipv4_scope, sin_loop, sin_local);
867                     if (sin == NULL)
868                               continue;
869                     if (stcb) {
870                               if ((non_asoc_addr_ok == 0) && sctp_is_addr_restricted(stcb, (struct sockaddr *)sin)) {
871                                         /* It is restricted for some reason.. probably
872                                          * not yet added.
873                                          */
874                                         continue;
875                               }
876                     }
877                     num_eligible_addr++;
878           }
879           return (num_eligible_addr);
880 
881 }
882 
883 static struct in_addr
sctp_choose_v4_boundall(struct sctp_inpcb * inp,struct sctp_tcb * stcb,struct sctp_nets * net,struct rtentry * rt,uint8_t ipv4_scope,uint8_t loopscope,int non_asoc_addr_ok)884 sctp_choose_v4_boundall(struct sctp_inpcb *inp,
885                               struct sctp_tcb *stcb,
886                               struct sctp_nets *net,
887                               struct rtentry *rt,
888                               uint8_t ipv4_scope,
889                               uint8_t loopscope,
890                               int non_asoc_addr_ok)
891 {
892           int cur_addr_num=0, num_prefered=0;
893           uint8_t sin_loop, sin_local;
894           struct ifnet *ifn;
895           struct sockaddr_in *sin;
896           struct in_addr ans;
897           struct ifaddr *ifa;
898           int s;
899           /*
900            * For v4 we can use (in boundall) any address in the association. If
901            * non_asoc_addr_ok is set we can use any address (at least in theory).
902            * So we look for prefered addresses first. If we find one, we use it.
903            * Otherwise we next try to get an address on the interface, which we
904            * should be able to do (unless non_asoc_addr_ok is false and we are
905            * routed out that way). In these cases where we can't use the address
906            * of the interface we go through all the ifn's looking for an address
907            * we can use and fill that in. Punting means we send back address
908            * 0, which will probably cause problems actually since then IP will
909            * fill in the address of the route ifn, which means we probably already
910            * rejected it.. i.e. here comes an abort :-<.
911            */
912           ifn = rt->rt_ifp;
913           if (net) {
914                     cur_addr_num = net->indx_of_eligible_next_to_use;
915           }
916           if (ifn == NULL) {
917                     goto bound_all_v4_plan_c;
918           }
919           num_prefered = sctp_count_v4_num_prefered_boundall (ifn, stcb, non_asoc_addr_ok, loopscope, ipv4_scope, &sin_loop, &sin_local);
920 #ifdef SCTP_DEBUG
921           if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
922                     printf("Found %d prefered source addresses\n", num_prefered);
923           }
924 #endif
925           if (num_prefered == 0) {
926                     /* no eligible addresses, we must use some other
927                      * interface address if we can find one.
928                      */
929                     goto bound_all_v4_plan_b;
930           }
931           /* Ok we have num_eligible_addr set with how many we can use,
932            * this may vary from call to call due to addresses being deprecated etc..
933            */
934           if (cur_addr_num >= num_prefered) {
935                     cur_addr_num = 0;
936           }
937           /* select the nth address from the list (where cur_addr_num is the nth) and
938            * 0 is the first one, 1 is the second one etc...
939            */
940 #ifdef SCTP_DEBUG
941           if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
942                     printf("cur_addr_num:%d\n", cur_addr_num);
943           }
944 #endif
945           sin = sctp_select_v4_nth_prefered_addr_from_ifn_boundall (ifn, stcb, non_asoc_addr_ok, loopscope,
946                                                                                    ipv4_scope, cur_addr_num);
947 
948           /* if sin is NULL something changed??, plan_a now */
949           if (sin) {
950                     return (sin->sin_addr);
951           }
952 
953           /*
954            * plan_b: Look at the interface that we emit on
955            *         and see if we can find an acceptable address.
956            */
957  bound_all_v4_plan_b:
958           IFADDR_READER_FOREACH(ifa, ifn) {
959                     sin = sctp_is_v4_ifa_addr_acceptable (ifa, loopscope, ipv4_scope, &sin_loop, &sin_local);
960                     if (sin == NULL)
961                               continue;
962                     if (stcb) {
963                               if ((non_asoc_addr_ok == 0) && sctp_is_addr_restricted(stcb, (struct sockaddr *)sin)) {
964                                         /* It is restricted for some reason.. probably
965                                          * not yet added.
966                                          */
967                                         continue;
968                               }
969                     }
970                     return (sin->sin_addr);
971           }
972           /*
973            * plan_c: Look at all interfaces and find a prefered
974            *         address. If we reache here we are in trouble I think.
975            */
976  bound_all_v4_plan_c:
977           s = pserialize_read_enter();
978           IFNET_READER_FOREACH(ifn) {
979                     if (ifn == inp->next_ifn_touse)
980                               break;
981                     if (loopscope == 0 && ifn->if_type == IFT_LOOP) {
982                               /* wrong base scope */
983                               continue;
984                     }
985                     if (ifn == rt->rt_ifp)
986                               /* already looked at this guy */
987                               continue;
988                     num_prefered = sctp_count_v4_num_prefered_boundall (ifn, stcb, non_asoc_addr_ok,
989                                                                                     loopscope, ipv4_scope, &sin_loop, &sin_local);
990 #ifdef SCTP_DEBUG
991                     if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
992                               printf("Found ifn:%p %d prefered source addresses\n", ifn, num_prefered);
993                     }
994 #endif
995                     if (num_prefered == 0) {
996                               /*
997                                * None on this interface.
998                                */
999                               continue;
1000                     }
1001                     /* Ok we have num_eligible_addr set with how many we can use,
1002                      * this may vary from call to call due to addresses being deprecated etc..
1003                      */
1004                     if (cur_addr_num >= num_prefered) {
1005                               cur_addr_num = 0;
1006                     }
1007                     sin = sctp_select_v4_nth_prefered_addr_from_ifn_boundall (ifn, stcb, non_asoc_addr_ok, loopscope,
1008                                                                                             ipv4_scope, cur_addr_num);
1009                     if (sin == NULL)
1010                               continue;
1011                     pserialize_read_exit(s);
1012                     return (sin->sin_addr);
1013 
1014           }
1015           pserialize_read_exit(s);
1016 
1017           /*
1018            * plan_d: We are in deep trouble. No prefered address on
1019            *         any interface. And the emit interface does not
1020            *         even have an acceptable address. Take anything
1021            *         we can get! If this does not work we are
1022            *         probably going to emit a packet that will
1023            *         illicit an ABORT, falling through.
1024            */
1025 
1026           s = pserialize_read_enter();
1027           IFNET_READER_FOREACH(ifn) {
1028                     if (ifn == inp->next_ifn_touse)
1029                               break;
1030                     if (loopscope == 0 && ifn->if_type == IFT_LOOP) {
1031                               /* wrong base scope */
1032                               continue;
1033                     }
1034                     if (ifn == rt->rt_ifp)
1035                               /* already looked at this guy */
1036                               continue;
1037 
1038                     IFADDR_READER_FOREACH(ifa, ifn) {
1039                               sin = sctp_is_v4_ifa_addr_acceptable (ifa, loopscope, ipv4_scope, &sin_loop, &sin_local);
1040                               if (sin == NULL)
1041                                         continue;
1042                               if (stcb) {
1043                                         if ((non_asoc_addr_ok == 0) && sctp_is_addr_restricted(stcb, (struct sockaddr *)sin)) {
1044                                                   /* It is restricted for some reason.. probably
1045                                                    * not yet added.
1046                                                    */
1047                                                   continue;
1048                                         }
1049                               }
1050                               pserialize_read_exit(s);
1051                               return (sin->sin_addr);
1052                     }
1053           }
1054           pserialize_read_exit(s);
1055           /*
1056            * Ok we can find NO address to source from that is
1057            * not on our negative list. It is either the special
1058            * ASCONF case where we are sourceing from a intf that
1059            * has been ifconfig'd to a different address (i.e.
1060            * it holds a ADD/DEL/SET-PRIM and the proper lookup
1061            * address. OR we are hosed, and this baby is going
1062            * to abort the association.
1063            */
1064           if (non_asoc_addr_ok) {
1065                     return (((struct sockaddr_in *)(rt->rt_ifa->ifa_addr))->sin_addr);
1066           } else {
1067                     memset(&ans, 0, sizeof(ans));
1068                     return (ans);
1069           }
1070 }
1071 
1072 
1073 
1074 /* tcb may be NULL */
1075 struct in_addr
sctp_ipv4_source_address_selection(struct sctp_inpcb * inp,struct sctp_tcb * stcb,struct route * ro,struct sctp_nets * net,int non_asoc_addr_ok)1076 sctp_ipv4_source_address_selection(struct sctp_inpcb *inp,
1077     struct sctp_tcb *stcb, struct route *ro, struct sctp_nets *net,
1078     int non_asoc_addr_ok)
1079 {
1080           struct in_addr ans;
1081           const struct sockaddr_in *to;
1082           struct rtentry *rt;
1083           uint8_t ipv4_scope, loopscope;
1084 
1085           /*
1086            * Rules:
1087            * - Find the route if needed, cache if I can.
1088            * - Look at interface address in route, Is it
1089            *   in the bound list. If so we have the best source.
1090            * - If not we must rotate amongst the addresses.
1091            *
1092            * Cavets and issues
1093            *
1094            * Do we need to pay attention to scope. We can have
1095            * a private address or a global address we are sourcing
1096            * or sending to. So if we draw it out
1097            *      source     *      dest   *  result
1098            *  ------------------------------------------
1099            *  a   Private    *     Global  *  NAT?
1100            *  ------------------------------------------
1101            *  b   Private    *     Private *  No problem
1102            *  ------------------------------------------
1103            *  c   Global     *     Private *  Huh, How will this work?
1104            *  ------------------------------------------
1105            *  d   Global     *     Global  *  No Problem
1106            *  ------------------------------------------
1107            *
1108            * And then we add to that what happens if there are multiple
1109            * addresses assigned to an interface. Remember the ifa on a
1110            * ifn is a linked list of addresses. So one interface can
1111            * have more than one IPv4 address. What happens if we
1112            * have both a private and a global address? Do we then
1113            * use context of destination to sort out which one is
1114            * best? And what about NAT's sending P->G may get you
1115            * a NAT translation, or should you select the G thats
1116            * on the interface in preference.
1117            *
1118            * Decisions:
1119            *
1120            *  - count the number of addresses on the interface.
1121            *  - if its one, no problem except case <c>. For <a>
1122            *    we will assume a NAT out there.
1123            *  - if there are more than one, then we need to worry
1124            *    about scope P or G. We should prefer G -> G and
1125            *    P -> P if possible. Then as a secondary fall back
1126            *    to mixed types G->P being a last ditch one.
1127            *  - The above all works for bound all, but bound
1128            *    specific we need to use the same concept but instead
1129            *    only consider the bound addresses. If the bound set
1130            *    is NOT assigned to the interface then we must use
1131            *    rotation amongst them.
1132            *
1133            * Notes: For v4, we can always punt and let ip_output
1134            * decide by sending back a source of 0.0.0.0
1135            */
1136 
1137           /*
1138            * Need a route to cache.
1139            *
1140            */
1141           rt = rtcache_validate(ro);
1142           if (rt == NULL) {
1143                     /* No route to host .. punt */
1144                     memset(&ans, 0, sizeof(ans));
1145                     return (ans);
1146           } else {
1147                     to = satocsin(rtcache_getdst(ro));
1148           }
1149           /* Setup our scopes */
1150           if (stcb) {
1151                     ipv4_scope = stcb->asoc.ipv4_local_scope;
1152                     loopscope = stcb->asoc.loopback_scope;
1153           } else {
1154                     /* Scope based on outbound address */
1155                     if ((IN4_ISPRIVATE_ADDRESS(&to->sin_addr))) {
1156                               ipv4_scope = 1;
1157                               loopscope = 0;
1158                     } else if (IN4_ISLOOPBACK_ADDRESS(&to->sin_addr)) {
1159                               ipv4_scope = 1;
1160                               loopscope = 1;
1161                     } else {
1162                               ipv4_scope = 0;
1163                               loopscope = 0;
1164                     }
1165           }
1166 #ifdef SCTP_DEBUG
1167           if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
1168                     printf("Scope setup loop:%d ipv4_scope:%d\n",
1169                            loopscope, ipv4_scope);
1170           }
1171 #endif
1172           if (inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) {
1173                     /*
1174                      * When bound to all if the address list is set
1175                      * it is a negative list. Addresses being added
1176                      * by asconf.
1177                      */
1178                     ans = sctp_choose_v4_boundall(inp, stcb, net, rt,
1179                         ipv4_scope, loopscope, non_asoc_addr_ok);
1180                     goto out;
1181         }
1182           /*
1183            * Three possiblities here:
1184            *
1185            * a) stcb is NULL, which means we operate only from
1186            *    the list of addresses (ifa's) bound to the assoc and
1187            *    we care not about the list.
1188            * b) stcb is NOT-NULL, which means we have an assoc structure and
1189            *    auto-asconf is on. This means that the list of addresses is
1190          *    a NOT list. We use the list from the inp, but any listed address
1191            *    in our list is NOT yet added. However if the non_asoc_addr_ok is
1192            *    set we CAN use an address NOT available (i.e. being added). Its
1193            *    a negative list.
1194            * c) stcb is NOT-NULL, which means we have an assoc structure and
1195            *    auto-asconf is off. This means that the list of addresses is
1196          *    the ONLY addresses I can use.. its positive.
1197            *
1198            *    Note we collapse b & c into the same function just like in
1199            *    the v6 address selection.
1200            */
1201           if (stcb) {
1202                     ans = sctp_choose_v4_boundspecific_stcb(inp, stcb, net,
1203                         rt, ipv4_scope, loopscope, non_asoc_addr_ok);
1204                     goto out;
1205           } else {
1206                     ans = sctp_choose_v4_boundspecific_inp(inp, rt,
1207                         ipv4_scope, loopscope);
1208                     goto out;
1209           }
1210           /* this should not be reached */
1211           memset(&ans, 0, sizeof(ans));
1212 out:
1213           rtcache_unref(rt, ro);
1214           return ans;
1215 }
1216 
1217 
1218 
1219 static struct sockaddr_in6 *
sctp_is_v6_ifa_addr_acceptable(struct ifaddr * ifa,int loopscope,int loc_scope,int * sin_loop,int * sin_local)1220 sctp_is_v6_ifa_addr_acceptable (struct ifaddr *ifa, int loopscope, int loc_scope, int *sin_loop, int *sin_local)
1221 {
1222           struct in6_ifaddr *ifa6;
1223           struct sockaddr_in6 *sin6;
1224 
1225           if (ifa->ifa_addr->sa_family != AF_INET6) {
1226                     /* forget non-v6 */
1227                     return (NULL);
1228           }
1229           ifa6 = (struct in6_ifaddr *)ifa;
1230           /* ok to use deprecated addresses? */
1231           if (!ip6_use_deprecated) {
1232                     if (IFA6_IS_DEPRECATED(ifa6)) {
1233                               /* can't use this type */
1234                               return (NULL);
1235                     }
1236           }
1237           /* are we ok, with the current state of this address? */
1238           if (ifa6->ia6_flags &
1239               (IN6_IFF_DETACHED | IN6_IFF_NOTREADY | IN6_IFF_ANYCAST)) {
1240                     /* Can't use these types */
1241                     return (NULL);
1242           }
1243           /* Ok the address may be ok */
1244           sin6 = (struct sockaddr_in6 *)ifa->ifa_addr;
1245           *sin_local = *sin_loop = 0;
1246           if ((ifa->ifa_ifp->if_type == IFT_LOOP) ||
1247               (IN6_IS_ADDR_LOOPBACK(&sin6->sin6_addr))) {
1248                     *sin_loop = 1;
1249           }
1250           if (!loopscope && *sin_loop) {
1251                     /* Its a loopback address and we don't have loop scope */
1252                     return (NULL);
1253           }
1254           if (IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr)) {
1255                     /* we skip unspecified addresses */
1256                     return (NULL);
1257           }
1258 
1259           if (IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr)) {
1260                     *sin_local = 1;
1261           }
1262           if (!loc_scope && *sin_local) {
1263                     /* Its a link local address, and we don't have link local scope */
1264                     return (NULL);
1265           }
1266           return (sin6);
1267 }
1268 
1269 
1270 static struct sockaddr_in6 *
sctp_choose_v6_boundspecific_stcb(struct sctp_inpcb * inp,struct sctp_tcb * stcb,struct sctp_nets * net,struct rtentry * rt,uint8_t loc_scope,uint8_t loopscope,int non_asoc_addr_ok)1271 sctp_choose_v6_boundspecific_stcb(struct sctp_inpcb *inp,
1272                                           struct sctp_tcb *stcb,
1273                                           struct sctp_nets *net,
1274                                           struct rtentry *rt,
1275                                         uint8_t loc_scope,
1276                                           uint8_t loopscope,
1277                                           int non_asoc_addr_ok)
1278 {
1279           /*
1280            *   Each endpoint has a list of local addresses associated
1281            *   with it. The address list is either a "negative list" i.e.
1282            *   those addresses that are NOT allowed to be used as a source OR
1283            *   a "positive list" i.e. those addresses that CAN be used.
1284            *
1285            *   Its a negative list if asconf is allowed. What we do
1286            *   in this case is use the ep address list BUT we have
1287            *   to cross check it against the negative list.
1288            *
1289            *   In the case where NO asconf is allowed, we have just
1290            *   a straight association level list that we must use to
1291            *   find a source address.
1292            */
1293           struct sctp_laddr *laddr, *starting_point;
1294           struct sockaddr_in6 *sin6;
1295           int sin_loop, sin_local;
1296           int start_at_beginning=0;
1297           struct ifnet *ifn;
1298           struct ifaddr *ifa;
1299 
1300           ifn = rt->rt_ifp;
1301           if (inp->sctp_flags & SCTP_PCB_FLAGS_DO_ASCONF) {
1302 #ifdef SCTP_DEBUG
1303                     if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
1304                               printf("Have a STCB - asconf allowed, not bound all have a netgative list\n");
1305                     }
1306 #endif
1307                     /* first question, is the ifn we will emit on
1308                      * in our list, if so, we want that one.
1309                      */
1310                     if (ifn) {
1311                               IFADDR_READER_FOREACH(ifa, ifn) {
1312                                         if (sctp_is_addr_in_ep(inp, ifa)) {
1313                                                   sin6 = sctp_is_v6_ifa_addr_acceptable (ifa, loopscope, loc_scope, &sin_loop, &sin_local);
1314                                                   if (sin6 == NULL)
1315                                                             continue;
1316                                                   if ((non_asoc_addr_ok == 0) &&
1317                                                       (sctp_is_addr_restricted(stcb, (struct sockaddr *)sin6))) {
1318                                                             /* on the no-no list */
1319                                                             continue;
1320                                                   }
1321                                                   return (sin6);
1322                                         }
1323                               }
1324                     }
1325                     starting_point = stcb->asoc.last_used_address;
1326                     /* First try for matching scope */
1327           sctp_from_the_top:
1328                     if (stcb->asoc.last_used_address == NULL) {
1329                               start_at_beginning=1;
1330                               stcb->asoc.last_used_address = LIST_FIRST(&inp->sctp_addr_list);
1331                     }
1332                     /* search beginning with the last used address */
1333                     for (laddr = stcb->asoc.last_used_address; laddr;
1334                          laddr = LIST_NEXT(laddr, sctp_nxt_addr)) {
1335                               if (laddr->ifa == NULL) {
1336                                         /* address has been removed */
1337                                         continue;
1338                               }
1339                               sin6 = sctp_is_v6_ifa_addr_acceptable (laddr->ifa, loopscope, loc_scope, &sin_loop, &sin_local);
1340                               if (sin6 == NULL)
1341                                         continue;
1342                               if ((non_asoc_addr_ok == 0) && (sctp_is_addr_restricted(stcb, (struct sockaddr *)sin6))) {
1343                                         /* on the no-no list */
1344                                         continue;
1345                               }
1346                               /* is it of matching scope ? */
1347                               if ((loopscope == 0) &&
1348                                   (loc_scope == 0) &&
1349                                   (sin_loop == 0) &&
1350                                   (sin_local == 0)) {
1351                                         /* all of global scope we are ok with it */
1352                                         return (sin6);
1353                               }
1354                               if (loopscope && sin_loop)
1355                                         /* both on the loopback, thats ok */
1356                                         return (sin6);
1357                               if (loc_scope && sin_local)
1358                                         /* both local scope */
1359                                         return (sin6);
1360 
1361                     }
1362                     if (start_at_beginning == 0) {
1363                               stcb->asoc.last_used_address = NULL;
1364                               goto sctp_from_the_top;
1365                     }
1366                     /* now try for any higher scope than the destination */
1367                     stcb->asoc.last_used_address = starting_point;
1368                     start_at_beginning = 0;
1369           sctp_from_the_top2:
1370                     if (stcb->asoc.last_used_address == NULL) {
1371                               start_at_beginning=1;
1372                               stcb->asoc.last_used_address = LIST_FIRST(&inp->sctp_addr_list);
1373                     }
1374                     /* search beginning with the last used address */
1375                     for (laddr = stcb->asoc.last_used_address; laddr;
1376                          laddr = LIST_NEXT(laddr, sctp_nxt_addr)) {
1377                               if (laddr->ifa == NULL) {
1378                                         /* address has been removed */
1379                                         continue;
1380                               }
1381                               sin6 = sctp_is_v6_ifa_addr_acceptable (laddr->ifa, loopscope, loc_scope, &sin_loop, &sin_local);
1382                               if (sin6 == NULL)
1383                                         continue;
1384                               if ((non_asoc_addr_ok == 0) && (sctp_is_addr_restricted(stcb, (struct sockaddr *)sin6))) {
1385                                         /* on the no-no list */
1386                                         continue;
1387                               }
1388                               return (sin6);
1389                     }
1390                     if (start_at_beginning == 0) {
1391                               stcb->asoc.last_used_address = NULL;
1392                               goto sctp_from_the_top2;
1393                     }
1394           } else {
1395 #ifdef SCTP_DEBUG
1396                     if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
1397                               printf("Have a STCB - no asconf allowed, not bound all have a positive list\n");
1398                     }
1399 #endif
1400                     /* First try for interface output match */
1401                     LIST_FOREACH(laddr, &stcb->asoc.sctp_local_addr_list,
1402                                    sctp_nxt_addr) {
1403                               if (laddr->ifa == NULL) {
1404                                         /* address has been removed */
1405                                         continue;
1406                               }
1407                               sin6 = sctp_is_v6_ifa_addr_acceptable (laddr->ifa, loopscope, loc_scope, &sin_loop, &sin_local);
1408                               if (sin6 == NULL)
1409                                         continue;
1410                               /* first question, is laddr->ifa an address associated with the emit interface */
1411                               if (ifn) {
1412                                         IFADDR_READER_FOREACH(ifa, ifn) {
1413                                                   if (laddr->ifa == ifa) {
1414                                                             sin6 = (struct sockaddr_in6 *)laddr->ifa->ifa_addr;
1415                                                             return (sin6);
1416                                                   }
1417                                                   if (sctp_cmpaddr(ifa->ifa_addr, laddr->ifa->ifa_addr) == 1) {
1418                                                             sin6 = (struct sockaddr_in6 *)laddr->ifa->ifa_addr;
1419                                                             return (sin6);
1420                                                   }
1421                                         }
1422                               }
1423                     }
1424                     /* Next try for matching scope */
1425                     LIST_FOREACH(laddr, &stcb->asoc.sctp_local_addr_list,
1426                                    sctp_nxt_addr) {
1427                               if (laddr->ifa == NULL) {
1428                                         /* address has been removed */
1429                                         continue;
1430                               }
1431                               sin6 = sctp_is_v6_ifa_addr_acceptable (laddr->ifa, loopscope, loc_scope, &sin_loop, &sin_local);
1432                               if (sin6 == NULL)
1433                                         continue;
1434 
1435                               if ((loopscope == 0) &&
1436                                   (loc_scope == 0) &&
1437                                   (sin_loop == 0) &&
1438                                   (sin_local == 0)) {
1439                                         /* all of global scope we are ok with it */
1440                                         return (sin6);
1441                               }
1442                               if (loopscope && sin_loop)
1443                                         /* both on the loopback, thats ok */
1444                                         return (sin6);
1445                               if (loc_scope && sin_local)
1446                                         /* both local scope */
1447                                         return (sin6);
1448                     }
1449                     /* ok, now try for a higher scope in the source address */
1450                     /* First try for matching scope */
1451                     LIST_FOREACH(laddr, &stcb->asoc.sctp_local_addr_list,
1452                                    sctp_nxt_addr) {
1453                               if (laddr->ifa == NULL) {
1454                                         /* address has been removed */
1455                                         continue;
1456                               }
1457                               sin6 = sctp_is_v6_ifa_addr_acceptable (laddr->ifa, loopscope, loc_scope, &sin_loop, &sin_local);
1458                               if (sin6 == NULL)
1459                                         continue;
1460                               return (sin6);
1461                     }
1462           }
1463           return (NULL);
1464 }
1465 
1466 static struct sockaddr_in6 *
sctp_choose_v6_boundspecific_inp(struct sctp_inpcb * inp,struct rtentry * rt,uint8_t loc_scope,uint8_t loopscope)1467 sctp_choose_v6_boundspecific_inp(struct sctp_inpcb *inp,
1468                                          struct rtentry *rt,
1469                                          uint8_t loc_scope,
1470                                          uint8_t loopscope)
1471 {
1472           /*
1473            * Here we are bound specific and have only
1474            * an inp. We must find an address that is bound
1475            * that we can give out as a src address. We
1476            * prefer two addresses of same scope if we can
1477            * find them that way.
1478            */
1479           struct sctp_laddr *laddr;
1480           struct sockaddr_in6 *sin6;
1481           struct ifnet *ifn;
1482           struct ifaddr *ifa;
1483           int sin_loop, sin_local;
1484 
1485           /* first question, is the ifn we will emit on
1486            * in our list, if so, we want that one.
1487            */
1488 
1489           ifn = rt->rt_ifp;
1490           if (ifn) {
1491                     IFADDR_READER_FOREACH(ifa, ifn) {
1492                               sin6 = sctp_is_v6_ifa_addr_acceptable (ifa, loopscope, loc_scope, &sin_loop, &sin_local);
1493                               if (sin6 == NULL)
1494                                         continue;
1495                               if (sctp_is_addr_in_ep(inp, ifa)) {
1496                                         return (sin6);
1497                               }
1498                     }
1499           }
1500           for (laddr = LIST_FIRST(&inp->sctp_addr_list);
1501                laddr && (laddr != inp->next_addr_touse);
1502                laddr = LIST_NEXT(laddr, sctp_nxt_addr)) {
1503                     if (laddr->ifa == NULL) {
1504                               /* address has been removed */
1505                               continue;
1506                     }
1507                     sin6 = sctp_is_v6_ifa_addr_acceptable (laddr->ifa, loopscope, loc_scope, &sin_loop, &sin_local);
1508                     if (sin6 == NULL)
1509                               continue;
1510 
1511                     if ((loopscope == 0) &&
1512                         (loc_scope == 0) &&
1513                         (sin_loop == 0) &&
1514                         (sin_local == 0)) {
1515                               /* all of global scope we are ok with it */
1516                               return (sin6);
1517                     }
1518                     if (loopscope && sin_loop)
1519                               /* both on the loopback, thats ok */
1520                               return (sin6);
1521                     if (loc_scope && sin_local)
1522                               /* both local scope */
1523                               return (sin6);
1524 
1525           }
1526           /* if we reach here, we could not find two addresses
1527            * of the same scope to give out. Lets look for any higher level
1528            * scope for a source address.
1529            */
1530           for (laddr = LIST_FIRST(&inp->sctp_addr_list);
1531                laddr && (laddr != inp->next_addr_touse);
1532                laddr = LIST_NEXT(laddr, sctp_nxt_addr)) {
1533                     if (laddr->ifa == NULL) {
1534                               /* address has been removed */
1535                               continue;
1536                     }
1537                     sin6 = sctp_is_v6_ifa_addr_acceptable (laddr->ifa, loopscope, loc_scope, &sin_loop, &sin_local);
1538                     if (sin6 == NULL)
1539                               continue;
1540                     return (sin6);
1541           }
1542           /* no address bound can be a source for the destination */
1543 #ifdef SCTP_DEBUG
1544           if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
1545                     printf("Src address selection for EP, no acceptable src address found for address\n");
1546           }
1547 #endif
1548           return (NULL);
1549 }
1550 
1551 
1552 static struct sockaddr_in6 *
sctp_select_v6_nth_addr_from_ifn_boundall(struct ifnet * ifn,struct sctp_tcb * stcb,int non_asoc_addr_ok,uint8_t loopscope,uint8_t loc_scope,int cur_addr_num,int match_scope)1553 sctp_select_v6_nth_addr_from_ifn_boundall (struct ifnet *ifn, struct sctp_tcb *stcb, int non_asoc_addr_ok, uint8_t loopscope,
1554                                                      uint8_t loc_scope, int cur_addr_num, int match_scope)
1555 {
1556           struct ifaddr *ifa;
1557           struct sockaddr_in6 *sin6;
1558           int sin_loop, sin_local;
1559           int num_eligible_addr = 0;
1560 
1561           IFADDR_READER_FOREACH(ifa, ifn) {
1562                     sin6 = sctp_is_v6_ifa_addr_acceptable (ifa, loopscope, loc_scope, &sin_loop, &sin_local);
1563                     if (sin6 == NULL)
1564                               continue;
1565                     if (stcb) {
1566                               if ((non_asoc_addr_ok == 0) && sctp_is_addr_restricted(stcb, (struct sockaddr *)sin6)) {
1567                                         /* It is restricted for some reason.. probably
1568                                          * not yet added.
1569                                          */
1570                                         continue;
1571                               }
1572                     }
1573                     if (match_scope) {
1574                               /* Here we are asked to match scope if possible */
1575                               if (loopscope && sin_loop)
1576                                         /* src and destination are loopback scope */
1577                                         return (sin6);
1578                               if (loc_scope && sin_local)
1579                                         /* src and destination are local scope */
1580                                         return (sin6);
1581                               if ((loopscope == 0) &&
1582                                   (loc_scope == 0)  &&
1583                                   (sin_loop == 0) &&
1584                                   (sin_local == 0)) {
1585                                         /* src and destination are global scope */
1586                                         return (sin6);
1587                               }
1588                               continue;
1589                     }
1590                     if (num_eligible_addr == cur_addr_num) {
1591                               /* this is it */
1592                               return (sin6);
1593                     }
1594                     num_eligible_addr++;
1595           }
1596           return (NULL);
1597 }
1598 
1599 
1600 static int
sctp_count_v6_num_eligible_boundall(struct ifnet * ifn,struct sctp_tcb * stcb,int non_asoc_addr_ok,uint8_t loopscope,uint8_t loc_scope)1601 sctp_count_v6_num_eligible_boundall (struct ifnet *ifn, struct sctp_tcb *stcb,
1602                                              int non_asoc_addr_ok, uint8_t loopscope, uint8_t loc_scope)
1603 {
1604           struct ifaddr *ifa;
1605           struct sockaddr_in6 *sin6;
1606           int num_eligible_addr = 0;
1607           int sin_loop, sin_local;
1608 
1609           IFADDR_READER_FOREACH(ifa, ifn) {
1610                     sin6 = sctp_is_v6_ifa_addr_acceptable (ifa, loopscope, loc_scope, &sin_loop, &sin_local);
1611                     if (sin6 == NULL)
1612                               continue;
1613                     if (stcb) {
1614                               if ((non_asoc_addr_ok == 0) && sctp_is_addr_restricted(stcb, (struct sockaddr *)sin6)) {
1615                                         /* It is restricted for some reason.. probably
1616                                          * not yet added.
1617                                          */
1618                                         continue;
1619                               }
1620                     }
1621                     num_eligible_addr++;
1622           }
1623           return (num_eligible_addr);
1624 }
1625 
1626 
1627 static struct sockaddr_in6 *
sctp_choose_v6_boundall(struct sctp_inpcb * inp,struct sctp_tcb * stcb,struct sctp_nets * net,struct rtentry * rt,uint8_t loc_scope,uint8_t loopscope,int non_asoc_addr_ok)1628 sctp_choose_v6_boundall(struct sctp_inpcb *inp,
1629                               struct sctp_tcb *stcb,
1630                               struct sctp_nets *net,
1631                               struct rtentry *rt,
1632                               uint8_t loc_scope,
1633                               uint8_t loopscope,
1634                               int non_asoc_addr_ok)
1635 {
1636           /* Ok, we are bound all SO any address
1637            * is ok to use as long as it is NOT in the negative
1638            * list.
1639            */
1640           int num_eligible_addr;
1641           int cur_addr_num=0;
1642           int started_at_beginning=0;
1643           int match_scope_prefered;
1644           /* first question is, how many eligible addresses are
1645            * there for the destination ifn that we are using that
1646            * are within the proper scope?
1647            */
1648           struct ifnet *ifn;
1649           struct sockaddr_in6 *sin6;
1650           int s;
1651 
1652           ifn = rt->rt_ifp;
1653           if (net) {
1654                     cur_addr_num = net->indx_of_eligible_next_to_use;
1655           }
1656           if (cur_addr_num == 0) {
1657                     match_scope_prefered = 1;
1658           } else {
1659                     match_scope_prefered = 0;
1660           }
1661           num_eligible_addr = sctp_count_v6_num_eligible_boundall (ifn, stcb, non_asoc_addr_ok, loopscope, loc_scope);
1662 #ifdef SCTP_DEBUG
1663           if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
1664                     printf("Found %d eligible source addresses\n", num_eligible_addr);
1665           }
1666 #endif
1667           if (num_eligible_addr == 0) {
1668                     /* no eligible addresses, we must use some other
1669                      * interface address if we can find one.
1670                      */
1671                     goto bound_all_v6_plan_b;
1672           }
1673           /* Ok we have num_eligible_addr set with how many we can use,
1674            * this may vary from call to call due to addresses being deprecated etc..
1675            */
1676           if (cur_addr_num >= num_eligible_addr) {
1677                     cur_addr_num = 0;
1678           }
1679           /* select the nth address from the list (where cur_addr_num is the nth) and
1680            * 0 is the first one, 1 is the second one etc...
1681            */
1682 #ifdef SCTP_DEBUG
1683           if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
1684                     printf("cur_addr_num:%d match_scope_prefered:%d select it\n",
1685                            cur_addr_num, match_scope_prefered);
1686           }
1687 #endif
1688           sin6 = sctp_select_v6_nth_addr_from_ifn_boundall (ifn, stcb, non_asoc_addr_ok, loopscope,
1689                                                                         loc_scope, cur_addr_num, match_scope_prefered);
1690           if (match_scope_prefered && (sin6 == NULL)) {
1691                     /* retry without the preference for matching scope */
1692 #ifdef SCTP_DEBUG
1693           if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
1694                     printf("retry with no match_scope_prefered\n");
1695           }
1696 #endif
1697                     sin6 = sctp_select_v6_nth_addr_from_ifn_boundall (ifn, stcb, non_asoc_addr_ok, loopscope,
1698                                                                                   loc_scope, cur_addr_num, 0);
1699           }
1700           if (sin6) {
1701 #ifdef SCTP_DEBUG
1702                     if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
1703                               printf("Selected address %d ifn:%p for the route\n", cur_addr_num, ifn);
1704                     }
1705 #endif
1706                     if (net) {
1707                               /* store so we get the next one */
1708                               if (cur_addr_num < 255)
1709                                         net->indx_of_eligible_next_to_use = cur_addr_num + 1;
1710                               else
1711                                         net->indx_of_eligible_next_to_use = 0;
1712                     }
1713                     return (sin6);
1714           }
1715           num_eligible_addr = 0;
1716  bound_all_v6_plan_b:
1717           /* ok, if we reach here we either fell through
1718            * due to something changing during an interrupt (unlikely)
1719            * or we have NO eligible source addresses for the ifn
1720            * of the route (most likely). We must look at all the other
1721            * interfaces EXCEPT rt->rt_ifp and do the same game.
1722            */
1723 #ifdef SCTP_DEBUG
1724           if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
1725                     printf("bound-all Plan B\n");
1726           }
1727 #endif
1728           if (inp->next_ifn_touse == NULL) {
1729                     started_at_beginning=1;
1730                     inp->next_ifn_touse = IFNET_READER_FIRST();
1731 #ifdef SCTP_DEBUG
1732                     if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
1733                               printf("Start at first IFN:%p\n", inp->next_ifn_touse);
1734                     }
1735 #endif
1736           } else {
1737                     inp->next_ifn_touse = IFNET_READER_NEXT(inp->next_ifn_touse);
1738 #ifdef SCTP_DEBUG
1739                     if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
1740                               printf("Resume at IFN:%p\n", inp->next_ifn_touse);
1741                     }
1742 #endif
1743                     if (inp->next_ifn_touse == NULL) {
1744 #ifdef SCTP_DEBUG
1745                               if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
1746                                         printf("IFN Resets\n");
1747                               }
1748 #endif
1749                               started_at_beginning=1;
1750                               inp->next_ifn_touse = IFNET_READER_FIRST();
1751                     }
1752           }
1753 
1754           s = pserialize_read_enter();
1755           IFNET_READER_FOREACH(ifn) {
1756                     if (loopscope == 0 && ifn->if_type == IFT_LOOP) {
1757                               /* wrong base scope */
1758                               continue;
1759                     }
1760                     if (loc_scope && (ifn->if_index != loc_scope)) {
1761                               /* by definition the scope (from to->sin6_scopeid)
1762                                * must match that of the interface. If not then
1763                                * we could pick a wrong scope for the address.
1764                                * Usually we don't hit plan-b since the route
1765                                * handles this. However we can hit plan-b when
1766                                * we send to local-host so the route is the
1767                                * loopback interface, but the destination is a
1768                                * link local.
1769                                */
1770                               continue;
1771                     }
1772                     if (ifn == rt->rt_ifp) {
1773                               /* already looked at this guy */
1774                               continue;
1775                     }
1776                     /* Address rotation will only work when we are not
1777                      * rotating sourced interfaces and are using the interface
1778                      * of the route. We would need to have a per interface index
1779                      * in order to do proper rotation.
1780                      */
1781                     num_eligible_addr = sctp_count_v6_num_eligible_boundall (ifn, stcb, non_asoc_addr_ok, loopscope, loc_scope);
1782 #ifdef SCTP_DEBUG
1783                     if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
1784                               printf("IFN:%p has %d eligible\n", ifn, num_eligible_addr);
1785                     }
1786 #endif
1787                     if (num_eligible_addr == 0) {
1788                               /* none we can use */
1789                               continue;
1790                     }
1791                     /* Ok we have num_eligible_addr set with how many we can use,
1792                      * this may vary from call to call due to addresses being deprecated etc..
1793                      */
1794                     inp->next_ifn_touse = ifn;
1795 
1796                     /* select the first one we can find with perference for matching scope.
1797                      */
1798                     sin6 = sctp_select_v6_nth_addr_from_ifn_boundall (ifn, stcb, non_asoc_addr_ok, loopscope, loc_scope, 0, 1);
1799                     if (sin6 == NULL) {
1800                               /* can't find one with matching scope how about a source with higher
1801                                * scope
1802                                */
1803                               sin6 = sctp_select_v6_nth_addr_from_ifn_boundall (ifn, stcb, non_asoc_addr_ok, loopscope, loc_scope, 0, 0);
1804                               if (sin6 == NULL)
1805                                         /* Hmm, can't find one in the interface now */
1806                                         continue;
1807                     }
1808 #ifdef SCTP_DEBUG
1809                     if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
1810                               printf("Selected the %d'th address of ifn:%p\n",
1811                                      cur_addr_num, ifn);
1812                     }
1813 #endif
1814                     pserialize_read_exit(s);
1815                     return (sin6);
1816           }
1817           pserialize_read_exit(s);
1818 
1819           if (started_at_beginning == 0) {
1820                     /* we have not been through all of them yet, force
1821                      * us to go through them all.
1822                      */
1823 #ifdef SCTP_DEBUG
1824                     if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
1825                               printf("Force a recycle\n");
1826                     }
1827 #endif
1828                     inp->next_ifn_touse = NULL;
1829                     goto bound_all_v6_plan_b;
1830           }
1831           return (NULL);
1832 
1833 }
1834 
1835 /* stcb and net may be NULL */
1836 struct in6_addr
sctp_ipv6_source_address_selection(struct sctp_inpcb * inp,struct sctp_tcb * stcb,struct route * ro,struct sctp_nets * net,int non_asoc_addr_ok)1837 sctp_ipv6_source_address_selection(struct sctp_inpcb *inp,
1838     struct sctp_tcb *stcb, struct route *ro, struct sctp_nets *net,
1839     int non_asoc_addr_ok)
1840 {
1841           struct in6_addr ans;
1842           struct sockaddr_in6 *rt_addr;
1843           uint8_t loc_scope, loopscope;
1844           struct sockaddr_in6 to;
1845           struct rtentry *rt;
1846 
1847           /*
1848            * This routine is tricky standard v6 src address
1849            * selection cannot take into account what we have
1850            * bound etc, so we can't use it.
1851            *
1852            * Instead here is what we must do:
1853            * 1) Make sure we have a route, if we
1854            *    don't have a route we can never reach the peer.
1855            * 2) Once we have a route, determine the scope of the
1856            *     route. Link local, loopback or global.
1857            * 3) Next we divide into three types. Either we
1858            *    are bound all.. which means we want to use
1859            *    one of the addresses of the interface we are
1860            *    going out. <or>
1861            * 4a) We have not stcb, which means we are using the
1862            *    specific addresses bound on an inp, in this
1863            *    case we are similar to the stcb case (4b below)
1864            *    accept the list is always a positive list.<or>
1865            * 4b) We are bound specific with a stcb, which means we have a
1866            *    list of bound addresses and we must see if the
1867            *    ifn of the route is actually one of the bound addresses.
1868            *    If not, then we must rotate addresses amongst properly
1869            *    scoped bound addresses, if so we use the address
1870            *    of the interface.
1871            * 5) Always, no matter which path we take through the above
1872            *    we must be sure the source address we use is allowed to
1873            *    be used. I.e.  IN6_IFF_DETACHED, IN6_IFF_NOTREADY, and IN6_IFF_ANYCAST
1874            *    addresses cannot be used.
1875            * 6) Addresses that are deprecated MAY be used
1876            *                  if (!ip6_use_deprecated) {
1877            *                    if (IFA6_IS_DEPRECATED(ifa6)) {
1878            *                          skip the address
1879            *                      }
1880            *                }
1881            */
1882 
1883           /*** 1> determine route, if not already done */
1884           rt = rtcache_validate(ro);
1885           if (rt == NULL) {
1886                     /*
1887                      * Need a route to cache.
1888                      */
1889                     int scope_save;
1890 
1891                     memcpy(&to, rtcache_getdst(ro), sizeof(struct sockaddr));
1892                     scope_save = to.sin6_scope_id;
1893                     to.sin6_scope_id = 0;
1894 
1895                     rt = rtcache_lookup(ro, (struct sockaddr *)&to);
1896                     to.sin6_scope_id = scope_save;
1897           }
1898           if (rt == NULL) {
1899                     /*
1900                      * no route to host. this packet is going no-where.
1901                      * We probably should make sure we arrange to send back
1902                      * an error.
1903                      */
1904 #ifdef SCTP_DEBUG
1905                     if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
1906                               printf("No route to host, this packet cannot be sent!\n");
1907                     }
1908 #endif
1909                     memset(&ans, 0, sizeof(ans));
1910                     return (ans);
1911           }
1912 
1913           /*** 2a> determine scope for outbound address/route */
1914           loc_scope = loopscope = 0;
1915           /*
1916            * We base our scope on the outbound packet scope and route,
1917            * NOT the TCB (if there is one). This way in local scope we will only
1918            * use a local scope src address when we send to a local address.
1919            */
1920 
1921           if (IN6_IS_ADDR_LOOPBACK(&to.sin6_addr)) {
1922                     /* If the route goes to the loopback address OR
1923                      * the address is a loopback address, we are loopback
1924                      * scope.
1925                      */
1926 #ifdef SCTP_DEBUG
1927                     if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
1928                               printf("Loopback scope is set\n");
1929                     }
1930 #endif
1931                     loc_scope = 0;
1932                     loopscope = 1;
1933                     if (net != NULL) {
1934                               /* mark it as local */
1935                               net->addr_is_local = 1;
1936                     }
1937 
1938           } else if (IN6_IS_ADDR_LINKLOCAL(&to.sin6_addr)) {
1939 #ifdef SCTP_DEBUG
1940                     if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
1941                               printf("Link local scope is set, id:%d\n", to.sin6_scope_id);
1942                     }
1943 #endif
1944                     if (to.sin6_scope_id)
1945                               loc_scope = to.sin6_scope_id;
1946                     else {
1947                               loc_scope = 1;
1948                     }
1949                     loopscope = 0;
1950           } else {
1951 #ifdef SCTP_DEBUG
1952                     if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
1953                               printf("Global scope is set\n");
1954                     }
1955 #endif
1956           }
1957 
1958           /* now, depending on which way we are bound we call the appropriate
1959            * routine to do steps 3-6
1960            */
1961 #ifdef SCTP_DEBUG
1962           if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
1963                     printf("Destination address:");
1964                     sctp_print_address((struct sockaddr *)&to);
1965           }
1966 #endif
1967 
1968           if (inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) {
1969 #ifdef SCTP_DEBUG
1970                     if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
1971                               printf("Calling bound-all src addr selection for v6\n");
1972                     }
1973 #endif
1974                     rt_addr = sctp_choose_v6_boundall(inp, stcb, net, rt, loc_scope, loopscope, non_asoc_addr_ok);
1975           } else {
1976 #ifdef SCTP_DEBUG
1977                     if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
1978                               printf("Calling bound-specific src addr selection for v6\n");
1979                     }
1980 #endif
1981                     if (stcb)
1982                               rt_addr = sctp_choose_v6_boundspecific_stcb(inp, stcb, net, rt, loc_scope, loopscope,  non_asoc_addr_ok);
1983                     else
1984                               /* we can't have a non-asoc address since we have no association */
1985                               rt_addr = sctp_choose_v6_boundspecific_inp(inp,  rt, loc_scope, loopscope);
1986           }
1987           rtcache_unref(rt, ro);
1988           if (rt_addr == NULL) {
1989                     /* no suitable address? */
1990                     struct in6_addr in6;
1991 #ifdef SCTP_DEBUG
1992                     if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
1993                               printf("V6 packet will reach dead-end no suitable src address\n");
1994                     }
1995 #endif
1996                     memset(&in6, 0, sizeof(in6));
1997                     return (in6);
1998           }
1999 #ifdef SCTP_DEBUG
2000           if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
2001                     printf("Source address selected is:");
2002                     sctp_print_address((struct sockaddr *)rt_addr);
2003           }
2004 #endif
2005           return (rt_addr->sin6_addr);
2006 }
2007 
2008 static uint8_t
sctp_get_ect(struct sctp_tcb * stcb,struct sctp_tmit_chunk * chk)2009 sctp_get_ect(struct sctp_tcb *stcb,
2010                struct sctp_tmit_chunk *chk)
2011 {
2012           uint8_t this_random;
2013 
2014           /* Huh? */
2015           if (sctp_ecn == 0)
2016                     return (0);
2017 
2018           if (sctp_ecn_nonce == 0)
2019                     /* no nonce, always return ECT0 */
2020                     return (SCTP_ECT0_BIT);
2021 
2022           if (stcb->asoc.peer_supports_ecn_nonce == 0) {
2023                     /* Peer does NOT support it, so we send a ECT0 only */
2024                     return (SCTP_ECT0_BIT);
2025           }
2026 
2027           if (chk == NULL)
2028              return (SCTP_ECT0_BIT);
2029 
2030           if (((stcb->asoc.hb_random_idx == 3) &&
2031                (stcb->asoc.hb_ect_randombit > 7)) ||
2032                (stcb->asoc.hb_random_idx > 3)) {
2033                     uint32_t rndval;
2034                     rndval = sctp_select_initial_TSN(&stcb->sctp_ep->sctp_ep);
2035                     memcpy(stcb->asoc.hb_random_values, &rndval,
2036                            sizeof(stcb->asoc.hb_random_values));
2037                     this_random = stcb->asoc.hb_random_values[0];
2038                     stcb->asoc.hb_random_idx = 0;
2039                     stcb->asoc.hb_ect_randombit = 0;
2040           } else {
2041                     if (stcb->asoc.hb_ect_randombit > 7) {
2042                       stcb->asoc.hb_ect_randombit = 0;
2043                       stcb->asoc.hb_random_idx++;
2044                     }
2045                     this_random = stcb->asoc.hb_random_values[stcb->asoc.hb_random_idx];
2046           }
2047           if ((this_random >> stcb->asoc.hb_ect_randombit) & 0x01) {
2048                     if (chk != NULL)
2049                               /* ECN Nonce stuff */
2050                               chk->rec.data.ect_nonce = SCTP_ECT1_BIT;
2051                     stcb->asoc.hb_ect_randombit++;
2052                     return (SCTP_ECT1_BIT);
2053           } else {
2054                     stcb->asoc.hb_ect_randombit++;
2055                     return (SCTP_ECT0_BIT);
2056           }
2057 }
2058 
2059 extern int sctp_no_csum_on_loopback;
2060 
2061 static int
sctp_lowlevel_chunk_output(struct sctp_inpcb * inp,struct sctp_tcb * stcb,struct sctp_nets * net,const struct sockaddr * to,struct mbuf * m,int nofragment_flag,int ecn_ok,struct sctp_tmit_chunk * chk,int out_of_asoc_ok)2062 sctp_lowlevel_chunk_output(struct sctp_inpcb *inp,
2063                                  struct sctp_tcb *stcb,    /* may be NULL */
2064                                  struct sctp_nets *net,
2065                                  const struct sockaddr *to,
2066                                  struct mbuf *m,
2067                                  int nofragment_flag,
2068                                  int ecn_ok,
2069                                  struct sctp_tmit_chunk *chk,
2070                                  int out_of_asoc_ok)
2071           /* nofragment_flag to tell if IP_DF should be set (IPv4 only) */
2072 {
2073           /*
2074            * Given a mbuf chain (via m_next) that holds a packet header
2075            * WITH a SCTPHDR but no IP header, endpoint inp and sa structure.
2076            * - calculate SCTP checksum and fill in
2077            * - prepend a IP address header
2078            * - if boundall use INADDR_ANY
2079            * - if boundspecific do source address selection
2080            * - set fragmentation option for ipV4
2081            * - On return from IP output, check/adjust mtu size
2082            * - of output interface and smallest_mtu size as well.
2083            */
2084           struct sctphdr *sctphdr;
2085           int o_flgs;
2086           uint32_t csum;
2087           int ret;
2088           unsigned int have_mtu;
2089           struct route *ro;
2090           struct rtentry *rt;
2091 
2092           if ((net) && (net->dest_state & SCTP_ADDR_OUT_OF_SCOPE)) {
2093                     sctp_m_freem(m);
2094                     return (EFAULT);
2095           }
2096           if ((m->m_flags & M_PKTHDR) == 0) {
2097 #ifdef SCTP_DEBUG
2098                     if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
2099                               printf("Software error: sctp_lowlevel_chunk_output() called with non pkthdr!\n");
2100                     }
2101 #endif
2102                     sctp_m_freem(m);
2103                     return (EFAULT);
2104           }
2105           /* Calculate the csum and fill in the length of the packet */
2106           sctphdr = mtod(m, struct sctphdr *);
2107           have_mtu = 0;
2108           if (sctp_no_csum_on_loopback &&
2109                (stcb) &&
2110                (stcb->asoc.loopback_scope)) {
2111                     sctphdr->checksum = 0;
2112                     m->m_pkthdr.len = sctp_calculate_len(m);
2113           } else {
2114                     sctphdr->checksum = 0;
2115                     csum = sctp_calculate_sum(m, &m->m_pkthdr.len, 0);
2116                     sctphdr->checksum = csum;
2117           }
2118           if (to->sa_family == AF_INET) {
2119                     struct ip *ip;
2120                     static struct route iproute;
2121                     M_PREPEND(m, sizeof(struct ip), M_DONTWAIT);
2122                     if (m == NULL) {
2123                               /* failed to prepend data, give up */
2124                               return (ENOMEM);
2125                     }
2126                     ip = mtod(m, struct ip *);
2127                     ip->ip_v = IPVERSION;
2128                     ip->ip_hl = (sizeof(struct ip) >> 2);
2129                     if (nofragment_flag) {
2130                               ip->ip_off = htons(IP_DF);
2131                     } else
2132                               ip->ip_off = 0;
2133 
2134                     ip->ip_id = htons(ip_newid(NULL));
2135                     ip->ip_ttl = inp->inp_ip_ttl;
2136                     ip->ip_len = htons(m->m_pkthdr.len);
2137                     if (stcb) {
2138                               if ((stcb->asoc.ecn_allowed) && ecn_ok) {
2139                                         /* Enable ECN */
2140                                         ip->ip_tos = (u_char)((in4p_ip(&inp->ip_inp.inp).ip_tos & 0x000000fc) |
2141                                                                   sctp_get_ect(stcb, chk));
2142                               } else {
2143                                         /* No ECN */
2144                                         ip->ip_tos = in4p_ip(&inp->ip_inp.inp).ip_tos;
2145                               }
2146                     } else {
2147                               /* no association at all */
2148                               ip->ip_tos = inp->inp_ip_tos;
2149                     }
2150                     ip->ip_p = IPPROTO_SCTP;
2151                     ip->ip_sum = 0;
2152 #ifdef SCTP_DEBUG
2153                     printf("chunk_output: net %p\n", net);
2154 #endif
2155                     if (net == NULL) {
2156                               ro = &iproute;
2157                               memset(&iproute, 0, sizeof(iproute));
2158                               /* XXX */
2159                               rt = rtcache_lookup(ro, to);
2160                               rtcache_unref(rt, ro);
2161                     } else {
2162                               ro = (struct route *)&net->ro;
2163                     }
2164                     /* Now the address selection part */
2165                     ip->ip_dst.s_addr = satocsin(to)->sin_addr.s_addr;
2166 
2167                     /* call the routine to select the src address */
2168                     if (net) {
2169                               if (net->src_addr_selected == 0) {
2170                                         /* Cache the source address */
2171                                         ((struct sockaddr_in *)&net->_s_addr)->sin_addr = sctp_ipv4_source_address_selection(inp,
2172                                             stcb,
2173                                             ro, net, out_of_asoc_ok);
2174                                         rt = rtcache_validate(ro);
2175                                         if (rt != NULL) {
2176                                                   net->src_addr_selected = 1;
2177                                         }
2178                                         rtcache_unref(rt, ro);
2179                               }
2180                               ip->ip_src = ((struct sockaddr_in *)&net->_s_addr)->sin_addr;
2181                     } else {
2182                               ip->ip_src = sctp_ipv4_source_address_selection(inp,
2183                                   stcb, ro, net, out_of_asoc_ok);
2184                     }
2185 #ifdef SCTP_DEBUG
2186                     printf("src addr %x\n", ip->ip_src.s_addr);
2187 #endif
2188                     /*
2189                      * If source address selection fails and we find no route then
2190                      * the ip_output should fail as well with a NO_ROUTE_TO_HOST
2191                      * type error. We probably should catch that somewhere and
2192                      * abort the association right away (assuming this is an INIT
2193                      * being sent).
2194                      */
2195                     rt = rtcache_validate(ro);
2196                     if (rt == NULL) {
2197                               /*
2198                                * src addr selection failed to find a route (or valid
2199                                * source addr), so we can't get there from here!
2200                                */
2201 #ifdef SCTP_DEBUG
2202                               if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
2203                                         printf("low_level_output: dropped v4 packet- no valid source addr\n");
2204                                         printf("Destination was %x\n", (u_int)(ntohl(ip->ip_dst.s_addr)));
2205                               }
2206 #endif /* SCTP_DEBUG */
2207                               if (net) {
2208                                         if ((net->dest_state & SCTP_ADDR_REACHABLE) && stcb)
2209                                                   sctp_ulp_notify(SCTP_NOTIFY_INTERFACE_DOWN,
2210                                                                       stcb,
2211                                                                       SCTP_FAILED_THRESHOLD,
2212                                                                       (void *)net);
2213                                         net->dest_state &= ~SCTP_ADDR_REACHABLE;
2214                                         net->dest_state |= SCTP_ADDR_NOT_REACHABLE;
2215                                         if (stcb) {
2216                                                   if (net == stcb->asoc.primary_destination) {
2217                                                             /* need a new primary */
2218                                                             struct sctp_nets *alt;
2219                                                             alt = sctp_find_alternate_net(stcb, net);
2220                                                             if (alt != net) {
2221                                                                       if (sctp_set_primary_addr(stcb,
2222                                                                                                 (struct sockaddr *)NULL,
2223                                                                                                      alt) == 0) {
2224                                                                                 net->dest_state |= SCTP_ADDR_WAS_PRIMARY;
2225                                                                                 net->src_addr_selected = 0;
2226                                                                       }
2227                                                             }
2228                                                   }
2229                                         }
2230                               }
2231                               sctp_m_freem(m);
2232                               return (EHOSTUNREACH);
2233                     } else {
2234                               have_mtu = rt->rt_ifp->if_mtu;
2235                     }
2236 
2237                     o_flgs = (IP_RAWOUTPUT | (inp->sctp_socket->so_options & (SO_DONTROUTE | SO_BROADCAST)));
2238 #ifdef SCTP_DEBUG
2239                     if (sctp_debug_on & SCTP_DEBUG_OUTPUT3) {
2240                               printf("Calling ipv4 output routine from low level src addr:%x\n",
2241                                      (u_int)(ntohl(ip->ip_src.s_addr)));
2242                               printf("Destination is %x\n", (u_int)(ntohl(ip->ip_dst.s_addr)));
2243                               printf("RTP route is %p through\n", rt);
2244                               printf("length %d\n", ntohs(ip->ip_len));
2245                     }
2246 #endif
2247                     if ((have_mtu) && (net) && (have_mtu > net->mtu)) {
2248                               rt->rt_ifp->if_mtu = net->mtu;
2249                     }
2250                     ret = ip_output(m, inp->ip_inp.inp.inp_options,
2251                                         ro, o_flgs, inp->ip_inp.inp.inp_moptions,
2252                                 &inp->ip_inp.inp);
2253                     if ((rt) && (have_mtu) && (net) && (have_mtu > net->mtu)) {
2254                               rt->rt_ifp->if_mtu = have_mtu;
2255                     }
2256                     sctp_pegs[SCTP_DATAGRAMS_SENT]++;
2257 #ifdef SCTP_DEBUG
2258                     if (sctp_debug_on & SCTP_DEBUG_OUTPUT3) {
2259                               printf("Ip output returns %d\n", ret);
2260                     }
2261 #endif
2262                     if (net == NULL) {
2263                     } else {
2264                               /* PMTU check versus smallest asoc MTU goes here */
2265                               if (rt != NULL) {
2266                                         if (rt->rt_rmx.rmx_mtu &&
2267                                             (stcb->asoc.smallest_mtu > rt->rt_rmx.rmx_mtu)) {
2268                                                   sctp_mtu_size_reset(inp, &stcb->asoc,
2269                                                       rt->rt_rmx.rmx_mtu);
2270                                         }
2271                               } else {
2272                                         /* route was freed */
2273                                         net->src_addr_selected = 0;
2274                               }
2275                     }
2276                     rtcache_unref(rt, ro);
2277                     return (ret);
2278           }
2279 #ifdef INET6
2280           else if (to->sa_family == AF_INET6) {
2281                     struct ip6_hdr *ip6h;
2282                     static struct route ip6route;
2283                     struct ifnet *ifp;
2284                     u_char flowTop;
2285                     uint16_t flowBottom;
2286                     u_char tosBottom, tosTop;
2287                     struct sockaddr_in6 *sin6, tmp, *lsa6, lsa6_tmp;
2288                     int prev_scope=0;
2289                     u_short prev_port=0;
2290 
2291                     M_PREPEND(m, sizeof(struct ip6_hdr), M_DONTWAIT);
2292                     if (m == NULL) {
2293                               /* failed to prepend data, give up */
2294                               return (ENOMEM);
2295                     }
2296                     ip6h = mtod(m, struct ip6_hdr *);
2297 
2298                     /*
2299                      * We assume here that inp_flow is in host byte order within
2300                      * the TCB!
2301                      */
2302                     flowBottom = in6p_flowinfo(inp) & 0x0000ffff;
2303                     flowTop = ((in6p_flowinfo(inp) & 0x000f0000) >> 16);
2304 
2305                     tosTop = (((in6p_flowinfo(inp) & 0xf0) >> 4) | IPV6_VERSION);
2306 
2307                     /* protect *sin6 from overwrite */
2308                     memcpy(&tmp, to, sizeof(struct sockaddr_in6));
2309                     sin6 = &tmp;
2310 
2311                     /* KAME hack: embed scopeid */
2312 #if defined(SCTP_BASE_FREEBSD) || defined(__APPLE__)
2313                     if (in6_embedscope(&sin6->sin6_addr, sin6, NULL, NULL) != 0)
2314 #else
2315                     /*
2316                      * XXX: appropriate scope zone must be provided or otherwise
2317                      * ip6_use_defzone must be 1.
2318                      */
2319                     if (sa6_embedscope(sin6, ip6_use_defzone) != 0)
2320 #endif
2321                               return (EINVAL);
2322                     if (net == NULL) {
2323                               memset(&ip6route, 0, sizeof(ip6route));
2324                               ro = (struct route *)&ip6route;
2325                               /* XXX */
2326                               rt = rtcache_lookup(ro, (struct sockaddr *) sin6);
2327                               rtcache_unref(rt, ro);
2328                     } else {
2329                               ro = (struct route *)&net->ro;
2330                     }
2331                     if (stcb != NULL) {
2332                               if ((stcb->asoc.ecn_allowed) && ecn_ok) {
2333                                         /* Enable ECN */
2334                                         tosBottom = (((in6p_flowinfo(inp) & 0x0c) | sctp_get_ect(stcb, chk)) << 4);
2335                               } else {
2336                                         /* No ECN */
2337                                         tosBottom = ((in6p_flowinfo(inp) & 0x0c) << 4);
2338                               }
2339                     } else {
2340                               /* we could get no asoc if it is a O-O-T-B packet */
2341                               tosBottom = ((in6p_flowinfo(inp) & 0x0c) << 4);
2342                     }
2343                     ip6h->ip6_flow = htonl(((tosTop << 24) | ((tosBottom|flowTop) << 16) | flowBottom));
2344                     ip6h->ip6_nxt = IPPROTO_SCTP;
2345                     ip6h->ip6_plen = m->m_pkthdr.len;
2346                     ip6h->ip6_dst = sin6->sin6_addr;
2347 
2348                     /*
2349                      * Add SRC address selection here:
2350                      * we can only reuse to a limited degree the kame src-addr-sel,
2351                      * since we can try their selection but it may not be bound.
2352                      */
2353                     memset(&lsa6_tmp, 0, sizeof(lsa6_tmp));
2354                     lsa6_tmp.sin6_family = AF_INET6;
2355                     lsa6_tmp.sin6_len = sizeof(lsa6_tmp);
2356                     lsa6 = &lsa6_tmp;
2357                     rt = rtcache_validate(ro);
2358                     if (net) {
2359                               if (net->src_addr_selected == 0) {
2360                                         /* Cache the source address */
2361                                         ((struct sockaddr_in6 *)&net->_s_addr)->sin6_addr = sctp_ipv6_source_address_selection(inp,
2362                                             stcb, ro, net, out_of_asoc_ok);
2363 
2364                                         if (rt != NULL) {
2365                                                   net->src_addr_selected = 1;
2366                                         }
2367                               }
2368                               lsa6->sin6_addr = ((struct sockaddr_in6 *)&net->_s_addr)->sin6_addr;
2369                     } else {
2370                               lsa6->sin6_addr = sctp_ipv6_source_address_selection(
2371                                   inp, stcb, ro, net, out_of_asoc_ok);
2372                     }
2373                     lsa6->sin6_port = inp->sctp_lport;
2374 
2375                     if (rt ==  NULL) {
2376                               /*
2377                                * src addr selection failed to find a route (or valid
2378                                * source addr), so we can't get there from here!
2379                                */
2380 #ifdef SCTP_DEBUG
2381                               if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
2382                                         printf("low_level_output: dropped v6 pkt- no valid source addr\n");
2383                               }
2384 #endif
2385                               sctp_m_freem(m);
2386                               if (net) {
2387                                         if ((net->dest_state & SCTP_ADDR_REACHABLE) && stcb)
2388                                                   sctp_ulp_notify(SCTP_NOTIFY_INTERFACE_DOWN,
2389                                                                       stcb,
2390                                                                       SCTP_FAILED_THRESHOLD,
2391                                                                       (void *)net);
2392                                         net->dest_state &= ~SCTP_ADDR_REACHABLE;
2393                                         net->dest_state |= SCTP_ADDR_NOT_REACHABLE;
2394                                         if (stcb) {
2395                                                   if (net == stcb->asoc.primary_destination) {
2396                                                             /* need a new primary */
2397                                                             struct sctp_nets *alt;
2398                                                             alt = sctp_find_alternate_net(stcb, net);
2399                                                             if (alt != net) {
2400                                                                       if (sctp_set_primary_addr(stcb,
2401                                                                                                 (struct sockaddr *)NULL,
2402                                                                                                      alt) == 0) {
2403                                                                                 net->dest_state |= SCTP_ADDR_WAS_PRIMARY;
2404                                                                                 net->src_addr_selected = 0;
2405                                                                       }
2406                                                             }
2407                                                   }
2408                                         }
2409                               }
2410                               return (EHOSTUNREACH);
2411                     }
2412 
2413                     ip6h->ip6_src = lsa6->sin6_addr;
2414 
2415                     /*
2416                      * We set the hop limit now since there is a good chance that
2417                      * our ro pointer is now filled
2418                      */
2419                     ip6h->ip6_hlim = in6pcb_selecthlim(&inp->ip_inp.inp,
2420                                                             (ro ?
2421                                                              (rt ? (rt->rt_ifp) : (NULL)) :
2422                                                              (NULL)));
2423                     o_flgs = 0;
2424                     ifp = rt->rt_ifp;
2425 #ifdef SCTP_DEBUG
2426                     if (sctp_debug_on & SCTP_DEBUG_OUTPUT3) {
2427                               /* Copy to be sure something bad is not happening */
2428                               sin6->sin6_addr = ip6h->ip6_dst;
2429                               lsa6->sin6_addr = ip6h->ip6_src;
2430 
2431                               printf("Calling ipv6 output routine from low level\n");
2432                               printf("src: ");
2433                               sctp_print_address((struct sockaddr *)lsa6);
2434                               printf("dst: ");
2435                               sctp_print_address((struct sockaddr *)sin6);
2436                     }
2437 #endif /* SCTP_DEBUG */
2438                     if (net) {
2439                               sin6 = (struct sockaddr_in6 *)&net->ro.ro_sa;
2440                               /* preserve the port and scope for link local send */
2441                               prev_scope = sin6->sin6_scope_id;
2442                               prev_port = sin6->sin6_port;
2443                     }
2444                     /* XXX NOMPSAFE need to hold ifp here */
2445                     rtcache_unref(rt, ro);
2446                     ret = ip6_output(m, ((struct in6pcb *)inp)->in6p_outputopts,
2447                                          ro,
2448                                          o_flgs,
2449                                          ((struct in6pcb *)inp)->in6p_moptions,
2450                                          (struct inpcb *)inp,
2451                                          &ifp);
2452                     if (net) {
2453                               /* for link local this must be done */
2454                               sin6->sin6_scope_id = prev_scope;
2455                               sin6->sin6_port = prev_port;
2456                     }
2457 #ifdef SCTP_DEBUG
2458                     if (sctp_debug_on & SCTP_DEBUG_OUTPUT3) {
2459                               printf("return from send is %d\n", ret);
2460                     }
2461 #endif /* SCTP_DEBUG_OUTPUT */
2462                     sctp_pegs[SCTP_DATAGRAMS_SENT]++;
2463                     if (net) {
2464                               /* PMTU check versus smallest asoc MTU goes here */
2465                               rt = rtcache_validate(ro);
2466                               if (rt == NULL) {
2467                                         /* Route was freed */
2468                                         net->src_addr_selected = 0;
2469                               }
2470                               if (rt != NULL) {
2471                                         if (rt->rt_rmx.rmx_mtu &&
2472                                             (stcb->asoc.smallest_mtu > rt->rt_rmx.rmx_mtu)) {
2473                                                   sctp_mtu_size_reset(inp,
2474                                                                           &stcb->asoc,
2475                                                                           rt->rt_rmx.rmx_mtu);
2476                                         }
2477                                         rtcache_unref(rt, ro);
2478                               } else if (ifp) {
2479                                         if (ifp->if_mtu &&
2480                                             (stcb->asoc.smallest_mtu > ifp->if_mtu)) {
2481                                                   sctp_mtu_size_reset(inp,
2482                                                                           &stcb->asoc,
2483                                                                           ifp->if_mtu);
2484                                         }
2485                               }
2486                     }
2487                     return (ret);
2488           }
2489 #endif
2490           else {
2491 #ifdef SCTP_DEBUG
2492                     if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
2493                               printf("Unknown protocol (TSNH) type %d\n", ((const struct sockaddr *)to)->sa_family);
2494                     }
2495 #endif
2496                     sctp_m_freem(m);
2497                     return (EFAULT);
2498           }
2499 }
2500 
2501 static
sctp_is_address_in_scope(struct ifaddr * ifa,int ipv4_addr_legal,int ipv6_addr_legal,int loopback_scope,int ipv4_local_scope,int local_scope,int site_scope)2502 int sctp_is_address_in_scope(struct ifaddr *ifa,
2503                                    int ipv4_addr_legal,
2504                                    int ipv6_addr_legal,
2505                                    int loopback_scope,
2506                                    int ipv4_local_scope,
2507                                    int local_scope,
2508                                    int site_scope)
2509 {
2510           if ((loopback_scope == 0) && (ifa->ifa_ifp->if_type == IFT_LOOP)) {
2511                     /* skip loopback if not in scope *
2512                      */
2513                     return (0);
2514           }
2515           if ((ifa->ifa_addr->sa_family == AF_INET) && ipv4_addr_legal) {
2516                     struct sockaddr_in *sin;
2517                     sin = (struct sockaddr_in *)ifa->ifa_addr;
2518                     if (sin->sin_addr.s_addr == 0) {
2519                               /* not in scope , unspecified */
2520                               return (0);
2521                     }
2522                     if ((ipv4_local_scope == 0) &&
2523                         (IN4_ISPRIVATE_ADDRESS(&sin->sin_addr))) {
2524                               /* private address not in scope */
2525                               return (0);
2526                     }
2527           } else if ((ifa->ifa_addr->sa_family == AF_INET6) && ipv6_addr_legal) {
2528                     struct sockaddr_in6 *sin6;
2529                     struct in6_ifaddr *ifa6;
2530 
2531                     ifa6 = (struct in6_ifaddr *)ifa;
2532                     /* ok to use deprecated addresses? */
2533                     if (!ip6_use_deprecated) {
2534                               if (ifa6->ia6_flags &
2535                                   IN6_IFF_DEPRECATED) {
2536                                         return (0);
2537                               }
2538                     }
2539                     if (ifa6->ia6_flags &
2540                         (IN6_IFF_DETACHED |
2541                          IN6_IFF_ANYCAST |
2542                          IN6_IFF_NOTREADY)) {
2543                               return (0);
2544                     }
2545                     sin6 = (struct sockaddr_in6 *)ifa->ifa_addr;
2546                     if (IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr)) {
2547                               /* skip unspecified addresses */
2548                               return (0);
2549                     }
2550                     if (/*(local_scope == 0) && */
2551                         (IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr))) {
2552                               return (0);
2553                     }
2554                     if ((site_scope == 0) &&
2555                         (IN6_IS_ADDR_SITELOCAL(&sin6->sin6_addr))) {
2556                               return (0);
2557                     }
2558           } else {
2559                     return (0);
2560           }
2561           return (1);
2562 }
2563 
2564 
2565 void
sctp_send_initiate(struct sctp_inpcb * inp,struct sctp_tcb * stcb)2566 sctp_send_initiate(struct sctp_inpcb *inp, struct sctp_tcb *stcb)
2567 {
2568           struct mbuf *m, *m_at, *m_last;
2569           struct sctp_nets *net;
2570           struct sctp_init_msg *initm;
2571           struct sctp_supported_addr_param *sup_addr;
2572           struct sctp_ecn_supported_param *ecn;
2573           struct sctp_prsctp_supported_param *prsctp;
2574           struct sctp_ecn_nonce_supported_param *ecn_nonce;
2575           struct sctp_supported_chunk_types_param *pr_supported;
2576           int cnt_inits_to=0;
2577           int padval, ret;
2578 
2579           /* INIT's always go to the primary (and usually ONLY address) */
2580           m_last = NULL;
2581           net = stcb->asoc.primary_destination;
2582           if (net == NULL) {
2583                     net = TAILQ_FIRST(&stcb->asoc.nets);
2584                     if (net == NULL) {
2585                               /* TSNH */
2586                               return;
2587                     }
2588                     /* we confirm any address we send an INIT to */
2589                     net->dest_state &= ~SCTP_ADDR_UNCONFIRMED;
2590                     sctp_set_primary_addr(stcb, NULL, net);
2591           } else {
2592                     /* we confirm any address we send an INIT to */
2593                     net->dest_state &= ~SCTP_ADDR_UNCONFIRMED;
2594           }
2595 #ifdef SCTP_DEBUG
2596           if (sctp_debug_on & SCTP_DEBUG_OUTPUT4) {
2597                     printf("Sending INIT to ");
2598                     sctp_print_address (rtcache_getdst(&net->ro));
2599           }
2600 #endif
2601           if (rtcache_getdst(&net->ro)->sa_family == AF_INET6) {
2602                     /* special hook, if we are sending to link local
2603                      * it will not show up in our private address count.
2604                      */
2605                     if (IN6_IS_ADDR_LINKLOCAL((const struct in6_addr *) rtcache_getdst(&net->ro)->sa_data))
2606                               cnt_inits_to = 1;
2607           }
2608           if (callout_pending(&net->rxt_timer.timer)) {
2609                     /* This case should not happen */
2610                     return;
2611           }
2612           /* start the INIT timer */
2613           if (sctp_timer_start(SCTP_TIMER_TYPE_INIT, inp, stcb, net)) {
2614                     /* we are hosed since I can't start the INIT timer? */
2615                     return;
2616           }
2617           MGETHDR(m, M_DONTWAIT, MT_HEADER);
2618           if (m == NULL) {
2619                     /* No memory, INIT timer will re-attempt. */
2620                     return;
2621           }
2622           /* make it into a M_EXT */
2623           MCLGET(m, M_DONTWAIT);
2624           if ((m->m_flags & M_EXT) != M_EXT) {
2625                     /* Failed to get cluster buffer */
2626                     sctp_m_freem(m);
2627                     return;
2628           }
2629           m->m_data += SCTP_MIN_OVERHEAD;
2630           m->m_len = sizeof(struct sctp_init_msg);
2631           /* Now lets put the SCTP header in place */
2632           initm = mtod(m, struct sctp_init_msg *);
2633           initm->sh.src_port = inp->sctp_lport;
2634           initm->sh.dest_port = stcb->rport;
2635           initm->sh.v_tag = 0;
2636           initm->sh.checksum = 0;       /* calculate later */
2637           /* now the chunk header */
2638           initm->msg.ch.chunk_type = SCTP_INITIATION;
2639           initm->msg.ch.chunk_flags = 0;
2640           /* fill in later from mbuf we build */
2641           initm->msg.ch.chunk_length = 0;
2642           /* place in my tag */
2643           initm->msg.init.initiate_tag = htonl(stcb->asoc.my_vtag);
2644           /* set up some of the credits. */
2645           initm->msg.init.a_rwnd = htonl(uimax(inp->sctp_socket->so_rcv.sb_hiwat,
2646               SCTP_MINIMAL_RWND));
2647 
2648           initm->msg.init.num_outbound_streams = htons(stcb->asoc.pre_open_streams);
2649           initm->msg.init.num_inbound_streams = htons(stcb->asoc.max_inbound_streams);
2650           initm->msg.init.initial_tsn = htonl(stcb->asoc.init_seq_number);
2651           /* now the address restriction */
2652           sup_addr = (struct sctp_supported_addr_param *)((vaddr_t)initm +
2653               sizeof(*initm));
2654           sup_addr->ph.param_type = htons(SCTP_SUPPORTED_ADDRTYPE);
2655           /* we support 2 types IPv6/IPv4 */
2656           sup_addr->ph.param_length = htons(sizeof(*sup_addr) +
2657                                                     sizeof(uint16_t));
2658           sup_addr->addr_type[0] = htons(SCTP_IPV4_ADDRESS);
2659           sup_addr->addr_type[1] = htons(SCTP_IPV6_ADDRESS);
2660           m->m_len += sizeof(*sup_addr) + sizeof(uint16_t);
2661 
2662 /*        if (inp->sctp_flags & SCTP_PCB_FLAGS_ADAPTIONEVNT) {*/
2663           if (inp->sctp_ep.adaption_layer_indicator) {
2664                     struct sctp_adaption_layer_indication *ali;
2665                     ali = (struct sctp_adaption_layer_indication *)(
2666                         (vaddr_t)sup_addr + sizeof(*sup_addr) + sizeof(uint16_t));
2667                     ali->ph.param_type = htons(SCTP_ULP_ADAPTION);
2668                     ali->ph.param_length = htons(sizeof(*ali));
2669                     ali->indication = ntohl(inp->sctp_ep.adaption_layer_indicator);
2670                     m->m_len += sizeof(*ali);
2671                     ecn = (struct sctp_ecn_supported_param *)((vaddr_t)ali +
2672                         sizeof(*ali));
2673           } else {
2674                     ecn = (struct sctp_ecn_supported_param *)((vaddr_t)sup_addr +
2675                         sizeof(*sup_addr) + sizeof(uint16_t));
2676           }
2677 
2678           /* now any cookie time extensions */
2679           if (stcb->asoc.cookie_preserve_req) {
2680                     struct sctp_cookie_perserve_param *cookie_preserve;
2681                     cookie_preserve = (struct sctp_cookie_perserve_param *)(ecn);
2682                     cookie_preserve->ph.param_type = htons(SCTP_COOKIE_PRESERVE);
2683                     cookie_preserve->ph.param_length = htons(
2684                         sizeof(*cookie_preserve));
2685                     cookie_preserve->time = htonl(stcb->asoc.cookie_preserve_req);
2686                     m->m_len += sizeof(*cookie_preserve);
2687                     ecn = (struct sctp_ecn_supported_param *)(
2688                         (vaddr_t)cookie_preserve + sizeof(*cookie_preserve));
2689                     stcb->asoc.cookie_preserve_req = 0;
2690           }
2691 
2692           /* ECN parameter */
2693           if (sctp_ecn == 1) {
2694                     ecn->ph.param_type = htons(SCTP_ECN_CAPABLE);
2695                     ecn->ph.param_length = htons(sizeof(*ecn));
2696                     m->m_len += sizeof(*ecn);
2697                     prsctp = (struct sctp_prsctp_supported_param *)((vaddr_t)ecn +
2698                         sizeof(*ecn));
2699           } else {
2700                     prsctp = (struct sctp_prsctp_supported_param *)((vaddr_t)ecn);
2701           }
2702           /* And now tell the peer we do pr-sctp */
2703           prsctp->ph.param_type = htons(SCTP_PRSCTP_SUPPORTED);
2704           prsctp->ph.param_length = htons(sizeof(*prsctp));
2705           m->m_len += sizeof(*prsctp);
2706 
2707 
2708           /* And now tell the peer we do all the extensions */
2709           pr_supported = (struct sctp_supported_chunk_types_param *)((vaddr_t)prsctp +
2710              sizeof(*prsctp));
2711 
2712           pr_supported->ph.param_type = htons(SCTP_SUPPORTED_CHUNK_EXT);
2713           pr_supported->ph.param_length = htons(sizeof(*pr_supported) + SCTP_EXT_COUNT);
2714           pr_supported->chunk_types[0] = SCTP_ASCONF;
2715           pr_supported->chunk_types[1] = SCTP_ASCONF_ACK;
2716           pr_supported->chunk_types[2] = SCTP_FORWARD_CUM_TSN;
2717           pr_supported->chunk_types[3] = SCTP_PACKET_DROPPED;
2718           pr_supported->chunk_types[4] = SCTP_STREAM_RESET;
2719           pr_supported->chunk_types[5] = 0; /* pad */
2720           pr_supported->chunk_types[6] = 0; /* pad */
2721           pr_supported->chunk_types[7] = 0; /* pad */
2722 
2723           m->m_len += (sizeof(*pr_supported) + SCTP_EXT_COUNT + SCTP_PAD_EXT_COUNT);
2724           /* ECN nonce: And now tell the peer we support ECN nonce */
2725 
2726           if (sctp_ecn_nonce) {
2727                     ecn_nonce = (struct sctp_ecn_nonce_supported_param *)((vaddr_t)pr_supported +
2728                         sizeof(*pr_supported) + SCTP_EXT_COUNT + SCTP_PAD_EXT_COUNT);
2729                     ecn_nonce->ph.param_type = htons(SCTP_ECN_NONCE_SUPPORTED);
2730                     ecn_nonce->ph.param_length = htons(sizeof(*ecn_nonce));
2731                     m->m_len += sizeof(*ecn_nonce);
2732           }
2733 
2734           m_at = m;
2735           /* now the addresses */
2736           if (inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) {
2737                     struct ifnet *ifn;
2738                     struct ifaddr *ifa;
2739                     int cnt;
2740                     int s;
2741 
2742                     cnt = cnt_inits_to;
2743                     s = pserialize_read_enter();
2744                     IFNET_READER_FOREACH(ifn) {
2745                               if ((stcb->asoc.loopback_scope == 0) &&
2746                                   (ifn->if_type == IFT_LOOP)) {
2747                                         /*
2748                                          * Skip loopback devices if loopback_scope
2749                                          * not set
2750                                          */
2751                                         continue;
2752                               }
2753                               IFADDR_READER_FOREACH(ifa, ifn) {
2754                                         if (sctp_is_address_in_scope(ifa,
2755                                             stcb->asoc.ipv4_addr_legal,
2756                                             stcb->asoc.ipv6_addr_legal,
2757                                             stcb->asoc.loopback_scope,
2758                                             stcb->asoc.ipv4_local_scope,
2759                                             stcb->asoc.local_scope,
2760                                             stcb->asoc.site_scope) == 0) {
2761                                                   continue;
2762                                         }
2763                                         cnt++;
2764                               }
2765                     }
2766                     pserialize_read_exit(s);
2767 
2768                     if (cnt > 1) {
2769                               s = pserialize_read_enter();
2770                               IFNET_READER_FOREACH(ifn) {
2771                                         if ((stcb->asoc.loopback_scope == 0) &&
2772                                             (ifn->if_type == IFT_LOOP)) {
2773                                                   /*
2774                                                    * Skip loopback devices if loopback_scope
2775                                                    * not set
2776                                                    */
2777                                                   continue;
2778                                         }
2779                                         IFADDR_READER_FOREACH(ifa, ifn) {
2780                                                   if (sctp_is_address_in_scope(ifa,
2781                                                       stcb->asoc.ipv4_addr_legal,
2782                                                       stcb->asoc.ipv6_addr_legal,
2783                                                       stcb->asoc.loopback_scope,
2784                                                       stcb->asoc.ipv4_local_scope,
2785                                                       stcb->asoc.local_scope,
2786                                                       stcb->asoc.site_scope) == 0) {
2787                                                             continue;
2788                                                   }
2789                                                   m_at = sctp_add_addr_to_mbuf(m_at, ifa);
2790                                         }
2791                               }
2792                               pserialize_read_exit(s);
2793                     }
2794           } else {
2795                     struct sctp_laddr *laddr;
2796                     int cnt;
2797                     cnt = cnt_inits_to;
2798                     /* First, how many ? */
2799                     LIST_FOREACH(laddr, &inp->sctp_addr_list, sctp_nxt_addr) {
2800                               if (laddr->ifa == NULL) {
2801                                         continue;
2802                               }
2803                               if (laddr->ifa->ifa_addr == NULL)
2804                                         continue;
2805                               if (sctp_is_address_in_scope(laddr->ifa,
2806                                   stcb->asoc.ipv4_addr_legal,
2807                                   stcb->asoc.ipv6_addr_legal,
2808                                   stcb->asoc.loopback_scope,
2809                                   stcb->asoc.ipv4_local_scope,
2810                                   stcb->asoc.local_scope,
2811                                   stcb->asoc.site_scope) == 0) {
2812                                         continue;
2813                               }
2814                               cnt++;
2815                     }
2816                     /* To get through a NAT we only list addresses if
2817                      * we have more than one. That way if you just
2818                      * bind a single address we let the source of the init
2819                      * dictate our address.
2820                      */
2821                     if (cnt > 1) {
2822                               LIST_FOREACH(laddr, &inp->sctp_addr_list, sctp_nxt_addr) {
2823                                         if (laddr->ifa == NULL) {
2824                                                   continue;
2825                                         }
2826                                         if (laddr->ifa->ifa_addr == NULL) {
2827                                                   continue;
2828                                         }
2829 
2830                                         if (sctp_is_address_in_scope(laddr->ifa,
2831                                             stcb->asoc.ipv4_addr_legal,
2832                                             stcb->asoc.ipv6_addr_legal,
2833                                             stcb->asoc.loopback_scope,
2834                                             stcb->asoc.ipv4_local_scope,
2835                                             stcb->asoc.local_scope,
2836                                             stcb->asoc.site_scope) == 0) {
2837                                                   continue;
2838                                         }
2839                                         m_at = sctp_add_addr_to_mbuf(m_at, laddr->ifa);
2840                               }
2841                     }
2842           }
2843           /* calulate the size and update pkt header and chunk header */
2844           m->m_pkthdr.len = 0;
2845           for (m_at = m; m_at; m_at = m_at->m_next) {
2846                     if (m_at->m_next == NULL)
2847                               m_last = m_at;
2848                     m->m_pkthdr.len += m_at->m_len;
2849           }
2850           initm->msg.ch.chunk_length = htons((m->m_pkthdr.len -
2851               sizeof(struct sctphdr)));
2852 #ifdef SCTP_DEBUG
2853           printf("chunk_length %d\n", ntohs(initm->msg.ch.chunk_length));
2854 #endif
2855           /* We pass 0 here to NOT set IP_DF if its IPv4, we
2856            * ignore the return here since the timer will drive
2857            * a retranmission.
2858            */
2859 
2860           /* I don't expect this to execute but we will be safe here */
2861           padval = m->m_pkthdr.len % 4;
2862           if ((padval) && (m_last)) {
2863                     /* The compiler worries that m_last may not be
2864                      * set even though I think it is impossible :->
2865                      * however we add m_last here just in case.
2866                      */
2867                     ret = sctp_add_pad_tombuf(m_last, (4-padval));
2868                     if (ret) {
2869                               /* Houston we have a problem, no space */
2870                               sctp_m_freem(m);
2871                               return;
2872                     }
2873                     m->m_pkthdr.len += padval;
2874           }
2875 #ifdef SCTP_DEBUG
2876           if (sctp_debug_on & SCTP_DEBUG_OUTPUT4) {
2877                     printf("Calling lowlevel output stcb:%p net:%p\n",
2878                            stcb, net);
2879           }
2880 #endif
2881           ret = sctp_lowlevel_chunk_output(inp, stcb, net,
2882                       rtcache_getdst(&net->ro), m, 0, 0, NULL, 0);
2883 #ifdef SCTP_DEBUG
2884           if (sctp_debug_on & SCTP_DEBUG_OUTPUT4) {
2885                     printf("Low level output returns %d\n", ret);
2886           }
2887 #endif
2888           sctp_timer_start(SCTP_TIMER_TYPE_INIT, inp, stcb, net);
2889           SCTP_GETTIME_TIMEVAL(&net->last_sent_time);
2890 }
2891 
2892 struct mbuf *
sctp_arethere_unrecognized_parameters(struct mbuf * in_initpkt,int param_offset,int * abort_processing,struct sctp_chunkhdr * cp)2893 sctp_arethere_unrecognized_parameters(struct mbuf *in_initpkt,
2894     int param_offset, int *abort_processing, struct sctp_chunkhdr *cp)
2895 {
2896           /* Given a mbuf containing an INIT or INIT-ACK
2897            * with the param_offset being equal to the
2898            * beginning of the params i.e. (iphlen + sizeof(struct sctp_init_msg)
2899            * parse through the parameters to the end of the mbuf verifying
2900            * that all parameters are known.
2901            *
2902            * For unknown parameters build and return a mbuf with
2903            * UNRECOGNIZED_PARAMETER errors. If the flags indicate
2904            * to stop processing this chunk stop, and set *abort_processing
2905            * to 1.
2906            *
2907            * By having param_offset be pre-set to where parameters begin
2908            * it is hoped that this routine may be reused in the future
2909            * by new features.
2910            */
2911           struct sctp_paramhdr *phdr, params;
2912 
2913           struct mbuf *mat, *op_err;
2914           char tempbuf[2048];
2915           int at, limit, pad_needed;
2916           uint16_t ptype, plen;
2917           int err_at;
2918 
2919           *abort_processing = 0;
2920           mat = in_initpkt;
2921           err_at = 0;
2922           limit = ntohs(cp->chunk_length) - sizeof(struct sctp_init_chunk);
2923 #ifdef SCTP_DEBUG
2924           if (sctp_debug_on & SCTP_DEBUG_OUTPUT4) {
2925                     printf("Limit is %d bytes\n", limit);
2926           }
2927 #endif
2928           at = param_offset;
2929           op_err = NULL;
2930 
2931           phdr = sctp_get_next_param(mat, at, &params, sizeof(params));
2932           while ((phdr != NULL) && ((size_t)limit >= sizeof(struct sctp_paramhdr))) {
2933                     ptype = ntohs(phdr->param_type);
2934                     plen = ntohs(phdr->param_length);
2935                     limit -= SCTP_SIZE32(plen);
2936                     if (plen < sizeof(struct sctp_paramhdr)) {
2937 #ifdef SCTP_DEBUG
2938           if (sctp_debug_on & SCTP_DEBUG_OUTPUT4) {
2939                               printf("sctp_output.c:Impossible length in parameter < %d\n", plen);
2940           }
2941 #endif
2942                               *abort_processing = 1;
2943                               break;
2944                     }
2945                     /* All parameters for all chunks that we
2946                      * know/understand are listed here. We process
2947                      * them other places and make appropriate
2948                      * stop actions per the upper bits. However
2949                      * this is the generic routine processor's can
2950                      * call to get back an operr.. to either incorporate (init-ack)
2951                      * or send.
2952                      */
2953                     if ((ptype == SCTP_HEARTBEAT_INFO) ||
2954                         (ptype == SCTP_IPV4_ADDRESS) ||
2955                         (ptype == SCTP_IPV6_ADDRESS) ||
2956                         (ptype == SCTP_STATE_COOKIE) ||
2957                         (ptype == SCTP_UNRECOG_PARAM) ||
2958                         (ptype == SCTP_COOKIE_PRESERVE) ||
2959                         (ptype == SCTP_SUPPORTED_ADDRTYPE) ||
2960                         (ptype == SCTP_PRSCTP_SUPPORTED) ||
2961                         (ptype == SCTP_ADD_IP_ADDRESS) ||
2962                         (ptype == SCTP_DEL_IP_ADDRESS) ||
2963                         (ptype == SCTP_ECN_CAPABLE) ||
2964                         (ptype == SCTP_ULP_ADAPTION) ||
2965                         (ptype == SCTP_ERROR_CAUSE_IND) ||
2966                         (ptype == SCTP_SET_PRIM_ADDR) ||
2967                         (ptype == SCTP_SUCCESS_REPORT) ||
2968                         (ptype == SCTP_ULP_ADAPTION) ||
2969                         (ptype == SCTP_SUPPORTED_CHUNK_EXT) ||
2970                         (ptype == SCTP_ECN_NONCE_SUPPORTED)
2971                               ) {
2972                               /* no skip it */
2973                               at += SCTP_SIZE32(plen);
2974                     } else if (ptype == SCTP_HOSTNAME_ADDRESS) {
2975                               /* We can NOT handle HOST NAME addresses!! */
2976 #ifdef SCTP_DEBUG
2977           if (sctp_debug_on & SCTP_DEBUG_OUTPUT4) {
2978                     printf("Can't handle hostname addresses.. abort processing\n");
2979           }
2980 #endif
2981                               *abort_processing = 1;
2982                               if (op_err == NULL) {
2983                                         /* Ok need to try to get a mbuf */
2984                                         MGETHDR(op_err, M_DONTWAIT, MT_DATA);
2985                                         if (op_err) {
2986                                                   op_err->m_len = 0;
2987                                                   op_err->m_pkthdr.len = 0;
2988                                                   /* pre-reserve space for ip and sctp header  and chunk hdr*/
2989                                                   op_err->m_data += sizeof(struct ip6_hdr);
2990                                                   op_err->m_data += sizeof(struct sctphdr);
2991                                                   op_err->m_data += sizeof(struct sctp_chunkhdr);
2992                                         }
2993                               }
2994                               if (op_err) {
2995                                         /* If we have space */
2996                                         struct sctp_paramhdr s;
2997                                         if (err_at % 4) {
2998                                                   u_int32_t cpthis=0;
2999                                                   pad_needed = 4 - (err_at % 4);
3000                                                   m_copyback(op_err, err_at, pad_needed, (void *)&cpthis);
3001                                                   err_at += pad_needed;
3002                                         }
3003                                         s.param_type = htons(SCTP_CAUSE_UNRESOLV_ADDR);
3004                                         s.param_length = htons(sizeof(s) + plen);
3005                                         m_copyback(op_err, err_at, sizeof(s), (void *)&s);
3006                                         err_at += sizeof(s);
3007                                         phdr = sctp_get_next_param(mat, at, (struct sctp_paramhdr *)tempbuf, plen);
3008                                         if (phdr == NULL) {
3009                                                   sctp_m_freem(op_err);
3010                                                   /* we are out of memory but we
3011                                                    * still need to have a look at what to
3012                                                    * do (the system is in trouble though).
3013                                                    */
3014                                                   return (NULL);
3015                                         }
3016                                         m_copyback(op_err, err_at, plen, (void *)phdr);
3017                                         err_at += plen;
3018                               }
3019                               return (op_err);
3020                     } else {
3021                               /* we do not recognize the parameter
3022                                * figure out what we do.
3023                                */
3024 #ifdef SCTP_DEBUG
3025                               if (sctp_debug_on & SCTP_DEBUG_OUTPUT4) {
3026                                         printf("Got parameter type %x - unknown\n",
3027                                                (u_int)ptype);
3028                               }
3029 #endif
3030                               if ((ptype & 0x4000) == 0x4000) {
3031                                         /* Report bit is set?? */
3032 #ifdef SCTP_DEBUG
3033                                         if (sctp_debug_on & SCTP_DEBUG_OUTPUT4) {
3034                                                   printf("Report bit is set\n");
3035                                         }
3036 #endif
3037                                         if (op_err == NULL) {
3038                                                   /* Ok need to try to get an mbuf */
3039                                                   MGETHDR(op_err, M_DONTWAIT, MT_DATA);
3040                                                   if (op_err) {
3041                                                             op_err->m_len = 0;
3042                                                             op_err->m_pkthdr.len = 0;
3043                                                             op_err->m_data += sizeof(struct ip6_hdr);
3044                                                             op_err->m_data += sizeof(struct sctphdr);
3045                                                             op_err->m_data += sizeof(struct sctp_chunkhdr);
3046                                                   }
3047                                         }
3048                                         if (op_err) {
3049                                                   /* If we have space */
3050                                                   struct sctp_paramhdr s;
3051                                                   if (err_at % 4) {
3052                                                             u_int32_t cpthis=0;
3053                                                             pad_needed = 4 - (err_at % 4);
3054                                                             m_copyback(op_err, err_at, pad_needed, (void *)&cpthis);
3055                                                             err_at += pad_needed;
3056                                                   }
3057                                                   s.param_type = htons(SCTP_UNRECOG_PARAM);
3058                                                   s.param_length = htons(sizeof(s) + plen);
3059                                                   m_copyback(op_err, err_at, sizeof(s), (void *)&s);
3060                                                   err_at += sizeof(s);
3061                                                   if (plen > sizeof(tempbuf)) {
3062                                                             plen = sizeof(tempbuf);
3063                                                   }
3064                                                   phdr = sctp_get_next_param(mat, at, (struct sctp_paramhdr *)tempbuf, plen);
3065                                                   if (phdr == NULL) {
3066                                                             sctp_m_freem(op_err);
3067                                                             /* we are out of memory but we
3068                                                              * still need to have a look at what to
3069                                                              * do (the system is in trouble though).
3070                                                              */
3071                                                             goto more_processing;
3072                                                   }
3073                                                   m_copyback(op_err, err_at, plen, (void *)phdr);
3074                                                   err_at += plen;
3075                                         }
3076                               }
3077                     more_processing:
3078                               if ((ptype & 0x8000) == 0x0000) {
3079 #ifdef SCTP_DEBUG
3080                                         if (sctp_debug_on & SCTP_DEBUG_OUTPUT4) {
3081                                                   printf("Abort bit is now setting1\n");
3082                                         }
3083 #endif
3084                                         return (op_err);
3085                               } else {
3086                                         /* skip this chunk and continue processing */
3087                                         at += SCTP_SIZE32(plen);
3088                               }
3089 
3090                     }
3091                     phdr = sctp_get_next_param(mat, at, &params, sizeof(params));
3092           }
3093           return (op_err);
3094 }
3095 
3096 static int
sctp_are_there_new_addresses(struct sctp_association * asoc,struct mbuf * in_initpkt,int iphlen,int offset)3097 sctp_are_there_new_addresses(struct sctp_association *asoc,
3098     struct mbuf *in_initpkt, int iphlen, int offset)
3099 {
3100           /*
3101            * Given a INIT packet, look through the packet to verify that
3102            * there are NO new addresses. As we go through the parameters
3103            * add reports of any un-understood parameters that require an
3104            * error.  Also we must return (1) to drop the packet if we see
3105            * a un-understood parameter that tells us to drop the chunk.
3106            */
3107           struct sockaddr_in sin4, *sa4;
3108           struct sockaddr_in6 sin6, *sa6;
3109           struct sockaddr *sa_touse;
3110           struct sockaddr *sa;
3111           struct sctp_paramhdr *phdr, params;
3112           struct ip *iph;
3113           struct mbuf *mat;
3114           uint16_t ptype, plen;
3115           uint8_t fnd;
3116           struct sctp_nets *net;
3117 
3118           memset(&sin4, 0, sizeof(sin4));
3119           memset(&sin6, 0, sizeof(sin6));
3120           sin4.sin_family = AF_INET;
3121           sin4.sin_len = sizeof(sin4);
3122           sin6.sin6_family = AF_INET6;
3123           sin6.sin6_len = sizeof(sin6);
3124 
3125           sa_touse = NULL;
3126           /* First what about the src address of the pkt ? */
3127           iph = mtod(in_initpkt, struct ip *);
3128           if (iph->ip_v == IPVERSION) {
3129                     /* source addr is IPv4 */
3130                     sin4.sin_addr = iph->ip_src;
3131                     sa_touse = (struct sockaddr *)&sin4;
3132           } else if (iph->ip_v == (IPV6_VERSION >> 4)) {
3133                     /* source addr is IPv6 */
3134                     struct ip6_hdr *ip6h;
3135                     ip6h = mtod(in_initpkt, struct ip6_hdr *);
3136                     sin6.sin6_addr = ip6h->ip6_src;
3137                     sa_touse = (struct sockaddr *)&sin6;
3138           } else {
3139                     return (1);
3140           }
3141 
3142           fnd = 0;
3143           TAILQ_FOREACH(net, &asoc->nets, sctp_next) {
3144                     sa = (struct sockaddr *)&net->ro.ro_sa;
3145                     if (sa->sa_family == sa_touse->sa_family) {
3146                               if (sa->sa_family == AF_INET) {
3147                                   sa4 = (struct sockaddr_in *)sa;
3148                                         if (sa4->sin_addr.s_addr ==
3149                                             sin4.sin_addr.s_addr) {
3150                                                   fnd = 1;
3151                                                   break;
3152                                         }
3153                               } else if (sa->sa_family == AF_INET6) {
3154                                         sa6 = (struct sockaddr_in6 *)sa;
3155                                         if (SCTP6_ARE_ADDR_EQUAL(&sa6->sin6_addr,
3156                                             &sin6.sin6_addr)) {
3157                                                   fnd = 1;
3158                                                   break;
3159                                         }
3160                               }
3161                     }
3162           }
3163           if (fnd == 0) {
3164                     /* New address added! no need to look further. */
3165                     return (1);
3166           }
3167           /* Ok so far lets munge through the rest of the packet */
3168           mat = in_initpkt;
3169           sa_touse = NULL;
3170           offset += sizeof(struct sctp_init_chunk);
3171           phdr = sctp_get_next_param(mat, offset, &params, sizeof(params));
3172           while (phdr) {
3173                     ptype = ntohs(phdr->param_type);
3174                     plen = ntohs(phdr->param_length);
3175                     if (ptype == SCTP_IPV4_ADDRESS) {
3176                               struct sctp_ipv4addr_param *p4, p4_buf;
3177 
3178                               phdr = sctp_get_next_param(mat, offset,
3179                                   (struct sctp_paramhdr *)&p4_buf, sizeof(p4_buf));
3180                               if (plen != sizeof(struct sctp_ipv4addr_param) ||
3181                                   phdr == NULL) {
3182                                 return (1);
3183                         }
3184                               p4 = (struct sctp_ipv4addr_param *)phdr;
3185                               sin4.sin_addr.s_addr = p4->addr;
3186                               sa_touse = (struct sockaddr *)&sin4;
3187                     } else if (ptype == SCTP_IPV6_ADDRESS) {
3188                               struct sctp_ipv6addr_param *p6, p6_buf;
3189 
3190                               phdr = sctp_get_next_param(mat, offset,
3191                                   (struct sctp_paramhdr *)&p6_buf, sizeof(p6_buf));
3192                               if (plen != sizeof(struct sctp_ipv6addr_param) ||
3193                                   phdr == NULL) {
3194                                 return (1);
3195                         }
3196                               p6 = (struct sctp_ipv6addr_param *)phdr;
3197                               memcpy((void *)&sin6.sin6_addr, p6->addr,
3198                                   sizeof(p6->addr));
3199                               sa_touse = (struct sockaddr *)&sin4;
3200                     }
3201 
3202                     if (sa_touse) {
3203                               /* ok, sa_touse points to one to check */
3204                               fnd = 0;
3205                               TAILQ_FOREACH(net, &asoc->nets, sctp_next) {
3206                                         sa = (struct sockaddr *)&net->ro.ro_sa;
3207                                         if (sa->sa_family != sa_touse->sa_family) {
3208                                                   continue;
3209                                         }
3210                                         if (sa->sa_family == AF_INET) {
3211                                                   sa4 = (struct sockaddr_in *)sa;
3212                                                   if (sa4->sin_addr.s_addr ==
3213                                                       sin4.sin_addr.s_addr) {
3214                                                             fnd = 1;
3215                                                             break;
3216                                                   }
3217                                         } else if (sa->sa_family == AF_INET6) {
3218                                                   sa6 = (struct sockaddr_in6 *)sa;
3219                                                   if (SCTP6_ARE_ADDR_EQUAL(
3220                                                       &sa6->sin6_addr, &sin6.sin6_addr)) {
3221                                                             fnd = 1;
3222                                                             break;
3223                                                   }
3224                                         }
3225                               }
3226                               if (!fnd) {
3227                                         /* New addr added! no need to look further */
3228                                         return (1);
3229                               }
3230                     }
3231                     offset += SCTP_SIZE32(plen);
3232                     phdr = sctp_get_next_param(mat, offset, &params, sizeof(params));
3233           }
3234           return (0);
3235 }
3236 
3237 /*
3238  * Given a MBUF chain that was sent into us containing an
3239  * INIT. Build a INIT-ACK with COOKIE and send back.
3240  * We assume that the in_initpkt has done a pullup to
3241  * include IPv6/4header, SCTP header and initial part of
3242  * INIT message (i.e. the struct sctp_init_msg).
3243  */
3244 void
sctp_send_initiate_ack(struct sctp_inpcb * inp,struct sctp_tcb * stcb,struct mbuf * init_pkt,int iphlen,int offset,struct sctphdr * sh,struct sctp_init_chunk * init_chk)3245 sctp_send_initiate_ack(struct sctp_inpcb *inp, struct sctp_tcb *stcb,
3246     struct mbuf *init_pkt, int iphlen, int offset, struct sctphdr *sh,
3247     struct sctp_init_chunk *init_chk)
3248 {
3249           struct sctp_association *asoc;
3250           struct mbuf *m, *m_at, *m_tmp, *m_cookie, *op_err, *m_last;
3251           struct sctp_init_msg *initackm_out;
3252           struct sctp_ecn_supported_param *ecn;
3253           struct sctp_prsctp_supported_param *prsctp;
3254           struct sctp_ecn_nonce_supported_param *ecn_nonce;
3255           struct sctp_supported_chunk_types_param *pr_supported;
3256           struct sockaddr_storage store;
3257           struct sockaddr_in *sin;
3258           struct sockaddr_in6 *sin6;
3259           struct route *ro;
3260           struct ip *iph;
3261           struct ip6_hdr *ip6;
3262           const struct sockaddr *to;
3263           struct sctp_state_cookie stc;
3264           struct sctp_nets *net=NULL;
3265           int cnt_inits_to=0;
3266           uint16_t his_limit, i_want;
3267           int abort_flag, padval, sz_of;
3268           struct rtentry *rt;
3269 
3270           if (stcb) {
3271                     asoc = &stcb->asoc;
3272           } else {
3273                     asoc = NULL;
3274           }
3275           m_last = NULL;
3276           if ((asoc != NULL) &&
3277               (SCTP_GET_STATE(asoc) != SCTP_STATE_COOKIE_WAIT) &&
3278               (sctp_are_there_new_addresses(asoc, init_pkt, iphlen, offset))) {
3279                     /* new addresses, out of here in non-cookie-wait states */
3280                     /*
3281                      * Send a ABORT, we don't add the new address error clause though
3282                      * we even set the T bit and copy in the 0 tag.. this looks no
3283                      * different than if no listner was present.
3284                      */
3285                     sctp_send_abort(init_pkt, iphlen, sh, 0, NULL);
3286                     return;
3287           }
3288           abort_flag = 0;
3289           op_err = sctp_arethere_unrecognized_parameters(init_pkt,
3290               (offset+sizeof(struct sctp_init_chunk)),
3291               &abort_flag, (struct sctp_chunkhdr *)init_chk);
3292           if (abort_flag) {
3293                     sctp_send_abort(init_pkt, iphlen, sh, init_chk->init.initiate_tag, op_err);
3294                     return;
3295           }
3296           MGETHDR(m, M_DONTWAIT, MT_HEADER);
3297           if (m == NULL) {
3298                     /* No memory, INIT timer will re-attempt. */
3299                     sctp_m_freem(op_err);
3300                     return;
3301           }
3302           MCLGET(m, M_DONTWAIT);
3303           if ((m->m_flags & M_EXT) != M_EXT) {
3304                     /* Failed to get cluster buffer */
3305                     sctp_m_freem(op_err);
3306                     sctp_m_freem(m);
3307                     return;
3308           }
3309           m->m_data += SCTP_MIN_OVERHEAD;
3310           m_reset_rcvif(m);
3311           m->m_len = sizeof(struct sctp_init_msg);
3312 
3313           /* the time I built cookie */
3314           SCTP_GETTIME_TIMEVAL(&stc.time_entered);
3315 
3316           /* populate any tie tags */
3317           if (asoc != NULL) {
3318                     /* unlock before tag selections */
3319                     SCTP_TCB_UNLOCK(stcb);
3320                     if (asoc->my_vtag_nonce == 0)
3321                               asoc->my_vtag_nonce = sctp_select_a_tag(inp);
3322                     stc.tie_tag_my_vtag = asoc->my_vtag_nonce;
3323 
3324                     if (asoc->peer_vtag_nonce == 0)
3325                               asoc->peer_vtag_nonce = sctp_select_a_tag(inp);
3326                     stc.tie_tag_peer_vtag = asoc->peer_vtag_nonce;
3327 
3328                     stc.cookie_life = asoc->cookie_life;
3329                     net = asoc->primary_destination;
3330                     /* now we must relock */
3331                     SCTP_INP_RLOCK(inp);
3332                     /* we may be in trouble here if the inp got freed
3333                      * most likely this set of tests will protect
3334                      * us but there is a chance not.
3335                      */
3336                     if (inp->sctp_flags & (SCTP_PCB_FLAGS_SOCKET_GONE|SCTP_PCB_FLAGS_SOCKET_ALLGONE)) {
3337                               sctp_m_freem(op_err);
3338                               sctp_m_freem(m);
3339                               sctp_send_abort(init_pkt, iphlen, sh, 0, NULL);
3340                               return;
3341                     }
3342                     SCTP_TCB_LOCK(stcb);
3343                     SCTP_INP_RUNLOCK(stcb->sctp_ep);
3344           } else {
3345                     stc.tie_tag_my_vtag = 0;
3346                     stc.tie_tag_peer_vtag = 0;
3347                     /* life I will award this cookie */
3348                     stc.cookie_life = inp->sctp_ep.def_cookie_life;
3349           }
3350 
3351           /* copy in the ports for later check */
3352           stc.myport = sh->dest_port;
3353           stc.peerport = sh->src_port;
3354 
3355           /*
3356            * If we wanted to honor cookie life extensions, we would add
3357            * to stc.cookie_life. For now we should NOT honor any extension
3358            */
3359           stc.site_scope = stc.local_scope = stc.loopback_scope = 0;
3360           if (inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) {
3361                     struct inpcb *in_inp;
3362                     /* Its a V6 socket */
3363                     in_inp = (struct inpcb *)inp;
3364                     stc.ipv6_addr_legal = 1;
3365                     /* Now look at the binding flag to see if V4 will be legal */
3366                     if (
3367 #if defined(__FreeBSD__) || defined(__APPLE__)
3368                         (in_inp->inp_flags & IN6P_IPV6_V6ONLY)
3369 #elif defined(__OpenBSD__)
3370                         (0)   /* For openbsd we do dual bind only */
3371 #else
3372                         (((struct in6pcb *)in_inp)->in6p_flags & IN6P_IPV6_V6ONLY)
3373 #endif
3374                         == 0) {
3375                               stc.ipv4_addr_legal = 1;
3376                     } else {
3377                               /* V4 addresses are NOT legal on the association */
3378                               stc.ipv4_addr_legal = 0;
3379                     }
3380           } else {
3381                     /* Its a V4 socket, no - V6 */
3382                     stc.ipv4_addr_legal = 1;
3383                     stc.ipv6_addr_legal = 0;
3384           }
3385 
3386 #ifdef SCTP_DONT_DO_PRIVADDR_SCOPE
3387           stc.ipv4_scope = 1;
3388 #else
3389           stc.ipv4_scope = 0;
3390 #endif
3391           /* now for scope setup */
3392           memset((void *)&store, 0, sizeof(store));
3393           sin = (struct sockaddr_in *)&store;
3394           sin6 = (struct sockaddr_in6 *)&store;
3395           if (net == NULL) {
3396                     to = (struct sockaddr *)&store;
3397                     iph = mtod(init_pkt, struct ip *);
3398                     if (iph->ip_v == IPVERSION) {
3399                               struct in_addr addr;
3400                               static struct route iproute;
3401 
3402                               sin->sin_family = AF_INET;
3403                               sin->sin_len = sizeof(struct sockaddr_in);
3404                               sin->sin_port = sh->src_port;
3405                               sin->sin_addr = iph->ip_src;
3406                               /* lookup address */
3407                               stc.address[0] = sin->sin_addr.s_addr;
3408                               stc.address[1] = 0;
3409                               stc.address[2] = 0;
3410                               stc.address[3] = 0;
3411                               stc.addr_type = SCTP_IPV4_ADDRESS;
3412                               /* local from address */
3413                               memset(&iproute, 0, sizeof(iproute));
3414                               ro = &iproute;
3415 
3416                               /* XXX */
3417                               rt = rtcache_lookup(ro, (struct sockaddr *) sin);
3418                               rtcache_unref(rt, ro);
3419                               addr = sctp_ipv4_source_address_selection(inp, NULL,
3420                                   ro, NULL, 0);
3421                               stc.laddress[0] = addr.s_addr;
3422                               stc.laddress[1] = 0;
3423                               stc.laddress[2] = 0;
3424                               stc.laddress[3] = 0;
3425                               stc.laddr_type = SCTP_IPV4_ADDRESS;
3426                               /* scope_id is only for v6 */
3427                               stc.scope_id = 0;
3428 #ifndef SCTP_DONT_DO_PRIVADDR_SCOPE
3429                               if (IN4_ISPRIVATE_ADDRESS(&sin->sin_addr)) {
3430                                         stc.ipv4_scope = 1;
3431                               }
3432 #else
3433                               stc.ipv4_scope = 1;
3434 #endif /* SCTP_DONT_DO_PRIVADDR_SCOPE */
3435                               /* Must use the address in this case */
3436                               if (sctp_is_address_on_local_host((struct sockaddr *)sin)) {
3437                                         stc.loopback_scope = 1;
3438                                         stc.ipv4_scope = 1;
3439                                         stc.site_scope = 1;
3440                                         stc.local_scope = 1;
3441                               }
3442                     } else if (iph->ip_v == (IPV6_VERSION >> 4)) {
3443                               struct in6_addr addr;
3444                         static struct route iproute6;
3445                               ip6 = mtod(init_pkt, struct ip6_hdr *);
3446                               sin6->sin6_family = AF_INET6;
3447                               sin6->sin6_len = sizeof(struct sockaddr_in6);
3448                               sin6->sin6_port = sh->src_port;
3449                               sin6->sin6_addr = ip6->ip6_src;
3450                               /* lookup address */
3451                               memcpy(&stc.address, &sin6->sin6_addr,
3452                                   sizeof(struct in6_addr));
3453                               sin6->sin6_scope_id = 0;
3454                               stc.addr_type = SCTP_IPV6_ADDRESS;
3455                               stc.scope_id = 0;
3456                               if (sctp_is_address_on_local_host((struct sockaddr *)sin6)) {
3457                                         stc.loopback_scope = 1;
3458                                         stc.local_scope = 1;
3459                                         stc.site_scope = 1;
3460                                         stc.ipv4_scope = 1;
3461                               } else if (IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr)) {
3462                                         /*
3463                                          * If the new destination is a LINK_LOCAL
3464                                          * we must have common both site and local
3465                                          * scope. Don't set local scope though since
3466                                          * we must depend on the source to be added
3467                                          * implicitly. We cannot assure just because
3468                                          * we share one link that all links are common.
3469                                          *
3470                                          * XXX: never treat link-local case explicitly.
3471                                          * Use general routines defined in scope6.c.
3472                                          * (jinmei@kame)
3473                                          */
3474                                         stc.local_scope = 0;
3475                                         stc.site_scope = 1;
3476                                         stc.ipv4_scope = 1;
3477                                         /* we start counting for the private
3478                                          * address stuff at 1. since the link
3479                                          * local we source from won't show
3480                                          * up in our scoped count.
3481                                          */
3482                                         cnt_inits_to=1;
3483                                         /* pull out the scope_id from incoming pkt */
3484 #if defined(SCTP_BASE_FREEBSD) || defined(__APPLE__)
3485                                         (void)in6_recoverscope(sin6, &in6_src,
3486                                             m_get_rcvif_NOMPSAFE(init_pkt));
3487                                         in6_embedscope(&sin6->sin6_addr, sin6, NULL,
3488                                             NULL);
3489 #else
3490                                         (void)sa6_recoverscope(sin6);
3491 #endif
3492                                         stc.scope_id = sin6->sin6_scope_id;
3493 
3494                               } else if (IN6_IS_ADDR_SITELOCAL(&sin6->sin6_addr)) {
3495                                         /*
3496                                          * If the new destination is SITE_LOCAL
3497                                          * then we must have site scope in common.
3498                                          */
3499                                         stc.site_scope = 1;
3500                               }
3501                               /* local from address */
3502                               memset(&iproute6, 0, sizeof(iproute6));
3503                               ro = (struct route *)&iproute6;
3504                               /* XXX */
3505                               rt = rtcache_lookup(ro, (struct sockaddr *) sin6);
3506                               rtcache_unref(rt, ro);
3507                               addr = sctp_ipv6_source_address_selection(inp, NULL,
3508                                   ro, NULL, 0);
3509                               memcpy(&stc.laddress, &addr, sizeof(struct in6_addr));
3510                               stc.laddr_type = SCTP_IPV6_ADDRESS;
3511                     }
3512           } else {
3513                     /* set the scope per the existing tcb */
3514                     struct sctp_nets *lnet;
3515 
3516                     stc.loopback_scope = asoc->loopback_scope;
3517                     stc.ipv4_scope = asoc->ipv4_local_scope;
3518                     stc.site_scope = asoc->site_scope;
3519                     stc.local_scope = asoc->local_scope;
3520                     TAILQ_FOREACH(lnet, &asoc->nets, sctp_next) {
3521                               if (rtcache_getdst(&lnet->ro)->sa_family == AF_INET6) {
3522                                         if (IN6_IS_ADDR_LINKLOCAL((const struct in6_addr *) rtcache_getdst(&lnet->ro)->sa_data)) {
3523                                                   /* if we have a LL address, start counting
3524                                                    * at 1.
3525                                                    */
3526                                                   cnt_inits_to = 1;
3527                                         }
3528                               }
3529                     }
3530 
3531                     /* use the net pointer */
3532                     to = rtcache_getdst(&net->ro);
3533                     if (to->sa_family == AF_INET) {
3534                               memcpy(&stc.address[0], to, sizeof(struct in_addr));
3535                               stc.address[1] = 0;
3536                               stc.address[2] = 0;
3537                               stc.address[3] = 0;
3538                               stc.addr_type = SCTP_IPV4_ADDRESS;
3539                               if (net->src_addr_selected == 0) {
3540                                         /* strange case here, the INIT
3541                                          * should have did the selection.
3542                                          */
3543                                         net->_s_addr.sin.sin_addr =
3544                                             sctp_ipv4_source_address_selection(inp,
3545                                             stcb, &net->ro, net, 0);
3546                                         net->src_addr_selected = 1;
3547 
3548                               }
3549 
3550                               stc.laddress[0] = net->_s_addr.sin.sin_addr.s_addr;
3551                               stc.laddress[1] = 0;
3552                               stc.laddress[2] = 0;
3553                               stc.laddress[3] = 0;
3554                               stc.laddr_type = SCTP_IPV4_ADDRESS;
3555                     } else if (to->sa_family == AF_INET6) {
3556                               memcpy(&stc.address, &to->sa_data,
3557                                   sizeof(struct in6_addr));
3558                               stc.addr_type = SCTP_IPV6_ADDRESS;
3559                               if (net->src_addr_selected == 0) {
3560                                         /* strange case here, the INIT
3561                                          * should have did the selection.
3562                                          */
3563                                         net->_s_addr.sin6.sin6_addr =
3564                                             sctp_ipv6_source_address_selection(inp,
3565                                             stcb, &net->ro, net, 0);
3566                                         net->src_addr_selected = 1;
3567                               }
3568                               memcpy(&stc.laddress, &net->_s_addr.sin6.sin6_addr,
3569                                   sizeof(struct in6_addr));
3570                               stc.laddr_type = SCTP_IPV6_ADDRESS;
3571                     }
3572           }
3573           /* Now lets put the SCTP header in place */
3574           initackm_out = mtod(m, struct sctp_init_msg *);
3575           initackm_out->sh.src_port = inp->sctp_lport;
3576           initackm_out->sh.dest_port = sh->src_port;
3577           initackm_out->sh.v_tag = init_chk->init.initiate_tag;
3578           /* Save it off for quick ref */
3579           stc.peers_vtag = init_chk->init.initiate_tag;
3580           initackm_out->sh.checksum = 0;          /* calculate later */
3581           /* who are we */
3582           strncpy(stc.identification, SCTP_VERSION_STRING,
3583              uimin(strlen(SCTP_VERSION_STRING), sizeof(stc.identification)));
3584           /* now the chunk header */
3585           initackm_out->msg.ch.chunk_type = SCTP_INITIATION_ACK;
3586           initackm_out->msg.ch.chunk_flags = 0;
3587           /* fill in later from mbuf we build */
3588           initackm_out->msg.ch.chunk_length = 0;
3589           /* place in my tag */
3590           if ((asoc != NULL) &&
3591               ((SCTP_GET_STATE(asoc) == SCTP_STATE_COOKIE_WAIT) ||
3592                (SCTP_GET_STATE(asoc) == SCTP_STATE_COOKIE_ECHOED))) {
3593                     /* re-use the v-tags and init-seq here */
3594                     initackm_out->msg.init.initiate_tag = htonl(asoc->my_vtag);
3595                     initackm_out->msg.init.initial_tsn = htonl(asoc->init_seq_number);
3596           } else {
3597                     initackm_out->msg.init.initiate_tag = htonl(sctp_select_a_tag(inp));
3598                     /* get a TSN to use too */
3599                     initackm_out->msg.init.initial_tsn = htonl(sctp_select_initial_TSN(&inp->sctp_ep));
3600           }
3601           /* save away my tag to */
3602           stc.my_vtag = initackm_out->msg.init.initiate_tag;
3603 
3604           /* set up some of the credits. */
3605           initackm_out->msg.init.a_rwnd = htonl(uimax(inp->sctp_socket->so_rcv.sb_hiwat, SCTP_MINIMAL_RWND));
3606           /* set what I want */
3607           his_limit = ntohs(init_chk->init.num_inbound_streams);
3608           /* choose what I want */
3609           if (asoc != NULL) {
3610                     if (asoc->streamoutcnt > inp->sctp_ep.pre_open_stream_count) {
3611                               i_want = asoc->streamoutcnt;
3612                     } else {
3613                               i_want = inp->sctp_ep.pre_open_stream_count;
3614                     }
3615           } else {
3616                     i_want = inp->sctp_ep.pre_open_stream_count;
3617           }
3618           if (his_limit < i_want) {
3619                     /* I Want more :< */
3620                     initackm_out->msg.init.num_outbound_streams = init_chk->init.num_inbound_streams;
3621           } else {
3622                     /* I can have what I want :> */
3623                     initackm_out->msg.init.num_outbound_streams = htons(i_want);
3624           }
3625           /* tell him his limt. */
3626           initackm_out->msg.init.num_inbound_streams =
3627               htons(inp->sctp_ep.max_open_streams_intome);
3628           /* setup the ECN pointer */
3629 
3630 /*        if (inp->sctp_flags & SCTP_PCB_FLAGS_ADAPTIONEVNT) {*/
3631           if (inp->sctp_ep.adaption_layer_indicator) {
3632                     struct sctp_adaption_layer_indication *ali;
3633                     ali = (struct sctp_adaption_layer_indication *)(
3634                         (vaddr_t)initackm_out + sizeof(*initackm_out));
3635                     ali->ph.param_type = htons(SCTP_ULP_ADAPTION);
3636                     ali->ph.param_length = htons(sizeof(*ali));
3637                     ali->indication = ntohl(inp->sctp_ep.adaption_layer_indicator);
3638                     m->m_len += sizeof(*ali);
3639                     ecn = (struct sctp_ecn_supported_param *)((vaddr_t)ali +
3640                         sizeof(*ali));
3641           } else {
3642                     ecn = (struct sctp_ecn_supported_param*)(
3643                         (vaddr_t)initackm_out + sizeof(*initackm_out));
3644           }
3645 
3646           /* ECN parameter */
3647           if (sctp_ecn == 1) {
3648                     ecn->ph.param_type = htons(SCTP_ECN_CAPABLE);
3649                     ecn->ph.param_length = htons(sizeof(*ecn));
3650                     m->m_len += sizeof(*ecn);
3651 
3652                     prsctp = (struct sctp_prsctp_supported_param *)((vaddr_t)ecn +
3653                         sizeof(*ecn));
3654           } else {
3655                     prsctp = (struct sctp_prsctp_supported_param *)((vaddr_t)ecn);
3656           }
3657           /* And now tell the peer we do  pr-sctp */
3658           prsctp->ph.param_type = htons(SCTP_PRSCTP_SUPPORTED);
3659           prsctp->ph.param_length = htons(sizeof(*prsctp));
3660           m->m_len += sizeof(*prsctp);
3661 
3662 
3663           /* And now tell the peer we do all the extensions */
3664           pr_supported = (struct sctp_supported_chunk_types_param *)((vaddr_t)prsctp +
3665              sizeof(*prsctp));
3666 
3667           pr_supported->ph.param_type = htons(SCTP_SUPPORTED_CHUNK_EXT);
3668           pr_supported->ph.param_length = htons(sizeof(*pr_supported) + SCTP_EXT_COUNT);
3669           pr_supported->chunk_types[0] = SCTP_ASCONF;
3670           pr_supported->chunk_types[1] = SCTP_ASCONF_ACK;
3671           pr_supported->chunk_types[2] = SCTP_FORWARD_CUM_TSN;
3672           pr_supported->chunk_types[3] = SCTP_PACKET_DROPPED;
3673           pr_supported->chunk_types[4] = SCTP_STREAM_RESET;
3674           pr_supported->chunk_types[5] = 0; /* pad */
3675           pr_supported->chunk_types[6] = 0; /* pad */
3676           pr_supported->chunk_types[7] = 0; /* pad */
3677 
3678           m->m_len += (sizeof(*pr_supported) + SCTP_EXT_COUNT + SCTP_PAD_EXT_COUNT);
3679           if (sctp_ecn_nonce) {
3680                     /* ECN nonce: And now tell the peer we support ECN nonce */
3681                     ecn_nonce = (struct sctp_ecn_nonce_supported_param *)((vaddr_t)pr_supported +
3682                          sizeof(*pr_supported) + SCTP_EXT_COUNT + SCTP_PAD_EXT_COUNT);
3683                     ecn_nonce->ph.param_type = htons(SCTP_ECN_NONCE_SUPPORTED);
3684                     ecn_nonce->ph.param_length = htons(sizeof(*ecn_nonce));
3685                     m->m_len += sizeof(*ecn_nonce);
3686           }
3687 
3688           m_at = m;
3689           /* now the addresses */
3690           if (inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) {
3691                     struct ifnet *ifn;
3692                     struct ifaddr *ifa;
3693                     int cnt = cnt_inits_to;
3694                     int s;
3695 
3696                     s = pserialize_read_enter();
3697                     IFNET_READER_FOREACH(ifn) {
3698                               if ((stc.loopback_scope == 0) &&
3699                                   (ifn->if_type == IFT_LOOP)) {
3700                                         /*
3701                                          * Skip loopback devices if loopback_scope
3702                                          * not set
3703                                          */
3704                                         continue;
3705                               }
3706                               IFADDR_READER_FOREACH(ifa, ifn) {
3707                                         if (sctp_is_address_in_scope(ifa,
3708                                             stc.ipv4_addr_legal, stc.ipv6_addr_legal,
3709                                             stc.loopback_scope, stc.ipv4_scope,
3710                                             stc.local_scope, stc.site_scope) == 0) {
3711                                                   continue;
3712                                         }
3713                                         cnt++;
3714                               }
3715                     }
3716                     pserialize_read_exit(s);
3717 
3718                     if (cnt > 1) {
3719                               s = pserialize_read_enter();
3720                               IFNET_READER_FOREACH(ifn) {
3721                                         if ((stc.loopback_scope == 0) &&
3722                                             (ifn->if_type == IFT_LOOP)) {
3723                                                   /*
3724                                                    * Skip loopback devices if
3725                                                    * loopback_scope not set
3726                                                    */
3727                                                   continue;
3728                                         }
3729                                         IFADDR_READER_FOREACH(ifa, ifn) {
3730                                                   if (sctp_is_address_in_scope(ifa,
3731                                                       stc.ipv4_addr_legal,
3732                                                       stc.ipv6_addr_legal,
3733                                                       stc.loopback_scope, stc.ipv4_scope,
3734                                                       stc.local_scope, stc.site_scope) == 0) {
3735                                                             continue;
3736                                                   }
3737                                                   m_at = sctp_add_addr_to_mbuf(m_at, ifa);
3738                                         }
3739                               }
3740                               pserialize_read_exit(s);
3741                     }
3742           } else {
3743                     struct sctp_laddr *laddr;
3744                     int cnt;
3745                     cnt = cnt_inits_to;
3746                     /* First, how many ? */
3747                     LIST_FOREACH(laddr, &inp->sctp_addr_list, sctp_nxt_addr) {
3748                               if (laddr->ifa == NULL) {
3749                                         continue;
3750                               }
3751                               if (laddr->ifa->ifa_addr == NULL)
3752                                         continue;
3753                               if (sctp_is_address_in_scope(laddr->ifa,
3754                                   stc.ipv4_addr_legal, stc.ipv6_addr_legal,
3755                                   stc.loopback_scope, stc.ipv4_scope,
3756                                   stc.local_scope, stc.site_scope) == 0) {
3757                                         continue;
3758                               }
3759                               cnt++;
3760                     }
3761                     /* If we bind a single address only we won't list
3762                      * any. This way you can get through a NAT
3763                      */
3764                     if (cnt > 1) {
3765                               LIST_FOREACH(laddr, &inp->sctp_addr_list, sctp_nxt_addr) {
3766                                         if (laddr->ifa == NULL) {
3767 #ifdef SCTP_DEBUG
3768                                                   if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
3769                                                             printf("Help I have fallen and I can't get up!\n");
3770                                                   }
3771 #endif
3772                                                   continue;
3773                                         }
3774                                         if (laddr->ifa->ifa_addr == NULL)
3775                                                   continue;
3776                                         if (sctp_is_address_in_scope(laddr->ifa,
3777                                             stc.ipv4_addr_legal, stc.ipv6_addr_legal,
3778                                             stc.loopback_scope, stc.ipv4_scope,
3779                                             stc.local_scope, stc.site_scope) == 0) {
3780                                                   continue;
3781                                         }
3782                                         m_at = sctp_add_addr_to_mbuf(m_at, laddr->ifa);
3783                               }
3784                     }
3785           }
3786 
3787           /* tack on the operational error if present */
3788           if (op_err) {
3789                     if (op_err->m_pkthdr.len % 4) {
3790                               /* must add a pad to the param */
3791                               u_int32_t cpthis=0;
3792                               int padlen;
3793                               padlen = 4 - (op_err->m_pkthdr.len % 4);
3794                               m_copyback(op_err, op_err->m_pkthdr.len, padlen, (void *)&cpthis);
3795                     }
3796                     while (m_at->m_next != NULL) {
3797                               m_at = m_at->m_next;
3798                     }
3799                     m_at->m_next = op_err;
3800                     while (m_at->m_next != NULL) {
3801                               m_at = m_at->m_next;
3802                     }
3803           }
3804           /* Get total size of init packet */
3805           sz_of = SCTP_SIZE32(ntohs(init_chk->ch.chunk_length));
3806           /* pre-calulate the size and update pkt header and chunk header */
3807           m->m_pkthdr.len = 0;
3808           for (m_tmp = m; m_tmp; m_tmp = m_tmp->m_next) {
3809                     m->m_pkthdr.len += m_tmp->m_len;
3810                     if (m_tmp->m_next == NULL) {
3811                               /* m_tmp should now point to last one */
3812                               break;
3813                     }
3814           }
3815           /*
3816            * Figure now the size of the cookie. We know the size of the
3817            * INIT-ACK. The Cookie is going to be the size of INIT, INIT-ACK,
3818            * COOKIE-STRUCTURE and SIGNATURE.
3819            */
3820 
3821           /*
3822            * take our earlier INIT calc and add in the sz we just calculated
3823            * minus the size of the sctphdr (its not included in chunk size
3824            */
3825 
3826           /* add once for the INIT-ACK */
3827           sz_of += (m->m_pkthdr.len - sizeof(struct sctphdr));
3828 
3829           /* add a second time for the INIT-ACK in the cookie */
3830           sz_of += (m->m_pkthdr.len - sizeof(struct sctphdr));
3831 
3832           /* Now add the cookie header and cookie message struct */
3833           sz_of += sizeof(struct sctp_state_cookie_param);
3834           /* ...and add the size of our signature */
3835           sz_of += SCTP_SIGNATURE_SIZE;
3836           initackm_out->msg.ch.chunk_length = htons(sz_of);
3837 
3838           /* Now we must build a cookie */
3839           m_cookie = sctp_add_cookie(inp, init_pkt, offset, m,
3840               sizeof(struct sctphdr), &stc);
3841           if (m_cookie == NULL) {
3842                     /* memory problem */
3843                     sctp_m_freem(m);
3844                     return;
3845           }
3846           /* Now append the cookie to the end and update the space/size */
3847           m_tmp->m_next = m_cookie;
3848 
3849           /*
3850            * We pass 0 here to NOT set IP_DF if its IPv4, we ignore the
3851            * return here since the timer will drive a retranmission.
3852            */
3853           padval = m->m_pkthdr.len % 4;
3854           if ((padval) && (m_last)) {
3855                     /* see my previous comments on m_last */
3856                     int ret;
3857                     ret = sctp_add_pad_tombuf(m_last, (4-padval));
3858                     if (ret) {
3859                               /* Houston we have a problem, no space */
3860                               sctp_m_freem(m);
3861                               return;
3862                     }
3863                     m->m_pkthdr.len += padval;
3864           }
3865           sctp_lowlevel_chunk_output(inp, NULL, NULL, to, m, 0, 0, NULL, 0);
3866 }
3867 
3868 
3869 static void
sctp_insert_on_wheel(struct sctp_association * asoc,struct sctp_stream_out * strq)3870 sctp_insert_on_wheel(struct sctp_association *asoc,
3871                          struct sctp_stream_out *strq)
3872 {
3873           struct sctp_stream_out *stre, *strn;
3874           stre = TAILQ_FIRST(&asoc->out_wheel);
3875           if (stre == NULL) {
3876                     /* only one on wheel */
3877                     TAILQ_INSERT_HEAD(&asoc->out_wheel, strq, next_spoke);
3878                     return;
3879           }
3880           for (; stre; stre = strn) {
3881                     strn = TAILQ_NEXT(stre, next_spoke);
3882                     if (stre->stream_no > strq->stream_no) {
3883                               TAILQ_INSERT_BEFORE(stre, strq, next_spoke);
3884                               return;
3885                     } else if (stre->stream_no == strq->stream_no) {
3886                               /* huh, should not happen */
3887                               return;
3888                     } else if (strn == NULL) {
3889                               /* next one is null */
3890                               TAILQ_INSERT_AFTER(&asoc->out_wheel, stre, strq,
3891                                                      next_spoke);
3892                     }
3893           }
3894 }
3895 
3896 static void
sctp_remove_from_wheel(struct sctp_association * asoc,struct sctp_stream_out * strq)3897 sctp_remove_from_wheel(struct sctp_association *asoc,
3898                            struct sctp_stream_out *strq)
3899 {
3900           /* take off and then setup so we know it is not on the wheel */
3901           TAILQ_REMOVE(&asoc->out_wheel, strq, next_spoke);
3902           strq->next_spoke.tqe_next = NULL;
3903           strq->next_spoke.tqe_prev = NULL;
3904 }
3905 
3906 
3907 static void
sctp_prune_prsctp(struct sctp_tcb * stcb,struct sctp_association * asoc,struct sctp_sndrcvinfo * srcv,int dataout)3908 sctp_prune_prsctp(struct sctp_tcb *stcb,
3909                       struct sctp_association *asoc,
3910                       struct sctp_sndrcvinfo *srcv,
3911                       int dataout
3912           )
3913 {
3914           int freed_spc=0;
3915           struct sctp_tmit_chunk *chk, *nchk;
3916           if ((asoc->peer_supports_prsctp) && (asoc->sent_queue_cnt_removeable > 0)) {
3917                     TAILQ_FOREACH(chk, &asoc->sent_queue, sctp_next) {
3918                               /*
3919                                * Look for chunks marked with the PR_SCTP
3920                                * flag AND the buffer space flag. If the one
3921                                * being sent is equal or greater priority then
3922                                * purge the old one and free some space.
3923                                */
3924                               if ((chk->flags & (SCTP_PR_SCTP_ENABLED |
3925                                                      SCTP_PR_SCTP_BUFFER)) ==
3926                                   (SCTP_PR_SCTP_ENABLED|SCTP_PR_SCTP_BUFFER)) {
3927                                         /*
3928                                          * This one is PR-SCTP AND buffer space
3929                                          * limited type
3930                                          */
3931                                         if (chk->rec.data.timetodrop.tv_sec >= (long)srcv->sinfo_timetolive) {
3932                                                   /* Lower numbers equates to
3933                                                    * higher priority so if the
3934                                                    * one we are looking at has a
3935                                                    * larger or equal priority we
3936                                                    * want to drop the data and
3937                                                    * NOT retransmit it.
3938                                                    */
3939                                                   if (chk->data) {
3940                                                             /* We release the
3941                                                              * book_size if the
3942                                                              * mbuf is here
3943                                                              */
3944                                                             int ret_spc;
3945                                                             int cause;
3946                                                             if (chk->sent > SCTP_DATAGRAM_UNSENT)
3947                                                                       cause = SCTP_RESPONSE_TO_USER_REQ|SCTP_NOTIFY_DATAGRAM_SENT;
3948                                                             else
3949                                                                       cause = SCTP_RESPONSE_TO_USER_REQ|SCTP_NOTIFY_DATAGRAM_UNSENT;
3950                                                             ret_spc  = sctp_release_pr_sctp_chunk(stcb, chk,
3951                                                                                                           cause,
3952                                                                                                           &asoc->sent_queue);
3953                                                             freed_spc += ret_spc;
3954                                                             if (freed_spc >= dataout) {
3955                                                                       return;
3956                                                             }
3957                                                   } /* if chunk was present */
3958                                         } /* if of sufficient priority */
3959                               } /* if chunk has enabled */
3960                     } /* tailqforeach */
3961 
3962                     chk = TAILQ_FIRST(&asoc->send_queue);
3963                     while (chk) {
3964                               nchk = TAILQ_NEXT(chk, sctp_next);
3965                               /* Here we must move to the sent queue and mark */
3966                               if ((chk->flags & (SCTP_PR_SCTP_ENABLED |
3967                                                      SCTP_PR_SCTP_BUFFER)) ==
3968                                   (SCTP_PR_SCTP_ENABLED|SCTP_PR_SCTP_BUFFER)) {
3969                                         if (chk->rec.data.timetodrop.tv_sec >= (long)srcv->sinfo_timetolive) {
3970                                                   if (chk->data) {
3971                                                             /* We release the
3972                                                              * book_size if the
3973                                                              * mbuf is here
3974                                                              */
3975                                                             int ret_spc;
3976                                                             ret_spc  = sctp_release_pr_sctp_chunk(stcb, chk,
3977                                                                 SCTP_RESPONSE_TO_USER_REQ|SCTP_NOTIFY_DATAGRAM_UNSENT,
3978                                                                 &asoc->send_queue);
3979 
3980                                                             freed_spc += ret_spc;
3981                                                             if (freed_spc >= dataout) {
3982                                                                       return;
3983                                                             }
3984                                                   } /* end if chk->data */
3985                                         } /* end if right class */
3986                               } /* end if chk pr-sctp */
3987                               chk = nchk;
3988                     } /* end while (chk) */
3989           } /* if enabled in asoc */
3990 }
3991 
3992 static void
sctp_prepare_chunk(struct sctp_tmit_chunk * template,struct sctp_tcb * stcb,struct sctp_sndrcvinfo * srcv,struct sctp_stream_out * strq,struct sctp_nets * net)3993 sctp_prepare_chunk(struct sctp_tmit_chunk *template,
3994                        struct sctp_tcb *stcb,
3995                        struct sctp_sndrcvinfo *srcv,
3996                        struct sctp_stream_out *strq,
3997                        struct sctp_nets *net)
3998 {
3999           memset(template, 0, sizeof(struct sctp_tmit_chunk));
4000           template->sent = SCTP_DATAGRAM_UNSENT;
4001           if ((stcb->asoc.peer_supports_prsctp) &&
4002               (srcv->sinfo_flags & (SCTP_PR_SCTP_TTL|SCTP_PR_SCTP_BUF)) &&
4003               (srcv->sinfo_timetolive > 0)
4004                     ) {
4005                     /* If:
4006                      *  Peer supports PR-SCTP
4007                      *  The flags is set against this send for PR-SCTP
4008                      *  And timetolive is a positive value, zero is reserved
4009                      *     to mean a reliable send for both buffer/time
4010                      *     related one.
4011                      */
4012                     if (srcv->sinfo_flags & SCTP_PR_SCTP_BUF) {
4013                               /*
4014                                * Time to live is a priority stored in tv_sec
4015                                * when doing the buffer drop thing.
4016                                */
4017                               template->rec.data.timetodrop.tv_sec = srcv->sinfo_timetolive;
4018                     } else {
4019                               struct timeval tv;
4020 
4021                               SCTP_GETTIME_TIMEVAL(&template->rec.data.timetodrop);
4022                               tv.tv_sec = srcv->sinfo_timetolive / 1000;
4023                               tv.tv_usec = (srcv->sinfo_timetolive * 1000) % 1000000;
4024 #ifndef __FreeBSD__
4025                               timeradd(&template->rec.data.timetodrop, &tv,
4026                                   &template->rec.data.timetodrop);
4027 #else
4028                               timevaladd(&template->rec.data.timetodrop, &tv);
4029 #endif
4030                     }
4031           }
4032           if ((srcv->sinfo_flags & SCTP_UNORDERED) == 0) {
4033                     template->rec.data.stream_seq = strq->next_sequence_sent;
4034           } else {
4035                     template->rec.data.stream_seq = 0;
4036           }
4037           template->rec.data.TSN_seq = 0;         /* not yet assigned */
4038 
4039           template->rec.data.stream_number = srcv->sinfo_stream;
4040           template->rec.data.payloadtype = srcv->sinfo_ppid;
4041           template->rec.data.context = srcv->sinfo_context;
4042           template->rec.data.doing_fast_retransmit = 0;
4043           template->rec.data.ect_nonce = 0;   /* ECN Nonce */
4044 
4045           if (srcv->sinfo_flags & SCTP_ADDR_OVER) {
4046                     template->whoTo = net;
4047           } else {
4048                     if (stcb->asoc.primary_destination)
4049                               template->whoTo = stcb->asoc.primary_destination;
4050                     else {
4051                               /* TSNH */
4052                               template->whoTo = net;
4053                     }
4054           }
4055           /* the actual chunk flags */
4056           if (srcv->sinfo_flags & SCTP_UNORDERED) {
4057                     template->rec.data.rcv_flags = SCTP_DATA_UNORDERED;
4058           } else {
4059                     template->rec.data.rcv_flags = 0;
4060           }
4061           /* no flags yet, FRAGMENT_OK goes here */
4062           template->flags = 0;
4063           /* PR sctp flags */
4064           if (stcb->asoc.peer_supports_prsctp) {
4065                     if (srcv->sinfo_timetolive > 0) {
4066                               /*
4067                                * We only set the flag if timetolive (or
4068                                * priority) was set to a positive number.
4069                                * Zero is reserved specifically to be
4070                                * EXCLUDED and sent reliable.
4071                                */
4072                               if (srcv->sinfo_flags & SCTP_PR_SCTP_TTL) {
4073                                         template->flags |= SCTP_PR_SCTP_ENABLED;
4074                               }
4075                               if (srcv->sinfo_flags & SCTP_PR_SCTP_BUF) {
4076                                         template->flags |= SCTP_PR_SCTP_BUFFER;
4077                               }
4078                     }
4079           }
4080           template->asoc = &stcb->asoc;
4081 }
4082 
4083 
4084 int
sctp_get_frag_point(struct sctp_tcb * stcb,struct sctp_association * asoc)4085 sctp_get_frag_point(struct sctp_tcb *stcb,
4086                         struct sctp_association *asoc)
4087 {
4088           int siz, ovh;
4089 
4090           /* For endpoints that have both 6 and 4 addresses
4091            * we must reserver room for the 6 ip header, for
4092            * those that are only dealing with V4 we use
4093            * a larger frag point.
4094            */
4095           if (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) {
4096                     ovh = SCTP_MED_OVERHEAD;
4097           } else {
4098                     ovh = SCTP_MED_V4_OVERHEAD;
4099           }
4100 
4101           if (stcb->sctp_ep->sctp_frag_point > asoc->smallest_mtu)
4102                     siz = asoc->smallest_mtu - ovh;
4103           else
4104                     siz = (stcb->sctp_ep->sctp_frag_point - ovh);
4105 /*
4106   if (siz > (MCLBYTES-sizeof(struct sctp_data_chunk))) { */
4107                     /* A data chunk MUST fit in a cluster */
4108 /*                  siz = (MCLBYTES - sizeof(struct sctp_data_chunk));*/
4109 /*        }*/
4110 
4111           if (siz % 4) {
4112                     /* make it an even word boundary please */
4113                     siz -= (siz % 4);
4114           }
4115           return (siz);
4116 }
4117 extern unsigned int sctp_max_chunks_on_queue;
4118 
4119 #define   SBLOCKWAIT(f)   (((f)&MSG_DONTWAIT) ? M_NOWAIT : M_WAITOK)
4120 
4121 static int
sctp_msg_append(struct sctp_tcb * stcb,struct sctp_nets * net,struct mbuf * m,struct sctp_sndrcvinfo * srcv,int flags)4122 sctp_msg_append(struct sctp_tcb *stcb,
4123                     struct sctp_nets *net,
4124                     struct mbuf *m,
4125                     struct sctp_sndrcvinfo *srcv,
4126                     int flags)
4127 {
4128           struct socket *so;
4129           struct sctp_association *asoc;
4130           struct sctp_stream_out *strq;
4131           struct sctp_tmit_chunk *chk;
4132           struct sctpchunk_listhead tmp;
4133           struct sctp_tmit_chunk template;
4134           struct mbuf *n, *mnext;
4135           struct mbuf *mm;
4136           unsigned int dataout, siz;
4137           int mbcnt = 0;
4138           int mbcnt_e = 0;
4139           int error = 0;
4140 
4141           if ((stcb == NULL) || (net == NULL) || (m == NULL) || (srcv == NULL)) {
4142                     /* Software fault, you blew it on the call */
4143 #ifdef SCTP_DEBUG
4144                     if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
4145                               printf("software error in sctp_msg_append:1\n");
4146                               printf("stcb:%p net:%p m:%p srcv:%p\n",
4147                                      stcb, net, m, srcv);
4148                     }
4149 #endif
4150                     sctp_m_freem(m);
4151                     return (EFAULT);
4152           }
4153           so = stcb->sctp_socket;
4154           asoc = &stcb->asoc;
4155           if (srcv->sinfo_flags & SCTP_ABORT) {
4156                     if ((SCTP_GET_STATE(asoc) != SCTP_STATE_COOKIE_WAIT) &&
4157                         (SCTP_GET_STATE(asoc) != SCTP_STATE_COOKIE_ECHOED)) {
4158                               /* It has to be up before we abort */
4159                               /* how big is the user initiated abort? */
4160                               if ((m->m_flags & M_PKTHDR) && (m->m_pkthdr.len)) {
4161                                         dataout = m->m_pkthdr.len;
4162                               } else {
4163                                         /* we must count */
4164                                         dataout = 0;
4165                                         for (n = m; n; n = n->m_next) {
4166                                                   dataout += n->m_len;
4167                                         }
4168                               }
4169                               M_PREPEND(m, sizeof(struct sctp_paramhdr), M_DONTWAIT);
4170                               if (m) {
4171                                         struct sctp_paramhdr *ph;
4172                                         m->m_len = sizeof(struct sctp_paramhdr) + dataout;
4173                                         ph = mtod(m, struct sctp_paramhdr *);
4174                                         ph->param_type = htons(SCTP_CAUSE_USER_INITIATED_ABT);
4175                                         ph->param_length = htons(m->m_len);
4176                               }
4177                               sctp_abort_an_association(stcb->sctp_ep, stcb, SCTP_RESPONSE_TO_USER_REQ, m);
4178                               m = NULL;
4179                     } else {
4180                               /* Only free if we don't send an abort */
4181                               ;
4182                     }
4183                     goto out;
4184           }
4185           if ((SCTP_GET_STATE(asoc) == SCTP_STATE_SHUTDOWN_SENT) ||
4186               (SCTP_GET_STATE(asoc) == SCTP_STATE_SHUTDOWN_ACK_SENT) ||
4187               (SCTP_GET_STATE(asoc) == SCTP_STATE_SHUTDOWN_RECEIVED) ||
4188               (asoc->state & SCTP_STATE_SHUTDOWN_PENDING)) {
4189                     /* got data while shutting down */
4190                     error = ECONNRESET;
4191                     goto out;
4192           }
4193 
4194           if (srcv->sinfo_stream >= asoc->streamoutcnt) {
4195                     /* Invalid stream number */
4196                     error = EINVAL;
4197                     goto out;
4198           }
4199           if (asoc->strmout == NULL) {
4200                     /* huh? software error */
4201 #ifdef SCTP_DEBUG
4202                     if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
4203                               printf("software error in sctp_msg_append:2\n");
4204                     }
4205 #endif
4206                     error = EFAULT;
4207                     goto out;
4208           }
4209           strq = &asoc->strmout[srcv->sinfo_stream];
4210           /* how big is it ? */
4211           if ((m->m_flags & M_PKTHDR) && (m->m_pkthdr.len)) {
4212                     dataout = m->m_pkthdr.len;
4213           } else {
4214                     /* we must count */
4215                     dataout = 0;
4216                     for (n = m; n; n = n->m_next) {
4217                               dataout += n->m_len;
4218                     }
4219           }
4220 #ifdef SCTP_DEBUG
4221           if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
4222                     printf("Attempt to send out %d bytes\n",
4223                            dataout);
4224           }
4225 #endif
4226 
4227           /* lock the socket buf */
4228           error = sblock(&so->so_snd, SBLOCKWAIT(flags));
4229           if (error)
4230                     goto out_locked;
4231 
4232           if (dataout > so->so_snd.sb_hiwat) {
4233                     /* It will NEVER fit */
4234                     error = EMSGSIZE;
4235                     goto release;
4236           }
4237           if ((srcv->sinfo_flags & SCTP_EOF) &&
4238               (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_UDPTYPE) &&
4239               (dataout == 0)
4240                     ) {
4241                     goto zap_by_it_all;
4242           }
4243           if ((so->so_snd.sb_hiwat <
4244                (dataout + asoc->total_output_queue_size)) ||
4245               (asoc->chunks_on_out_queue > sctp_max_chunks_on_queue) ||
4246               (asoc->total_output_mbuf_queue_size >
4247                so->so_snd.sb_mbmax)
4248                     ) {
4249                     /* XXX Buffer space hunt for data to skip */
4250                     if (asoc->peer_supports_prsctp) {
4251                               sctp_prune_prsctp(stcb, asoc, srcv, dataout);
4252                     }
4253                     while ((so->so_snd.sb_hiwat <
4254                         (dataout + asoc->total_output_queue_size)) ||
4255                         (asoc->chunks_on_out_queue > sctp_max_chunks_on_queue) ||
4256                         (asoc->total_output_mbuf_queue_size >
4257                         so->so_snd.sb_mbmax)) {
4258                               struct sctp_inpcb *inp;
4259                               /* Now did we free up enough room? */
4260                               if (so->so_state & SS_NBIO) {
4261                                         /* Non-blocking io in place */
4262                                         error = EWOULDBLOCK;
4263                                         goto release;
4264                               }
4265                               /*
4266                                * We store off a pointer to the endpoint.
4267                                * Since on return from this we must check to
4268                                * see if an so_error is set. If so we may have
4269                                * been reset and our stcb destroyed. Returning
4270                                * an error will cause the correct error return
4271                                * through and fix this all.
4272                                */
4273                               inp = stcb->sctp_ep;
4274                               /*
4275                                * Not sure how else to do this since
4276                                * the level we suspended at is not
4277                                * known deep down where we are. I will
4278                                * drop to spl0() so that others can
4279                                * get in.
4280                                */
4281 
4282                               inp->sctp_tcb_at_block = (void *)stcb;
4283                               inp->error_on_block = 0;
4284                               sbunlock(&so->so_snd);
4285                               error = sbwait(&so->so_snd);
4286                               /*
4287                                * XXX: This is ugly but I have
4288                                * recreated most of what goes on to
4289                                * block in the sb. UGHH
4290                                * May want to add the bit about being
4291                                * no longer connected.. but this then
4292                                * further dooms the UDP model NOT to
4293                                * allow this.
4294                                */
4295                               inp->sctp_tcb_at_block = 0;
4296                               if (inp->error_on_block)
4297                                         error = inp->error_on_block;
4298                               if (so->so_error)
4299                                         error = so->so_error;
4300                               if (error) {
4301                                         goto out_locked;
4302                               }
4303                               error = sblock(&so->so_snd, M_WAITOK);
4304                               if (error)
4305                                         goto out_locked;
4306                               /* Otherwise we cycle back and recheck
4307                                * the space
4308                                */
4309 #if defined(__FreeBSD__) && __FreeBSD_version >= 502115
4310                               if (so->so_rcv.sb_state & SBS_CANTSENDMORE) {
4311 #else
4312                               if (so->so_state & SS_CANTSENDMORE) {
4313 #endif
4314                                         error = EPIPE;
4315                                         goto release;
4316                               }
4317                               if (so->so_error) {
4318                                         error = so->so_error;
4319                                         goto release;
4320                               }
4321                     }
4322           }
4323           /* If we have a packet header fix it if it was broke */
4324           if (m->m_flags & M_PKTHDR) {
4325                     m->m_pkthdr.len = dataout;
4326           }
4327           /* use the smallest one, user set value or
4328            * smallest mtu of the asoc
4329            */
4330           siz = sctp_get_frag_point(stcb, asoc);
4331           if ((dataout) && (dataout <= siz)) {
4332                     /* Fast path */
4333                     chk = (struct sctp_tmit_chunk *)SCTP_ZONE_GET(sctppcbinfo.ipi_zone_chunk);
4334                     if (chk == NULL) {
4335                               error = ENOMEM;
4336                               goto release;
4337                     }
4338                     sctp_prepare_chunk(chk, stcb, srcv, strq, net);
4339                     chk->whoTo->ref_count++;
4340                     chk->rec.data.rcv_flags |= SCTP_DATA_NOT_FRAG;
4341 
4342                     /* no flags yet, FRAGMENT_OK goes here */
4343                     sctppcbinfo.ipi_count_chunk++;
4344                     sctppcbinfo.ipi_gencnt_chunk++;
4345                     asoc->chunks_on_out_queue++;
4346                     chk->data = m;
4347                     m = NULL;
4348                     /* Total in the MSIZE */
4349                     for (mm = chk->data; mm; mm = mm->m_next) {
4350                               mbcnt += MSIZE;
4351                               if (mm->m_flags & M_EXT) {
4352                                         mbcnt += chk->data->m_ext.ext_size;
4353                               }
4354                     }
4355                     /* fix up the send_size if it is not present */
4356                     chk->send_size = dataout;
4357                     chk->book_size = chk->send_size;
4358                     chk->mbcnt = mbcnt;
4359                     /* ok, we are committed */
4360                     if ((srcv->sinfo_flags & SCTP_UNORDERED) == 0) {
4361                               /* bump the ssn if we are unordered. */
4362                               strq->next_sequence_sent++;
4363                     }
4364                     chk->data->m_nextpkt = 0;
4365                     asoc->stream_queue_cnt++;
4366                     TAILQ_INSERT_TAIL(&strq->outqueue, chk, sctp_next);
4367                     /* now check if this stream is on the wheel */
4368                     if ((strq->next_spoke.tqe_next == NULL) &&
4369                         (strq->next_spoke.tqe_prev == NULL)) {
4370                               /* Insert it on the wheel since it is not
4371                                * on it currently
4372                                */
4373                               sctp_insert_on_wheel(asoc, strq);
4374                     }
4375           } else if ((dataout) && (dataout > siz)) {
4376                     /* Slow path */
4377                     if ((stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_NO_FRAGMENT) &&
4378                         (dataout > siz)) {
4379                               error = EMSGSIZE;
4380                               goto release;
4381                     }
4382                     /* setup the template */
4383                     sctp_prepare_chunk(&template, stcb, srcv, strq, net);
4384 
4385                     n = m;
4386                     while (dataout > siz) {
4387                               /*
4388                                * We can wait since this is called from the user
4389                                * send side
4390                                */
4391                               n->m_nextpkt = m_split(n, siz, M_WAIT);
4392                               if (n->m_nextpkt == NULL) {
4393                                         error = EFAULT;
4394                                         goto release;
4395                               }
4396                               dataout -= siz;
4397                               n = n->m_nextpkt;
4398                     }
4399                     /*
4400                      * ok, now we have a chain on m where m->m_nextpkt points to
4401                      * the next chunk and m/m->m_next chain is the piece to send.
4402                      * We must go through the chains and thread them on to
4403                      * sctp_tmit_chunk chains and place them all on the stream
4404                      * queue, breaking the m->m_nextpkt pointers as we go.
4405                      */
4406                     n = m;
4407                     TAILQ_INIT(&tmp);
4408                     while (n) {
4409                               /*
4410                                * first go through and allocate a sctp_tmit chunk
4411                                * for each chunk piece
4412                                */
4413                               chk = (struct sctp_tmit_chunk *)SCTP_ZONE_GET(sctppcbinfo.ipi_zone_chunk);
4414                               if (chk == NULL) {
4415                                         /*
4416                                          * ok we must spin through and dump anything
4417                                          * we have allocated and then jump to the
4418                                          * no_membad
4419                                          */
4420                                         chk = TAILQ_FIRST(&tmp);
4421                                         while (chk) {
4422                                                   TAILQ_REMOVE(&tmp, chk, sctp_next);
4423                                                   SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_chunk, chk);
4424                                                   sctppcbinfo.ipi_count_chunk--;
4425                                                   asoc->chunks_on_out_queue--;
4426                                                   if ((int)sctppcbinfo.ipi_count_chunk < 0) {
4427                                                             panic("Chunk count is negative");
4428                                                   }
4429                                                   sctppcbinfo.ipi_gencnt_chunk++;
4430                                                   chk = TAILQ_FIRST(&tmp);
4431                                         }
4432                                         error = ENOMEM;
4433                                         goto release;
4434                               }
4435                               sctppcbinfo.ipi_count_chunk++;
4436                               asoc->chunks_on_out_queue++;
4437 
4438                               sctppcbinfo.ipi_gencnt_chunk++;
4439                               *chk = template;
4440                               chk->whoTo->ref_count++;
4441                               chk->data = n;
4442                               /* Total in the MSIZE */
4443                               mbcnt_e = 0;
4444                               for (mm = chk->data; mm; mm = mm->m_next) {
4445                                         mbcnt_e += MSIZE;
4446                                         if (mm->m_flags & M_EXT) {
4447                                                   mbcnt_e += chk->data->m_ext.ext_size;
4448                                         }
4449                               }
4450                               /* now fix the chk->send_size */
4451                               if (chk->data->m_flags & M_PKTHDR) {
4452                                         chk->send_size = chk->data->m_pkthdr.len;
4453                               } else {
4454                                         struct mbuf *nn;
4455                                         chk->send_size = 0;
4456                                         for (nn = chk->data; nn; nn = nn->m_next) {
4457                                                   chk->send_size += nn->m_len;
4458                                         }
4459                               }
4460                               chk->book_size = chk->send_size;
4461                               chk->mbcnt = mbcnt_e;
4462                               mbcnt += mbcnt_e;
4463                               if (chk->flags & SCTP_PR_SCTP_BUFFER) {
4464                                         asoc->sent_queue_cnt_removeable++;
4465                               }
4466                               n = n->m_nextpkt;
4467                               TAILQ_INSERT_TAIL(&tmp, chk, sctp_next);
4468                     }
4469                     m = NULL;
4470                     /* now that we have enough space for all de-couple the
4471                      * chain of mbufs by going through our temp array
4472                      * and breaking the pointers.
4473                      */
4474                     /* ok, we are committed */
4475                     if ((srcv->sinfo_flags & SCTP_UNORDERED) == 0) {
4476                               /* bump the ssn if we are unordered. */
4477                               strq->next_sequence_sent++;
4478                     }
4479                     /* Mark the first/last flags. This will
4480                      * result int a 3 for a single item on the list
4481                      */
4482                     chk = TAILQ_FIRST(&tmp);
4483                     chk->rec.data.rcv_flags |= SCTP_DATA_FIRST_FRAG;
4484                     chk = TAILQ_LAST(&tmp, sctpchunk_listhead);
4485                     chk->rec.data.rcv_flags |= SCTP_DATA_LAST_FRAG;
4486                     /* now break any chains on the queue and
4487                      * move it to the streams actual queue.
4488                      */
4489                     chk = TAILQ_FIRST(&tmp);
4490                     while (chk) {
4491                               chk->data->m_nextpkt = 0;
4492                               TAILQ_REMOVE(&tmp, chk, sctp_next);
4493                               asoc->stream_queue_cnt++;
4494                               TAILQ_INSERT_TAIL(&strq->outqueue, chk, sctp_next);
4495                               chk = TAILQ_FIRST(&tmp);
4496                     }
4497                     /* now check if this stream is on the wheel */
4498                     if ((strq->next_spoke.tqe_next == NULL) &&
4499                         (strq->next_spoke.tqe_prev == NULL)) {
4500                               /* Insert it on the wheel since it is not
4501                                * on it currently
4502                                */
4503                               sctp_insert_on_wheel(asoc, strq);
4504                     }
4505           }
4506           /* has a SHUTDOWN been (also) requested by the user on this asoc? */
4507 zap_by_it_all:
4508 
4509           if ((srcv->sinfo_flags & SCTP_EOF) &&
4510               (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_UDPTYPE)) {
4511 
4512                     int some_on_streamwheel = 0;
4513 
4514                     if (!TAILQ_EMPTY(&asoc->out_wheel)) {
4515                               /* Check to see if some data queued */
4516                               struct sctp_stream_out *outs;
4517                               TAILQ_FOREACH(outs, &asoc->out_wheel, next_spoke) {
4518                                         if (!TAILQ_EMPTY(&outs->outqueue)) {
4519                                                   some_on_streamwheel = 1;
4520                                                   break;
4521                                         }
4522                               }
4523                     }
4524 
4525                     if (TAILQ_EMPTY(&asoc->send_queue) &&
4526                         TAILQ_EMPTY(&asoc->sent_queue) &&
4527                         (some_on_streamwheel == 0)) {
4528                               /* there is nothing queued to send, so I'm done... */
4529                               if ((SCTP_GET_STATE(asoc) != SCTP_STATE_SHUTDOWN_SENT) &&
4530                                   (SCTP_GET_STATE(asoc) != SCTP_STATE_SHUTDOWN_ACK_SENT)) {
4531                                         /* only send SHUTDOWN the first time through */
4532 #ifdef SCTP_DEBUG
4533                                         if (sctp_debug_on & SCTP_DEBUG_OUTPUT4) {
4534                                                   printf("%s:%d sends a shutdown\n",
4535                                                          __FILE__,
4536                                                          __LINE__
4537                                                             );
4538                                         }
4539 #endif
4540                                         sctp_send_shutdown(stcb, stcb->asoc.primary_destination);
4541                                         asoc->state = SCTP_STATE_SHUTDOWN_SENT;
4542                                         sctp_timer_start(SCTP_TIMER_TYPE_SHUTDOWN, stcb->sctp_ep, stcb,
4543                                                              asoc->primary_destination);
4544                                         sctp_timer_start(SCTP_TIMER_TYPE_SHUTDOWNGUARD, stcb->sctp_ep, stcb,
4545                                                              asoc->primary_destination);
4546                               }
4547                     } else {
4548                               /*
4549                                * we still got (or just got) data to send, so set
4550                                * SHUTDOWN_PENDING
4551                                */
4552                               asoc->state |= SCTP_STATE_SHUTDOWN_PENDING;
4553                     }
4554           }
4555 #ifdef SCTP_MBCNT_LOGGING
4556           sctp_log_mbcnt(SCTP_LOG_MBCNT_INCREASE,
4557                            asoc->total_output_queue_size,
4558                            dataout,
4559                            asoc->total_output_mbuf_queue_size,
4560                            mbcnt);
4561 #endif
4562           asoc->total_output_queue_size += dataout;
4563           asoc->total_output_mbuf_queue_size += mbcnt;
4564           if ((stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE) ||
4565               (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL)) {
4566                     so->so_snd.sb_cc += dataout;
4567                     so->so_snd.sb_mbcnt += mbcnt;
4568           }
4569 
4570 #ifdef SCTP_DEBUG
4571           if (sctp_debug_on & SCTP_DEBUG_OUTPUT2) {
4572                     printf("++total out:%d total_mbuf_out:%d\n",
4573                            (int)asoc->total_output_queue_size,
4574                            (int)asoc->total_output_mbuf_queue_size);
4575           }
4576 #endif
4577 
4578 release:
4579           sbunlock(&so->so_snd);
4580 out_locked:
4581 
4582 out:
4583           if (m && m->m_nextpkt) {
4584                     n = m;
4585                     while (n) {
4586                               mnext = n->m_nextpkt;
4587                               n->m_nextpkt = NULL;
4588                               sctp_m_freem(n);
4589                               n = mnext;
4590                     }
4591           } else {
4592                     sctp_m_freem(m);
4593           }
4594 
4595           return (error);
4596 }
4597 
4598 static struct mbuf *
4599 sctp_copy_mbufchain(struct mbuf *clonechain,
4600                         struct mbuf *outchain)
4601 {
4602           struct mbuf *appendchain;
4603 #if defined(__FreeBSD__) || defined(__NetBSD__)
4604           /* Supposedly m_copypacket is an optimization, use it if we can */
4605           if (clonechain->m_flags & M_PKTHDR) {
4606                     appendchain = m_copypacket(clonechain, M_DONTWAIT);
4607                     sctp_pegs[SCTP_CACHED_SRC]++;
4608           } else
4609                     appendchain = m_copym(clonechain, 0, M_COPYALL, M_DONTWAIT);
4610 #elif defined(__APPLE__)
4611           appendchain = sctp_m_copym(clonechain, 0, M_COPYALL, M_DONTWAIT);
4612 #else
4613           appendchain = m_copy(clonechain, 0, M_COPYALL);
4614 #endif
4615 
4616           if (appendchain == NULL) {
4617                     /* error */
4618                     sctp_m_freem(outchain);
4619                     return (NULL);
4620           }
4621           if (outchain) {
4622                     /* tack on to the end */
4623                     struct mbuf *m;
4624                     m = outchain;
4625                     while (m) {
4626                               if (m->m_next == NULL) {
4627                                         m->m_next = appendchain;
4628                                         break;
4629                               }
4630                               m = m->m_next;
4631                     }
4632                     if (outchain->m_flags & M_PKTHDR) {
4633                               int append_tot;
4634                               struct mbuf *t;
4635                               t = appendchain;
4636                               append_tot = 0;
4637                               while (t) {
4638                                         append_tot += t->m_len;
4639                                         t = t->m_next;
4640                               }
4641                               outchain->m_pkthdr.len += append_tot;
4642                     }
4643                     return (outchain);
4644           } else {
4645                     return (appendchain);
4646           }
4647 }
4648 
4649 static void
4650 sctp_sendall_iterator(struct sctp_inpcb *inp, struct sctp_tcb *stcb, void *ptr, u_int32_t val)
4651 {
4652           struct sctp_copy_all *ca;
4653           struct mbuf *m;
4654           int turned_on_nonblock=0, ret;
4655 
4656           ca = (struct sctp_copy_all *)ptr;
4657           if (ca->m == NULL) {
4658                     return;
4659           }
4660           if (ca->inp != inp) {
4661                     /* TSNH */
4662                     return;
4663           }
4664           m = sctp_copy_mbufchain(ca->m, NULL);
4665           if (m == NULL) {
4666                     /* can't copy so we are done */
4667                     ca->cnt_failed++;
4668                     return;
4669           }
4670           if ((stcb->sctp_socket->so_state & SS_NBIO) == 0) {
4671                     /* we have to do this non-blocking */
4672                     turned_on_nonblock = 1;
4673                     stcb->sctp_socket->so_state |= SS_NBIO;
4674           }
4675           ret = sctp_msg_append(stcb, stcb->asoc.primary_destination, m, &ca->sndrcv, 0);
4676           if (turned_on_nonblock) {
4677                     /* we turned on non-blocking so turn it off */
4678                     stcb->sctp_socket->so_state &= ~SS_NBIO;
4679           }
4680           if (ret) {
4681                     ca->cnt_failed++;
4682           } else {
4683                     ca->cnt_sent++;
4684           }
4685 }
4686 
4687 static void
4688 sctp_sendall_completes(void *ptr, u_int32_t val)
4689 {
4690           struct sctp_copy_all *ca;
4691           ca = (struct sctp_copy_all *)ptr;
4692           /* Do a notify here?
4693            * Kacheong suggests that the notify
4694            * be done at the send time.. so you would
4695            * push up a notification if any send failed.
4696            * Don't know if this is feasible since the
4697            * only failures we have is "memory" related and
4698            * if you cannot get an mbuf to send the data
4699            * you surely can't get an mbuf to send up
4700            * to notify the user you can't send the data :->
4701            */
4702 
4703           /* now free everything */
4704           m_freem(ca->m);
4705           free(ca, M_PCB);
4706 }
4707 
4708 
4709 #define   MC_ALIGN(m, len) do {                                                           \
4710           (m)->m_data += (MCLBYTES - (len)) & ~(sizeof(long) - 1);              \
4711 } while (0)
4712 
4713 
4714 
4715 static struct mbuf *
4716 sctp_copy_out_all(struct uio *uio, int len)
4717 {
4718           struct mbuf *ret, *at;
4719           int left, willcpy, cancpy, error;
4720 
4721           MGETHDR(ret, M_WAIT, MT_HEADER);
4722           if (ret == NULL) {
4723                     /* TSNH */
4724                     return (NULL);
4725           }
4726           left = len;
4727           ret->m_len = 0;
4728           ret->m_pkthdr.len = len;
4729           MCLGET(ret, M_WAIT);
4730           if (ret == NULL) {
4731                     return (NULL);
4732           }
4733           if ((ret->m_flags & M_EXT) == 0) {
4734                     m_freem (ret);
4735                     return (NULL);
4736           }
4737           cancpy = M_TRAILINGSPACE(ret);
4738           willcpy = uimin(cancpy, left);
4739           at = ret;
4740           while (left > 0) {
4741                     /* Align data to the end */
4742                     MC_ALIGN(at, willcpy);
4743                     error = uiomove(mtod(at, void *), willcpy, uio);
4744                     if (error) {
4745                     err_out_now:
4746                               m_freem(ret);
4747                               return (NULL);
4748                     }
4749                     at->m_len = willcpy;
4750                     at->m_nextpkt = at->m_next = 0;
4751                     left -= willcpy;
4752                     if (left > 0) {
4753                               MGET(at->m_next, M_WAIT, MT_DATA);
4754                               if (at->m_next == NULL) {
4755                                         goto err_out_now;
4756                               }
4757                               at = at->m_next;
4758                               at->m_len = 0;
4759                               MCLGET(at, M_WAIT);
4760                               if (at == NULL) {
4761                                         goto err_out_now;
4762                               }
4763                               if ((at->m_flags & M_EXT) == 0) {
4764                                         goto err_out_now;
4765                               }
4766                               cancpy = M_TRAILINGSPACE(at);
4767                               willcpy = uimin(cancpy, left);
4768                     }
4769           }
4770           return (ret);
4771 }
4772 
4773 static int
4774 sctp_sendall (struct sctp_inpcb *inp, struct uio *uio, struct mbuf *m, struct sctp_sndrcvinfo *srcv)
4775 {
4776           int ret;
4777           struct sctp_copy_all *ca;
4778           ca = malloc(sizeof(struct sctp_copy_all), M_PCB, M_WAIT);
4779           if (ca == NULL) {
4780                     m_freem(m);
4781                     return (ENOMEM);
4782           }
4783           memset (ca, 0, sizeof(struct sctp_copy_all));
4784 
4785           ca->inp = inp;
4786           ca->sndrcv = *srcv;
4787           /* take off the sendall flag, it would
4788            * be bad if we failed to do this  :-0
4789            */
4790           ca->sndrcv.sinfo_flags &= ~SCTP_SENDALL;
4791 
4792           /* get length and mbuf chain */
4793           if (uio) {
4794                     ca->sndlen = uio->uio_resid;
4795                     ca->m = sctp_copy_out_all(uio, ca->sndlen);
4796                     if (ca->m == NULL) {
4797                               free(ca, M_PCB);
4798                               return (ENOMEM);
4799                     }
4800           } else {
4801                     if ((m->m_flags & M_PKTHDR) == 0) {
4802                               ca->sndlen = 0;
4803                               while(m) {
4804                                         ca->sndlen += m->m_len;
4805                                         m = m->m_next;
4806                               }
4807                     } else {
4808                               ca->sndlen = m->m_pkthdr.len;
4809                     }
4810                     ca->m = m;
4811           }
4812 
4813           ret = sctp_initiate_iterator(sctp_sendall_iterator, SCTP_PCB_ANY_FLAGS, SCTP_ASOC_ANY_STATE,
4814                                              (void *)ca, 0, sctp_sendall_completes, inp);
4815           if (ret) {
4816 #ifdef SCTP_DEBUG
4817                     printf("Failed to initiate iterator to takeover associations\n");
4818 #endif
4819                     free(ca, M_PCB);
4820                     return (EFAULT);
4821 
4822           }
4823           return (0);
4824 }
4825 
4826 
4827 void
4828 sctp_toss_old_cookies(struct sctp_association *asoc)
4829 {
4830           struct sctp_tmit_chunk *chk, *nchk;
4831           chk = TAILQ_FIRST(&asoc->control_send_queue);
4832           while (chk) {
4833                     nchk = TAILQ_NEXT(chk, sctp_next);
4834                     if (chk->rec.chunk_id == SCTP_COOKIE_ECHO) {
4835                               TAILQ_REMOVE(&asoc->control_send_queue, chk, sctp_next);
4836                               sctp_m_freem(chk->data);
4837                               chk->data = NULL;
4838                               asoc->ctrl_queue_cnt--;
4839                               if (chk->whoTo)
4840                                         sctp_free_remote_addr(chk->whoTo);
4841                               SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_chunk, chk);
4842                               sctppcbinfo.ipi_count_chunk--;
4843                               if ((int)sctppcbinfo.ipi_count_chunk < 0) {
4844                                         panic("Chunk count is negative");
4845                               }
4846                               sctppcbinfo.ipi_gencnt_chunk++;
4847                     }
4848                     chk = nchk;
4849           }
4850 }
4851 
4852 void
4853 sctp_toss_old_asconf(struct sctp_tcb *stcb)
4854 {
4855           struct sctp_association *asoc;
4856           struct sctp_tmit_chunk *chk, *chk_tmp;
4857 
4858           asoc = &stcb->asoc;
4859           for (chk = TAILQ_FIRST(&asoc->control_send_queue); chk != NULL;
4860                chk = chk_tmp) {
4861                     /* get next chk */
4862                     chk_tmp = TAILQ_NEXT(chk, sctp_next);
4863                     /* find SCTP_ASCONF chunk in queue (only one ever in queue) */
4864                     if (chk->rec.chunk_id == SCTP_ASCONF) {
4865                               TAILQ_REMOVE(&asoc->control_send_queue, chk, sctp_next);
4866                               sctp_m_freem(chk->data);
4867                               chk->data = NULL;
4868                               asoc->ctrl_queue_cnt--;
4869                               if (chk->whoTo)
4870                                         sctp_free_remote_addr(chk->whoTo);
4871                               SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_chunk, chk);
4872                               sctppcbinfo.ipi_count_chunk--;
4873                               if ((int)sctppcbinfo.ipi_count_chunk < 0) {
4874                                         panic("Chunk count is negative");
4875                               }
4876                               sctppcbinfo.ipi_gencnt_chunk++;
4877                     }
4878           }
4879 }
4880 
4881 
4882 static void
4883 sctp_clean_up_datalist(struct sctp_tcb *stcb,
4884                            struct sctp_association *asoc,
4885                            struct sctp_tmit_chunk **data_list,
4886                            int bundle_at,
4887                            struct sctp_nets *net)
4888 {
4889           int i;
4890           for (i = 0; i < bundle_at; i++) {
4891                     /* off of the send queue */
4892                     if (i) {
4893                               /* Any chunk NOT 0 you zap the time
4894                                * chunk 0 gets zapped or set based on
4895                                * if a RTO measurement is needed.
4896                                */
4897                               data_list[i]->do_rtt = 0;
4898                     }
4899                     /* record time */
4900                     data_list[i]->sent_rcv_time = net->last_sent_time;
4901                     TAILQ_REMOVE(&asoc->send_queue,
4902                                    data_list[i],
4903                                    sctp_next);
4904                     /* on to the sent queue */
4905                     TAILQ_INSERT_TAIL(&asoc->sent_queue,
4906                                           data_list[i],
4907                                           sctp_next);
4908                     /* This does not lower until the cum-ack passes it */
4909                     asoc->sent_queue_cnt++;
4910                     asoc->send_queue_cnt--;
4911                     if ((asoc->peers_rwnd <= 0) &&
4912                         (asoc->total_flight == 0) &&
4913                         (bundle_at == 1)) {
4914                               /* Mark the chunk as being a window probe */
4915 #ifdef SCTP_DEBUG
4916                               if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
4917                                         printf("WINDOW PROBE SET\n");
4918                               }
4919 #endif
4920                               sctp_pegs[SCTP_WINDOW_PROBES]++;
4921                               data_list[i]->rec.data.state_flags |= SCTP_WINDOW_PROBE;
4922                     } else {
4923                               data_list[i]->rec.data.state_flags &= ~SCTP_WINDOW_PROBE;
4924                     }
4925 #ifdef SCTP_AUDITING_ENABLED
4926                     sctp_audit_log(0xC2, 3);
4927 #endif
4928                     data_list[i]->sent = SCTP_DATAGRAM_SENT;
4929                     data_list[i]->snd_count = 1;
4930                     net->flight_size += data_list[i]->book_size;
4931                     asoc->total_flight += data_list[i]->book_size;
4932                     asoc->total_flight_count++;
4933 #ifdef SCTP_LOG_RWND
4934                     sctp_log_rwnd(SCTP_DECREASE_PEER_RWND,
4935                                     asoc->peers_rwnd , data_list[i]->send_size, sctp_peer_chunk_oh);
4936 #endif
4937                     asoc->peers_rwnd = sctp_sbspace_sub(asoc->peers_rwnd,
4938                                                                 (u_int32_t)(data_list[i]->send_size + sctp_peer_chunk_oh));
4939                     if (asoc->peers_rwnd < stcb->sctp_ep->sctp_ep.sctp_sws_sender) {
4940                               /* SWS sender side engages */
4941                               asoc->peers_rwnd = 0;
4942                     }
4943           }
4944 }
4945 
4946 static void
4947 sctp_clean_up_ctl(struct sctp_association *asoc)
4948 {
4949           struct sctp_tmit_chunk *chk, *nchk;
4950           for (chk = TAILQ_FIRST(&asoc->control_send_queue);
4951               chk; chk = nchk) {
4952                     nchk = TAILQ_NEXT(chk, sctp_next);
4953                     if ((chk->rec.chunk_id == SCTP_SELECTIVE_ACK) ||
4954                         (chk->rec.chunk_id == SCTP_HEARTBEAT_REQUEST) ||
4955                         (chk->rec.chunk_id == SCTP_HEARTBEAT_ACK) ||
4956                         (chk->rec.chunk_id == SCTP_SHUTDOWN) ||
4957                         (chk->rec.chunk_id == SCTP_SHUTDOWN_ACK) ||
4958                         (chk->rec.chunk_id == SCTP_OPERATION_ERROR) ||
4959                         (chk->rec.chunk_id == SCTP_PACKET_DROPPED) ||
4960                         (chk->rec.chunk_id == SCTP_COOKIE_ACK) ||
4961                         (chk->rec.chunk_id == SCTP_ECN_CWR) ||
4962                         (chk->rec.chunk_id == SCTP_ASCONF_ACK)) {
4963                               /* Stray chunks must be cleaned up */
4964                     clean_up_anyway:
4965                               TAILQ_REMOVE(&asoc->control_send_queue, chk, sctp_next);
4966                               sctp_m_freem(chk->data);
4967                               chk->data = NULL;
4968                               asoc->ctrl_queue_cnt--;
4969                               sctp_free_remote_addr(chk->whoTo);
4970                               SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_chunk, chk);
4971                               sctppcbinfo.ipi_count_chunk--;
4972                               if ((int)sctppcbinfo.ipi_count_chunk < 0) {
4973                                         panic("Chunk count is negative");
4974                               }
4975                               sctppcbinfo.ipi_gencnt_chunk++;
4976                     } else if (chk->rec.chunk_id == SCTP_STREAM_RESET) {
4977                               struct sctp_stream_reset_req *strreq;
4978                               /* special handling, we must look into the param */
4979                               strreq = mtod(chk->data, struct sctp_stream_reset_req *);
4980                               if (strreq->sr_req.ph.param_type == ntohs(SCTP_STR_RESET_RESPONSE)) {
4981                                         goto clean_up_anyway;
4982                               }
4983                     }
4984           }
4985 }
4986 
4987 static int
4988 sctp_move_to_outqueue(struct sctp_tcb *stcb,
4989                           struct sctp_stream_out *strq)
4990 {
4991           /* Move from the stream to the send_queue keeping track of the total */
4992           struct sctp_association *asoc;
4993           int tot_moved = 0;
4994           int failed = 0;
4995           int padval;
4996           struct sctp_tmit_chunk *chk, *nchk;
4997           struct sctp_data_chunk *dchkh;
4998           struct sctpchunk_listhead tmp;
4999           struct mbuf *orig;
5000 
5001           asoc = &stcb->asoc;
5002           TAILQ_INIT(&tmp);
5003           chk = TAILQ_FIRST(&strq->outqueue);
5004           while (chk) {
5005                     nchk = TAILQ_NEXT(chk, sctp_next);
5006                     /* now put in the chunk header */
5007                     orig = chk->data;
5008                     M_PREPEND(chk->data, sizeof(struct sctp_data_chunk), M_DONTWAIT);
5009                     if (chk->data == NULL) {
5010                               /* HELP */
5011                               failed++;
5012                               break;
5013                     }
5014                     if (orig != chk->data) {
5015                               /* A new mbuf was added, account for it */
5016                               if ((stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE) ||
5017                                   (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL)) {
5018                                         stcb->sctp_socket->so_snd.sb_mbcnt += MSIZE;
5019                               }
5020 #ifdef SCTP_MBCNT_LOGGING
5021                               sctp_log_mbcnt(SCTP_LOG_MBCNT_INCREASE,
5022                                                asoc->total_output_queue_size,
5023                                                0,
5024                                                asoc->total_output_mbuf_queue_size,
5025                                                MSIZE);
5026 #endif
5027                               stcb->asoc.total_output_mbuf_queue_size += MSIZE;
5028                               chk->mbcnt += MSIZE;
5029                     }
5030                     chk->send_size += sizeof(struct sctp_data_chunk);
5031                     /* This should NOT have to do anything, but
5032                      * I would rather be cautious
5033                      */
5034                     if (!failed && ((size_t)chk->data->m_len < sizeof(struct sctp_data_chunk))) {
5035                               m_pullup(chk->data, sizeof(struct sctp_data_chunk));
5036                               if (chk->data == NULL) {
5037                                         failed++;
5038                                         break;
5039                               }
5040                     }
5041                     dchkh = mtod(chk->data, struct sctp_data_chunk *);
5042                     dchkh->ch.chunk_length = htons(chk->send_size);
5043                     /* Chunks must be padded to even word boundary */
5044                     padval = chk->send_size % 4;
5045                     if (padval) {
5046                               /* For fragmented messages this should not
5047                                * run except possibly on the last chunk
5048                                */
5049                               if (sctp_pad_lastmbuf(chk->data, (4 - padval))) {
5050                                         /* we are in big big trouble no mbufs :< */
5051                                         failed++;
5052                                         break;
5053                               }
5054                               chk->send_size += (4 - padval);
5055                     }
5056                     /* pull from stream queue */
5057                     TAILQ_REMOVE(&strq->outqueue, chk, sctp_next);
5058                     asoc->stream_queue_cnt--;
5059                     TAILQ_INSERT_TAIL(&tmp, chk, sctp_next);
5060                     /* add it in to the size of moved chunks */
5061                     if (chk->rec.data.rcv_flags & SCTP_DATA_LAST_FRAG) {
5062                               /* we pull only one message */
5063                               break;
5064                     }
5065                     chk = nchk;
5066           }
5067           if (failed) {
5068                     /* Gak, we just lost the user message */
5069                     chk = TAILQ_FIRST(&tmp);
5070                     while (chk) {
5071                               nchk = TAILQ_NEXT(chk, sctp_next);
5072                               TAILQ_REMOVE(&tmp, chk, sctp_next);
5073 
5074                               sctp_ulp_notify(SCTP_NOTIFY_DG_FAIL, stcb,
5075                                                   (SCTP_NOTIFY_DATAGRAM_UNSENT|SCTP_INTERNAL_ERROR),
5076                                                   chk);
5077 
5078                               sctp_m_freem(chk->data);
5079                               chk->data = NULL;
5080                               if (chk->whoTo) {
5081                                         sctp_free_remote_addr(chk->whoTo);
5082                                         chk->whoTo = NULL;
5083                               }
5084                               SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_chunk, chk);
5085                               sctppcbinfo.ipi_count_chunk--;
5086                               if ((int)sctppcbinfo.ipi_count_chunk < 0) {
5087                                         panic("Chunk count is negative");
5088                               }
5089                               sctppcbinfo.ipi_gencnt_chunk++;
5090                               chk = nchk;
5091                     }
5092                     return (0);
5093           }
5094           /* now pull them off of temp wheel */
5095           chk = TAILQ_FIRST(&tmp);
5096           while (chk) {
5097                     nchk = TAILQ_NEXT(chk, sctp_next);
5098                     /* insert on send_queue */
5099                     TAILQ_REMOVE(&tmp, chk, sctp_next);
5100                     TAILQ_INSERT_TAIL(&asoc->send_queue, chk, sctp_next);
5101                     asoc->send_queue_cnt++;
5102                     /* assign TSN */
5103                     chk->rec.data.TSN_seq = asoc->sending_seq++;
5104 
5105                     dchkh = mtod(chk->data, struct sctp_data_chunk *);
5106                     /* Put the rest of the things in place now. Size
5107                      * was done earlier in previous loop prior to
5108                      * padding.
5109                      */
5110                     dchkh->ch.chunk_type = SCTP_DATA;
5111                     dchkh->ch.chunk_flags = chk->rec.data.rcv_flags;
5112                     dchkh->dp.tsn = htonl(chk->rec.data.TSN_seq);
5113                     dchkh->dp.stream_id = htons(strq->stream_no);
5114                     dchkh->dp.stream_sequence = htons(chk->rec.data.stream_seq);
5115                     dchkh->dp.protocol_id = chk->rec.data.payloadtype;
5116                     /* total count moved */
5117                     tot_moved += chk->send_size;
5118                     chk = nchk;
5119           }
5120           return (tot_moved);
5121 }
5122 
5123 static void
5124 sctp_fill_outqueue(struct sctp_tcb *stcb,
5125                        struct sctp_nets *net)
5126 {
5127           struct sctp_association *asoc;
5128           struct sctp_tmit_chunk *chk;
5129           struct sctp_stream_out *strq, *strqn;
5130           int mtu_fromwheel, goal_mtu;
5131           unsigned int moved, seenend, cnt_mvd=0;
5132 
5133           asoc = &stcb->asoc;
5134           /* Attempt to move at least 1 MTU's worth
5135            * onto the wheel for each destination address
5136            */
5137           goal_mtu = net->cwnd - net->flight_size;
5138           if ((unsigned int)goal_mtu < net->mtu) {
5139                     goal_mtu = net->mtu;
5140           }
5141           if (sctp_pegs[SCTP_MOVED_MTU] < (unsigned int)goal_mtu) {
5142                     sctp_pegs[SCTP_MOVED_MTU] = goal_mtu;
5143           }
5144           seenend = moved = mtu_fromwheel = 0;
5145           if (asoc->last_out_stream == NULL) {
5146                     strq = asoc->last_out_stream = TAILQ_FIRST(&asoc->out_wheel);
5147                     if (asoc->last_out_stream == NULL) {
5148                               /* huh nothing on the wheel, TSNH */
5149                               return;
5150                     }
5151                     goto done_it;
5152           }
5153           strq = TAILQ_NEXT(asoc->last_out_stream, next_spoke);
5154  done_it:
5155           if (strq == NULL) {
5156                     asoc->last_out_stream = TAILQ_FIRST(&asoc->out_wheel);
5157           }
5158           while (mtu_fromwheel < goal_mtu) {
5159                     if (strq == NULL) {
5160                               if (seenend == 0) {
5161                                         seenend = 1;
5162                                         strq = TAILQ_FIRST(&asoc->out_wheel);
5163                               } else if ((moved == 0) && (seenend)) {
5164                                         /* none left on the wheel */
5165                                         sctp_pegs[SCTP_MOVED_NLEF]++;
5166                                         return;
5167                               } else if (moved) {
5168                                         /*
5169                                          * clear the flags and rotate back through
5170                                          * again
5171                                          */
5172                                         moved = 0;
5173                                         seenend = 0;
5174                                         strq = TAILQ_FIRST(&asoc->out_wheel);
5175                               }
5176                               if (strq == NULL)
5177                                         break;
5178                               continue;
5179                     }
5180                     strqn = TAILQ_NEXT(strq, next_spoke);
5181                     if ((chk = TAILQ_FIRST(&strq->outqueue)) == NULL) {
5182                               /* none left on this queue, prune a spoke?  */
5183                               sctp_remove_from_wheel(asoc, strq);
5184                               if (strq == asoc->last_out_stream) {
5185                                   /* the last one we used went off the wheel */
5186                                   asoc->last_out_stream = NULL;
5187                               }
5188                               strq = strqn;
5189                               continue;
5190                     }
5191                     if (chk->whoTo != net) {
5192                               /* Skip this stream, first one on stream
5193                                * does not head to our current destination.
5194                                */
5195                               strq = strqn;
5196                               continue;
5197                     }
5198                     mtu_fromwheel += sctp_move_to_outqueue(stcb, strq);
5199                     cnt_mvd++;
5200                     moved++;
5201                     asoc->last_out_stream = strq;
5202                     strq = strqn;
5203           }
5204           sctp_pegs[SCTP_MOVED_MAX]++;
5205 #ifdef SCTP_DEBUG
5206           if (sctp_debug_on & SCTP_DEBUG_OUTPUT3) {
5207                     printf("Ok we moved %d chunks to send queue\n",
5208                            moved);
5209           }
5210 #endif
5211           if (sctp_pegs[SCTP_MOVED_QMAX] < cnt_mvd) {
5212                     sctp_pegs[SCTP_MOVED_QMAX] = cnt_mvd;
5213           }
5214 }
5215 
5216 void
5217 sctp_fix_ecn_echo(struct sctp_association *asoc)
5218 {
5219           struct sctp_tmit_chunk *chk;
5220           TAILQ_FOREACH(chk, &asoc->control_send_queue, sctp_next) {
5221                     if (chk->rec.chunk_id == SCTP_ECN_ECHO) {
5222                               chk->sent = SCTP_DATAGRAM_UNSENT;
5223                     }
5224           }
5225 }
5226 
5227 static void
5228 sctp_move_to_an_alt(struct sctp_tcb *stcb,
5229                         struct sctp_association *asoc,
5230                         struct sctp_nets *net)
5231 {
5232           struct sctp_tmit_chunk *chk;
5233           struct sctp_nets *a_net;
5234           a_net = sctp_find_alternate_net(stcb, net);
5235           if ((a_net != net) &&
5236               ((a_net->dest_state & SCTP_ADDR_REACHABLE) == SCTP_ADDR_REACHABLE)) {
5237                     /*
5238                      * We only proceed if a valid alternate is found that is
5239                      * not this one and is reachable. Here we must move all
5240                      * chunks queued in the send queue off of the destination
5241                      * address to our alternate.
5242                      */
5243                     TAILQ_FOREACH(chk, &asoc->send_queue, sctp_next) {
5244                               if (chk->whoTo == net) {
5245                                         /* Move the chunk to our alternate */
5246                                         sctp_free_remote_addr(chk->whoTo);
5247                                         chk->whoTo = a_net;
5248                                         a_net->ref_count++;
5249                               }
5250                     }
5251           }
5252 }
5253 
5254 static int sctp_from_user_send=0;
5255 
5256 static int
5257 sctp_med_chunk_output(struct sctp_inpcb *inp,
5258                           struct sctp_tcb *stcb,
5259                           struct sctp_association *asoc,
5260                           int *num_out,
5261                           int *reason_code,
5262                           int control_only, int *cwnd_full, int from_where,
5263                           struct timeval *now, int *now_filled)
5264 {
5265           /*
5266            * Ok this is the generic chunk service queue.
5267            * we must do the following:
5268            *  - Service the stream queue that is next, moving any message
5269            *    (note I must get a complete message i.e. FIRST/MIDDLE and
5270            *    LAST to the out queue in one pass) and assigning TSN's
5271            *  - Check to see if the cwnd/rwnd allows any output, if so we
5272            *    go ahead and fomulate and send the low level chunks. Making
5273            *    sure to combine any control in the control chunk queue also.
5274            */
5275           struct sctp_nets *net;
5276           struct mbuf *outchain;
5277           struct sctp_tmit_chunk *chk, *nchk;
5278           struct sctphdr *shdr;
5279           /* temp arrays for unlinking */
5280           struct sctp_tmit_chunk *data_list[SCTP_MAX_DATA_BUNDLING];
5281           int no_fragmentflg, error;
5282           int one_chunk, hbflag;
5283           int asconf, cookie, no_out_cnt;
5284           int bundle_at, ctl_cnt, no_data_chunks, cwnd_full_ind;
5285         unsigned int mtu, r_mtu, omtu;
5286           *num_out = 0;
5287           cwnd_full_ind = 0;
5288           ctl_cnt = no_out_cnt = asconf = cookie = 0;
5289           /*
5290            * First lets prime the pump. For each destination, if there
5291            * is room in the flight size, attempt to pull an MTU's worth
5292            * out of the stream queues into the general send_queue
5293            */
5294 #ifdef SCTP_AUDITING_ENABLED
5295           sctp_audit_log(0xC2, 2);
5296 #endif
5297 #ifdef SCTP_DEBUG
5298           if (sctp_debug_on & SCTP_DEBUG_OUTPUT3) {
5299                     printf("***********************\n");
5300           }
5301 #endif
5302           hbflag = 0;
5303           if (control_only)
5304                     no_data_chunks = 1;
5305           else
5306                     no_data_chunks = 0;
5307 
5308           /* Nothing to possible to send? */
5309           if (TAILQ_EMPTY(&asoc->control_send_queue) &&
5310               TAILQ_EMPTY(&asoc->send_queue) &&
5311               TAILQ_EMPTY(&asoc->out_wheel)) {
5312 #ifdef SCTP_DEBUG
5313                     if (sctp_debug_on & SCTP_DEBUG_OUTPUT3) {
5314                               printf("All wheels empty\n");
5315                     }
5316 #endif
5317                     return (0);
5318           }
5319           if (asoc->peers_rwnd <= 0) {
5320                     /* No room in peers rwnd */
5321                     *cwnd_full = 1;
5322                     *reason_code = 1;
5323                     if (asoc->total_flight > 0) {
5324                               /* we are allowed one chunk in flight */
5325                               no_data_chunks = 1;
5326                               sctp_pegs[SCTP_RWND_BLOCKED]++;
5327                     }
5328           }
5329 #ifdef SCTP_DEBUG
5330           if (sctp_debug_on & SCTP_DEBUG_OUTPUT3) {
5331                     printf("Ok we have done the fillup no_data_chunk=%d tf=%d prw:%d\n",
5332                            (int)no_data_chunks,
5333                            (int)asoc->total_flight, (int)asoc->peers_rwnd);
5334           }
5335 #endif
5336           TAILQ_FOREACH(net, &asoc->nets, sctp_next) {
5337 #ifdef SCTP_DEBUG
5338                     if (sctp_debug_on & SCTP_DEBUG_OUTPUT3) {
5339                               printf("net:%p fs:%d  cwnd:%d\n",
5340                                      net, net->flight_size, net->cwnd);
5341                     }
5342 #endif
5343                     if (net->flight_size >= net->cwnd) {
5344                               /* skip this network, no room */
5345                               cwnd_full_ind++;
5346 #ifdef SCTP_DEBUG
5347                               if (sctp_debug_on & SCTP_DEBUG_OUTPUT3) {
5348                                         printf("Ok skip fillup->fs:%d > cwnd:%d\n",
5349                                                net->flight_size,
5350                                                net->cwnd);
5351                               }
5352 #endif
5353                               sctp_pegs[SCTP_CWND_NOFILL]++;
5354                               continue;
5355                     }
5356                     /*
5357                      * spin through the stream queues moving one message and
5358                      * assign TSN's as appropriate.
5359                      */
5360                     sctp_fill_outqueue(stcb, net);
5361           }
5362           *cwnd_full = cwnd_full_ind;
5363           /* now service each destination and send out what we can for it */
5364 #ifdef SCTP_DEBUG
5365           if (sctp_debug_on & SCTP_DEBUG_OUTPUT3) {
5366                     int chk_cnt = 0;
5367                     TAILQ_FOREACH(chk, &asoc->send_queue, sctp_next) {
5368                               chk_cnt++;
5369                     }
5370                     printf("We have %d chunks on the send_queue\n", chk_cnt);
5371                     chk_cnt = 0;
5372                     TAILQ_FOREACH(chk, &asoc->sent_queue, sctp_next) {
5373                               chk_cnt++;
5374                     }
5375                     printf("We have %d chunks on the sent_queue\n", chk_cnt);
5376                     TAILQ_FOREACH(chk, &asoc->control_send_queue, sctp_next) {
5377                               chk_cnt++;
5378                     }
5379                     printf("We have %d chunks on the control_queue\n", chk_cnt);
5380           }
5381 #endif
5382           /* If we have data to send, and DSACK is running, stop it
5383            * and build a SACK to dump on to bundle with output. This
5384            * actually MAY make it so the bundling does not occur if
5385            * the SACK is big but I think this is ok because basic SACK
5386            * space is pre-reserved in our fragmentation size choice.
5387            */
5388           if ((TAILQ_FIRST(&asoc->send_queue) != NULL) &&
5389               (no_data_chunks == 0)) {
5390                     /* We will be sending something */
5391                     if (callout_pending(&stcb->asoc.dack_timer.timer)) {
5392                               /* Yep a callout is pending */
5393                               sctp_timer_stop(SCTP_TIMER_TYPE_RECV,
5394                                                   stcb->sctp_ep,
5395                                                   stcb, NULL);
5396                               sctp_send_sack(stcb);
5397                     }
5398           }
5399           /* Nothing to send? */
5400           if ((TAILQ_FIRST(&asoc->control_send_queue) == NULL) &&
5401               (TAILQ_FIRST(&asoc->send_queue) == NULL)) {
5402                     return (0);
5403           }
5404           TAILQ_FOREACH(net, &asoc->nets, sctp_next) {
5405                     struct rtentry *rt;
5406                     /* how much can we send? */
5407                     if (net->ref_count < 2) {
5408                               /* Ref-count of 1 so we cannot have data or control
5409                                * queued to this address. Skip it.
5410                                */
5411                               continue;
5412                     }
5413                     ctl_cnt = bundle_at = 0;
5414                     outchain = NULL;
5415                     no_fragmentflg = 1;
5416                     one_chunk = 0;
5417 
5418                     rt = rtcache_validate(&net->ro);
5419                     if (rt != NULL) {
5420                               /* if we have a route and an ifp
5421                                * check to see if we have room to
5422                                * send to this guy
5423                                */
5424                               struct ifnet *ifp;
5425                               ifp = net->ro._ro_rt->rt_ifp;
5426                               if ((ifp->if_snd.ifq_len + 2) >= ifp->if_snd.ifq_maxlen) {
5427                                         sctp_pegs[SCTP_IFP_QUEUE_FULL]++;
5428 #ifdef SCTP_LOG_MAXBURST
5429                                         sctp_log_maxburst(net, ifp->if_snd.ifq_len, ifp->if_snd.ifq_maxlen, SCTP_MAX_IFP_APPLIED);
5430   #endif
5431                                         rtcache_unref(rt, &net->ro);
5432                                         continue;
5433                               }
5434                               rtcache_unref(rt, &net->ro);
5435                     }
5436                     if (((struct sockaddr *)&net->ro.ro_sa)->sa_family == AF_INET) {
5437                               mtu = net->mtu - (sizeof(struct ip) + sizeof(struct sctphdr));
5438                     } else {
5439                               mtu = net->mtu - (sizeof(struct ip6_hdr) + sizeof(struct sctphdr));
5440                     }
5441                     if (mtu > asoc->peers_rwnd) {
5442                               if (asoc->total_flight > 0) {
5443                                         /* We have a packet in flight somewhere */
5444                                         r_mtu = asoc->peers_rwnd;
5445                               } else {
5446                                         /* We are always allowed to send one MTU out */
5447                                         one_chunk = 1;
5448                                         r_mtu = mtu;
5449                               }
5450                     } else {
5451                               r_mtu = mtu;
5452                     }
5453 #ifdef SCTP_DEBUG
5454                     if (sctp_debug_on & SCTP_DEBUG_OUTPUT3) {
5455                               printf("Ok r_mtu is %d mtu is %d for this net:%p one_chunk:%d\n",
5456                                      r_mtu, mtu, net, one_chunk);
5457                     }
5458 #endif
5459                     /************************/
5460                     /* Control transmission */
5461                     /************************/
5462                     /* Now first lets go through the control queue */
5463                     for (chk = TAILQ_FIRST(&asoc->control_send_queue);
5464                          chk; chk = nchk) {
5465                               nchk = TAILQ_NEXT(chk, sctp_next);
5466                               if (chk->whoTo != net) {
5467                                         /*
5468                                          * No, not sent to the network we are
5469                                          * looking at
5470                                          */
5471                                         continue;
5472                               }
5473                               if (chk->data == NULL) {
5474                                         continue;
5475                               }
5476                               if ((chk->data->m_flags & M_PKTHDR) == 0) {
5477                                         /*
5478                                          * NOTE: the chk queue MUST have the PKTHDR
5479                                          * flag set on it with a total in the
5480                                          * m_pkthdr.len field!! else the chunk will
5481                                          * ALWAYS be skipped
5482                                          */
5483                                         continue;
5484                               }
5485                               if (chk->sent != SCTP_DATAGRAM_UNSENT) {
5486                                         /*
5487                                          * It must be unsent. Cookies and ASCONF's
5488                                          * hang around but there timers will force
5489                                          * when marked for resend.
5490                                          */
5491                                         continue;
5492                               }
5493                               /* Here we do NOT factor the r_mtu */
5494                               if ((chk->data->m_pkthdr.len < (int)mtu) ||
5495                                   (chk->flags & CHUNK_FLAGS_FRAGMENT_OK)) {
5496                                         /*
5497                                          * We probably should glom the mbuf chain from
5498                                          * the chk->data for control but the problem
5499                                          * is it becomes yet one more level of
5500                                          * tracking to do if for some reason output
5501                                          * fails. Then I have got to reconstruct the
5502                                          * merged control chain.. el yucko.. for now
5503                                          * we take the easy way and do the copy
5504                                          */
5505                                         outchain = sctp_copy_mbufchain(chk->data,
5506                                                                              outchain);
5507                                         if (outchain == NULL) {
5508                                                   return (ENOMEM);
5509                                         }
5510                                         /* update our MTU size */
5511                                         if (mtu > chk->data->m_pkthdr.len)
5512                                                   mtu -= chk->data->m_pkthdr.len;
5513                                         else
5514                                                   mtu = 0;
5515                                         /* Do clear IP_DF ? */
5516                                         if (chk->flags & CHUNK_FLAGS_FRAGMENT_OK) {
5517                                                   no_fragmentflg = 0;
5518                                         }
5519                                         /* Mark things to be removed, if needed */
5520                                         if ((chk->rec.chunk_id == SCTP_SELECTIVE_ACK) ||
5521                                             (chk->rec.chunk_id == SCTP_HEARTBEAT_REQUEST) ||
5522                                             (chk->rec.chunk_id == SCTP_HEARTBEAT_ACK) ||
5523                                             (chk->rec.chunk_id == SCTP_SHUTDOWN) ||
5524                                             (chk->rec.chunk_id == SCTP_SHUTDOWN_ACK) ||
5525                                             (chk->rec.chunk_id == SCTP_OPERATION_ERROR) ||
5526                                             (chk->rec.chunk_id == SCTP_COOKIE_ACK) ||
5527                                             (chk->rec.chunk_id == SCTP_ECN_CWR) ||
5528                                             (chk->rec.chunk_id == SCTP_PACKET_DROPPED) ||
5529                                             (chk->rec.chunk_id == SCTP_ASCONF_ACK)) {
5530 
5531                                                   if (chk->rec.chunk_id == SCTP_HEARTBEAT_REQUEST)
5532                                                             hbflag = 1;
5533                                                   /* remove these chunks at the end */
5534                                                   if (chk->rec.chunk_id == SCTP_SELECTIVE_ACK) {
5535                                                             /* turn off the timer */
5536                                                             if (callout_pending(&stcb->asoc.dack_timer.timer)) {
5537                                                                       sctp_timer_stop(SCTP_TIMER_TYPE_RECV,
5538                                                                                           inp, stcb, net);
5539                                                             }
5540                                                   }
5541                                                   ctl_cnt++;
5542                                         } else {
5543                                                   /*
5544                                                    * Other chunks, since they have
5545                                                    * timers running (i.e. COOKIE or
5546                                                    * ASCONF) we just "trust" that it
5547                                                    * gets sent or retransmitted.
5548                                                    */
5549                                                   ctl_cnt++;
5550                                                   if (chk->rec.chunk_id == SCTP_COOKIE_ECHO) {
5551                                                             cookie = 1;
5552                                                             no_out_cnt = 1;
5553                                                   } else if (chk->rec.chunk_id == SCTP_ASCONF) {
5554                                                             /*
5555                                                              * set hb flag since we can use
5556                                                              * these for RTO
5557                                                              */
5558                                                             hbflag = 1;
5559                                                             asconf = 1;
5560                                                   }
5561                                                   chk->sent = SCTP_DATAGRAM_SENT;
5562                                                   chk->snd_count++;
5563                                         }
5564                                         if (mtu == 0) {
5565                                                   /*
5566                                                    * Ok we are out of room but we can
5567                                                    * output without effecting the flight
5568                                                    * size since this little guy is a
5569                                                    * control only packet.
5570                                                    */
5571                                                   if (asconf) {
5572                                                             sctp_timer_start(SCTP_TIMER_TYPE_ASCONF, inp, stcb, net);
5573                                                             asconf = 0;
5574                                                   }
5575                                                   if (cookie) {
5576                                                             sctp_timer_start(SCTP_TIMER_TYPE_COOKIE, inp, stcb, net);
5577                                                             cookie = 0;
5578                                                   }
5579                                                   if (outchain->m_len == 0) {
5580                                                             /*
5581                                                              * Special case for when you
5582                                                              * get a 0 len mbuf at the
5583                                                              * head due to the lack of a
5584                                                              * MHDR at the beginning.
5585                                                              */
5586                                                             outchain->m_len = sizeof(struct sctphdr);
5587                                                   } else {
5588                                                             M_PREPEND(outchain, sizeof(struct sctphdr), M_DONTWAIT);
5589                                                             if (outchain == NULL) {
5590                                                                       /* no memory */
5591                                                                       error = ENOBUFS;
5592                                                                       goto error_out_again;
5593                                                             }
5594                                                   }
5595                                                   shdr = mtod(outchain, struct sctphdr *);
5596                                                   shdr->src_port = inp->sctp_lport;
5597                                                   shdr->dest_port = stcb->rport;
5598                                                   shdr->v_tag = htonl(stcb->asoc.peer_vtag);
5599                                                   shdr->checksum = 0;
5600 
5601                                                   if ((error = sctp_lowlevel_chunk_output(inp, stcb, net,
5602                                                                                                     rtcache_getdst(&net->ro),
5603                                                                                                     outchain,
5604                                                                                                     no_fragmentflg, 0, NULL, asconf))) {
5605                                                             if (error == ENOBUFS) {
5606                                                                       asoc->ifp_had_enobuf = 1;
5607                                                             }
5608                                                             sctp_pegs[SCTP_DATA_OUT_ERR]++;
5609                                                             if (from_where == 0) {
5610                                                                       sctp_pegs[SCTP_ERROUT_FRM_USR]++;
5611                                                             }
5612                                                   error_out_again:
5613 #ifdef SCTP_DEBUG
5614                                                             if (sctp_debug_on & SCTP_DEBUG_OUTPUT2) {
5615                                                                       printf("Gak got ctrl error %d\n", error);
5616                                                             }
5617 #endif
5618                                                             /* error, could not output */
5619                                                             if (hbflag) {
5620 #ifdef SCTP_DEBUG
5621                                                                       if (sctp_debug_on & SCTP_DEBUG_OUTPUT3) {
5622                                                                                 printf("Update HB anyway\n");
5623                                                                       }
5624 #endif
5625                                                                       if (*now_filled == 0) {
5626                                                                                 SCTP_GETTIME_TIMEVAL(&net->last_sent_time);
5627                                                                                 *now_filled = 1;
5628                                                                                 *now = net->last_sent_time;
5629                                                                       } else {
5630                                                                                 net->last_sent_time = *now;
5631                                                                       }
5632                                                                       hbflag = 0;
5633                                                             }
5634                                                             if (error == EHOSTUNREACH ||
5635                                                                 error == EHOSTDOWN) {
5636                                                                       /*
5637                                                                        * Destination went
5638                                                                        * unreachable during
5639                                                                        * this send
5640                                                                        */
5641 #ifdef SCTP_DEBUG
5642                                                                       if (sctp_debug_on & SCTP_DEBUG_OUTPUT3) {
5643                                                                                 printf("Moving data to an alterante\n");
5644                                                                       }
5645 #endif
5646                                                                       sctp_move_to_an_alt(stcb, asoc, net);
5647                                                             }
5648                                                             sctp_clean_up_ctl (asoc);
5649                                                             return (error);
5650                                                   } else
5651                                                             asoc->ifp_had_enobuf = 0;
5652                                                   /* Only HB or ASCONF advances time */
5653                                                   if (hbflag) {
5654                                                             if (*now_filled == 0) {
5655                                                                       SCTP_GETTIME_TIMEVAL(&net->last_sent_time);
5656                                                                       *now_filled = 1;
5657                                                                       *now = net->last_sent_time;
5658                                                             } else {
5659                                                                       net->last_sent_time = *now;
5660                                                             }
5661                                                             hbflag = 0;
5662                                                   }
5663                                                   /*
5664                                                    * increase the number we sent, if a
5665                                                    * cookie is sent we don't tell them
5666                                                    * any was sent out.
5667                                                    */
5668                                                   if (!no_out_cnt)
5669                                                             *num_out +=  ctl_cnt;
5670                                                   /* recalc a clean slate and setup */
5671                                                   if (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) {
5672                                                             mtu = (net->mtu - SCTP_MIN_OVERHEAD);
5673                                                   } else {
5674                                                             mtu = (net->mtu - SCTP_MIN_V4_OVERHEAD);
5675                                                   }
5676                                                   no_fragmentflg = 1;
5677                                         }
5678                               }
5679                     }
5680                     /*********************/
5681                     /* Data transmission */
5682                     /*********************/
5683                     /* now lets add any data within the MTU constraints */
5684                     if (((struct sockaddr *)&net->ro.ro_sa)->sa_family == AF_INET) {
5685                               omtu = net->mtu - (sizeof(struct ip) + sizeof(struct sctphdr));
5686                     } else {
5687                               omtu = net->mtu - (sizeof(struct ip6_hdr) + sizeof(struct sctphdr));
5688                     }
5689 
5690 #ifdef SCTP_DEBUG
5691                     if (sctp_debug_on & SCTP_DEBUG_OUTPUT3) {
5692                               printf("Now to data transmission\n");
5693                     }
5694 #endif
5695 
5696                     if (((asoc->state & SCTP_STATE_OPEN) == SCTP_STATE_OPEN) ||
5697                         (cookie)) {
5698                               for (chk = TAILQ_FIRST(&asoc->send_queue); chk; chk = nchk) {
5699                                         if (no_data_chunks) {
5700                                                   /* let only control go out */
5701 #ifdef SCTP_DEBUG
5702                                                   if (sctp_debug_on & SCTP_DEBUG_OUTPUT3) {
5703                                                             printf("Either nothing to send or we are full\n");
5704                                                   }
5705 #endif
5706                                                   break;
5707                                         }
5708                                         if (net->flight_size >= net->cwnd) {
5709                                                   /* skip this net, no room for data */
5710 #ifdef SCTP_DEBUG
5711                                                   if (sctp_debug_on & SCTP_DEBUG_OUTPUT3) {
5712                                                             printf("fs:%d > cwnd:%d\n",
5713                                                                    net->flight_size, net->cwnd);
5714                                                   }
5715 #endif
5716                                                   sctp_pegs[SCTP_CWND_BLOCKED]++;
5717                                                   *reason_code = 2;
5718                                                   break;
5719                                         }
5720                                         nchk = TAILQ_NEXT(chk, sctp_next);
5721                                         if (chk->whoTo != net) {
5722                                                   /* No, not sent to this net */
5723 #ifdef SCTP_DEBUG
5724                                                   if (sctp_debug_on & SCTP_DEBUG_OUTPUT3) {
5725                                                             printf("chk->whoTo:%p not %p\n",
5726                                                                    chk->whoTo, net);
5727 
5728                                                   }
5729 #endif
5730                                                   continue;
5731                                         }
5732 #ifdef SCTP_DEBUG
5733                                         if (sctp_debug_on & SCTP_DEBUG_OUTPUT3) {
5734                                                   printf("Can we pick up a chunk?\n");
5735                                         }
5736 #endif
5737                                         if ((chk->send_size > omtu) && ((chk->flags & CHUNK_FLAGS_FRAGMENT_OK) == 0)) {
5738                                                   /* strange, we have a chunk that is to bit
5739                                                    * for its destination and yet no fragment ok flag.
5740                                                    * Something went wrong when the PMTU changed...we did
5741                                                    * not mark this chunk for some reason?? I will
5742                                                    * fix it here by letting IP fragment it for now and
5743                                                    * printing a warning. This really should not happen ...
5744                                                    */
5745 /*#ifdef SCTP_DEBUG*/
5746                                                   printf("Warning chunk of %d bytes > mtu:%d and yet PMTU disc missed\n",
5747                                                          chk->send_size, mtu);
5748 /*#endif*/
5749                                                   chk->flags |= CHUNK_FLAGS_FRAGMENT_OK;
5750                                         }
5751 
5752                                         if (((chk->send_size <= mtu) && (chk->send_size <= r_mtu)) ||
5753                                             ((chk->flags & CHUNK_FLAGS_FRAGMENT_OK) && (chk->send_size <= asoc->peers_rwnd))) {
5754                                                   /* ok we will add this one */
5755 #ifdef SCTP_DEBUG
5756                                                   if (sctp_debug_on & SCTP_DEBUG_OUTPUT3) {
5757                                                             printf("Picking up the chunk\n");
5758                                                   }
5759 #endif
5760                                                   outchain = sctp_copy_mbufchain(chk->data, outchain);
5761                                                   if (outchain == NULL) {
5762 #ifdef SCTP_DEBUG
5763                                                             if (sctp_debug_on & SCTP_DEBUG_OUTPUT3) {
5764                                                                       printf("Gakk no memory\n");
5765                                                             }
5766 #endif
5767                                                             if (!callout_pending(&net->rxt_timer.timer)) {
5768                                                                       sctp_timer_start(SCTP_TIMER_TYPE_SEND, inp, stcb, net);
5769                                                             }
5770                                                             return (ENOMEM);
5771                                                   }
5772                                                   /* update our MTU size */
5773                                                   /* Do clear IP_DF ? */
5774                                                   if (chk->flags & CHUNK_FLAGS_FRAGMENT_OK) {
5775                                                             no_fragmentflg = 0;
5776                                                   }
5777                                                   mtu -= chk->send_size;
5778                                                   r_mtu -= chk->send_size;
5779                                                   data_list[bundle_at++] = chk;
5780                                                   if (bundle_at >= SCTP_MAX_DATA_BUNDLING) {
5781                                                             mtu = 0;
5782                                                             break;
5783                                                   }
5784                                                   if (mtu <= 0) {
5785                                                             mtu = 0;
5786                                                             break;
5787                                                   }
5788                                                   if ((r_mtu <= 0) || one_chunk) {
5789                                                             r_mtu = 0;
5790                                                             break;
5791                                                   }
5792                                         } else {
5793                                                   /*
5794                                                    * Must be sent in order of the TSN's
5795                                                    * (on a network)
5796                                                    */
5797 #ifdef SCTP_DEBUG
5798                                                   if (sctp_debug_on & SCTP_DEBUG_OUTPUT3) {
5799                                                             printf("ok no more chk:%d > mtu:%d || < r_mtu:%d\n",
5800                                                                    chk->send_size, mtu, r_mtu);
5801                                                   }
5802 #endif
5803 
5804                                                   break;
5805                                         }
5806                               }/* for () */
5807                     } /* if asoc.state OPEN */
5808                     /* Is there something to send for this destination? */
5809 #ifdef SCTP_DEBUG
5810                     if (sctp_debug_on & SCTP_DEBUG_OUTPUT3) {
5811                               printf("ok now is chain assembled? %p\n",
5812                                      outchain);
5813                     }
5814 #endif
5815 
5816                     if (outchain) {
5817                               /* We may need to start a control timer or two */
5818                               if (asconf) {
5819                                         sctp_timer_start(SCTP_TIMER_TYPE_ASCONF, inp, stcb, net);
5820                                         asconf = 0;
5821                               }
5822                               if (cookie) {
5823                                         sctp_timer_start(SCTP_TIMER_TYPE_COOKIE, inp, stcb, net);
5824                                         cookie = 0;
5825                               }
5826                               /* must start a send timer if data is being sent */
5827                               if (bundle_at && (!callout_pending(&net->rxt_timer.timer))) {
5828                                         /* no timer running on this destination
5829                                          * restart it.
5830                                          */
5831 #ifdef SCTP_DEBUG
5832                                         if (sctp_debug_on & SCTP_DEBUG_OUTPUT3) {
5833                                                   printf("ok lets start a send timer .. we will transmit %p\n",
5834                                                          outchain);
5835                                         }
5836 #endif
5837                                         sctp_timer_start(SCTP_TIMER_TYPE_SEND, inp, stcb, net);
5838                               }
5839                               /* Now send it, if there is anything to send :> */
5840                               if ((outchain->m_flags & M_PKTHDR) == 0) {
5841                                         struct mbuf *t;
5842 
5843                                         MGETHDR(t, M_DONTWAIT, MT_HEADER);
5844                                         if (t == NULL) {
5845                                                   sctp_m_freem(outchain);
5846                                                   return (ENOMEM);
5847                                         }
5848                                         t->m_next = outchain;
5849                                         t->m_pkthdr.len = 0;
5850                                         m_reset_rcvif(t);
5851                                         t->m_len = 0;
5852 
5853                                         outchain = t;
5854                                         while (t) {
5855                                                   outchain->m_pkthdr.len += t->m_len;
5856                                                   t = t->m_next;
5857                                         }
5858                               }
5859                               if (outchain->m_len == 0) {
5860                                         /* Special case for when you get a 0 len
5861                                          * mbuf at the head due to the lack
5862                                          * of a MHDR at the beginning.
5863                                          */
5864                                         m_align(outchain, sizeof(struct sctphdr));
5865                                         outchain->m_len = sizeof(struct sctphdr);
5866                               } else {
5867                                         M_PREPEND(outchain, sizeof(struct sctphdr), M_DONTWAIT);
5868                                         if (outchain == NULL) {
5869                                                   /* out of mbufs */
5870                                                   error = ENOBUFS;
5871                                                   goto errored_send;
5872                                         }
5873                               }
5874                               shdr = mtod(outchain, struct sctphdr *);
5875                               shdr->src_port = inp->sctp_lport;
5876                               shdr->dest_port = stcb->rport;
5877                               shdr->v_tag = htonl(stcb->asoc.peer_vtag);
5878                               shdr->checksum = 0;
5879                               if ((error = sctp_lowlevel_chunk_output(inp, stcb, net,
5880                                                                                 rtcache_getdst(&net->ro),
5881                                                                                 outchain,
5882                                                                                 no_fragmentflg, bundle_at, data_list[0], asconf))) {
5883                                         /* error, we could not output */
5884                                         if (error == ENOBUFS) {
5885                                                   asoc->ifp_had_enobuf = 1;
5886                                         }
5887                                         sctp_pegs[SCTP_DATA_OUT_ERR]++;
5888                                         if (from_where == 0) {
5889                                                   sctp_pegs[SCTP_ERROUT_FRM_USR]++;
5890                                         }
5891 
5892                               errored_send:
5893 #ifdef SCTP_DEBUG
5894                                         if (sctp_debug_on & SCTP_DEBUG_OUTPUT3) {
5895                                                   printf("Gak send error %d\n", error);
5896                                         }
5897 #endif
5898                                         if (hbflag) {
5899 #ifdef SCTP_DEBUG
5900                                                   if (sctp_debug_on & SCTP_DEBUG_OUTPUT3) {
5901                                                             printf("Update HB time anyway\n");
5902                                                   }
5903 #endif
5904                                                   if (*now_filled == 0) {
5905                                                             SCTP_GETTIME_TIMEVAL(&net->last_sent_time);
5906                                                             *now_filled = 1;
5907                                                             *now = net->last_sent_time;
5908                                                   } else {
5909                                                             net->last_sent_time = *now;
5910                                                   }
5911                                                   hbflag = 0;
5912                                         }
5913                                         if (error == EHOSTUNREACH ||
5914                                             error == EHOSTDOWN) {
5915                                                   /*
5916                                                    * Destination went unreachable during
5917                                                    * this send
5918                                                    */
5919 #ifdef SCTP_DEBUG
5920                                                   if (sctp_debug_on & SCTP_DEBUG_OUTPUT3) {
5921                                                             printf("Calling the movement routine\n");
5922                                                   }
5923 #endif
5924                                                   sctp_move_to_an_alt(stcb, asoc, net);
5925                                         }
5926                                         sctp_clean_up_ctl (asoc);
5927                                         return (error);
5928                               } else {
5929                                         asoc->ifp_had_enobuf = 0;
5930                               }
5931                               if (bundle_at || hbflag) {
5932                                         /* For data/asconf and hb set time */
5933                                         if (*now_filled == 0) {
5934                                                   SCTP_GETTIME_TIMEVAL(&net->last_sent_time);
5935                                                   *now_filled = 1;
5936                                                   *now = net->last_sent_time;
5937                                         } else {
5938                                                   net->last_sent_time = *now;
5939                                         }
5940                               }
5941 
5942                               if (!no_out_cnt) {
5943                                         *num_out += (ctl_cnt + bundle_at);
5944                               }
5945                               if (bundle_at) {
5946                                         if (!net->rto_pending) {
5947                                                   /* setup for a RTO measurement */
5948                                                   net->rto_pending = 1;
5949                                                   data_list[0]->do_rtt = 1;
5950                                         } else {
5951                                                   data_list[0]->do_rtt = 0;
5952                                         }
5953                                         sctp_pegs[SCTP_PEG_TSNS_SENT] += bundle_at;
5954                                         sctp_clean_up_datalist(stcb, asoc, data_list, bundle_at, net);
5955                               }
5956                               if (one_chunk) {
5957                                         break;
5958                               }
5959                     }
5960           }
5961           /* At the end there should be no NON timed
5962            * chunks hanging on this queue.
5963            */
5964           if ((*num_out == 0) && (*reason_code == 0)) {
5965                     *reason_code = 3;
5966           }
5967           sctp_clean_up_ctl (asoc);
5968           return (0);
5969 }
5970 
5971 void
5972 sctp_queue_op_err(struct sctp_tcb *stcb, struct mbuf *op_err)
5973 {
5974           /* Prepend a OPERATIONAL_ERROR chunk header
5975            * and put on the end of the control chunk queue.
5976            */
5977           /* Sender had better have gotten a MGETHDR or else
5978            * the control chunk will be forever skipped
5979            */
5980           struct sctp_chunkhdr *hdr;
5981           struct sctp_tmit_chunk *chk;
5982           struct mbuf *mat;
5983 
5984           chk = (struct sctp_tmit_chunk *)SCTP_ZONE_GET(sctppcbinfo.ipi_zone_chunk);
5985           if (chk == NULL) {
5986                     /* no memory */
5987                     sctp_m_freem(op_err);
5988                     return;
5989           }
5990           sctppcbinfo.ipi_count_chunk++;
5991           sctppcbinfo.ipi_gencnt_chunk++;
5992           M_PREPEND(op_err, sizeof(struct sctp_chunkhdr), M_DONTWAIT);
5993           if (op_err == NULL) {
5994                     SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_chunk, chk);
5995                     sctppcbinfo.ipi_count_chunk--;
5996                     if ((int)sctppcbinfo.ipi_count_chunk < 0) {
5997                               panic("Chunk count is negative");
5998                     }
5999                     sctppcbinfo.ipi_gencnt_chunk++;
6000                     return;
6001           }
6002           chk->send_size = 0;
6003           mat = op_err;
6004           while (mat != NULL) {
6005                     chk->send_size += mat->m_len;
6006                     mat = mat->m_next;
6007           }
6008           chk->rec.chunk_id = SCTP_OPERATION_ERROR;
6009           chk->sent = SCTP_DATAGRAM_UNSENT;
6010           chk->snd_count = 0;
6011           chk->flags = 0;
6012           chk->asoc = &stcb->asoc;
6013           chk->data = op_err;
6014           chk->whoTo = chk->asoc->primary_destination;
6015           chk->whoTo->ref_count++;
6016           hdr = mtod(op_err, struct sctp_chunkhdr *);
6017           hdr->chunk_type = SCTP_OPERATION_ERROR;
6018           hdr->chunk_flags = 0;
6019           hdr->chunk_length = htons(chk->send_size);
6020           TAILQ_INSERT_TAIL(&chk->asoc->control_send_queue,
6021                                 chk,
6022                                 sctp_next);
6023           chk->asoc->ctrl_queue_cnt++;
6024 }
6025 
6026 int
6027 sctp_send_cookie_echo(struct mbuf *m,
6028                           int offset,
6029                           struct sctp_tcb *stcb,
6030                           struct sctp_nets *net)
6031 {
6032           /*
6033            * pull out the cookie and put it at the front of the control
6034            * chunk queue.
6035            */
6036           int at;
6037           struct mbuf *cookie, *mat;
6038           struct sctp_paramhdr parm, *phdr;
6039           struct sctp_chunkhdr *hdr;
6040           struct sctp_tmit_chunk *chk;
6041           uint16_t ptype, plen;
6042           /* First find the cookie in the param area */
6043           cookie = NULL;
6044           at = offset + sizeof(struct sctp_init_chunk);
6045 
6046           do {
6047                     phdr = sctp_get_next_param(m, at, &parm, sizeof(parm));
6048                     if (phdr == NULL) {
6049                               return (-3);
6050                     }
6051                     ptype = ntohs(phdr->param_type);
6052                     plen = ntohs(phdr->param_length);
6053                     if (ptype == SCTP_STATE_COOKIE) {
6054                               int pad;
6055                               /* found the cookie */
6056                               if ((pad = (plen % 4))) {
6057                                         plen += 4 - pad;
6058                               }
6059                               cookie = sctp_m_copym(m, at, plen, M_DONTWAIT);
6060                               if (cookie == NULL) {
6061                                         /* No memory */
6062                                         return (-2);
6063                               }
6064                               break;
6065                     }
6066                     at += SCTP_SIZE32(plen);
6067           } while (phdr);
6068           if (cookie == NULL) {
6069                     /* Did not find the cookie */
6070                     return (-3);
6071           }
6072           /* ok, we got the cookie lets change it into a cookie echo chunk */
6073 
6074           /* first the change from param to cookie */
6075           hdr = mtod(cookie, struct sctp_chunkhdr *);
6076           hdr->chunk_type = SCTP_COOKIE_ECHO;
6077           hdr->chunk_flags = 0;
6078           /* now we MUST have a PKTHDR on it */
6079           if ((cookie->m_flags & M_PKTHDR) != M_PKTHDR) {
6080                     /* we hope this happens rarely */
6081                     MGETHDR(mat, M_DONTWAIT, MT_HEADER);
6082                     if (mat == NULL) {
6083                               sctp_m_freem(cookie);
6084                               return (-4);
6085                     }
6086                     mat->m_len = 0;
6087                     m_reset_rcvif(mat);
6088                     mat->m_next = cookie;
6089                     cookie = mat;
6090           }
6091           cookie->m_pkthdr.len = plen;
6092           /* get the chunk stuff now and place it in the FRONT of the queue */
6093           chk = (struct sctp_tmit_chunk *)SCTP_ZONE_GET(sctppcbinfo.ipi_zone_chunk);
6094           if (chk == NULL) {
6095                     /* no memory */
6096                     sctp_m_freem(cookie);
6097                     return (-5);
6098           }
6099           sctppcbinfo.ipi_count_chunk++;
6100           sctppcbinfo.ipi_gencnt_chunk++;
6101           chk->send_size = cookie->m_pkthdr.len;
6102           chk->rec.chunk_id = SCTP_COOKIE_ECHO;
6103           chk->sent = SCTP_DATAGRAM_UNSENT;
6104           chk->snd_count = 0;
6105           chk->flags = 0;
6106           chk->asoc = &stcb->asoc;
6107           chk->data = cookie;
6108           chk->whoTo = chk->asoc->primary_destination;
6109           chk->whoTo->ref_count++;
6110           TAILQ_INSERT_HEAD(&chk->asoc->control_send_queue, chk, sctp_next);
6111           chk->asoc->ctrl_queue_cnt++;
6112           return (0);
6113 }
6114 
6115 void
6116 sctp_send_heartbeat_ack(struct sctp_tcb *stcb,
6117                               struct mbuf *m,
6118                               int offset,
6119                               int chk_length,
6120                               struct sctp_nets *net)
6121 {
6122           /* take a HB request and make it into a
6123            * HB ack and send it.
6124            */
6125           struct mbuf *outchain;
6126           struct sctp_chunkhdr *chdr;
6127           struct sctp_tmit_chunk *chk;
6128 
6129 
6130           if (net == NULL)
6131                     /* must have a net pointer */
6132                     return;
6133 
6134           outchain = sctp_m_copym(m, offset, chk_length, M_DONTWAIT);
6135           if (outchain == NULL) {
6136                     /* gak out of memory */
6137                     return;
6138           }
6139           chdr = mtod(outchain, struct sctp_chunkhdr *);
6140           chdr->chunk_type = SCTP_HEARTBEAT_ACK;
6141           chdr->chunk_flags = 0;
6142           if ((outchain->m_flags & M_PKTHDR) != M_PKTHDR) {
6143                     /* should not happen but we are cautious. */
6144                     struct mbuf *tmp;
6145                     MGETHDR(tmp, M_DONTWAIT, MT_HEADER);
6146                     if (tmp == NULL) {
6147                               return;
6148                     }
6149                     tmp->m_len = 0;
6150                     m_reset_rcvif(tmp);
6151                     tmp->m_next = outchain;
6152                     outchain = tmp;
6153           }
6154           outchain->m_pkthdr.len = chk_length;
6155           if (chk_length % 4) {
6156                     /* need pad */
6157                     u_int32_t cpthis=0;
6158                     int padlen;
6159                     padlen = 4 - (outchain->m_pkthdr.len % 4);
6160                     m_copyback(outchain, outchain->m_pkthdr.len, padlen, (void *)&cpthis);
6161           }
6162           chk = (struct sctp_tmit_chunk *)SCTP_ZONE_GET(sctppcbinfo.ipi_zone_chunk);
6163           if (chk == NULL) {
6164                     /* no memory */
6165                     sctp_m_freem(outchain);
6166                     return ;
6167           }
6168           sctppcbinfo.ipi_count_chunk++;
6169           sctppcbinfo.ipi_gencnt_chunk++;
6170 
6171           chk->send_size = chk_length;
6172           chk->rec.chunk_id = SCTP_HEARTBEAT_ACK;
6173           chk->sent = SCTP_DATAGRAM_UNSENT;
6174           chk->snd_count = 0;
6175           chk->flags = 0;
6176           chk->asoc = &stcb->asoc;
6177           chk->data = outchain;
6178           chk->whoTo = net;
6179           chk->whoTo->ref_count++;
6180           TAILQ_INSERT_TAIL(&chk->asoc->control_send_queue, chk, sctp_next);
6181           chk->asoc->ctrl_queue_cnt++;
6182 }
6183 
6184 int
6185 sctp_send_cookie_ack(struct sctp_tcb *stcb) {
6186           /* formulate and queue a cookie-ack back to sender */
6187           struct mbuf *cookie_ack;
6188           struct sctp_chunkhdr *hdr;
6189           struct sctp_tmit_chunk *chk;
6190 
6191           cookie_ack = NULL;
6192           MGETHDR(cookie_ack, M_DONTWAIT, MT_HEADER);
6193           if (cookie_ack == NULL) {
6194                     /* no mbuf's */
6195                     return (-1);
6196           }
6197           cookie_ack->m_data += SCTP_MIN_OVERHEAD;
6198           chk = (struct sctp_tmit_chunk *)SCTP_ZONE_GET(sctppcbinfo.ipi_zone_chunk);
6199           if (chk == NULL) {
6200                     /* no memory */
6201                     sctp_m_freem(cookie_ack);
6202                     return (-1);
6203           }
6204           sctppcbinfo.ipi_count_chunk++;
6205           sctppcbinfo.ipi_gencnt_chunk++;
6206 
6207           chk->send_size = sizeof(struct sctp_chunkhdr);
6208           chk->rec.chunk_id = SCTP_COOKIE_ACK;
6209           chk->sent = SCTP_DATAGRAM_UNSENT;
6210           chk->snd_count = 0;
6211           chk->flags = 0;
6212           chk->asoc = &stcb->asoc;
6213           chk->data = cookie_ack;
6214           if (chk->asoc->last_control_chunk_from != NULL) {
6215                     chk->whoTo = chk->asoc->last_control_chunk_from;
6216           } else {
6217                     chk->whoTo = chk->asoc->primary_destination;
6218           }
6219           chk->whoTo->ref_count++;
6220           hdr = mtod(cookie_ack, struct sctp_chunkhdr *);
6221           hdr->chunk_type = SCTP_COOKIE_ACK;
6222           hdr->chunk_flags = 0;
6223           hdr->chunk_length = htons(chk->send_size);
6224           cookie_ack->m_pkthdr.len = cookie_ack->m_len = chk->send_size;
6225           m_reset_rcvif(cookie_ack);
6226           TAILQ_INSERT_TAIL(&chk->asoc->control_send_queue, chk, sctp_next);
6227           chk->asoc->ctrl_queue_cnt++;
6228           return (0);
6229 }
6230 
6231 
6232 int
6233 sctp_send_shutdown_ack(struct sctp_tcb *stcb, struct sctp_nets *net)
6234 {
6235           /* formulate and queue a SHUTDOWN-ACK back to the sender */
6236           struct mbuf *m_shutdown_ack;
6237           struct sctp_shutdown_ack_chunk *ack_cp;
6238           struct sctp_tmit_chunk *chk;
6239 
6240           m_shutdown_ack = NULL;
6241           MGETHDR(m_shutdown_ack, M_DONTWAIT, MT_HEADER);
6242           if (m_shutdown_ack == NULL) {
6243                     /* no mbuf's */
6244                     return (-1);
6245           }
6246           m_shutdown_ack->m_data += SCTP_MIN_OVERHEAD;
6247           chk = (struct sctp_tmit_chunk *)SCTP_ZONE_GET(sctppcbinfo.ipi_zone_chunk);
6248           if (chk == NULL) {
6249                     /* no memory */
6250                     sctp_m_freem(m_shutdown_ack);
6251                     return (-1);
6252           }
6253           sctppcbinfo.ipi_count_chunk++;
6254           sctppcbinfo.ipi_gencnt_chunk++;
6255 
6256           chk->send_size = sizeof(struct sctp_chunkhdr);
6257           chk->rec.chunk_id = SCTP_SHUTDOWN_ACK;
6258           chk->sent = SCTP_DATAGRAM_UNSENT;
6259           chk->snd_count = 0;
6260           chk->flags = 0;
6261           chk->asoc = &stcb->asoc;
6262           chk->data = m_shutdown_ack;
6263           chk->whoTo = net;
6264           net->ref_count++;
6265 
6266           ack_cp = mtod(m_shutdown_ack, struct sctp_shutdown_ack_chunk *);
6267           ack_cp->ch.chunk_type = SCTP_SHUTDOWN_ACK;
6268           ack_cp->ch.chunk_flags = 0;
6269           ack_cp->ch.chunk_length = htons(chk->send_size);
6270           m_shutdown_ack->m_pkthdr.len = m_shutdown_ack->m_len = chk->send_size;
6271           m_reset_rcvif(m_shutdown_ack);
6272           TAILQ_INSERT_TAIL(&chk->asoc->control_send_queue, chk, sctp_next);
6273           chk->asoc->ctrl_queue_cnt++;
6274           return (0);
6275 }
6276 
6277 int
6278 sctp_send_shutdown(struct sctp_tcb *stcb, struct sctp_nets *net)
6279 {
6280           /* formulate and queue a SHUTDOWN to the sender */
6281           struct mbuf *m_shutdown;
6282           struct sctp_shutdown_chunk *shutdown_cp;
6283           struct sctp_tmit_chunk *chk;
6284 
6285           m_shutdown = NULL;
6286           MGETHDR(m_shutdown, M_DONTWAIT, MT_HEADER);
6287           if (m_shutdown == NULL) {
6288                     /* no mbuf's */
6289                     return (-1);
6290           }
6291           m_shutdown->m_data += SCTP_MIN_OVERHEAD;
6292           chk = (struct sctp_tmit_chunk *)SCTP_ZONE_GET(sctppcbinfo.ipi_zone_chunk);
6293           if (chk == NULL) {
6294                     /* no memory */
6295                     sctp_m_freem(m_shutdown);
6296                     return (-1);
6297           }
6298           sctppcbinfo.ipi_count_chunk++;
6299           sctppcbinfo.ipi_gencnt_chunk++;
6300 
6301           chk->send_size = sizeof(struct sctp_shutdown_chunk);
6302           chk->rec.chunk_id = SCTP_SHUTDOWN;
6303           chk->sent = SCTP_DATAGRAM_UNSENT;
6304           chk->snd_count = 0;
6305           chk->flags = 0;
6306           chk->asoc = &stcb->asoc;
6307           chk->data = m_shutdown;
6308           chk->whoTo = net;
6309           net->ref_count++;
6310 
6311           shutdown_cp = mtod(m_shutdown, struct sctp_shutdown_chunk *);
6312           shutdown_cp->ch.chunk_type = SCTP_SHUTDOWN;
6313           shutdown_cp->ch.chunk_flags = 0;
6314           shutdown_cp->ch.chunk_length = htons(chk->send_size);
6315           shutdown_cp->cumulative_tsn_ack = htonl(stcb->asoc.cumulative_tsn);
6316           m_shutdown->m_pkthdr.len = m_shutdown->m_len = chk->send_size;
6317           m_reset_rcvif(m_shutdown);
6318           TAILQ_INSERT_TAIL(&chk->asoc->control_send_queue, chk, sctp_next);
6319           chk->asoc->ctrl_queue_cnt++;
6320 
6321           if ((stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE) ||
6322               (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL)) {
6323                     stcb->sctp_ep->sctp_socket->so_snd.sb_cc = 0;
6324                     soisdisconnecting(stcb->sctp_ep->sctp_socket);
6325           }
6326           return (0);
6327 }
6328 
6329 int
6330 sctp_send_asconf(struct sctp_tcb *stcb, struct sctp_nets *net)
6331 {
6332           /*
6333            * formulate and queue an ASCONF to the peer
6334            * ASCONF parameters should be queued on the assoc queue
6335            */
6336           struct sctp_tmit_chunk *chk;
6337           struct mbuf *m_asconf;
6338 
6339           /* compose an ASCONF chunk, maximum length is PMTU */
6340           m_asconf = sctp_compose_asconf(stcb);
6341           if (m_asconf == NULL) {
6342                     return (-1);
6343           }
6344           chk = (struct sctp_tmit_chunk *)SCTP_ZONE_GET(sctppcbinfo.ipi_zone_chunk);
6345           if (chk == NULL) {
6346                     /* no memory */
6347                     sctp_m_freem(m_asconf);
6348                     return (-1);
6349           }
6350           sctppcbinfo.ipi_count_chunk++;
6351           sctppcbinfo.ipi_gencnt_chunk++;
6352 
6353           chk->data = m_asconf;
6354           chk->send_size = m_asconf->m_pkthdr.len;
6355           chk->rec.chunk_id = SCTP_ASCONF;
6356           chk->sent = SCTP_DATAGRAM_UNSENT;
6357           chk->snd_count = 0;
6358           chk->flags = 0;
6359           chk->asoc = &stcb->asoc;
6360           chk->whoTo = chk->asoc->primary_destination;
6361           chk->whoTo->ref_count++;
6362           TAILQ_INSERT_TAIL(&chk->asoc->control_send_queue, chk, sctp_next);
6363           chk->asoc->ctrl_queue_cnt++;
6364           return (0);
6365 }
6366 
6367 int
6368 sctp_send_asconf_ack(struct sctp_tcb *stcb, uint32_t retrans)
6369 {
6370           /*
6371            * formulate and queue a asconf-ack back to sender
6372            * the asconf-ack must be stored in the tcb
6373            */
6374           struct sctp_tmit_chunk *chk;
6375           struct mbuf *m_ack;
6376 
6377           /* is there a asconf-ack mbuf chain to send? */
6378           if (stcb->asoc.last_asconf_ack_sent == NULL) {
6379                     return (-1);
6380           }
6381 
6382           /* copy the asconf_ack */
6383 #if defined(__FreeBSD__) || defined(__NetBSD__)
6384           /* Supposedly the m_copypacket is a optimzation,
6385            * use it if we can.
6386            */
6387           if (stcb->asoc.last_asconf_ack_sent->m_flags & M_PKTHDR) {
6388                     m_ack = m_copypacket(stcb->asoc.last_asconf_ack_sent, M_DONTWAIT);
6389                     sctp_pegs[SCTP_CACHED_SRC]++;
6390           } else
6391                     m_ack = m_copym(stcb->asoc.last_asconf_ack_sent, 0, M_COPYALL, M_DONTWAIT);
6392 #else
6393                     m_ack = m_copy(stcb->asoc.last_asconf_ack_sent, 0, M_COPYALL);
6394 #endif
6395           if (m_ack == NULL) {
6396                     /* couldn't copy it */
6397 
6398                     return (-1);
6399           }
6400           chk = (struct sctp_tmit_chunk *)SCTP_ZONE_GET(sctppcbinfo.ipi_zone_chunk);
6401           if (chk == NULL) {
6402                     /* no memory */
6403                     sctp_m_freem(m_ack);
6404                     return (-1);
6405           }
6406           sctppcbinfo.ipi_count_chunk++;
6407           sctppcbinfo.ipi_gencnt_chunk++;
6408 
6409           /* figure out where it goes to */
6410           if (retrans) {
6411                     /* we're doing a retransmission */
6412                     if (stcb->asoc.used_alt_asconfack > 2) {
6413                               /* tried alternate nets already, go back */
6414                               chk->whoTo = NULL;
6415                     } else {
6416                               /* need to try and alternate net */
6417                               chk->whoTo = sctp_find_alternate_net(stcb, stcb->asoc.last_control_chunk_from);
6418                               stcb->asoc.used_alt_asconfack++;
6419                     }
6420                     if (chk->whoTo == NULL) {
6421                               /* no alternate */
6422                               if (stcb->asoc.last_control_chunk_from == NULL)
6423                                         chk->whoTo = stcb->asoc.primary_destination;
6424                               else
6425                                         chk->whoTo = stcb->asoc.last_control_chunk_from;
6426                               stcb->asoc.used_alt_asconfack = 0;
6427                     }
6428           } else {
6429                     /* normal case */
6430                     if (stcb->asoc.last_control_chunk_from == NULL)
6431                               chk->whoTo = stcb->asoc.primary_destination;
6432                     else
6433                               chk->whoTo = stcb->asoc.last_control_chunk_from;
6434                     stcb->asoc.used_alt_asconfack = 0;
6435           }
6436           chk->data = m_ack;
6437           chk->send_size = m_ack->m_pkthdr.len;
6438           chk->rec.chunk_id = SCTP_ASCONF_ACK;
6439           chk->sent = SCTP_DATAGRAM_UNSENT;
6440           chk->snd_count = 0;
6441           chk->flags = 0;
6442           chk->asoc = &stcb->asoc;
6443           chk->whoTo->ref_count++;
6444           TAILQ_INSERT_TAIL(&chk->asoc->control_send_queue, chk, sctp_next);
6445           chk->asoc->ctrl_queue_cnt++;
6446           return (0);
6447 }
6448 
6449 
6450 static int
6451 sctp_chunk_retransmission(struct sctp_inpcb *inp,
6452                                 struct sctp_tcb *stcb,
6453                                 struct sctp_association *asoc,
6454                                 int *cnt_out, struct timeval *now, int *now_filled)
6455 {
6456           /*
6457            * send out one MTU of retransmission.
6458            * If fast_retransmit is happening we ignore the cwnd.
6459            * Otherwise we obey the cwnd and rwnd.
6460            * For a Cookie or Asconf in the control chunk queue we retransmit
6461            * them by themselves.
6462            *
6463            * For data chunks we will pick out the lowest TSN's in the
6464            * sent_queue marked for resend and bundle them all together
6465            * (up to a MTU of destination). The address to send to should
6466            * have been selected/changed where the retransmission was
6467            * marked (i.e. in FR or t3-timeout routines).
6468            */
6469           struct sctp_tmit_chunk *data_list[SCTP_MAX_DATA_BUNDLING];
6470           struct sctp_tmit_chunk *chk, *fwd;
6471           struct mbuf *m;
6472           struct sctphdr *shdr;
6473           int asconf;
6474           struct sctp_nets *net;
6475           int no_fragmentflg, bundle_at, cnt_thru;
6476           unsigned int mtu;
6477           int error, i, one_chunk, fwd_tsn, ctl_cnt, tmr_started;
6478 
6479           tmr_started = ctl_cnt = bundle_at =  error = 0;
6480           no_fragmentflg = 1;
6481           asconf = 0;
6482           fwd_tsn = 0;
6483           *cnt_out = 0;
6484           fwd = NULL;
6485           m = NULL;
6486 #ifdef SCTP_AUDITING_ENABLED
6487           sctp_audit_log(0xC3, 1);
6488 #endif
6489           if (TAILQ_EMPTY(&asoc->sent_queue)) {
6490 #ifdef SCTP_DEBUG
6491                     if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
6492                               printf("SCTP hits empty queue with cnt set to %d?\n",
6493                                      asoc->sent_queue_retran_cnt);
6494                     }
6495 #endif
6496                     asoc->sent_queue_cnt = 0;
6497                     asoc->sent_queue_cnt_removeable = 0;
6498           }
6499           TAILQ_FOREACH(chk, &asoc->control_send_queue, sctp_next) {
6500                     if (chk->sent != SCTP_DATAGRAM_RESEND) {
6501                               /* we only worry about things marked for resend */
6502                               continue;
6503                     }
6504                     if ((chk->rec.chunk_id == SCTP_COOKIE_ECHO) ||
6505                         (chk->rec.chunk_id == SCTP_ASCONF) ||
6506                         (chk->rec.chunk_id == SCTP_STREAM_RESET) ||
6507                         (chk->rec.chunk_id == SCTP_FORWARD_CUM_TSN)) {
6508                               if (chk->rec.chunk_id == SCTP_STREAM_RESET) {
6509                                         /* For stream reset we only retran the request
6510                                          * not the response.
6511                                          */
6512                                         struct sctp_stream_reset_req *strreq;
6513                                         strreq = mtod(chk->data, struct sctp_stream_reset_req *);
6514                                         if (strreq->sr_req.ph.param_type != ntohs(SCTP_STR_RESET_REQUEST)) {
6515                                                   continue;
6516                                         }
6517                               }
6518                               ctl_cnt++;
6519                               if (chk->rec.chunk_id == SCTP_ASCONF) {
6520                                         no_fragmentflg = 1;
6521                                         asconf = 1;
6522                               }
6523                               if (chk->rec.chunk_id == SCTP_FORWARD_CUM_TSN) {
6524                                         fwd_tsn = 1;
6525                                         fwd = chk;
6526                               }
6527                               m = sctp_copy_mbufchain(chk->data, m);
6528                               break;
6529                     }
6530           }
6531           one_chunk = 0;
6532           cnt_thru = 0;
6533           /* do we have control chunks to retransmit? */
6534           if (m != NULL) {
6535                     /* Start a timer no matter if we suceed or fail */
6536                     if (chk->rec.chunk_id == SCTP_COOKIE_ECHO) {
6537                               sctp_timer_start(SCTP_TIMER_TYPE_COOKIE, inp, stcb, chk->whoTo);
6538                     } else if (chk->rec.chunk_id == SCTP_ASCONF)
6539                               sctp_timer_start(SCTP_TIMER_TYPE_ASCONF, inp, stcb, chk->whoTo);
6540 
6541                     if (m->m_len == 0) {
6542                               /* Special case for when you get a 0 len
6543                                * mbuf at the head due to the lack
6544                                * of a MHDR at the beginning.
6545                                */
6546                               m->m_len = sizeof(struct sctphdr);
6547                     } else {
6548                               M_PREPEND(m, sizeof(struct sctphdr), M_DONTWAIT);
6549                               if (m == NULL) {
6550                                         return (ENOBUFS);
6551                               }
6552                     }
6553                     shdr = mtod(m, struct sctphdr *);
6554                     shdr->src_port = inp->sctp_lport;
6555                     shdr->dest_port = stcb->rport;
6556                     shdr->v_tag = htonl(stcb->asoc.peer_vtag);
6557                     shdr->checksum = 0;
6558                     chk->snd_count++;             /* update our count */
6559 
6560                     if ((error = sctp_lowlevel_chunk_output(inp, stcb, chk->whoTo,
6561                         rtcache_getdst(&chk->whoTo->ro), m,
6562                         no_fragmentflg, 0, NULL, asconf))) {
6563                               sctp_pegs[SCTP_DATA_OUT_ERR]++;
6564                               return (error);
6565                     }
6566                     /*
6567                      *We don't want to mark the net->sent time here since this
6568                      * we use this for HB and retrans cannot measure RTT
6569                      */
6570                     /*    SCTP_GETTIME_TIMEVAL(&chk->whoTo->last_sent_time);*/
6571                     *cnt_out += 1;
6572                     chk->sent = SCTP_DATAGRAM_SENT;
6573                     sctp_ucount_decr(asoc->sent_queue_retran_cnt);
6574                     if (fwd_tsn == 0) {
6575                               return (0);
6576                     } else {
6577                               /* Clean up the fwd-tsn list */
6578                               sctp_clean_up_ctl (asoc);
6579                               return (0);
6580                     }
6581           }
6582           /* Ok, it is just data retransmission we need to do or
6583            * that and a fwd-tsn with it all.
6584            */
6585           if (TAILQ_EMPTY(&asoc->sent_queue)) {
6586                     return (-1);
6587           }
6588 #ifdef SCTP_DEBUG
6589           if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
6590                     printf("Normal chunk retransmission cnt:%d\n",
6591                            asoc->sent_queue_retran_cnt);
6592           }
6593 #endif
6594           if ((SCTP_GET_STATE(asoc) == SCTP_STATE_COOKIE_ECHOED) ||
6595               (SCTP_GET_STATE(asoc) == SCTP_STATE_COOKIE_WAIT)) {
6596                     /* not yet open, resend the cookie and that is it */
6597                     return (1);
6598           }
6599 
6600 
6601 #ifdef SCTP_AUDITING_ENABLED
6602           sctp_auditing(20, inp, stcb, NULL);
6603 #endif
6604           TAILQ_FOREACH(chk, &asoc->sent_queue, sctp_next) {
6605                     if (chk->sent != SCTP_DATAGRAM_RESEND) {
6606                               /* No, not sent to this net or not ready for rtx */
6607                               continue;
6608 
6609                     }
6610                     /* pick up the net */
6611                     net = chk->whoTo;
6612                     if (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) {
6613                               mtu = (net->mtu - SCTP_MIN_OVERHEAD);
6614                     } else {
6615                               mtu = net->mtu- SCTP_MIN_V4_OVERHEAD;
6616                     }
6617 
6618                     if ((asoc->peers_rwnd < mtu) && (asoc->total_flight > 0)) {
6619                               /* No room in peers rwnd */
6620                               uint32_t tsn;
6621                               tsn = asoc->last_acked_seq + 1;
6622                               if (tsn == chk->rec.data.TSN_seq) {
6623                                         /* we make a special exception for this case.
6624                                          * The peer has no rwnd but is missing the
6625                                          * lowest chunk.. which is probably what is
6626                                          * holding up the rwnd.
6627                                          */
6628                                         goto one_chunk_around;
6629                               }
6630 #ifdef SCTP_DEBUG
6631                               if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
6632                                         printf("blocked-peers_rwnd:%d tf:%d\n",
6633                                                (int)asoc->peers_rwnd,
6634                                                (int)asoc->total_flight);
6635                               }
6636 #endif
6637                               sctp_pegs[SCTP_RWND_BLOCKED]++;
6638                               return (1);
6639                     }
6640           one_chunk_around:
6641                     if (asoc->peers_rwnd < mtu) {
6642                               one_chunk = 1;
6643                     }
6644 #ifdef SCTP_AUDITING_ENABLED
6645                     sctp_audit_log(0xC3, 2);
6646 #endif
6647                     bundle_at = 0;
6648                     m = NULL;
6649                     net->fast_retran_ip = 0;
6650                     if (chk->rec.data.doing_fast_retransmit == 0) {
6651                               /* if no FR in progress skip destination that
6652                                * have flight_size > cwnd.
6653                                */
6654                               if (net->flight_size >= net->cwnd) {
6655                                         sctp_pegs[SCTP_CWND_BLOCKED]++;
6656                                         continue;
6657                               }
6658                     } else {
6659                               /* Mark the destination net to have FR recovery
6660                                * limits put on it.
6661                                */
6662                               net->fast_retran_ip = 1;
6663                     }
6664 
6665                     if ((chk->send_size <= mtu) || (chk->flags & CHUNK_FLAGS_FRAGMENT_OK)) {
6666                               /* ok we will add this one */
6667                               m = sctp_copy_mbufchain(chk->data, m);
6668                               if (m == NULL) {
6669                                         return (ENOMEM);
6670                               }
6671                               /* update our MTU size */
6672                               /* Do clear IP_DF ? */
6673                               if (chk->flags & CHUNK_FLAGS_FRAGMENT_OK) {
6674                                         no_fragmentflg = 0;
6675                               }
6676                               mtu -= chk->send_size;
6677                               data_list[bundle_at++] = chk;
6678                               if (one_chunk && (asoc->total_flight <= 0)) {
6679                                         sctp_pegs[SCTP_WINDOW_PROBES]++;
6680                                         chk->rec.data.state_flags |= SCTP_WINDOW_PROBE;
6681                               }
6682                     }
6683                     if (one_chunk == 0) {
6684                               /* now are there anymore forward from chk to pick up?*/
6685                               fwd = TAILQ_NEXT(chk, sctp_next);
6686                               while (fwd) {
6687                                         if (fwd->sent != SCTP_DATAGRAM_RESEND) {
6688                                                   /* Nope, not for retran */
6689                                                   fwd = TAILQ_NEXT(fwd, sctp_next);
6690                                                   continue;
6691                                         }
6692                                         if (fwd->whoTo != net) {
6693                                                   /* Nope, not the net in question */
6694                                                   fwd = TAILQ_NEXT(fwd, sctp_next);
6695                                                   continue;
6696                                         }
6697                                         if (fwd->send_size <= mtu) {
6698                                                   m = sctp_copy_mbufchain(fwd->data, m);
6699                                                   if (m == NULL) {
6700                                                             return (ENOMEM);
6701                                                   }
6702                                                   /* update our MTU size */
6703                                                   /* Do clear IP_DF ? */
6704                                                   if (fwd->flags & CHUNK_FLAGS_FRAGMENT_OK) {
6705                                                             no_fragmentflg = 0;
6706                                                   }
6707                                                   mtu -= fwd->send_size;
6708                                                   data_list[bundle_at++] = fwd;
6709                                                   if (bundle_at >= SCTP_MAX_DATA_BUNDLING) {
6710                                                             break;
6711                                                   }
6712                                                   fwd = TAILQ_NEXT(fwd, sctp_next);
6713                                         } else {
6714                                                   /* can't fit so we are done */
6715                                                   break;
6716                                         }
6717                               }
6718                     }
6719                     /* Is there something to send for this destination? */
6720                     if (m) {
6721                               /* No matter if we fail/or suceed we should
6722                                * start a timer. A failure is like a lost
6723                                * IP packet :-)
6724                                */
6725                               if (!callout_pending(&net->rxt_timer.timer)) {
6726                                         /* no timer running on this destination
6727                                          * restart it.
6728                                          */
6729                                         sctp_timer_start(SCTP_TIMER_TYPE_SEND, inp, stcb, net);
6730                                         tmr_started = 1;
6731                               }
6732                               if (m->m_len == 0) {
6733                                         /* Special case for when you get a 0 len
6734                                          * mbuf at the head due to the lack
6735                                          * of a MHDR at the beginning.
6736                                          */
6737                                         m->m_len = sizeof(struct sctphdr);
6738                               } else {
6739                                         M_PREPEND(m, sizeof(struct sctphdr), M_DONTWAIT);
6740                                         if (m == NULL) {
6741                                                   return (ENOBUFS);
6742                                         }
6743                               }
6744                               shdr = mtod(m, struct sctphdr *);
6745                               shdr->src_port = inp->sctp_lport;
6746                               shdr->dest_port = stcb->rport;
6747                               shdr->v_tag = htonl(stcb->asoc.peer_vtag);
6748                               shdr->checksum = 0;
6749 
6750                               /* Now lets send it, if there is anything to send :> */
6751                               if ((error = sctp_lowlevel_chunk_output(inp, stcb, net,
6752                                                                              rtcache_getdst(&net->ro),
6753                                                                              m,
6754                                                                              no_fragmentflg, 0, NULL, asconf))) {
6755                                         /* error, we could not output */
6756                                         sctp_pegs[SCTP_DATA_OUT_ERR]++;
6757                                         return (error);
6758                               }
6759                               /* For HB's */
6760                               /*
6761                                * We don't want to mark the net->sent time here since
6762                                * this we use this for HB and retrans cannot measure
6763                                * RTT
6764                                */
6765                               /*      SCTP_GETTIME_TIMEVAL(&net->last_sent_time);*/
6766 
6767                               /* For auto-close */
6768                               cnt_thru++;
6769                               if (*now_filled == 0) {
6770                                         SCTP_GETTIME_TIMEVAL(&asoc->time_last_sent);
6771                                         *now = asoc->time_last_sent;
6772                                         *now_filled = 1;
6773                               } else {
6774                                         asoc->time_last_sent = *now;
6775                               }
6776                               *cnt_out += bundle_at;
6777 #ifdef SCTP_AUDITING_ENABLED
6778                               sctp_audit_log(0xC4, bundle_at);
6779 #endif
6780                               for (i = 0; i < bundle_at; i++) {
6781                                         sctp_pegs[SCTP_RETRANTSN_SENT]++;
6782                                         data_list[i]->sent = SCTP_DATAGRAM_SENT;
6783                                         data_list[i]->snd_count++;
6784                                         sctp_ucount_decr(asoc->sent_queue_retran_cnt);
6785                                         /* record the time */
6786                                         data_list[i]->sent_rcv_time = asoc->time_last_sent;
6787                                         net->flight_size += data_list[i]->book_size;
6788                                         asoc->total_flight += data_list[i]->book_size;
6789                                         asoc->total_flight_count++;
6790 
6791 #ifdef SCTP_LOG_RWND
6792                                         sctp_log_rwnd(SCTP_DECREASE_PEER_RWND,
6793                                                         asoc->peers_rwnd , data_list[i]->send_size, sctp_peer_chunk_oh);
6794 #endif
6795                                         asoc->peers_rwnd = sctp_sbspace_sub(asoc->peers_rwnd,
6796                                                                                     (u_int32_t)(data_list[i]->send_size + sctp_peer_chunk_oh));
6797                                         if (asoc->peers_rwnd < stcb->sctp_ep->sctp_ep.sctp_sws_sender) {
6798                                                   /* SWS sender side engages */
6799                                                   asoc->peers_rwnd = 0;
6800                                         }
6801 
6802                                         if ((i == 0) &&
6803                                             (data_list[i]->rec.data.doing_fast_retransmit)) {
6804                                                   sctp_pegs[SCTP_FAST_RETRAN]++;
6805                                                   if ((data_list[i] == TAILQ_FIRST(&asoc->sent_queue)) &&
6806                                                       (tmr_started == 0)) {
6807                                                             /*
6808                                                              * ok we just fast-retrans'd
6809                                                              * the lowest TSN, i.e the
6810                                                              * first on the list. In this
6811                                                              * case we want to give some
6812                                                              * more time to get a SACK
6813                                                              * back without a t3-expiring.
6814                                                              */
6815                                                             sctp_timer_stop(SCTP_TIMER_TYPE_SEND, inp, stcb, net);
6816                                                             sctp_timer_start(SCTP_TIMER_TYPE_SEND, inp, stcb, net);
6817                                                   }
6818                                         }
6819                               }
6820 #ifdef SCTP_AUDITING_ENABLED
6821                               sctp_auditing(21, inp, stcb, NULL);
6822 #endif
6823                     } else {
6824                               /* None will fit */
6825                               return (1);
6826                     }
6827                     if (asoc->sent_queue_retran_cnt <= 0) {
6828                               /* all done we have no more to retran */
6829                               asoc->sent_queue_retran_cnt = 0;
6830                               break;
6831                     }
6832                     if (one_chunk) {
6833                               /* No more room in rwnd */
6834                               return (1);
6835                     }
6836                     /* stop the for loop here. we sent out a packet */
6837                     break;
6838           }
6839           return (0);
6840 }
6841 
6842 
6843 static int
6844 sctp_timer_validation(struct sctp_inpcb *inp,
6845                           struct sctp_tcb *stcb,
6846                           struct sctp_association *asoc,
6847                           int ret)
6848 {
6849           struct sctp_nets *net;
6850           /* Validate that a timer is running somewhere */
6851           TAILQ_FOREACH(net, &asoc->nets, sctp_next) {
6852                     if (callout_pending(&net->rxt_timer.timer)) {
6853                               /* Here is a timer */
6854                               return (ret);
6855                     }
6856           }
6857           /* Gak, we did not have a timer somewhere */
6858 #ifdef SCTP_DEBUG
6859           if (sctp_debug_on & SCTP_DEBUG_OUTPUT3) {
6860                     printf("Deadlock avoided starting timer on a dest at retran\n");
6861           }
6862 #endif
6863           sctp_timer_start(SCTP_TIMER_TYPE_SEND, inp, stcb, asoc->primary_destination);
6864           return (ret);
6865 }
6866 
6867 int
6868 sctp_chunk_output(struct sctp_inpcb *inp,
6869                       struct sctp_tcb *stcb,
6870                       int from_where)
6871 {
6872           /* Ok this is the generic chunk service queue.
6873            * we must do the following:
6874            *  - See if there are retransmits pending, if so we
6875            *        must do these first and return.
6876            *  - Service the stream queue that is next,
6877            *    moving any message (note I must get a complete
6878            *    message i.e. FIRST/MIDDLE and LAST to the out
6879            *    queue in one pass) and assigning TSN's
6880            *  - Check to see if the cwnd/rwnd allows any output, if
6881            *        so we go ahead and fomulate and send the low level
6882            *    chunks. Making sure to combine any control in the
6883            *    control chunk queue also.
6884            */
6885           struct sctp_association *asoc;
6886           struct sctp_nets *net;
6887           int error, num_out, tot_out, ret, reason_code, burst_cnt, burst_limit;
6888           struct timeval now;
6889           int now_filled=0;
6890           int cwnd_full=0;
6891           asoc = &stcb->asoc;
6892           tot_out = 0;
6893           num_out = 0;
6894           reason_code = 0;
6895           sctp_pegs[SCTP_CALLS_TO_CO]++;
6896 #ifdef SCTP_DEBUG
6897           if (sctp_debug_on & SCTP_DEBUG_OUTPUT3) {
6898                     printf("in co - retran count:%d\n", asoc->sent_queue_retran_cnt);
6899           }
6900 #endif
6901           while (asoc->sent_queue_retran_cnt) {
6902                     /* Ok, it is retransmission time only, we send out only ONE
6903                      * packet with a single call off to the retran code.
6904                      */
6905                     ret = sctp_chunk_retransmission(inp, stcb, asoc, &num_out, &now, &now_filled);
6906                     if (ret > 0) {
6907                               /* Can't send anymore */
6908 #ifdef SCTP_DEBUG
6909                               if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
6910                                         printf("retransmission ret:%d -- full\n", ret);
6911                               }
6912 #endif
6913                               /*
6914                                * now lets push out control by calling med-level
6915                                * output once. this assures that we WILL send HB's
6916                                * if queued too.
6917                                */
6918                               (void)sctp_med_chunk_output(inp, stcb, asoc, &num_out, &reason_code, 1,
6919                                                                 &cwnd_full, from_where,
6920                                                                 &now, &now_filled);
6921 #ifdef SCTP_DEBUG
6922                               if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
6923                                         printf("Control send outputs:%d@full\n", num_out);
6924                               }
6925 #endif
6926 #ifdef SCTP_AUDITING_ENABLED
6927                               sctp_auditing(8, inp, stcb, NULL);
6928 #endif
6929                               return (sctp_timer_validation(inp, stcb, asoc, ret));
6930                     }
6931                     if (ret < 0) {
6932                               /*
6933                                * The count was off.. retran is not happening so do
6934                                * the normal retransmission.
6935                                */
6936 #ifdef SCTP_DEBUG
6937                               if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
6938                                         printf("Done with retrans, none left fill up window\n");
6939                               }
6940 #endif
6941 #ifdef SCTP_AUDITING_ENABLED
6942                               sctp_auditing(9, inp, stcb, NULL);
6943 #endif
6944                               break;
6945                     }
6946                     if (from_where == 1) {
6947                               /* Only one transmission allowed out of a timeout */
6948 #ifdef SCTP_DEBUG
6949                               if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
6950                                         printf("Only one packet allowed out\n");
6951                               }
6952 #endif
6953 #ifdef SCTP_AUDITING_ENABLED
6954                               sctp_auditing(10, inp, stcb, NULL);
6955 #endif
6956                               /* Push out any control */
6957                               (void)sctp_med_chunk_output(inp, stcb, asoc, &num_out, &reason_code, 1, &cwnd_full, from_where,
6958                                                                 &now, &now_filled);
6959                               return (ret);
6960                     }
6961                     if ((num_out == 0) && (ret == 0)) {
6962                               /* No more retrans to send */
6963                               break;
6964                     }
6965           }
6966 #ifdef SCTP_AUDITING_ENABLED
6967           sctp_auditing(12, inp, stcb, NULL);
6968 #endif
6969           /* Check for bad destinations, if they exist move chunks around. */
6970           burst_limit = asoc->max_burst;
6971           TAILQ_FOREACH(net, &asoc->nets, sctp_next) {
6972                     if ((net->dest_state & SCTP_ADDR_NOT_REACHABLE) ==
6973                         SCTP_ADDR_NOT_REACHABLE) {
6974                               /*
6975                                * if possible move things off of this address
6976                                * we still may send below due to the dormant state
6977                                * but we try to find an alternate address to send
6978                                * to and if we have one we move all queued data on
6979                                * the out wheel to this alternate address.
6980                                */
6981                               sctp_move_to_an_alt(stcb, asoc, net);
6982                     } else {
6983                               /*
6984                               if ((asoc->sat_network) || (net->addr_is_local)) {
6985                                         burst_limit = asoc->max_burst * SCTP_SAT_NETWORK_BURST_INCR;
6986                               }
6987                               */
6988 #ifdef SCTP_DEBUG
6989                               if (sctp_debug_on & SCTP_DEBUG_OUTPUT3) {
6990                                         printf("examined net:%p burst limit:%d\n", net, asoc->max_burst);
6991                               }
6992 #endif
6993 
6994 #ifdef SCTP_USE_ALLMAN_BURST
6995                               if ((net->flight_size+(burst_limit*net->mtu)) < net->cwnd) {
6996                                         if (net->ssthresh < net->cwnd)
6997                                                   net->ssthresh = net->cwnd;
6998                                         net->cwnd = (net->flight_size+(burst_limit*net->mtu));
6999 #ifdef SCTP_LOG_MAXBURST
7000                                         sctp_log_maxburst(net, 0, burst_limit, SCTP_MAX_BURST_APPLIED);
7001 #endif
7002                                         sctp_pegs[SCTP_MAX_BURST_APL]++;
7003                               }
7004                               net->fast_retran_ip = 0;
7005 #endif
7006                     }
7007 
7008           }
7009           /* Fill up what we can to the destination */
7010           burst_cnt = 0;
7011           cwnd_full = 0;
7012           do {
7013 #ifdef SCTP_DEBUG
7014                     if (sctp_debug_on & SCTP_DEBUG_OUTPUT3) {
7015                               printf("Burst count:%d - call m-c-o\n", burst_cnt);
7016                     }
7017 #endif
7018                     error = sctp_med_chunk_output(inp, stcb, asoc, &num_out,
7019                                                         &reason_code, 0,  &cwnd_full, from_where,
7020                                                         &now, &now_filled);
7021                     if (error) {
7022 #ifdef SCTP_DEBUG
7023                               if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
7024                                         printf("Error %d was returned from med-c-op\n", error);
7025                               }
7026 #endif
7027 #ifdef SCTP_LOG_MAXBURST
7028                               sctp_log_maxburst(asoc->primary_destination, error , burst_cnt, SCTP_MAX_BURST_ERROR_STOP);
7029 #endif
7030                               break;
7031                     }
7032 #ifdef SCTP_DEBUG
7033                     if (sctp_debug_on & SCTP_DEBUG_OUTPUT3) {
7034                               printf("m-c-o put out %d\n", num_out);
7035                     }
7036 #endif
7037                     tot_out += num_out;
7038                     burst_cnt++;
7039           } while (num_out
7040 #ifndef SCTP_USE_ALLMAN_BURST
7041                      &&  (burst_cnt < burst_limit)
7042 #endif
7043                     );
7044 #ifndef SCTP_USE_ALLMAN_BURST
7045           if (burst_cnt >= burst_limit) {
7046                     sctp_pegs[SCTP_MAX_BURST_APL]++;
7047                     asoc->burst_limit_applied = 1;
7048 #ifdef SCTP_LOG_MAXBURST
7049                     sctp_log_maxburst(asoc->primary_destination, 0 , burst_cnt, SCTP_MAX_BURST_APPLIED);
7050 #endif
7051           } else {
7052                     asoc->burst_limit_applied = 0;
7053           }
7054 #endif
7055 
7056 #ifdef SCTP_DEBUG
7057           if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
7058                     printf("Ok, we have put out %d chunks\n", tot_out);
7059           }
7060 #endif
7061           if (tot_out == 0) {
7062                     sctp_pegs[SCTP_CO_NODATASNT]++;
7063                     if (asoc->stream_queue_cnt > 0) {
7064                               sctp_pegs[SCTP_SOS_NOSNT]++;
7065                     } else {
7066                               sctp_pegs[SCTP_NOS_NOSNT]++;
7067                     }
7068                     if (asoc->send_queue_cnt > 0) {
7069                               sctp_pegs[SCTP_SOSE_NOSNT]++;
7070                     } else {
7071                               sctp_pegs[SCTP_NOSE_NOSNT]++;
7072                     }
7073           }
7074           /* Now we need to clean up the control chunk chain if
7075            * a ECNE is on it. It must be marked as UNSENT again
7076            * so next call will continue to send it until
7077            * such time that we get a CWR, to remove it.
7078            */
7079           sctp_fix_ecn_echo(asoc);
7080           return (error);
7081 }
7082 
7083 
7084 int
7085 sctp_output(struct sctp_inpcb *inp, struct mbuf *m,
7086      struct sockaddr *addr, struct mbuf *control, struct lwp *l, int flags)
7087 {
7088           struct sctp_inpcb *t_inp;
7089           struct sctp_tcb *stcb;
7090           struct sctp_nets *net;
7091           struct sctp_association *asoc;
7092           int create_lock_applied = 0;
7093           int queue_only, error = 0;
7094           struct sctp_sndrcvinfo srcv;
7095           int un_sent = 0;
7096           int use_rcvinfo = 0;
7097           t_inp = inp;
7098           /*  struct route ro;*/
7099 
7100           queue_only = 0;
7101           stcb = NULL;
7102           asoc = NULL;
7103           net = NULL;
7104 
7105 #ifdef SCTP_DEBUG
7106           if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
7107                     printf("USR Send BEGINS\n");
7108           }
7109 #endif
7110 
7111           if ((inp->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE) &&
7112               (inp->sctp_flags & SCTP_PCB_FLAGS_ACCEPTING)) {
7113                     /* The listner can NOT send */
7114                     if (control) {
7115                               sctppcbinfo.mbuf_track--;
7116                               sctp_m_freem(control);
7117                               control = NULL;
7118                     }
7119                     sctp_m_freem(m);
7120                     return (EFAULT);
7121           }
7122           /* Can't allow a V6 address on a non-v6 socket */
7123           if (addr) {
7124                     SCTP_ASOC_CREATE_LOCK(inp);
7125                     if ((inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE) ||
7126                         (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE)) {
7127                               /* Should I really unlock ? */
7128                               SCTP_ASOC_CREATE_UNLOCK(inp);
7129                               if (control) {
7130                                         sctppcbinfo.mbuf_track--;
7131                                         sctp_m_freem(control);
7132                                         control = NULL;
7133                               }
7134                               sctp_m_freem(m);
7135                               return (EFAULT);
7136                     }
7137                     create_lock_applied = 1;
7138                     if (((inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) == 0) &&
7139                         (addr->sa_family == AF_INET6)) {
7140                               SCTP_ASOC_CREATE_UNLOCK(inp);
7141                               if (control) {
7142                                         sctppcbinfo.mbuf_track--;
7143                                         sctp_m_freem(control);
7144                                         control = NULL;
7145                               }
7146                               sctp_m_freem(m);
7147                               return (EINVAL);
7148                     }
7149           }
7150           if (control) {
7151                     sctppcbinfo.mbuf_track++;
7152                     if (sctp_find_cmsg(SCTP_SNDRCV, (void *)&srcv, control,
7153                                            sizeof(srcv))) {
7154                               if (srcv.sinfo_flags & SCTP_SENDALL) {
7155                                         /* its a sendall */
7156                                         sctppcbinfo.mbuf_track--;
7157                                         sctp_m_freem(control);
7158                                         if (create_lock_applied) {
7159                                                   SCTP_ASOC_CREATE_UNLOCK(inp);
7160                                                   create_lock_applied = 0;
7161                                         }
7162                                         return (sctp_sendall(inp, NULL, m, &srcv));
7163                               }
7164                               if (srcv.sinfo_assoc_id) {
7165                                         if (inp->sctp_flags & SCTP_PCB_FLAGS_CONNECTED) {
7166                                                   SCTP_INP_RLOCK(inp);
7167                                                   stcb = LIST_FIRST(&inp->sctp_asoc_list);
7168                                                   if (stcb) {
7169                                                             SCTP_TCB_LOCK(stcb);
7170                                                   }
7171                                                   SCTP_INP_RUNLOCK(inp);
7172 
7173                                                   if (stcb == NULL) {
7174                                                             if (create_lock_applied) {
7175                                                                       SCTP_ASOC_CREATE_UNLOCK(inp);
7176                                                                       create_lock_applied = 0;
7177                                                             }
7178                                                             sctppcbinfo.mbuf_track--;
7179                                                             sctp_m_freem(control);
7180                                                             sctp_m_freem(m);
7181                                                             return (ENOTCONN);
7182                                                   }
7183                                                   net = stcb->asoc.primary_destination;
7184                                         } else {
7185                                                   stcb = sctp_findassociation_ep_asocid(inp, srcv.sinfo_assoc_id);
7186                                         }
7187                                         /*
7188                                          * Question: Should I error here if the
7189 
7190                                          * assoc_id is no longer valid?
7191                                          * i.e. I can't find it?
7192                                          */
7193                                         if ((stcb) &&
7194                                             (addr != NULL)) {
7195                                                   /* Must locate the net structure */
7196                                                   if (addr)
7197                                                             net = sctp_findnet(stcb, addr);
7198                                         }
7199                                         if (net == NULL)
7200                                                   net = stcb->asoc.primary_destination;
7201                               }
7202                               use_rcvinfo = 1;
7203                     }
7204           }
7205           if (stcb == NULL) {
7206                     if (inp->sctp_flags & SCTP_PCB_FLAGS_CONNECTED) {
7207                               SCTP_INP_RLOCK(inp);
7208                               stcb = LIST_FIRST(&inp->sctp_asoc_list);
7209                               if (stcb) {
7210                                         SCTP_TCB_LOCK(stcb);
7211                               }
7212                               SCTP_INP_RUNLOCK(inp);
7213                               if (stcb == NULL) {
7214                                         if (create_lock_applied) {
7215                                                   SCTP_ASOC_CREATE_UNLOCK(inp);
7216                                                   create_lock_applied = 0;
7217                                         }
7218                                         if (control) {
7219                                                   sctppcbinfo.mbuf_track--;
7220                                                   sctp_m_freem(control);
7221                                                   control = NULL;
7222                                         }
7223                                         sctp_m_freem(m);
7224                                         return (ENOTCONN);
7225                               }
7226                               if (addr == NULL) {
7227                                         net = stcb->asoc.primary_destination;
7228                               } else {
7229                                         net = sctp_findnet(stcb, addr);
7230                                         if (net == NULL) {
7231                                                   net = stcb->asoc.primary_destination;
7232                                         }
7233                               }
7234                     } else {
7235                               if (addr != NULL) {
7236                                         SCTP_INP_WLOCK(inp);
7237                                         SCTP_INP_INCR_REF(inp);
7238                                         SCTP_INP_WUNLOCK(inp);
7239                                         stcb = sctp_findassociation_ep_addr(&t_inp, addr, &net, NULL, NULL);
7240                                         if (stcb == NULL) {
7241                                                   SCTP_INP_WLOCK(inp);
7242                                                   SCTP_INP_DECR_REF(inp);
7243                                                   SCTP_INP_WUNLOCK(inp);
7244                                         }
7245                               }
7246                     }
7247           }
7248           if ((stcb == NULL) &&
7249               (inp->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE)) {
7250                     if (control) {
7251                               sctppcbinfo.mbuf_track--;
7252                               sctp_m_freem(control);
7253                               control = NULL;
7254                     }
7255                     if (create_lock_applied) {
7256                               SCTP_ASOC_CREATE_UNLOCK(inp);
7257                               create_lock_applied = 0;
7258                     }
7259                     sctp_m_freem(m);
7260                     return (ENOTCONN);
7261           } else if ((stcb == NULL) &&
7262                        (addr == NULL)) {
7263                     if (control) {
7264                               sctppcbinfo.mbuf_track--;
7265                               sctp_m_freem(control);
7266                               control = NULL;
7267                     }
7268                     if (create_lock_applied) {
7269                               SCTP_ASOC_CREATE_UNLOCK(inp);
7270                               create_lock_applied = 0;
7271                     }
7272                     sctp_m_freem(m);
7273                     return (ENOENT);
7274           } else if (stcb == NULL) {
7275                     /* UDP mode, we must go ahead and start the INIT process */
7276                     if ((use_rcvinfo) && (srcv.sinfo_flags & SCTP_ABORT)) {
7277                               /* Strange user to do this */
7278                               if (control) {
7279                                         sctppcbinfo.mbuf_track--;
7280                                         sctp_m_freem(control);
7281                                         control = NULL;
7282                               }
7283                               if (create_lock_applied) {
7284                                         SCTP_ASOC_CREATE_UNLOCK(inp);
7285                                         create_lock_applied = 0;
7286                               }
7287                               sctp_m_freem(m);
7288                               return (ENOENT);
7289                     }
7290                     stcb = sctp_aloc_assoc(inp, addr, 1, &error, 0);
7291                     if (stcb == NULL) {
7292                               if (control) {
7293                                         sctppcbinfo.mbuf_track--;
7294                                         sctp_m_freem(control);
7295                                         control = NULL;
7296                               }
7297                               if (create_lock_applied) {
7298                                         SCTP_ASOC_CREATE_UNLOCK(inp);
7299                                         create_lock_applied = 0;
7300                               }
7301                               sctp_m_freem(m);
7302                               return (error);
7303                     }
7304                     if (create_lock_applied) {
7305                               SCTP_ASOC_CREATE_UNLOCK(inp);
7306                               create_lock_applied = 0;
7307                     } else {
7308                               printf("Huh-1, create lock should have been applied!\n");
7309                     }
7310                     queue_only = 1;
7311                     asoc = &stcb->asoc;
7312                     asoc->state = SCTP_STATE_COOKIE_WAIT;
7313                     SCTP_GETTIME_TIMEVAL(&asoc->time_entered);
7314                     if (control) {
7315                               /* see if a init structure exists in cmsg headers */
7316                               struct sctp_initmsg initm;
7317                               int i;
7318                               if (sctp_find_cmsg(SCTP_INIT, (void *)&initm, control,
7319                                                      sizeof(initm))) {
7320                                         /* we have an INIT override of the default */
7321                                         if (initm.sinit_max_attempts)
7322                                                   asoc->max_init_times = initm.sinit_max_attempts;
7323                                         if (initm.sinit_num_ostreams)
7324                                                   asoc->pre_open_streams = initm.sinit_num_ostreams;
7325                                         if (initm.sinit_max_instreams)
7326                                                   asoc->max_inbound_streams = initm.sinit_max_instreams;
7327                                         if (initm.sinit_max_init_timeo)
7328                                                   asoc->initial_init_rto_max = initm.sinit_max_init_timeo;
7329                               }
7330                               if (asoc->streamoutcnt < asoc->pre_open_streams) {
7331                                         /* Default is NOT correct */
7332 #ifdef SCTP_DEBUG
7333                                         if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
7334                                                   printf("Ok, defout:%d pre_open:%d\n",
7335                                                          asoc->streamoutcnt, asoc->pre_open_streams);
7336                                         }
7337 #endif
7338                                         free(asoc->strmout, M_PCB);
7339                                         asoc->strmout = NULL;
7340                                         asoc->streamoutcnt = asoc->pre_open_streams;
7341                                         asoc->strmout = malloc(asoc->streamoutcnt *
7342                                                sizeof(struct sctp_stream_out), M_PCB,
7343                                                M_WAIT);
7344                                         for (i = 0; i < asoc->streamoutcnt; i++) {
7345                                                   /*
7346                                                    * inbound side must be set to 0xffff,
7347                                                    * also NOTE when we get the INIT-ACK
7348                                                    * back (for INIT sender) we MUST
7349                                                    * reduce the count (streamoutcnt) but
7350                                                    * first check if we sent to any of the
7351                                                    * upper streams that were dropped (if
7352                                                    * some were). Those that were dropped
7353                                                    * must be notified to the upper layer
7354                                                    * as failed to send.
7355                                                    */
7356                                                   asoc->strmout[i].next_sequence_sent = 0x0;
7357                                                   TAILQ_INIT(&asoc->strmout[i].outqueue);
7358                                                   asoc->strmout[i].stream_no = i;
7359                                                   asoc->strmout[i].next_spoke.tqe_next = 0;
7360                                                   asoc->strmout[i].next_spoke.tqe_prev = 0;
7361                                         }
7362                               }
7363                     }
7364                     sctp_send_initiate(inp, stcb);
7365                     /*
7366                      * we may want to dig in after this call and adjust the MTU
7367                      * value. It defaulted to 1500 (constant) but the ro structure
7368                      * may now have an update and thus we may need to change it
7369                      * BEFORE we append the message.
7370                      */
7371                     net = stcb->asoc.primary_destination;
7372           } else {
7373                     if (create_lock_applied) {
7374                               SCTP_ASOC_CREATE_UNLOCK(inp);
7375                               create_lock_applied = 0;
7376                     }
7377                     asoc = &stcb->asoc;
7378                     if ((SCTP_GET_STATE(asoc) == SCTP_STATE_COOKIE_WAIT) ||
7379                         (SCTP_GET_STATE(asoc) == SCTP_STATE_COOKIE_ECHOED)) {
7380                               queue_only = 1;
7381                     }
7382                     if ((SCTP_GET_STATE(asoc) == SCTP_STATE_SHUTDOWN_SENT) ||
7383                         (SCTP_GET_STATE(asoc) == SCTP_STATE_SHUTDOWN_RECEIVED) ||
7384                         (SCTP_GET_STATE(asoc) == SCTP_STATE_SHUTDOWN_ACK_SENT) ||
7385                         (asoc->state & SCTP_STATE_SHUTDOWN_PENDING)) {
7386                               if (control) {
7387                                         sctppcbinfo.mbuf_track--;
7388                                         sctp_m_freem(control);
7389                                         control = NULL;
7390                               }
7391                               if ((use_rcvinfo) &&
7392                                   (srcv.sinfo_flags & SCTP_ABORT)) {
7393                                         sctp_msg_append(stcb, net, m, &srcv, flags);
7394                                         error = 0;
7395                               } else {
7396                                         sctp_m_freem(m);
7397                                         error = ECONNRESET;
7398                               }
7399                               SCTP_TCB_UNLOCK(stcb);
7400                               return (error);
7401                     }
7402           }
7403           if (create_lock_applied) {
7404                     /* we should never hit here with the create lock applied
7405                      *
7406                      */
7407                     SCTP_ASOC_CREATE_UNLOCK(inp);
7408                     create_lock_applied = 0;
7409           }
7410 
7411 
7412           if (use_rcvinfo == 0) {
7413                     srcv = stcb->asoc.def_send;
7414           }
7415 #ifdef SCTP_DEBUG
7416           else {
7417                     if (sctp_debug_on & SCTP_DEBUG_OUTPUT5) {
7418                               printf("stream:%d\n", srcv.sinfo_stream);
7419                               printf("flags:%x\n", (u_int)srcv.sinfo_flags);
7420                               printf("ppid:%d\n", srcv.sinfo_ppid);
7421                               printf("context:%d\n", srcv.sinfo_context);
7422                     }
7423           }
7424 #endif
7425           if (control) {
7426                     sctppcbinfo.mbuf_track--;
7427                     sctp_m_freem(control);
7428                     control = NULL;
7429           }
7430           if (net && ((srcv.sinfo_flags & SCTP_ADDR_OVER))) {
7431                     /* we take the override or the unconfirmed */
7432                     ;
7433           } else {
7434                     net = stcb->asoc.primary_destination;
7435           }
7436           if ((error = sctp_msg_append(stcb, net, m, &srcv, flags))) {
7437                     SCTP_TCB_UNLOCK(stcb);
7438                     return (error);
7439           }
7440           if (net->flight_size > net->cwnd) {
7441                     sctp_pegs[SCTP_SENDTO_FULL_CWND]++;
7442                     queue_only = 1;
7443           } else if (asoc->ifp_had_enobuf) {
7444                     sctp_pegs[SCTP_QUEONLY_BURSTLMT]++;
7445                     queue_only = 1;
7446           } else {
7447                     un_sent = ((stcb->asoc.total_output_queue_size - stcb->asoc.total_flight) +
7448                                  ((stcb->asoc.chunks_on_out_queue - stcb->asoc.total_flight_count) * sizeof(struct sctp_data_chunk)) +
7449                                  SCTP_MED_OVERHEAD);
7450 
7451                     if (((inp->sctp_flags & SCTP_PCB_FLAGS_NODELAY) == 0) &&
7452                         (stcb->asoc.total_flight > 0) &&
7453                         (un_sent < (int)stcb->asoc.smallest_mtu)
7454                               ) {
7455 
7456                               /* Ok, Nagle is set on and we have
7457                                * data outstanding. Don't send anything
7458                                * and let the SACK drive out the data.
7459                                */
7460                               sctp_pegs[SCTP_NAGLE_NOQ]++;
7461                               queue_only = 1;
7462                     } else {
7463                               sctp_pegs[SCTP_NAGLE_OFF]++;
7464                     }
7465           }
7466           if ((queue_only == 0) && stcb->asoc.peers_rwnd) {
7467                     /* we can attempt to send too.*/
7468 #ifdef SCTP_DEBUG
7469                     if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
7470                               printf("USR Send calls sctp_chunk_output\n");
7471                     }
7472 #endif
7473 #ifdef SCTP_AUDITING_ENABLED
7474                     sctp_audit_log(0xC0, 1);
7475                     sctp_auditing(6, inp, stcb, net);
7476 #endif
7477                     sctp_pegs[SCTP_OUTPUT_FRM_SND]++;
7478                     sctp_chunk_output(inp, stcb, 0);
7479 #ifdef SCTP_AUDITING_ENABLED
7480                     sctp_audit_log(0xC0, 2);
7481                     sctp_auditing(7, inp, stcb, net);
7482 #endif
7483 
7484           }
7485 #ifdef SCTP_DEBUG
7486           if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
7487                     printf("USR Send complete qo:%d prw:%d\n", queue_only, stcb->asoc.peers_rwnd);
7488           }
7489 #endif
7490           SCTP_TCB_UNLOCK(stcb);
7491           return (0);
7492 }
7493 
7494 void
7495 send_forward_tsn(struct sctp_tcb *stcb,
7496                      struct sctp_association *asoc)
7497 {
7498           struct sctp_tmit_chunk *chk;
7499           struct sctp_forward_tsn_chunk *fwdtsn;
7500 
7501           TAILQ_FOREACH(chk, &asoc->control_send_queue, sctp_next) {
7502                     if (chk->rec.chunk_id == SCTP_FORWARD_CUM_TSN) {
7503                               /* mark it to unsent */
7504                               chk->sent = SCTP_DATAGRAM_UNSENT;
7505                               chk->snd_count = 0;
7506                               /* Do we correct its output location? */
7507                               if (chk->whoTo != asoc->primary_destination) {
7508                                         sctp_free_remote_addr(chk->whoTo);
7509                                         chk->whoTo = asoc->primary_destination;
7510                                         chk->whoTo->ref_count++;
7511                               }
7512                               goto sctp_fill_in_rest;
7513                     }
7514           }
7515           /* Ok if we reach here we must build one */
7516           chk = (struct sctp_tmit_chunk *)SCTP_ZONE_GET(sctppcbinfo.ipi_zone_chunk);
7517           if (chk == NULL) {
7518                     return;
7519           }
7520           sctppcbinfo.ipi_count_chunk++;
7521           sctppcbinfo.ipi_gencnt_chunk++;
7522           chk->rec.chunk_id = SCTP_FORWARD_CUM_TSN;
7523           chk->asoc = asoc;
7524           MGETHDR(chk->data, M_DONTWAIT, MT_DATA);
7525           if (chk->data == NULL) {
7526                     chk->whoTo->ref_count--;
7527                     SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_chunk, chk);
7528                     sctppcbinfo.ipi_count_chunk--;
7529                     if ((int)sctppcbinfo.ipi_count_chunk < 0) {
7530                               panic("Chunk count is negative");
7531                     }
7532                     sctppcbinfo.ipi_gencnt_chunk++;
7533                     return;
7534           }
7535           chk->data->m_data += SCTP_MIN_OVERHEAD;
7536           chk->sent = SCTP_DATAGRAM_UNSENT;
7537           chk->snd_count = 0;
7538           chk->whoTo = asoc->primary_destination;
7539           chk->whoTo->ref_count++;
7540           TAILQ_INSERT_TAIL(&asoc->control_send_queue, chk, sctp_next);
7541           asoc->ctrl_queue_cnt++;
7542  sctp_fill_in_rest:
7543           /* Here we go through and fill out the part that
7544            * deals with stream/seq of the ones we skip.
7545            */
7546           chk->data->m_pkthdr.len = chk->data->m_len = 0;
7547           {
7548                     struct sctp_tmit_chunk *at, *tp1, *last;
7549                     struct sctp_strseq *strseq;
7550                     unsigned int cnt_of_space, i, ovh;
7551                     unsigned int space_needed;
7552                     unsigned int cnt_of_skipped = 0;
7553                     TAILQ_FOREACH(at, &asoc->sent_queue, sctp_next) {
7554                               if (at->sent != SCTP_FORWARD_TSN_SKIP) {
7555                                         /* no more to look at */
7556                                         break;
7557                               }
7558                               if (at->rec.data.rcv_flags & SCTP_DATA_UNORDERED) {
7559                                         /* We don't report these */
7560                                         continue;
7561                               }
7562                               cnt_of_skipped++;
7563                     }
7564                     space_needed = (sizeof(struct sctp_forward_tsn_chunk) +
7565                                         (cnt_of_skipped * sizeof(struct sctp_strseq)));
7566                     if ((M_TRAILINGSPACE(chk->data) < (int)space_needed) &&
7567                         ((chk->data->m_flags & M_EXT) == 0)) {
7568                               /* Need a M_EXT, get one and move
7569                                * fwdtsn to data area.
7570                                */
7571                               MCLGET(chk->data, M_DONTWAIT);
7572                     }
7573                     cnt_of_space = M_TRAILINGSPACE(chk->data);
7574 
7575                     if (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) {
7576                               ovh = SCTP_MIN_OVERHEAD;
7577                     } else {
7578                               ovh = SCTP_MIN_V4_OVERHEAD;
7579                     }
7580                     if (cnt_of_space > (asoc->smallest_mtu-ovh)) {
7581                               /* trim to a mtu size */
7582                               cnt_of_space = asoc->smallest_mtu - ovh;
7583                     }
7584                     if (cnt_of_space < space_needed) {
7585                               /* ok we must trim down the chunk by lowering
7586                                * the advance peer ack point.
7587                                */
7588                               cnt_of_skipped = (cnt_of_space-
7589                                                     ((sizeof(struct sctp_forward_tsn_chunk))/
7590                                                       sizeof(struct sctp_strseq)));
7591                               /* Go through and find the TSN that
7592                                * will be the one we report.
7593                                */
7594                               at = TAILQ_FIRST(&asoc->sent_queue);
7595                               for (i = 0; i < cnt_of_skipped; i++) {
7596                                         tp1 = TAILQ_NEXT(at, sctp_next);
7597                                         at = tp1;
7598                               }
7599                               last = at;
7600                               /* last now points to last one I can report, update peer ack point */
7601                               asoc->advanced_peer_ack_point = last->rec.data.TSN_seq;
7602                               space_needed -= (cnt_of_skipped * sizeof(struct sctp_strseq));
7603                     }
7604                     chk->send_size = space_needed;
7605                     /* Setup the chunk */
7606                     fwdtsn = mtod(chk->data, struct sctp_forward_tsn_chunk *);
7607                     fwdtsn->ch.chunk_length = htons(chk->send_size);
7608                     fwdtsn->ch.chunk_flags = 0;
7609                     fwdtsn->ch.chunk_type = SCTP_FORWARD_CUM_TSN;
7610                     fwdtsn->new_cumulative_tsn = htonl(asoc->advanced_peer_ack_point);
7611                     chk->send_size = (sizeof(struct sctp_forward_tsn_chunk) +
7612                                           (cnt_of_skipped * sizeof(struct sctp_strseq)));
7613                     chk->data->m_pkthdr.len = chk->data->m_len = chk->send_size;
7614                     fwdtsn++;
7615                     /* Move pointer to after the fwdtsn and transfer to
7616                      * the strseq pointer.
7617                      */
7618                     strseq = (struct sctp_strseq *)fwdtsn;
7619                     /*
7620                      * Now populate the strseq list. This is done blindly
7621                      * without pulling out duplicate stream info. This is
7622                      * inefficent but won't harm the process since the peer
7623                      * will look at these in sequence and will thus release
7624                      * anything. It could mean we exceed the PMTU and chop
7625                      * off some that we could have included.. but this is
7626                      * unlikely (aka 1432/4 would mean 300+ stream seq's would
7627                      * have to be reported in one FWD-TSN. With a bit of work
7628                      * we can later FIX this to optimize and pull out duplicates..
7629                      * but it does add more overhead. So for now... not!
7630                      */
7631                     at = TAILQ_FIRST(&asoc->sent_queue);
7632                     for (i = 0; i < cnt_of_skipped; i++) {
7633                               tp1 = TAILQ_NEXT(at, sctp_next);
7634                               if (at->rec.data.rcv_flags & SCTP_DATA_UNORDERED) {
7635                                         /* We don't report these */
7636                                         i--;
7637                                         at = tp1;
7638                                         continue;
7639                               }
7640                               strseq->stream = ntohs(at->rec.data.stream_number);
7641                               strseq->sequence = ntohs(at->rec.data.stream_seq);
7642                               strseq++;
7643                               at = tp1;
7644                     }
7645           }
7646           return;
7647 
7648 }
7649 
7650 void
7651 sctp_send_sack(struct sctp_tcb *stcb)
7652 {
7653           /*
7654            * Queue up a SACK in the control queue. We must first check to
7655            * see if a SACK is somehow on the control queue. If so, we will
7656            * take and remove the old one.
7657            */
7658           struct sctp_association *asoc;
7659           struct sctp_tmit_chunk *chk, *a_chk;
7660           struct sctp_sack_chunk *sack;
7661           struct sctp_gap_ack_block *gap_descriptor;
7662           uint32_t *dup;
7663           int start;
7664           unsigned int i, maxi, seeing_ones, m_size;
7665           unsigned int num_gap_blocks, space;
7666 
7667           start = maxi = 0;
7668           seeing_ones = 1;
7669           a_chk = NULL;
7670           asoc = &stcb->asoc;
7671           if (asoc->last_data_chunk_from == NULL) {
7672                     /* Hmm we never received anything */
7673                     return;
7674           }
7675           sctp_set_rwnd(stcb, asoc);
7676           TAILQ_FOREACH(chk, &asoc->control_send_queue, sctp_next) {
7677                     if (chk->rec.chunk_id == SCTP_SELECTIVE_ACK) {
7678                               /* Hmm, found a sack already on queue, remove it */
7679                               TAILQ_REMOVE(&asoc->control_send_queue, chk, sctp_next);
7680                               asoc->ctrl_queue_cnt++;
7681                               a_chk = chk;
7682                               sctp_m_freem(a_chk->data);
7683                               a_chk->data = NULL;
7684                               sctp_free_remote_addr(a_chk->whoTo);
7685                               a_chk->whoTo = NULL;
7686                               break;
7687                     }
7688           }
7689           if (a_chk == NULL) {
7690                     a_chk = (struct sctp_tmit_chunk *)SCTP_ZONE_GET(sctppcbinfo.ipi_zone_chunk);
7691                     if (a_chk == NULL) {
7692                               /* No memory so we drop the idea, and set a timer */
7693                               sctp_timer_stop(SCTP_TIMER_TYPE_RECV,
7694                                                   stcb->sctp_ep, stcb, NULL);
7695                               sctp_timer_start(SCTP_TIMER_TYPE_RECV,
7696                                                    stcb->sctp_ep, stcb, NULL);
7697                               return;
7698                     }
7699                     sctppcbinfo.ipi_count_chunk++;
7700                     sctppcbinfo.ipi_gencnt_chunk++;
7701                     a_chk->rec.chunk_id = SCTP_SELECTIVE_ACK;
7702           }
7703           a_chk->asoc = asoc;
7704           a_chk->snd_count = 0;
7705           a_chk->send_size = 0;         /* fill in later */
7706           a_chk->sent = SCTP_DATAGRAM_UNSENT;
7707           m_size = (asoc->mapping_array_size << 3);
7708 
7709           if ((asoc->numduptsns) ||
7710               (asoc->last_data_chunk_from->dest_state & SCTP_ADDR_NOT_REACHABLE)
7711                     ) {
7712                     /* Ok, we have some duplicates or the destination for the
7713                      * sack is unreachable, lets see if we can select an alternate
7714                      * than asoc->last_data_chunk_from
7715                      */
7716                     if ((!(asoc->last_data_chunk_from->dest_state &
7717                           SCTP_ADDR_NOT_REACHABLE)) &&
7718                         (asoc->used_alt_onsack > 2)) {
7719                               /* We used an alt last time, don't this time */
7720                               a_chk->whoTo = NULL;
7721                     } else {
7722                               asoc->used_alt_onsack++;
7723                               a_chk->whoTo = sctp_find_alternate_net(stcb, asoc->last_data_chunk_from);
7724                     }
7725                     if (a_chk->whoTo == NULL) {
7726                               /* Nope, no alternate */
7727                               a_chk->whoTo = asoc->last_data_chunk_from;
7728                               asoc->used_alt_onsack = 0;
7729                     }
7730           } else {
7731                     /* No duplicates so we use the last
7732                      * place we received data from.
7733                      */
7734 #ifdef SCTP_DEBUG
7735                     if (asoc->last_data_chunk_from == NULL) {
7736                               printf("Huh, last_data_chunk_from is null when we want to sack??\n");
7737                     }
7738 #endif
7739                     asoc->used_alt_onsack = 0;
7740                     a_chk->whoTo = asoc->last_data_chunk_from;
7741           }
7742           if (a_chk->whoTo)
7743                     a_chk->whoTo->ref_count++;
7744 
7745           /* Ok now lets formulate a MBUF with our sack */
7746           MGETHDR(a_chk->data, M_DONTWAIT, MT_DATA);
7747           if ((a_chk->data == NULL) ||
7748               (a_chk->whoTo == NULL)) {
7749                     /* rats, no mbuf memory */
7750                     if (a_chk->data) {
7751                               /* was a problem with the destination */
7752                               sctp_m_freem(a_chk->data);
7753                               a_chk->data = NULL;
7754                     }
7755                     a_chk->whoTo->ref_count--;
7756                     SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_chunk, a_chk);
7757                     sctppcbinfo.ipi_count_chunk--;
7758                     if ((int)sctppcbinfo.ipi_count_chunk < 0) {
7759                               panic("Chunk count is negative");
7760                     }
7761                     sctppcbinfo.ipi_gencnt_chunk++;
7762                     sctp_timer_stop(SCTP_TIMER_TYPE_RECV,
7763                                         stcb->sctp_ep, stcb, NULL);
7764                     sctp_timer_start(SCTP_TIMER_TYPE_RECV,
7765                                          stcb->sctp_ep, stcb, NULL);
7766                     return;
7767           }
7768           /* First count the number of gap ack blocks we need */
7769           if (asoc->highest_tsn_inside_map == asoc->cumulative_tsn) {
7770                     /* We know if there are none above the cum-ack we
7771                      * have everything with NO gaps
7772                      */
7773                     num_gap_blocks = 0;
7774           } else {
7775                     /* Ok we must count how many gaps we
7776                      * have.
7777                      */
7778                     num_gap_blocks = 0;
7779                     if (asoc->highest_tsn_inside_map >= asoc->mapping_array_base_tsn) {
7780                               maxi = (asoc->highest_tsn_inside_map - asoc->mapping_array_base_tsn);
7781                     } else {
7782                               maxi = (asoc->highest_tsn_inside_map  + (MAX_TSN - asoc->mapping_array_base_tsn) + 1);
7783                     }
7784                     if (maxi > m_size) {
7785                               /* impossible but who knows, someone is playing with us  :> */
7786 #ifdef SCTP_DEBUG
7787                               printf("GAK maxi:%d  > m_size:%d came out higher than allowed htsn:%u base:%u cumack:%u\n",
7788                                      maxi,
7789                                      m_size,
7790                                      asoc->highest_tsn_inside_map,
7791                                      asoc->mapping_array_base_tsn,
7792                                      asoc->cumulative_tsn
7793                                      );
7794 #endif
7795                               num_gap_blocks = 0;
7796                               goto no_gaps_now;
7797                     }
7798                     if (asoc->cumulative_tsn >= asoc->mapping_array_base_tsn) {
7799                               start = (asoc->cumulative_tsn - asoc->mapping_array_base_tsn);
7800                     } else {
7801                               /* Set it so we start at 0 */
7802                               start = -1;
7803                     }
7804                     /* Ok move start up one to look at the NEXT past the cum-ack */
7805                     start++;
7806                     for (i = start; i <= maxi; i++) {
7807                               if (seeing_ones) {
7808                                         /* while seeing ones I must
7809                                          * transition back to 0 before
7810                                          * finding the next gap and
7811                                          * counting the segment.
7812                                          */
7813                                         if (SCTP_IS_TSN_PRESENT(asoc->mapping_array, i) == 0) {
7814                                                   seeing_ones = 0;
7815                                         }
7816                               } else {
7817                                         if (SCTP_IS_TSN_PRESENT(asoc->mapping_array, i)) {
7818                                                   seeing_ones = 1;
7819                                                   num_gap_blocks++;
7820                                         }
7821                               }
7822                     }
7823           no_gaps_now:
7824                     if (num_gap_blocks == 0) {
7825                               /*
7826                                * Traveled all of the bits and NO one,
7827                                * must have reneged
7828                                */
7829                               if (compare_with_wrap(asoc->cumulative_tsn, asoc->highest_tsn_inside_map, MAX_TSN)) {
7830                                  asoc->highest_tsn_inside_map = asoc->cumulative_tsn;
7831 #ifdef SCTP_MAP_LOGGING
7832                                  sctp_log_map(0, 4, asoc->highest_tsn_inside_map, SCTP_MAP_SLIDE_RESULT);
7833 #endif
7834                               }
7835                     }
7836           }
7837 
7838           /* Now calculate the space needed */
7839           space = (sizeof(struct sctp_sack_chunk) +
7840                      (num_gap_blocks * sizeof(struct sctp_gap_ack_block)) +
7841                      (asoc->numduptsns * sizeof(int32_t))
7842                     );
7843           if (space > (asoc->smallest_mtu-SCTP_MAX_OVERHEAD)) {
7844                     /* Reduce the size of the sack to fit */
7845                     int calc, fit;
7846                     calc = (asoc->smallest_mtu - SCTP_MAX_OVERHEAD);
7847                     calc -= sizeof(struct sctp_gap_ack_block);
7848                     fit = calc/sizeof(struct sctp_gap_ack_block);
7849                     if (fit > (int)num_gap_blocks) {
7850                               /* discard some dups */
7851                               asoc->numduptsns = (fit - num_gap_blocks);
7852                     } else {
7853                               /* discard all dups and some gaps */
7854                               num_gap_blocks = fit;
7855                               asoc->numduptsns = 0;
7856                     }
7857                     /* recalc space */
7858                     space = (sizeof(struct sctp_sack_chunk) +
7859                                (num_gap_blocks * sizeof(struct sctp_gap_ack_block)) +
7860                                (asoc->numduptsns * sizeof(int32_t))
7861                               );
7862 
7863           }
7864 
7865           if ((space+SCTP_MIN_OVERHEAD) > MHLEN) {
7866                     /* We need a cluster */
7867                     MCLGET(a_chk->data, M_DONTWAIT);
7868                     if ((a_chk->data->m_flags & M_EXT) != M_EXT) {
7869                               /* can't get a cluster
7870                                * give up and try later.
7871                                */
7872                               sctp_m_freem(a_chk->data);
7873                               a_chk->data = NULL;
7874                               a_chk->whoTo->ref_count--;
7875                               SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_chunk, a_chk);
7876                               sctppcbinfo.ipi_count_chunk--;
7877                               if ((int)sctppcbinfo.ipi_count_chunk < 0) {
7878                                         panic("Chunk count is negative");
7879                               }
7880                               sctppcbinfo.ipi_gencnt_chunk++;
7881                               sctp_timer_stop(SCTP_TIMER_TYPE_RECV,
7882                                                   stcb->sctp_ep, stcb, NULL);
7883                               sctp_timer_start(SCTP_TIMER_TYPE_RECV,
7884                                                    stcb->sctp_ep, stcb, NULL);
7885                               return;
7886                     }
7887           }
7888 
7889           /* ok, lets go through and fill it in */
7890           a_chk->data->m_data += SCTP_MIN_OVERHEAD;
7891           sack = mtod(a_chk->data, struct sctp_sack_chunk *);
7892           sack->ch.chunk_type = SCTP_SELECTIVE_ACK;
7893           sack->ch.chunk_flags = asoc->receiver_nonce_sum & SCTP_SACK_NONCE_SUM;
7894           sack->sack.cum_tsn_ack = htonl(asoc->cumulative_tsn);
7895           sack->sack.a_rwnd = htonl(asoc->my_rwnd);
7896           asoc->my_last_reported_rwnd = asoc->my_rwnd;
7897           sack->sack.num_gap_ack_blks = htons(num_gap_blocks);
7898           sack->sack.num_dup_tsns = htons(asoc->numduptsns);
7899 
7900           a_chk->send_size = (sizeof(struct sctp_sack_chunk) +
7901                                   (num_gap_blocks * sizeof(struct sctp_gap_ack_block)) +
7902                                   (asoc->numduptsns * sizeof(int32_t)));
7903           a_chk->data->m_pkthdr.len = a_chk->data->m_len = a_chk->send_size;
7904           sack->ch.chunk_length = htons(a_chk->send_size);
7905 
7906           gap_descriptor = (struct sctp_gap_ack_block *)((vaddr_t)sack + sizeof(struct sctp_sack_chunk));
7907           seeing_ones = 0;
7908           for (i = start; i <= maxi; i++) {
7909                     if (num_gap_blocks == 0) {
7910                               break;
7911                     }
7912                     if (seeing_ones) {
7913                               /* while seeing Ones I must
7914                                * transition back to 0 before
7915                                * finding the next gap
7916                                */
7917                               if (SCTP_IS_TSN_PRESENT(asoc->mapping_array, i) == 0) {
7918                                         gap_descriptor->end = htons(((uint16_t)(i-start)));
7919                                         gap_descriptor++;
7920                                         seeing_ones = 0;
7921                                         num_gap_blocks--;
7922                               }
7923                     } else {
7924                               if (SCTP_IS_TSN_PRESENT(asoc->mapping_array, i)) {
7925                                         gap_descriptor->start = htons(((uint16_t)(i+1-start)));
7926                                         /* advance struct to next pointer */
7927                                         seeing_ones = 1;
7928                               }
7929                     }
7930           }
7931           if (num_gap_blocks) {
7932                     /* special case where the array is all 1's
7933                      * to the end of the array.
7934                      */
7935                     gap_descriptor->end = htons(((uint16_t)((i-start))));
7936                     gap_descriptor++;
7937           }
7938           /* now we must add any dups we are going to report. */
7939           if (asoc->numduptsns) {
7940                     dup = (uint32_t *)gap_descriptor;
7941                     for (i = 0; i < asoc->numduptsns; i++) {
7942                               *dup = htonl(asoc->dup_tsns[i]);
7943                               dup++;
7944                     }
7945                     asoc->numduptsns = 0;
7946           }
7947           /* now that the chunk is prepared queue it to the control
7948            * chunk queue.
7949            */
7950           TAILQ_INSERT_TAIL(&asoc->control_send_queue, a_chk, sctp_next);
7951           asoc->ctrl_queue_cnt++;
7952           sctp_pegs[SCTP_PEG_SACKS_SENT]++;
7953           return;
7954 }
7955 
7956 void
7957 sctp_send_abort_tcb(struct sctp_tcb *stcb, struct mbuf *operr)
7958 {
7959           struct mbuf *m_abort;
7960           struct sctp_abort_msg *abort_m;
7961           int sz;
7962           abort_m = NULL;
7963           MGETHDR(m_abort, M_DONTWAIT, MT_HEADER);
7964           if (m_abort == NULL) {
7965                     /* no mbuf's */
7966                     return;
7967           }
7968           m_abort->m_data += SCTP_MIN_OVERHEAD;
7969           abort_m = mtod(m_abort, struct sctp_abort_msg *);
7970           m_abort->m_len = sizeof(struct sctp_abort_msg);
7971           m_abort->m_next = operr;
7972           sz = 0;
7973           if (operr) {
7974                     struct mbuf *n;
7975                     n = operr;
7976                     while (n) {
7977                               sz += n->m_len;
7978                               n = n->m_next;
7979                     }
7980           }
7981           abort_m->msg.ch.chunk_type = SCTP_ABORT_ASSOCIATION;
7982           abort_m->msg.ch.chunk_flags = 0;
7983           abort_m->msg.ch.chunk_length = htons(sizeof(struct sctp_abort_chunk) +
7984                                                        sz);
7985           abort_m->sh.src_port = stcb->sctp_ep->sctp_lport;
7986           abort_m->sh.dest_port = stcb->rport;
7987           abort_m->sh.v_tag = htonl(stcb->asoc.peer_vtag);
7988           abort_m->sh.checksum = 0;
7989           m_abort->m_pkthdr.len = m_abort->m_len + sz;
7990           m_reset_rcvif(m_abort);
7991           sctp_lowlevel_chunk_output(stcb->sctp_ep, stcb,
7992               stcb->asoc.primary_destination,
7993               rtcache_getdst(&stcb->asoc.primary_destination->ro),
7994               m_abort, 1, 0, NULL, 0);
7995 }
7996 
7997 int
7998 sctp_send_shutdown_complete(struct sctp_tcb *stcb,
7999                                   struct sctp_nets *net)
8000 
8001 {
8002           /* formulate and SEND a SHUTDOWN-COMPLETE */
8003           struct mbuf *m_shutdown_comp;
8004           struct sctp_shutdown_complete_msg *comp_cp;
8005 
8006           m_shutdown_comp = NULL;
8007           MGETHDR(m_shutdown_comp, M_DONTWAIT, MT_HEADER);
8008           if (m_shutdown_comp == NULL) {
8009                     /* no mbuf's */
8010                     return (-1);
8011           }
8012           m_shutdown_comp->m_data += sizeof(struct ip6_hdr);
8013           comp_cp = mtod(m_shutdown_comp, struct sctp_shutdown_complete_msg *);
8014           comp_cp->shut_cmp.ch.chunk_type = SCTP_SHUTDOWN_COMPLETE;
8015           comp_cp->shut_cmp.ch.chunk_flags = 0;
8016           comp_cp->shut_cmp.ch.chunk_length = htons(sizeof(struct sctp_shutdown_complete_chunk));
8017           comp_cp->sh.src_port = stcb->sctp_ep->sctp_lport;
8018           comp_cp->sh.dest_port = stcb->rport;
8019           comp_cp->sh.v_tag = htonl(stcb->asoc.peer_vtag);
8020           comp_cp->sh.checksum = 0;
8021 
8022           m_shutdown_comp->m_pkthdr.len = m_shutdown_comp->m_len = sizeof(struct sctp_shutdown_complete_msg);
8023           m_reset_rcvif(m_shutdown_comp);
8024           sctp_lowlevel_chunk_output(stcb->sctp_ep, stcb, net,
8025               rtcache_getdst(&net->ro), m_shutdown_comp,
8026               1, 0, NULL, 0);
8027           if ((stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE) ||
8028               (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL)) {
8029                     stcb->sctp_ep->sctp_flags &= ~SCTP_PCB_FLAGS_CONNECTED;
8030                     stcb->sctp_ep->sctp_socket->so_snd.sb_cc = 0;
8031                     soisdisconnected(stcb->sctp_ep->sctp_socket);
8032           }
8033           return (0);
8034 }
8035 
8036 int
8037 sctp_send_shutdown_complete2(struct mbuf *m, int iphlen, struct sctphdr *sh)
8038 {
8039           /* formulate and SEND a SHUTDOWN-COMPLETE */
8040           struct mbuf *mout;
8041           struct ip *iph, *iph_out;
8042           struct ip6_hdr *ip6, *ip6_out;
8043           int offset_out;
8044           struct sctp_shutdown_complete_msg *comp_cp;
8045 
8046           MGETHDR(mout, M_DONTWAIT, MT_HEADER);
8047           if (mout == NULL) {
8048                     /* no mbuf's */
8049                     return (-1);
8050           }
8051           iph = mtod(m, struct ip *);
8052           iph_out = NULL;
8053           ip6_out = NULL;
8054           offset_out = 0;
8055           if (iph->ip_v == IPVERSION) {
8056                     mout->m_len = sizeof(struct ip) +
8057                         sizeof(struct sctp_shutdown_complete_msg);
8058                     mout->m_next = NULL;
8059                     iph_out = mtod(mout, struct ip *);
8060 
8061                     /* Fill in the IP header for the ABORT */
8062                     iph_out->ip_v = IPVERSION;
8063                     iph_out->ip_hl = (sizeof(struct ip)/4);
8064                     iph_out->ip_tos = (u_char)0;
8065                     iph_out->ip_id = 0;
8066                     iph_out->ip_off = 0;
8067                     iph_out->ip_ttl = MAXTTL;
8068                     iph_out->ip_p = IPPROTO_SCTP;
8069                     iph_out->ip_src.s_addr = iph->ip_dst.s_addr;
8070                     iph_out->ip_dst.s_addr = iph->ip_src.s_addr;
8071 
8072                     /* let IP layer calculate this */
8073                     iph_out->ip_sum = 0;
8074                     offset_out += sizeof(*iph_out);
8075                     comp_cp = (struct sctp_shutdown_complete_msg *)(
8076                         (vaddr_t)iph_out + offset_out);
8077           } else if (iph->ip_v == (IPV6_VERSION >> 4)) {
8078                     ip6 = (struct ip6_hdr *)iph;
8079                     mout->m_len = sizeof(struct ip6_hdr) +
8080                         sizeof(struct sctp_shutdown_complete_msg);
8081                     mout->m_next = NULL;
8082                     ip6_out = mtod(mout, struct ip6_hdr *);
8083 
8084                     /* Fill in the IPv6 header for the ABORT */
8085                     ip6_out->ip6_flow = ip6->ip6_flow;
8086                     ip6_out->ip6_hlim = ip6_defhlim;
8087                     ip6_out->ip6_nxt = IPPROTO_SCTP;
8088                     ip6_out->ip6_src = ip6->ip6_dst;
8089                     ip6_out->ip6_dst = ip6->ip6_src;
8090                     ip6_out->ip6_plen = mout->m_len;
8091                     offset_out += sizeof(*ip6_out);
8092                     comp_cp = (struct sctp_shutdown_complete_msg *)(
8093                         (vaddr_t)ip6_out + offset_out);
8094           } else {
8095                     /* Currently not supported. */
8096                     return (-1);
8097           }
8098 
8099           /* Now copy in and fill in the ABORT tags etc. */
8100           comp_cp->sh.src_port = sh->dest_port;
8101           comp_cp->sh.dest_port = sh->src_port;
8102           comp_cp->sh.checksum = 0;
8103           comp_cp->sh.v_tag = sh->v_tag;
8104           comp_cp->shut_cmp.ch.chunk_flags = SCTP_HAD_NO_TCB;
8105           comp_cp->shut_cmp.ch.chunk_type = SCTP_SHUTDOWN_COMPLETE;
8106           comp_cp->shut_cmp.ch.chunk_length = htons(sizeof(struct sctp_shutdown_complete_chunk));
8107 
8108           mout->m_pkthdr.len = mout->m_len;
8109           /* add checksum */
8110           if ((sctp_no_csum_on_loopback) && m_get_rcvif_NOMPSAFE(m) != NULL &&
8111               m_get_rcvif_NOMPSAFE(m)->if_type == IFT_LOOP) {
8112                     comp_cp->sh.checksum =  0;
8113           } else {
8114                     comp_cp->sh.checksum = sctp_calculate_sum(mout, NULL, offset_out);
8115           }
8116 
8117           /* zap the rcvif, it should be null */
8118           m_reset_rcvif(mout);
8119           /* zap the stack pointer to the route */
8120           if (iph_out != NULL) {
8121                     struct route ro;
8122 
8123                     memset(&ro, 0, sizeof ro);
8124 #ifdef SCTP_DEBUG
8125                     if (sctp_debug_on & SCTP_DEBUG_OUTPUT2) {
8126                               printf("sctp_shutdown_complete2 calling ip_output:\n");
8127                               sctp_print_address_pkt(iph_out, &comp_cp->sh);
8128                     }
8129 #endif
8130                     /* set IPv4 length */
8131                     iph_out->ip_len = htons(mout->m_pkthdr.len);
8132                     /* out it goes */
8133                     ip_output(mout, 0, &ro, IP_RAWOUTPUT, NULL, NULL);
8134           } else if (ip6_out != NULL) {
8135                     struct route ro;
8136 
8137                     memset(&ro, 0, sizeof(ro));
8138 #ifdef SCTP_DEBUG
8139                     if (sctp_debug_on & SCTP_DEBUG_OUTPUT2) {
8140                               printf("sctp_shutdown_complete2 calling ip6_output:\n");
8141                               sctp_print_address_pkt((struct ip *)ip6_out,
8142                                   &comp_cp->sh);
8143                     }
8144 #endif
8145                     ip6_output(mout, NULL, &ro, 0, NULL, NULL, NULL);
8146           }
8147           sctp_pegs[SCTP_DATAGRAMS_SENT]++;
8148           return (0);
8149 }
8150 
8151 static struct sctp_nets *
8152 sctp_select_hb_destination(struct sctp_tcb *stcb, struct timeval *now)
8153 {
8154           struct sctp_nets *net, *hnet;
8155           int ms_goneby, highest_ms, state_override=0;
8156 
8157           SCTP_GETTIME_TIMEVAL(now);
8158           highest_ms = 0;
8159           hnet = NULL;
8160           TAILQ_FOREACH(net, &stcb->asoc.nets, sctp_next) {
8161                     if (
8162                               ((net->dest_state & SCTP_ADDR_NOHB) && ((net->dest_state & SCTP_ADDR_UNCONFIRMED) == 0)) ||
8163                               (net->dest_state & SCTP_ADDR_OUT_OF_SCOPE)
8164                               ) {
8165                               /* Skip this guy from consideration if HB is off AND its confirmed*/
8166 #ifdef SCTP_DEBUG
8167                               if (sctp_debug_on & SCTP_DEBUG_OUTPUT4) {
8168                                         printf("Skipping net:%p state:%d nohb/out-of-scope\n",
8169                                                net, net->dest_state);
8170                               }
8171 #endif
8172                               continue;
8173                     }
8174                     if (sctp_destination_is_reachable(stcb, (struct sockaddr *)&net->ro.ro_sa) == 0) {
8175                               /* skip this dest net from consideration */
8176 #ifdef SCTP_DEBUG
8177                               if (sctp_debug_on & SCTP_DEBUG_OUTPUT4) {
8178                                         printf("Skipping net:%p reachable NOT\n",
8179                                                net);
8180                               }
8181 #endif
8182                               continue;
8183                     }
8184                     if (net->last_sent_time.tv_sec) {
8185                               /* Sent to so we subtract */
8186                               ms_goneby = (now->tv_sec - net->last_sent_time.tv_sec) * 1000;
8187                     } else
8188                               /* Never been sent to */
8189                               ms_goneby = 0x7fffffff;
8190 #ifdef SCTP_DEBUG
8191                     if (sctp_debug_on & SCTP_DEBUG_OUTPUT4) {
8192                               printf("net:%p ms_goneby:%d\n",
8193                                      net, ms_goneby);
8194                     }
8195 #endif
8196                     /* When the address state is unconfirmed but still considered reachable, we
8197                      * HB at a higher rate. Once it goes confirmed OR reaches the "unreachable"
8198                      * state, then we cut it back to HB at a more normal pace.
8199                      */
8200                     if ((net->dest_state & (SCTP_ADDR_UNCONFIRMED|SCTP_ADDR_NOT_REACHABLE)) == SCTP_ADDR_UNCONFIRMED) {
8201                               state_override = 1;
8202                     } else {
8203                               state_override = 0;
8204                     }
8205 
8206                     if ((((unsigned int)ms_goneby >= net->RTO) || (state_override)) &&
8207                         (ms_goneby > highest_ms)) {
8208                               highest_ms = ms_goneby;
8209                               hnet = net;
8210 #ifdef SCTP_DEBUG
8211                               if (sctp_debug_on & SCTP_DEBUG_OUTPUT4) {
8212                                         printf("net:%p is the new high\n",
8213                                                net);
8214                               }
8215 #endif
8216                     }
8217           }
8218           if (hnet &&
8219              ((hnet->dest_state & (SCTP_ADDR_UNCONFIRMED|SCTP_ADDR_NOT_REACHABLE)) == SCTP_ADDR_UNCONFIRMED)) {
8220                     state_override = 1;
8221           } else {
8222                     state_override = 0;
8223           }
8224 
8225           if (highest_ms && (((unsigned int)highest_ms >= hnet->RTO) || state_override)) {
8226                     /* Found the one with longest delay bounds
8227                      * OR it is unconfirmed and still not marked
8228                      * unreachable.
8229                      */
8230 #ifdef SCTP_DEBUG
8231                     if (sctp_debug_on & SCTP_DEBUG_OUTPUT4) {
8232                               printf("net:%p is the hb winner -",
8233                                         hnet);
8234                               if (hnet)
8235                                         sctp_print_address((struct sockaddr *)&hnet->ro.ro_sa);
8236                               else
8237                                         printf(" none\n");
8238                     }
8239 #endif
8240                     /* update the timer now */
8241                     hnet->last_sent_time = *now;
8242                     return (hnet);
8243           }
8244           /* Nothing to HB */
8245           return (NULL);
8246 }
8247 
8248 int
8249 sctp_send_hb(struct sctp_tcb *stcb, int user_req, struct sctp_nets *u_net)
8250 {
8251           struct sctp_tmit_chunk *chk;
8252           struct sctp_nets *net;
8253           struct sctp_heartbeat_chunk *hb;
8254           struct timeval now;
8255           struct sockaddr_in *sin;
8256           struct sockaddr_in6 *sin6;
8257 
8258           if (user_req == 0) {
8259                     net = sctp_select_hb_destination(stcb, &now);
8260                     if (net == NULL) {
8261                               /* All our busy none to send to, just
8262                                * start the timer again.
8263                                */
8264                               if (stcb->asoc.state == 0) {
8265                                         return (0);
8266                               }
8267                               sctp_timer_start(SCTP_TIMER_TYPE_HEARTBEAT,
8268                                                    stcb->sctp_ep,
8269                                                    stcb,
8270                                                    net);
8271                               return (0);
8272                     }
8273 #ifndef SCTP_USE_ALLMAN_BURST
8274                     else {
8275                               /* found one idle.. decay cwnd on this one
8276                                * by 1/2 if none outstanding.
8277                                */
8278 
8279                               if (net->flight_size == 0) {
8280                                         net->cwnd /= 2;
8281                                         if (net->addr_is_local) {
8282                                                   if (net->cwnd < (net->mtu *4)) {
8283                                                             net->cwnd = net->mtu * 4;
8284                                                   }
8285                                         } else {
8286                                                   if (net->cwnd < (net->mtu * 2)) {
8287                                                             net->cwnd = net->mtu * 2;
8288                                                   }
8289                                         }
8290 
8291                               }
8292 
8293                     }
8294 #endif
8295           } else {
8296                     net = u_net;
8297                     if (net == NULL) {
8298                               return (0);
8299                     }
8300                     SCTP_GETTIME_TIMEVAL(&now);
8301           }
8302           sin = (struct sockaddr_in *)&net->ro.ro_sa;
8303           if (sin->sin_family != AF_INET) {
8304                     if (sin->sin_family != AF_INET6) {
8305                               /* huh */
8306                               return (0);
8307                     }
8308           }
8309           chk = (struct sctp_tmit_chunk *)SCTP_ZONE_GET(sctppcbinfo.ipi_zone_chunk);
8310           if (chk == NULL) {
8311 #ifdef SCTP_DEBUG
8312                     if (sctp_debug_on & SCTP_DEBUG_OUTPUT4) {
8313                               printf("Gak, can't get a chunk for hb\n");
8314                     }
8315 #endif
8316                     return (0);
8317           }
8318           sctppcbinfo.ipi_gencnt_chunk++;
8319           sctppcbinfo.ipi_count_chunk++;
8320           chk->rec.chunk_id = SCTP_HEARTBEAT_REQUEST;
8321           chk->asoc = &stcb->asoc;
8322           chk->send_size = sizeof(struct sctp_heartbeat_chunk);
8323           MGETHDR(chk->data, M_DONTWAIT, MT_DATA);
8324           if (chk->data == NULL) {
8325                     SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_chunk, chk);
8326                     sctppcbinfo.ipi_count_chunk--;
8327                     if ((int)sctppcbinfo.ipi_count_chunk < 0) {
8328                               panic("Chunk count is negative");
8329                     }
8330                     sctppcbinfo.ipi_gencnt_chunk++;
8331                     return (0);
8332           }
8333           chk->data->m_data += SCTP_MIN_OVERHEAD;
8334           chk->data->m_pkthdr.len = chk->data->m_len = chk->send_size;
8335           chk->sent = SCTP_DATAGRAM_UNSENT;
8336           chk->snd_count = 0;
8337           chk->whoTo = net;
8338           chk->whoTo->ref_count++;
8339           /* Now we have a mbuf that we can fill in with the details */
8340           hb = mtod(chk->data, struct sctp_heartbeat_chunk *);
8341 
8342           /* fill out chunk header */
8343           hb->ch.chunk_type = SCTP_HEARTBEAT_REQUEST;
8344           hb->ch.chunk_flags = 0;
8345           hb->ch.chunk_length = htons(chk->send_size);
8346           /* Fill out hb parameter */
8347           hb->heartbeat.hb_info.ph.param_type = htons(SCTP_HEARTBEAT_INFO);
8348           hb->heartbeat.hb_info.ph.param_length = htons(sizeof(struct sctp_heartbeat_info_param));
8349           hb->heartbeat.hb_info.time_value_1 = now.tv_sec;
8350           hb->heartbeat.hb_info.time_value_2 = now.tv_usec;
8351           /* Did our user request this one, put it in */
8352           hb->heartbeat.hb_info.user_req = user_req;
8353           hb->heartbeat.hb_info.addr_family = sin->sin_family;
8354           hb->heartbeat.hb_info.addr_len = sin->sin_len;
8355           if (net->dest_state & SCTP_ADDR_UNCONFIRMED) {
8356                     /* we only take from the entropy pool if the address is
8357                      * not confirmed.
8358                      */
8359                     net->heartbeat_random1 = hb->heartbeat.hb_info.random_value1 = sctp_select_initial_TSN(&stcb->sctp_ep->sctp_ep);
8360                     net->heartbeat_random2 = hb->heartbeat.hb_info.random_value2 = sctp_select_initial_TSN(&stcb->sctp_ep->sctp_ep);
8361           } else {
8362                     net->heartbeat_random1 = hb->heartbeat.hb_info.random_value1 = 0;
8363                     net->heartbeat_random2 = hb->heartbeat.hb_info.random_value2 = 0;
8364           }
8365           if (sin->sin_family == AF_INET) {
8366                     memcpy(hb->heartbeat.hb_info.address, &sin->sin_addr, sizeof(sin->sin_addr));
8367           } else if (sin->sin_family == AF_INET6) {
8368                     /* We leave the scope the way it is in our lookup table. */
8369                     sin6 = (struct sockaddr_in6 *)&net->ro.ro_sa;
8370                     memcpy(hb->heartbeat.hb_info.address, &sin6->sin6_addr, sizeof(sin6->sin6_addr));
8371           } else {
8372                     /* huh compiler bug */
8373 #ifdef SCTP_DEBUG
8374                     if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
8375                               printf("Compiler bug bleeds a mbuf and a chunk\n");
8376                     }
8377 #endif
8378                     return (0);
8379           }
8380           /* ok we have a destination that needs a beat */
8381           /* lets do the theshold management Qiaobing style */
8382           if (user_req == 0) {
8383                     if (sctp_threshold_management(stcb->sctp_ep, stcb, net,
8384                                                         stcb->asoc.max_send_times)) {
8385                               /* we have lost the association, in a way this
8386                                * is quite bad since we really are one less time
8387                                * since we really did not send yet. This is the
8388                                * down side to the Q's style as defined in the RFC
8389                                * and not my alternate style defined in the RFC.
8390                                */
8391                               sctp_m_freem(chk->data);
8392                               chk->data = NULL;
8393                               SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_chunk, chk);
8394                               sctppcbinfo.ipi_count_chunk--;
8395                               if ((int)sctppcbinfo.ipi_count_chunk < 0) {
8396                                         panic("Chunk count is negative");
8397                               }
8398                               sctppcbinfo.ipi_gencnt_chunk++;
8399                               return (-1);
8400                     }
8401           }
8402           net->hb_responded = 0;
8403 #ifdef SCTP_DEBUG
8404           if (sctp_debug_on & SCTP_DEBUG_OUTPUT4) {
8405                     printf("Inserting chunk for HB\n");
8406           }
8407 #endif
8408           TAILQ_INSERT_TAIL(&stcb->asoc.control_send_queue, chk, sctp_next);
8409           stcb->asoc.ctrl_queue_cnt++;
8410           sctp_pegs[SCTP_HB_SENT]++;
8411           /*
8412            * Call directly med level routine to put out the chunk. It will
8413            * always tumble out control chunks aka HB but it may even tumble
8414            * out data too.
8415            */
8416           if (user_req == 0) {
8417                     /* Ok now lets start the HB timer if it is NOT a user req */
8418                     sctp_timer_start(SCTP_TIMER_TYPE_HEARTBEAT, stcb->sctp_ep,
8419                                          stcb, net);
8420           }
8421           return (1);
8422 }
8423 
8424 void
8425 sctp_send_ecn_echo(struct sctp_tcb *stcb, struct sctp_nets *net,
8426                        uint32_t high_tsn)
8427 {
8428           struct sctp_association *asoc;
8429           struct sctp_ecne_chunk *ecne;
8430           struct sctp_tmit_chunk *chk;
8431           asoc = &stcb->asoc;
8432           TAILQ_FOREACH(chk, &asoc->control_send_queue, sctp_next) {
8433                     if (chk->rec.chunk_id == SCTP_ECN_ECHO) {
8434                               /* found a previous ECN_ECHO update it if needed */
8435                               ecne = mtod(chk->data, struct sctp_ecne_chunk *);
8436                               ecne->tsn = htonl(high_tsn);
8437                               return;
8438                     }
8439           }
8440           /* nope could not find one to update so we must build one */
8441           chk = (struct sctp_tmit_chunk *)SCTP_ZONE_GET(sctppcbinfo.ipi_zone_chunk);
8442           if (chk == NULL) {
8443                     return;
8444           }
8445           sctp_pegs[SCTP_ECNE_SENT]++;
8446           sctppcbinfo.ipi_count_chunk++;
8447           sctppcbinfo.ipi_gencnt_chunk++;
8448           chk->rec.chunk_id = SCTP_ECN_ECHO;
8449           chk->asoc = &stcb->asoc;
8450           chk->send_size = sizeof(struct sctp_ecne_chunk);
8451           MGETHDR(chk->data, M_DONTWAIT, MT_DATA);
8452           if (chk->data == NULL) {
8453                     SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_chunk, chk);
8454                     sctppcbinfo.ipi_count_chunk--;
8455                     if ((int)sctppcbinfo.ipi_count_chunk < 0) {
8456                               panic("Chunk count is negative");
8457                     }
8458                     sctppcbinfo.ipi_gencnt_chunk++;
8459                     return;
8460           }
8461           chk->data->m_data += SCTP_MIN_OVERHEAD;
8462           chk->data->m_pkthdr.len = chk->data->m_len = chk->send_size;
8463           chk->sent = SCTP_DATAGRAM_UNSENT;
8464           chk->snd_count = 0;
8465           chk->whoTo = net;
8466           chk->whoTo->ref_count++;
8467           ecne = mtod(chk->data, struct sctp_ecne_chunk *);
8468           ecne->ch.chunk_type = SCTP_ECN_ECHO;
8469           ecne->ch.chunk_flags = 0;
8470           ecne->ch.chunk_length = htons(sizeof(struct sctp_ecne_chunk));
8471           ecne->tsn = htonl(high_tsn);
8472           TAILQ_INSERT_TAIL(&stcb->asoc.control_send_queue, chk, sctp_next);
8473           asoc->ctrl_queue_cnt++;
8474 }
8475 
8476 void
8477 sctp_send_packet_dropped(struct sctp_tcb *stcb, struct sctp_nets *net,
8478                                struct mbuf *m, int iphlen, int bad_crc)
8479 {
8480           struct sctp_association *asoc;
8481           struct sctp_pktdrop_chunk *drp;
8482           struct sctp_tmit_chunk *chk;
8483           uint8_t *datap;
8484           int len;
8485           unsigned int small_one;
8486           struct ip *iph;
8487 
8488           long spc;
8489           asoc = &stcb->asoc;
8490           if (asoc->peer_supports_pktdrop == 0) {
8491                     /* peer must declare support before I
8492                      * send one.
8493                      */
8494                     return;
8495           }
8496           chk = (struct sctp_tmit_chunk *)SCTP_ZONE_GET(sctppcbinfo.ipi_zone_chunk);
8497           if (chk == NULL) {
8498                     return;
8499           }
8500           sctppcbinfo.ipi_count_chunk++;
8501           sctppcbinfo.ipi_gencnt_chunk++;
8502 
8503           iph = mtod(m, struct ip *);
8504           if (iph == NULL) {
8505                     return;
8506           }
8507           if (iph->ip_v == IPVERSION) {
8508                     /* IPv4 */
8509 #if defined(__FreeBSD__)
8510                     len = chk->send_size = iph->ip_len;
8511 #else
8512                     len = chk->send_size = (iph->ip_len - iphlen);
8513 #endif
8514           } else {
8515                     struct ip6_hdr *ip6h;
8516                     /* IPv6 */
8517                     ip6h = mtod(m, struct ip6_hdr *);
8518                     len = chk->send_size = htons(ip6h->ip6_plen);
8519           }
8520           if ((len+iphlen) > m->m_pkthdr.len) {
8521                     /* huh */
8522                     chk->send_size = len = m->m_pkthdr.len - iphlen;
8523           }
8524           chk->asoc = &stcb->asoc;
8525           MGETHDR(chk->data, M_DONTWAIT, MT_DATA);
8526           if (chk->data == NULL) {
8527           jump_out:
8528                     SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_chunk, chk);
8529                     sctppcbinfo.ipi_count_chunk--;
8530                     if ((int)sctppcbinfo.ipi_count_chunk < 0) {
8531                               panic("Chunk count is negative");
8532                     }
8533                     sctppcbinfo.ipi_gencnt_chunk++;
8534                     return;
8535           }
8536           if ((chk->send_size+sizeof(struct sctp_pktdrop_chunk)+SCTP_MIN_OVERHEAD) > MHLEN) {
8537                     MCLGET(chk->data, M_DONTWAIT);
8538                     if ((chk->data->m_flags & M_EXT) == 0) {
8539                               /* Give up */
8540                               sctp_m_freem(chk->data);
8541                               chk->data = NULL;
8542                               goto jump_out;
8543                     }
8544           }
8545           chk->data->m_data += SCTP_MIN_OVERHEAD;
8546           drp = mtod(chk->data, struct sctp_pktdrop_chunk *);
8547           if (drp == NULL) {
8548                     sctp_m_freem(chk->data);
8549                     chk->data = NULL;
8550                     goto jump_out;
8551           }
8552           small_one = asoc->smallest_mtu;
8553           if (small_one > MCLBYTES) {
8554                     /* Only one cluster worth of data MAX */
8555                     small_one = MCLBYTES;
8556           }
8557           chk->book_size = (chk->send_size + sizeof(struct sctp_pktdrop_chunk) +
8558                                 sizeof(struct sctphdr) + SCTP_MED_OVERHEAD);
8559           if (chk->book_size > small_one) {
8560                     drp->ch.chunk_flags = SCTP_PACKET_TRUNCATED;
8561                     drp->trunc_len = htons(chk->send_size);
8562                     chk->send_size = small_one - (SCTP_MED_OVERHEAD +
8563                                                        sizeof(struct sctp_pktdrop_chunk) +
8564                                                        sizeof(struct sctphdr));
8565                     len = chk->send_size;
8566           } else {
8567                     /* no truncation needed */
8568                     drp->ch.chunk_flags = 0;
8569                     drp->trunc_len = htons(0);
8570           }
8571           if (bad_crc) {
8572                     drp->ch.chunk_flags |= SCTP_BADCRC;
8573           }
8574           chk->send_size += sizeof(struct sctp_pktdrop_chunk);
8575           chk->data->m_pkthdr.len = chk->data->m_len = chk->send_size;
8576           chk->sent = SCTP_DATAGRAM_UNSENT;
8577           chk->snd_count = 0;
8578           if (net) {
8579                     /* we should hit here */
8580                     chk->whoTo = net;
8581           } else {
8582                     chk->whoTo = asoc->primary_destination;
8583           }
8584           chk->whoTo->ref_count++;
8585           chk->rec.chunk_id = SCTP_PACKET_DROPPED;
8586           drp->ch.chunk_type = SCTP_PACKET_DROPPED;
8587           drp->ch.chunk_length = htons(chk->send_size);
8588           spc = stcb->sctp_socket->so_rcv.sb_hiwat;
8589           if (spc < 0) {
8590                     spc = 0;
8591           }
8592           drp->bottle_bw = htonl(spc);
8593           drp->current_onq = htonl(asoc->size_on_delivery_queue +
8594                                          asoc->size_on_reasm_queue +
8595                                          asoc->size_on_all_streams +
8596                                          asoc->my_rwnd_control_len +
8597                                      stcb->sctp_socket->so_rcv.sb_cc);
8598           drp->reserved = 0;
8599           datap = drp->data;
8600         m_copydata(m, iphlen, len, datap);
8601           TAILQ_INSERT_TAIL(&stcb->asoc.control_send_queue, chk, sctp_next);
8602           asoc->ctrl_queue_cnt++;
8603 }
8604 
8605 void
8606 sctp_send_cwr(struct sctp_tcb *stcb, struct sctp_nets *net, uint32_t high_tsn)
8607 {
8608           struct sctp_association *asoc;
8609           struct sctp_cwr_chunk *cwr;
8610           struct sctp_tmit_chunk *chk;
8611 
8612           asoc = &stcb->asoc;
8613           TAILQ_FOREACH(chk, &asoc->control_send_queue, sctp_next) {
8614                     if (chk->rec.chunk_id == SCTP_ECN_CWR) {
8615                               /* found a previous ECN_CWR update it if needed */
8616                               cwr = mtod(chk->data, struct sctp_cwr_chunk *);
8617                               if (compare_with_wrap(high_tsn, ntohl(cwr->tsn),
8618                                                         MAX_TSN)) {
8619                                         cwr->tsn = htonl(high_tsn);
8620                               }
8621                               return;
8622                     }
8623           }
8624           /* nope could not find one to update so we must build one */
8625           chk = (struct sctp_tmit_chunk *)SCTP_ZONE_GET(sctppcbinfo.ipi_zone_chunk);
8626           if (chk == NULL) {
8627                     return;
8628           }
8629           sctppcbinfo.ipi_count_chunk++;
8630           sctppcbinfo.ipi_gencnt_chunk++;
8631           chk->rec.chunk_id = SCTP_ECN_CWR;
8632           chk->asoc = &stcb->asoc;
8633           chk->send_size = sizeof(struct sctp_cwr_chunk);
8634           MGETHDR(chk->data, M_DONTWAIT, MT_DATA);
8635           if (chk->data == NULL) {
8636                     SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_chunk, chk);
8637                     sctppcbinfo.ipi_count_chunk--;
8638                     if ((int)sctppcbinfo.ipi_count_chunk < 0) {
8639                               panic("Chunk count is negative");
8640                     }
8641                     sctppcbinfo.ipi_gencnt_chunk++;
8642                     return;
8643           }
8644           chk->data->m_data += SCTP_MIN_OVERHEAD;
8645           chk->data->m_pkthdr.len = chk->data->m_len = chk->send_size;
8646           chk->sent = SCTP_DATAGRAM_UNSENT;
8647           chk->snd_count = 0;
8648           chk->whoTo = net;
8649           chk->whoTo->ref_count++;
8650           cwr = mtod(chk->data, struct sctp_cwr_chunk *);
8651           cwr->ch.chunk_type = SCTP_ECN_CWR;
8652           cwr->ch.chunk_flags = 0;
8653           cwr->ch.chunk_length = htons(sizeof(struct sctp_cwr_chunk));
8654           cwr->tsn = htonl(high_tsn);
8655           TAILQ_INSERT_TAIL(&stcb->asoc.control_send_queue, chk, sctp_next);
8656           asoc->ctrl_queue_cnt++;
8657 }
8658 static void
8659 sctp_reset_the_streams(struct sctp_tcb *stcb,
8660      struct sctp_stream_reset_request *req, int number_entries, uint16_t *list)
8661 {
8662           int i;
8663 
8664           if (req->reset_flags & SCTP_RESET_ALL) {
8665                     for (i=0; i<stcb->asoc.streamoutcnt; i++) {
8666                               stcb->asoc.strmout[i].next_sequence_sent = 0;
8667                     }
8668           } else if (number_entries) {
8669                     for (i=0; i<number_entries; i++) {
8670                               if (list[i] >= stcb->asoc.streamoutcnt) {
8671                                         /* no such stream */
8672                                         continue;
8673                               }
8674                               stcb->asoc.strmout[(list[i])].next_sequence_sent = 0;
8675                     }
8676           }
8677           sctp_ulp_notify(SCTP_NOTIFY_STR_RESET_SEND, stcb, number_entries, (void *)list);
8678 }
8679 
8680 void
8681 sctp_send_str_reset_ack(struct sctp_tcb *stcb,
8682      struct sctp_stream_reset_request *req)
8683 {
8684           struct sctp_association *asoc;
8685           struct sctp_stream_reset_resp *strack;
8686           struct sctp_tmit_chunk *chk;
8687           uint32_t seq;
8688           int number_entries, i;
8689           uint8_t two_way=0, not_peer=0;
8690           uint16_t *list=NULL;
8691 
8692           asoc = &stcb->asoc;
8693           if (req->reset_flags & SCTP_RESET_ALL)
8694                     number_entries = 0;
8695           else
8696                     number_entries = (ntohs(req->ph.param_length) - sizeof(struct sctp_stream_reset_request)) / sizeof(uint16_t);
8697 
8698           chk = (struct sctp_tmit_chunk *)SCTP_ZONE_GET(sctppcbinfo.ipi_zone_chunk);
8699           if (chk == NULL) {
8700                     return;
8701           }
8702           sctppcbinfo.ipi_count_chunk++;
8703           sctppcbinfo.ipi_gencnt_chunk++;
8704           chk->rec.chunk_id = SCTP_STREAM_RESET;
8705           chk->asoc = &stcb->asoc;
8706           chk->send_size = sizeof(struct sctp_stream_reset_resp) + (number_entries * sizeof(uint16_t));
8707           MGETHDR(chk->data, M_DONTWAIT, MT_DATA);
8708           if (chk->data == NULL) {
8709           strresp_jump_out:
8710                     SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_chunk, chk);
8711                     sctppcbinfo.ipi_count_chunk--;
8712                     if ((int)sctppcbinfo.ipi_count_chunk < 0) {
8713                               panic("Chunk count is negative");
8714                     }
8715                     sctppcbinfo.ipi_gencnt_chunk++;
8716                     return;
8717           }
8718           chk->data->m_data += SCTP_MIN_OVERHEAD;
8719           chk->data->m_pkthdr.len = chk->data->m_len = SCTP_SIZE32(chk->send_size);
8720           if (M_TRAILINGSPACE(chk->data) < (int)SCTP_SIZE32(chk->send_size)) {
8721                     MCLGET(chk->data, M_DONTWAIT);
8722                     if ((chk->data->m_flags & M_EXT) == 0) {
8723                               /* Give up */
8724                               sctp_m_freem(chk->data);
8725                               chk->data = NULL;
8726                               goto strresp_jump_out;
8727                     }
8728                     chk->data->m_data += SCTP_MIN_OVERHEAD;
8729           }
8730           if (M_TRAILINGSPACE(chk->data) < (int)SCTP_SIZE32(chk->send_size)) {
8731                     /* can't do it, no room */
8732                     /* Give up */
8733                     sctp_m_freem(chk->data);
8734                     chk->data = NULL;
8735                     goto strresp_jump_out;
8736 
8737           }
8738           chk->sent = SCTP_DATAGRAM_UNSENT;
8739           chk->snd_count = 0;
8740           chk->whoTo = asoc->primary_destination;
8741           chk->whoTo->ref_count++;
8742           strack = mtod(chk->data, struct sctp_stream_reset_resp *);
8743 
8744           strack->ch.chunk_type = SCTP_STREAM_RESET;
8745           strack->ch.chunk_flags = 0;
8746           strack->ch.chunk_length = htons(chk->send_size);
8747 
8748           memset(strack->sr_resp.reset_pad, 0, sizeof(strack->sr_resp.reset_pad));
8749 
8750           strack->sr_resp.ph.param_type = ntohs(SCTP_STR_RESET_RESPONSE);
8751           strack->sr_resp.ph.param_length = htons((chk->send_size - sizeof(struct sctp_chunkhdr)));
8752 
8753 
8754 
8755           if (chk->send_size % 4) {
8756                     /* need a padding for the end */
8757                     int pad;
8758                     uint8_t *end;
8759                     end = (uint8_t *)((vaddr_t)strack + chk->send_size);
8760                     pad = chk->send_size % 4;
8761                     for (i = 0; i < pad; i++) {
8762                               end[i] = 0;
8763                     }
8764                     chk->send_size += pad;
8765           }
8766 
8767         /* actual response */
8768           if (req->reset_flags & SCTP_RESET_YOUR) {
8769                     strack->sr_resp.reset_flags = SCTP_RESET_PERFORMED;
8770           } else {
8771                     strack->sr_resp.reset_flags = 0;
8772           }
8773 
8774           /* copied from reset request */
8775           strack->sr_resp.reset_req_seq_resp = req->reset_req_seq;
8776           seq = ntohl(req->reset_req_seq);
8777 
8778           list = req->list_of_streams;
8779           /* copy the un-converted network byte order streams */
8780           for (i=0; i<number_entries; i++) {
8781                     strack->sr_resp.list_of_streams[i] = list[i];
8782           }
8783           if (asoc->str_reset_seq_in == seq) {
8784                     /* is it the next expected? */
8785                     asoc->str_reset_seq_in++;
8786                     strack->sr_resp.reset_at_tsn = htonl(asoc->sending_seq);
8787                     asoc->str_reset_sending_seq = asoc->sending_seq;
8788                     if (number_entries) {
8789                               uint16_t temp;
8790                               /* convert them to host byte order */
8791                               for (i=0 ; i<number_entries; i++) {
8792                                         temp = ntohs(list[i]);
8793                                         list[i] = temp;
8794                               }
8795                     }
8796                     if (req->reset_flags & SCTP_RESET_YOUR) {
8797                               /* reset my outbound streams */
8798                               sctp_reset_the_streams(stcb, req , number_entries, list);
8799                     }
8800                     if (req->reset_flags & SCTP_RECIPRICAL) {
8801                               /* reset peer too */
8802                               sctp_send_str_reset_req(stcb, number_entries, list, two_way, not_peer);
8803                     }
8804 
8805           } else {
8806                     /* no its a retran so I must just ack and do nothing */
8807                     strack->sr_resp.reset_at_tsn = htonl(asoc->str_reset_sending_seq);
8808           }
8809           strack->sr_resp.cumulative_tsn = htonl(asoc->cumulative_tsn);
8810           TAILQ_INSERT_TAIL(&asoc->control_send_queue,
8811                                 chk,
8812                                 sctp_next);
8813           asoc->ctrl_queue_cnt++;
8814 }
8815 
8816 
8817 void
8818 sctp_send_str_reset_req(struct sctp_tcb *stcb,
8819      int number_entrys, uint16_t *list, uint8_t two_way, uint8_t not_peer)
8820 {
8821           /* Send a stream reset request. The number_entrys may be 0 and list NULL
8822            * if the request is to reset all streams. If two_way is true then we
8823            * not only request a RESET of the received streams but we also
8824            * request the peer to send a reset req to us too.
8825            * Flag combinations in table:
8826            *
8827            *       two_way | not_peer  | = | Flags
8828            *       ------------------------------
8829            *         0     |    0      | = | SCTP_RESET_YOUR (just the peer)
8830            *         1     |    0      | = | SCTP_RESET_YOUR | SCTP_RECIPRICAL (both sides)
8831            *         0     |    1      | = | Not a Valid Request (not anyone)
8832            *         1     |    1      | = | SCTP_RESET_RECIPRICAL (Just local host)
8833            */
8834           struct sctp_association *asoc;
8835           struct sctp_stream_reset_req *strreq;
8836           struct sctp_tmit_chunk *chk;
8837 
8838 
8839           asoc = &stcb->asoc;
8840           if (asoc->stream_reset_outstanding) {
8841                     /* Already one pending, must get ACK back
8842                      * to clear the flag.
8843                      */
8844                     return;
8845           }
8846 
8847           if ((two_way == 0) && (not_peer == 1)) {
8848                     /* not a valid request */
8849                     return;
8850           }
8851 
8852           chk = (struct sctp_tmit_chunk *)SCTP_ZONE_GET(sctppcbinfo.ipi_zone_chunk);
8853           if (chk == NULL) {
8854                     return;
8855           }
8856           sctppcbinfo.ipi_count_chunk++;
8857           sctppcbinfo.ipi_gencnt_chunk++;
8858           chk->rec.chunk_id = SCTP_STREAM_RESET;
8859           chk->asoc = &stcb->asoc;
8860           chk->send_size = sizeof(struct sctp_stream_reset_req) + (number_entrys * sizeof(uint16_t));
8861           MGETHDR(chk->data, M_DONTWAIT, MT_DATA);
8862           if (chk->data == NULL) {
8863           strreq_jump_out:
8864                     SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_chunk, chk);
8865                     sctppcbinfo.ipi_count_chunk--;
8866                     if ((int)sctppcbinfo.ipi_count_chunk < 0) {
8867                               panic("Chunk count is negative");
8868                     }
8869                     sctppcbinfo.ipi_gencnt_chunk++;
8870                     return;
8871           }
8872           chk->data->m_data += SCTP_MIN_OVERHEAD;
8873           chk->data->m_pkthdr.len = chk->data->m_len = SCTP_SIZE32(chk->send_size);
8874           if (M_TRAILINGSPACE(chk->data) < (int)SCTP_SIZE32(chk->send_size)) {
8875                     MCLGET(chk->data, M_DONTWAIT);
8876                     if ((chk->data->m_flags & M_EXT) == 0) {
8877                               /* Give up */
8878                               sctp_m_freem(chk->data);
8879                               chk->data = NULL;
8880                               goto strreq_jump_out;
8881                     }
8882                     chk->data->m_data += SCTP_MIN_OVERHEAD;
8883           }
8884           if (M_TRAILINGSPACE(chk->data) < (int)SCTP_SIZE32(chk->send_size)) {
8885                     /* can't do it, no room */
8886                     /* Give up */
8887                     sctp_m_freem(chk->data);
8888                     chk->data = NULL;
8889                     goto strreq_jump_out;
8890           }
8891           chk->sent = SCTP_DATAGRAM_UNSENT;
8892           chk->snd_count = 0;
8893           chk->whoTo = asoc->primary_destination;
8894           chk->whoTo->ref_count++;
8895 
8896           strreq = mtod(chk->data, struct sctp_stream_reset_req *);
8897           strreq->ch.chunk_type = SCTP_STREAM_RESET;
8898           strreq->ch.chunk_flags = 0;
8899           strreq->ch.chunk_length = htons(chk->send_size);
8900 
8901           strreq->sr_req.ph.param_type = ntohs(SCTP_STR_RESET_REQUEST);
8902           strreq->sr_req.ph.param_length = htons((chk->send_size - sizeof(struct sctp_chunkhdr)));
8903 
8904           if (chk->send_size % 4) {
8905                     /* need a padding for the end */
8906                     int pad, i;
8907                     uint8_t *end;
8908                     end = (uint8_t *)((vaddr_t)strreq + chk->send_size);
8909                     pad = chk->send_size % 4;
8910                     for (i=0; i<pad; i++) {
8911                               end[i] = 0;
8912                     }
8913                     chk->send_size += pad;
8914           }
8915 
8916           strreq->sr_req.reset_flags = 0;
8917           if (number_entrys == 0) {
8918                     strreq->sr_req.reset_flags |= SCTP_RESET_ALL;
8919           }
8920           if (two_way == 0) {
8921                     strreq->sr_req.reset_flags |= SCTP_RESET_YOUR;
8922           } else {
8923                     if (not_peer == 0) {
8924                               strreq->sr_req.reset_flags |= SCTP_RECIPRICAL | SCTP_RESET_YOUR;
8925                     } else {
8926                               strreq->sr_req.reset_flags |= SCTP_RECIPRICAL;
8927                     }
8928           }
8929           memset(strreq->sr_req.reset_pad, 0, sizeof(strreq->sr_req.reset_pad));
8930           strreq->sr_req.reset_req_seq = htonl(asoc->str_reset_seq_out);
8931           if (number_entrys) {
8932                     /* populate the specific entry's */
8933                     int i;
8934                     for (i=0; i < number_entrys; i++) {
8935                               strreq->sr_req.list_of_streams[i] = htons(list[i]);
8936                     }
8937           }
8938           TAILQ_INSERT_TAIL(&asoc->control_send_queue,
8939                                 chk,
8940                                 sctp_next);
8941           asoc->ctrl_queue_cnt++;
8942           sctp_timer_start(SCTP_TIMER_TYPE_STRRESET, stcb->sctp_ep, stcb, chk->whoTo);
8943           asoc->stream_reset_outstanding = 1;
8944 }
8945 
8946 void
8947 sctp_send_abort(struct mbuf *m, int iphlen, struct sctphdr *sh, uint32_t vtag,
8948     struct mbuf *err_cause)
8949 {
8950           /*
8951            * Formulate the abort message, and send it back down.
8952            */
8953           struct mbuf *mout;
8954           struct sctp_abort_msg *abm;
8955           struct ip *iph, *iph_out;
8956           struct ip6_hdr *ip6, *ip6_out;
8957           int iphlen_out;
8958 
8959           /* don't respond to ABORT with ABORT */
8960           if (sctp_is_there_an_abort_here(m, iphlen, &vtag)) {
8961                     sctp_m_freem(err_cause);
8962                     return;
8963           }
8964           MGETHDR(mout, M_DONTWAIT, MT_HEADER);
8965           if (mout == NULL) {
8966                     sctp_m_freem(err_cause);
8967                     return;
8968           }
8969           iph = mtod(m, struct ip *);
8970           iph_out = NULL;
8971           ip6_out = NULL;
8972           if (iph->ip_v == IPVERSION) {
8973                     iph_out = mtod(mout, struct ip *);
8974                     mout->m_len = sizeof(*iph_out) + sizeof(*abm);
8975                     mout->m_next = err_cause;
8976 
8977                     /* Fill in the IP header for the ABORT */
8978                     iph_out->ip_v = IPVERSION;
8979                     iph_out->ip_hl = (sizeof(struct ip) / 4);
8980                     iph_out->ip_tos = (u_char)0;
8981                     iph_out->ip_id = 0;
8982                     iph_out->ip_off = 0;
8983                     iph_out->ip_ttl = MAXTTL;
8984                     iph_out->ip_p = IPPROTO_SCTP;
8985                     iph_out->ip_src.s_addr = iph->ip_dst.s_addr;
8986                     iph_out->ip_dst.s_addr = iph->ip_src.s_addr;
8987                     /* let IP layer calculate this */
8988                     iph_out->ip_sum = 0;
8989 
8990                     iphlen_out = sizeof(*iph_out);
8991                     abm = (struct sctp_abort_msg *)((vaddr_t)iph_out + iphlen_out);
8992           } else if (iph->ip_v == (IPV6_VERSION >> 4)) {
8993                     ip6 = (struct ip6_hdr *)iph;
8994                     ip6_out = mtod(mout, struct ip6_hdr *);
8995                     mout->m_len = sizeof(*ip6_out) + sizeof(*abm);
8996                     mout->m_next = err_cause;
8997 
8998                     /* Fill in the IP6 header for the ABORT */
8999                     ip6_out->ip6_flow = ip6->ip6_flow;
9000                     ip6_out->ip6_hlim = ip6_defhlim;
9001                     ip6_out->ip6_nxt = IPPROTO_SCTP;
9002                     ip6_out->ip6_src = ip6->ip6_dst;
9003                     ip6_out->ip6_dst = ip6->ip6_src;
9004 
9005                     iphlen_out = sizeof(*ip6_out);
9006                     abm = (struct sctp_abort_msg *)((vaddr_t)ip6_out + iphlen_out);
9007           } else {
9008                     /* Currently not supported */
9009                     return;
9010           }
9011 
9012           abm->sh.src_port = sh->dest_port;
9013           abm->sh.dest_port = sh->src_port;
9014           abm->sh.checksum = 0;
9015           if (vtag == 0) {
9016                     abm->sh.v_tag = sh->v_tag;
9017                     abm->msg.ch.chunk_flags = SCTP_HAD_NO_TCB;
9018           } else {
9019                     abm->sh.v_tag = htonl(vtag);
9020                     abm->msg.ch.chunk_flags = 0;
9021           }
9022           abm->msg.ch.chunk_type = SCTP_ABORT_ASSOCIATION;
9023 
9024           if (err_cause) {
9025                     struct mbuf *m_tmp = err_cause;
9026                     int err_len = 0;
9027                     /* get length of the err_cause chain */
9028                     while (m_tmp != NULL) {
9029                               err_len += m_tmp->m_len;
9030                               m_tmp = m_tmp->m_next;
9031                     }
9032                     mout->m_pkthdr.len = mout->m_len + err_len;
9033                     if (err_len % 4) {
9034                               /* need pad at end of chunk */
9035                               u_int32_t cpthis=0;
9036                               int padlen;
9037                               padlen = 4 - (mout->m_pkthdr.len % 4);
9038                               m_copyback(mout, mout->m_pkthdr.len, padlen, (void *)&cpthis);
9039                     }
9040                     abm->msg.ch.chunk_length = htons(sizeof(abm->msg.ch) + err_len);
9041           } else {
9042                     mout->m_pkthdr.len = mout->m_len;
9043                     abm->msg.ch.chunk_length = htons(sizeof(abm->msg.ch));
9044           }
9045 
9046           /* add checksum */
9047           if ((sctp_no_csum_on_loopback) && m_get_rcvif_NOMPSAFE(m) != NULL &&
9048               m_get_rcvif_NOMPSAFE(m)->if_type == IFT_LOOP) {
9049                     abm->sh.checksum =  0;
9050           } else {
9051                     abm->sh.checksum = sctp_calculate_sum(mout, NULL, iphlen_out);
9052           }
9053 
9054           /* zap the rcvif, it should be null */
9055           m_reset_rcvif(mout);
9056           if (iph_out != NULL) {
9057                     struct route ro;
9058 
9059                     /* zap the stack pointer to the route */
9060                     memset(&ro, 0, sizeof ro);
9061 #ifdef SCTP_DEBUG
9062                     if (sctp_debug_on & SCTP_DEBUG_OUTPUT2) {
9063                         printf("sctp_send_abort calling ip_output:\n");
9064                               sctp_print_address_pkt(iph_out, &abm->sh);
9065                 }
9066 #endif
9067                     /* set IPv4 length */
9068                     iph_out->ip_len = htons(mout->m_pkthdr.len);
9069                     /* out it goes */
9070                     (void)ip_output(mout, 0, &ro, IP_RAWOUTPUT, NULL, NULL);
9071           } else if (ip6_out != NULL) {
9072                     struct route ro;
9073 
9074                     /* zap the stack pointer to the route */
9075                     memset(&ro, 0, sizeof(ro));
9076 #ifdef SCTP_DEBUG
9077                     if (sctp_debug_on & SCTP_DEBUG_OUTPUT2) {
9078                         printf("sctp_send_abort calling ip6_output:\n");
9079                               sctp_print_address_pkt((struct ip *)ip6_out, &abm->sh);
9080                 }
9081 #endif
9082                     ip6_output(mout, NULL, &ro, 0, NULL, NULL, NULL);
9083           }
9084         sctp_pegs[SCTP_DATAGRAMS_SENT]++;
9085 }
9086 
9087 void
9088 sctp_send_operr_to(struct mbuf *m, int iphlen,
9089                        struct mbuf *scm,
9090                        uint32_t vtag)
9091 {
9092           struct sctphdr *ihdr;
9093           struct sctphdr *ohdr;
9094           struct sctp_chunkhdr *ophdr;
9095 
9096           struct ip *iph;
9097 #ifdef SCTP_DEBUG
9098           struct sockaddr_in6 lsa6, fsa6;
9099 #endif
9100           uint32_t val;
9101           iph = mtod(m, struct ip *);
9102           ihdr = (struct sctphdr *)((vaddr_t)iph + iphlen);
9103           if (!(scm->m_flags & M_PKTHDR)) {
9104                     /* must be a pkthdr */
9105                     printf("Huh, not a packet header in send_operr\n");
9106                     m_freem(scm);
9107                     return;
9108           }
9109           M_PREPEND(scm, (sizeof(struct sctphdr) + sizeof(struct sctp_chunkhdr)), M_DONTWAIT);
9110           if (scm == NULL) {
9111                     /* can't send because we can't add a mbuf */
9112                     return;
9113           }
9114           ohdr = mtod(scm, struct sctphdr *);
9115           ohdr->src_port = ihdr->dest_port;
9116           ohdr->dest_port = ihdr->src_port;
9117           ohdr->v_tag = vtag;
9118           ohdr->checksum = 0;
9119           ophdr = (struct sctp_chunkhdr *)(ohdr + 1);
9120           ophdr->chunk_type = SCTP_OPERATION_ERROR;
9121           ophdr->chunk_flags = 0;
9122           ophdr->chunk_length = htons(scm->m_pkthdr.len - sizeof(struct sctphdr));
9123           if (scm->m_pkthdr.len % 4) {
9124                     /* need padding */
9125                     u_int32_t cpthis=0;
9126                     int padlen;
9127                     padlen = 4 - (scm->m_pkthdr.len % 4);
9128                     m_copyback(scm, scm->m_pkthdr.len, padlen, (void *)&cpthis);
9129           }
9130           if ((sctp_no_csum_on_loopback) && m_get_rcvif_NOMPSAFE(m) != NULL &&
9131               m_get_rcvif_NOMPSAFE(m)->if_type == IFT_LOOP) {
9132                     val = 0;
9133           } else {
9134                     val = sctp_calculate_sum(scm, NULL, 0);
9135           }
9136           ohdr->checksum = val;
9137           if (iph->ip_v == IPVERSION) {
9138                     /* V4 */
9139                     struct ip *out;
9140                     struct route ro;
9141                     M_PREPEND(scm, sizeof(struct ip), M_DONTWAIT);
9142                     if (scm == NULL)
9143                               return;
9144                     memset(&ro, 0, sizeof ro);
9145                     out = mtod(scm, struct ip *);
9146                     out->ip_v = iph->ip_v;
9147                     out->ip_hl = (sizeof(struct ip)/4);
9148                     out->ip_tos = iph->ip_tos;
9149                     out->ip_id = iph->ip_id;
9150                     out->ip_off = 0;
9151                     out->ip_ttl = MAXTTL;
9152                     out->ip_p = IPPROTO_SCTP;
9153                     out->ip_sum = 0;
9154                     out->ip_src = iph->ip_dst;
9155                     out->ip_dst = iph->ip_src;
9156                     out->ip_len = htons(scm->m_pkthdr.len);
9157                     ip_output(scm, 0, &ro, IP_RAWOUTPUT, NULL, NULL);
9158                     sctp_pegs[SCTP_DATAGRAMS_SENT]++;
9159           } else {
9160                     /* V6 */
9161                     struct route ro;
9162                     struct ip6_hdr *out6, *in6;
9163 
9164                     M_PREPEND(scm, sizeof(struct ip6_hdr), M_DONTWAIT);
9165                     if (scm == NULL)
9166                               return;
9167                     memset(&ro, 0, sizeof ro);
9168                     in6 = mtod(m, struct ip6_hdr *);
9169                     out6 = mtod(scm, struct ip6_hdr *);
9170                     out6->ip6_flow = in6->ip6_flow;
9171                     out6->ip6_hlim = ip6_defhlim;
9172                     out6->ip6_nxt = IPPROTO_SCTP;
9173                     out6->ip6_src = in6->ip6_dst;
9174                     out6->ip6_dst = in6->ip6_src;
9175 
9176 #ifdef SCTP_DEBUG
9177                     memset(&lsa6, 0, sizeof(lsa6));
9178                     lsa6.sin6_len = sizeof(lsa6);
9179                     lsa6.sin6_family = AF_INET6;
9180                     lsa6.sin6_addr = out6->ip6_src;
9181                     memset(&fsa6, 0, sizeof(fsa6));
9182                     fsa6.sin6_len = sizeof(fsa6);
9183                     fsa6.sin6_family = AF_INET6;
9184                     fsa6.sin6_addr = out6->ip6_dst;
9185                     if (sctp_debug_on & SCTP_DEBUG_OUTPUT2) {
9186                               printf("sctp_operr_to calling ipv6 output:\n");
9187                               printf("src: ");
9188                               sctp_print_address((struct sockaddr *)&lsa6);
9189                               printf("dst ");
9190                               sctp_print_address((struct sockaddr *)&fsa6);
9191                     }
9192 #endif /* SCTP_DEBUG */
9193                     ip6_output(scm, NULL, &ro, 0, NULL, NULL, NULL);
9194                     sctp_pegs[SCTP_DATAGRAMS_SENT]++;
9195           }
9196 }
9197 
9198 static int
9199 sctp_copy_one(struct mbuf *m, struct uio *uio, int cpsz, int resv_upfront, int *mbcnt)
9200 {
9201           int left, cancpy, willcpy, error;
9202           left = cpsz;
9203 
9204           if (m == NULL) {
9205                     /* TSNH */
9206                     *mbcnt = 0;
9207                     return (ENOMEM);
9208           }
9209           m->m_len = 0;
9210           if ((left+resv_upfront) > (int)MHLEN) {
9211                     MCLGET(m, M_WAIT);
9212                     if (m == NULL) {
9213                               *mbcnt = 0;
9214                               return (ENOMEM);
9215                     }
9216                     if ((m->m_flags & M_EXT) == 0) {
9217                               *mbcnt = 0;
9218                               return (ENOMEM);
9219                     }
9220                     *mbcnt += m->m_ext.ext_size;
9221           }
9222           *mbcnt += MSIZE;
9223           cancpy = M_TRAILINGSPACE(m);
9224           willcpy = uimin(cancpy, left);
9225           if ((willcpy + resv_upfront) > cancpy) {
9226                     willcpy -= resv_upfront;
9227           }
9228           while (left > 0) {
9229                     /* Align data to the end */
9230                     if ((m->m_flags & M_EXT) == 0) {
9231                               m_align(m, willcpy);
9232                     } else {
9233                               MC_ALIGN(m, willcpy);
9234                     }
9235                     error = uiomove(mtod(m, void *), willcpy, uio);
9236                     if (error) {
9237                               return (error);
9238                     }
9239                     m->m_len = willcpy;
9240                     m->m_nextpkt = 0;
9241                     left -= willcpy;
9242                     if (left > 0) {
9243                               MGET(m->m_next, M_WAIT, MT_DATA);
9244                               if (m->m_next == NULL) {
9245                                         *mbcnt = 0;
9246                                         return (ENOMEM);
9247                               }
9248                               m = m->m_next;
9249                               m->m_len = 0;
9250                               *mbcnt += MSIZE;
9251                               if (left > (int)MHLEN) {
9252                                         MCLGET(m, M_WAIT);
9253                                         if (m == NULL) {
9254                                                   *mbcnt = 0;
9255                                                   return (ENOMEM);
9256                                         }
9257                                         if ((m->m_flags & M_EXT) == 0) {
9258                                                   *mbcnt = 0;
9259                                                   return (ENOMEM);
9260                                         }
9261                                         *mbcnt += m->m_ext.ext_size;
9262                               }
9263                               cancpy = M_TRAILINGSPACE(m);
9264                               willcpy = uimin(cancpy, left);
9265                     }
9266           }
9267           return (0);
9268 }
9269 
9270 static int
9271 sctp_copy_it_in(struct sctp_inpcb *inp,
9272                     struct sctp_tcb *stcb,
9273                     struct sctp_association *asoc,
9274                     struct sctp_nets *net,
9275                     struct sctp_sndrcvinfo *srcv,
9276                     struct uio *uio,
9277                     int flags)
9278 {
9279           /* This routine must be very careful in
9280            * its work. Protocol processing is
9281            * up and running so care must be taken to
9282            * spl...() when you need to do something
9283            * that may effect the stcb/asoc. The sb is
9284            * locked however. When data is copied the
9285            * protocol processing should be enabled since
9286            * this is a slower operation...
9287            */
9288           struct socket *so;
9289           int error = 0;
9290           int frag_size, mbcnt = 0, mbcnt_e = 0;
9291           unsigned int sndlen;
9292           unsigned int tot_demand;
9293           int tot_out, dataout;
9294           struct sctp_tmit_chunk *chk;
9295           struct mbuf *mm;
9296           struct sctp_stream_out *strq;
9297           uint32_t my_vtag;
9298           int resv_in_first;
9299 
9300           so = stcb->sctp_socket;
9301           solock(so);
9302           chk = NULL;
9303           mm = NULL;
9304 
9305           sndlen = uio->uio_resid;
9306           /* lock the socket buf */
9307           error = sblock(&so->so_snd, SBLOCKWAIT(flags));
9308           if (error)
9309                     goto out_locked;
9310 
9311 #ifdef SCTP_DEBUG
9312           printf("sctp_copy_it_in: %d\n", sndlen);
9313 #endif
9314           /* will it ever fit ? */
9315           if (sndlen > so->so_snd.sb_hiwat) {
9316                     /* It will NEVER fit */
9317                     error = EMSGSIZE;
9318                     goto release;
9319           }
9320           /* Do I need to block? */
9321           if ((so->so_snd.sb_hiwat <
9322               (sndlen + asoc->total_output_queue_size)) ||
9323               (asoc->chunks_on_out_queue > sctp_max_chunks_on_queue) ||
9324               (asoc->total_output_mbuf_queue_size >
9325               so->so_snd.sb_mbmax)
9326           ) {
9327                     /* prune any prsctp bufs out */
9328                     if (asoc->peer_supports_prsctp) {
9329                               sctp_prune_prsctp(stcb, asoc, srcv, sndlen);
9330                     }
9331                     /*
9332                      * We store off a pointer to the endpoint.
9333                      * Since on return from this we must check to
9334                      * see if an so_error is set. If so we may have
9335                      * been reset and our stcb destroyed. Returning
9336                      * an error will flow back to the user...
9337                      */
9338                     while ((so->so_snd.sb_hiwat <
9339                         (sndlen + asoc->total_output_queue_size)) ||
9340                         (asoc->chunks_on_out_queue >
9341                         sctp_max_chunks_on_queue) ||
9342                         (asoc->total_output_mbuf_queue_size >
9343                         so->so_snd.sb_mbmax)
9344                     ) {
9345                               if ((so->so_state & SS_NBIO)
9346 #if defined(__FreeBSD__) && __FreeBSD_version >= 500000
9347                                   || (flags & MSG_NBIO)
9348 #endif
9349                                         ) {
9350                                         /* Non-blocking io in place */
9351                                         error = EWOULDBLOCK;
9352                                         goto release;
9353                               }
9354                               inp->sctp_tcb_at_block = (void *)stcb;
9355                               inp->error_on_block = 0;
9356 #ifdef SCTP_BLK_LOGGING
9357                               sctp_log_block(SCTP_BLOCK_LOG_INTO_BLK,
9358                                   so, asoc);
9359 #endif
9360                               sbunlock(&so->so_snd);
9361                               SCTP_TCB_UNLOCK(stcb);
9362                               error = sbwait(&so->so_snd);
9363                               SCTP_INP_RLOCK(inp);
9364                               if ((inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE) ||
9365                                   (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE)) {
9366                                         /* Should I really unlock ? */
9367                                         SCTP_INP_RUNLOCK(inp);
9368                                         error = EFAULT;
9369                                         goto out_locked;
9370                               }
9371                               SCTP_TCB_LOCK(stcb);
9372                               SCTP_INP_RUNLOCK(inp);
9373 
9374                               inp->sctp_tcb_at_block = 0;
9375 #ifdef SCTP_BLK_LOGGING
9376                               sctp_log_block(SCTP_BLOCK_LOG_OUTOF_BLK,
9377                                   so, asoc);
9378 #endif
9379                               if (inp->error_on_block) {
9380                                         /*
9381                                          * if our asoc was killed, the free code
9382                                          * (in sctp_pcb.c) will save a error in
9383                                          * here for us
9384                                          */
9385                                         error = inp->error_on_block;
9386                                         goto out_locked;
9387                               }
9388                               if (error) {
9389                                         goto out_locked;
9390                               }
9391                               /* did we encounter a socket error? */
9392                               if (so->so_error) {
9393                                         error = so->so_error;
9394                                         goto out_locked;
9395                               }
9396                               error = sblock(&so->so_snd, M_WAITOK);
9397                               if (error) {
9398                                         /* Can't acquire the lock */
9399                                         goto out_locked;
9400                               }
9401 #if defined(__FreeBSD__) && __FreeBSD_version >= 502115
9402                               if (so->so_rcv.sb_state & SBS_CANTSENDMORE) {
9403 #else
9404                               if (so->so_state & SS_CANTSENDMORE) {
9405 #endif
9406                                         /* The socket is now set not to sendmore.. its gone */
9407                                         error = EPIPE;
9408                                         goto release;
9409                               }
9410                               if (so->so_error) {
9411                                         error = so->so_error;
9412                                         goto release;
9413                               }
9414                               if (asoc->peer_supports_prsctp) {
9415                                         sctp_prune_prsctp(stcb, asoc, srcv, sndlen);
9416                               }
9417                     }
9418           }
9419           dataout = tot_out = uio->uio_resid;
9420           if (inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) {
9421                     resv_in_first = SCTP_MED_OVERHEAD;
9422           } else {
9423                     resv_in_first = SCTP_MED_V4_OVERHEAD;
9424           }
9425 
9426           /* Are we aborting? */
9427           if (srcv->sinfo_flags & SCTP_ABORT) {
9428                     if ((SCTP_GET_STATE(asoc) != SCTP_STATE_COOKIE_WAIT) &&
9429                         (SCTP_GET_STATE(asoc) != SCTP_STATE_COOKIE_ECHOED)) {
9430                               /* It has to be up before we abort */
9431                               /* how big is the user initiated abort? */
9432 
9433                               /* I wonder about doing a MGET without a splnet set.
9434                                * it is done that way in the sosend code so I guess
9435                                * it is ok :-0
9436                                */
9437                               MGETHDR(mm, M_WAIT, MT_DATA);
9438                               if (mm) {
9439                                         struct sctp_paramhdr *ph;
9440 
9441                                         tot_demand = (tot_out + sizeof(struct sctp_paramhdr));
9442                                         if (tot_demand > MHLEN) {
9443                                                   if (tot_demand > MCLBYTES) {
9444                                                             /* truncate user data */
9445                                                             tot_demand = MCLBYTES;
9446                                                             tot_out = tot_demand - sizeof(struct sctp_paramhdr);
9447                                                   }
9448                                                   MCLGET(mm, M_WAIT);
9449                                                   if ((mm->m_flags & M_EXT) == 0) {
9450                                                             /* truncate further */
9451                                                             tot_demand = MHLEN;
9452                                                             tot_out = tot_demand - sizeof(struct sctp_paramhdr);
9453                                                   }
9454                                         }
9455                                         /* now move forward the data pointer */
9456                                         ph = mtod(mm, struct sctp_paramhdr *);
9457                                         ph->param_type = htons(SCTP_CAUSE_USER_INITIATED_ABT);
9458                                         ph->param_length = htons((sizeof(struct sctp_paramhdr) + tot_out));
9459                                         ph++;
9460                                         mm->m_pkthdr.len = tot_out + sizeof(struct sctp_paramhdr);
9461                                         mm->m_len = mm->m_pkthdr.len;
9462                                         error = uiomove((void *)ph, (int)tot_out, uio);
9463                                         if (error) {
9464                                                   /*
9465                                                    * Here if we can't get his data we
9466                                                    * still abort we just don't get to
9467                                                    * send the users note :-0
9468                                                    */
9469                                                   sctp_m_freem(mm);
9470                                                   mm = NULL;
9471                                         }
9472                               }
9473                               sbunlock(&so->so_snd);
9474                               sctp_abort_an_association(stcb->sctp_ep, stcb,
9475                                                               SCTP_RESPONSE_TO_USER_REQ,
9476                                                               mm);
9477                               mm = NULL;
9478                               goto out_locked;
9479                     }
9480                     goto release;
9481           }
9482 
9483           /* Now can we send this? */
9484           if ((SCTP_GET_STATE(asoc) == SCTP_STATE_SHUTDOWN_SENT) ||
9485               (SCTP_GET_STATE(asoc) == SCTP_STATE_SHUTDOWN_ACK_SENT) ||
9486               (SCTP_GET_STATE(asoc) == SCTP_STATE_SHUTDOWN_RECEIVED) ||
9487               (asoc->state & SCTP_STATE_SHUTDOWN_PENDING)) {
9488                     /* got data while shutting down */
9489                     error = ECONNRESET;
9490                     goto release;
9491           }
9492           /* Is the stream no. valid? */
9493           if (srcv->sinfo_stream >= asoc->streamoutcnt) {
9494                     /* Invalid stream number */
9495                     error = EINVAL;
9496                     goto release;
9497           }
9498           if (asoc->strmout == NULL) {
9499                     /* huh? software error */
9500 #ifdef SCTP_DEBUG
9501                     if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
9502                               printf("software error in sctp_copy_it_in\n");
9503                     }
9504 #endif
9505                     error = EFAULT;
9506                     goto release;
9507           }
9508           if ((srcv->sinfo_flags & SCTP_EOF) &&
9509               (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_UDPTYPE) &&
9510               (tot_out == 0)) {
9511                     sounlock(so);
9512                     goto zap_by_it_now;
9513           }
9514           if (tot_out == 0) {
9515                     /* not allowed */
9516                     error = EMSGSIZE;
9517                     goto release;
9518           }
9519           /* save off the tag */
9520           my_vtag = asoc->my_vtag;
9521           strq = &asoc->strmout[srcv->sinfo_stream];
9522           /* First lets figure out the "chunking" point */
9523           frag_size = sctp_get_frag_point(stcb, asoc);
9524 
9525           /* two choices here, it all fits in one chunk or
9526            * we need multiple chunks.
9527            */
9528           sounlock(so);
9529           if (tot_out <= frag_size) {
9530                     /* no need to setup a template */
9531                     chk = (struct sctp_tmit_chunk *)SCTP_ZONE_GET(sctppcbinfo.ipi_zone_chunk);
9532                     if (chk == NULL) {
9533                               error = ENOMEM;
9534                               goto release;
9535                     }
9536                     sctppcbinfo.ipi_count_chunk++;
9537                     sctppcbinfo.ipi_gencnt_chunk++;
9538                     asoc->chunks_on_out_queue++;
9539                     MGETHDR(mm, M_WAIT, MT_DATA);
9540                     if (mm == NULL) {
9541                               error = ENOMEM;
9542                               goto clean_up;
9543                     }
9544                     error = sctp_copy_one(mm, uio, tot_out, resv_in_first, &mbcnt_e);
9545                     if (error)
9546                               goto clean_up;
9547                     sctp_prepare_chunk(chk, stcb, srcv, strq, net);
9548                     chk->mbcnt = mbcnt_e;
9549                     mbcnt += mbcnt_e;
9550                     mbcnt_e = 0;
9551                     mm->m_pkthdr.len = tot_out;
9552                     chk->data = mm;
9553                     mm = NULL;
9554 
9555                     /* the actual chunk flags */
9556                     chk->rec.data.rcv_flags |= SCTP_DATA_NOT_FRAG;
9557                     chk->whoTo->ref_count++;
9558 
9559                     /* fix up the send_size if it is not present */
9560                     chk->send_size = tot_out;
9561                     chk->book_size = chk->send_size;
9562                     /* ok, we are committed */
9563                     if ((srcv->sinfo_flags & SCTP_UNORDERED) == 0) {
9564                               /* bump the ssn if we are unordered. */
9565                               strq->next_sequence_sent++;
9566                     }
9567                     if (chk->flags & SCTP_PR_SCTP_BUFFER) {
9568                               asoc->sent_queue_cnt_removeable++;
9569                     }
9570                     solock(so);
9571                     if ((asoc->state == 0) ||
9572                         (my_vtag != asoc->my_vtag) ||
9573                         (so != inp->sctp_socket) ||
9574                         (inp->sctp_socket == 0)) {
9575                               /* connection was aborted */
9576                               sounlock(so);
9577                               error = ECONNRESET;
9578                               goto clean_up;
9579                     }
9580                     asoc->stream_queue_cnt++;
9581                     TAILQ_INSERT_TAIL(&strq->outqueue, chk, sctp_next);
9582                     /* now check if this stream is on the wheel */
9583                     if ((strq->next_spoke.tqe_next == NULL) &&
9584                         (strq->next_spoke.tqe_prev == NULL)) {
9585                               /* Insert it on the wheel since it is not
9586                                * on it currently
9587                                */
9588                               sctp_insert_on_wheel(asoc, strq);
9589                     }
9590                     sounlock(so);
9591 clean_up:
9592                     if (error) {
9593                               SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_chunk, chk);
9594                               sctppcbinfo.ipi_count_chunk--;
9595                               if ((int)sctppcbinfo.ipi_count_chunk < 0) {
9596                                         panic("Chunk count is negative");
9597                               }
9598                               goto release;
9599                     }
9600           } else {
9601                     /* we need to setup a template */
9602                     struct sctp_tmit_chunk template;
9603                     struct sctpchunk_listhead tmp;
9604 
9605                     /* setup the template */
9606                     sctp_prepare_chunk(&template, stcb, srcv, strq, net);
9607 
9608                     /* Prepare the temp list */
9609                     TAILQ_INIT(&tmp);
9610 
9611                     /* Template is complete, now time for the work */
9612                     while (tot_out > 0) {
9613                               /* Get a chunk */
9614                               chk = (struct sctp_tmit_chunk *)SCTP_ZONE_GET(sctppcbinfo.ipi_zone_chunk);
9615                               if (chk == NULL) {
9616                                         /*
9617                                          * ok we must spin through and dump anything
9618                                          * we have allocated and then jump to the
9619                                          * no_membad
9620                                          */
9621                                         error = ENOMEM;
9622                               }
9623                               sctppcbinfo.ipi_count_chunk++;
9624                               asoc->chunks_on_out_queue++;
9625 
9626                               sctppcbinfo.ipi_gencnt_chunk++;
9627                               *chk = template;
9628                               chk->whoTo->ref_count++;
9629                               MGETHDR(chk->data, M_WAIT, MT_DATA);
9630                               if (chk->data == NULL) {
9631                                         error = ENOMEM;
9632                                         goto temp_clean_up;
9633                               }
9634                               tot_demand = uimin(tot_out, frag_size);
9635                               error = sctp_copy_one(chk->data, uio, tot_demand , resv_in_first, &mbcnt_e);
9636                               if (error)
9637                                         goto temp_clean_up;
9638                               /* now fix the chk->send_size */
9639                               chk->mbcnt = mbcnt_e;
9640                               mbcnt += mbcnt_e;
9641                               mbcnt_e = 0;
9642                               chk->send_size = tot_demand;
9643                               chk->data->m_pkthdr.len = tot_demand;
9644                               chk->book_size = chk->send_size;
9645                               if (chk->flags & SCTP_PR_SCTP_BUFFER) {
9646                                         asoc->sent_queue_cnt_removeable++;
9647                               }
9648                               TAILQ_INSERT_TAIL(&tmp, chk, sctp_next);
9649                               tot_out -= tot_demand;
9650                     }
9651                     /* Now the tmp list holds all chunks and data */
9652                     if ((srcv->sinfo_flags & SCTP_UNORDERED) == 0) {
9653                               /* bump the ssn if we are unordered. */
9654                               strq->next_sequence_sent++;
9655                     }
9656                     /* Mark the first/last flags. This will
9657                      * result int a 3 for a single item on the list
9658                      */
9659                     chk = TAILQ_FIRST(&tmp);
9660                     chk->rec.data.rcv_flags |= SCTP_DATA_FIRST_FRAG;
9661                     chk = TAILQ_LAST(&tmp, sctpchunk_listhead);
9662                     chk->rec.data.rcv_flags |= SCTP_DATA_LAST_FRAG;
9663 
9664                     /* now move it to the streams actual queue */
9665                     /* first stop protocol processing */
9666                     mutex_enter(softnet_lock);
9667                     if ((asoc->state == 0) ||
9668                         (my_vtag != asoc->my_vtag) ||
9669                         (so != inp->sctp_socket) ||
9670                         (inp->sctp_socket == 0)) {
9671                               /* connection was aborted */
9672                               mutex_exit(softnet_lock);
9673                               error = ECONNRESET;
9674                               goto temp_clean_up;
9675                     }
9676                     chk = TAILQ_FIRST(&tmp);
9677                     while (chk) {
9678                               chk->data->m_nextpkt = 0;
9679                               TAILQ_REMOVE(&tmp, chk, sctp_next);
9680                               asoc->stream_queue_cnt++;
9681                               TAILQ_INSERT_TAIL(&strq->outqueue, chk, sctp_next);
9682                               chk = TAILQ_FIRST(&tmp);
9683                     }
9684                     /* now check if this stream is on the wheel */
9685                     if ((strq->next_spoke.tqe_next == NULL) &&
9686                         (strq->next_spoke.tqe_prev == NULL)) {
9687                               /* Insert it on the wheel since it is not
9688                                * on it currently
9689                                */
9690                               sctp_insert_on_wheel(asoc, strq);
9691                     }
9692                     /* Ok now we can allow pping */
9693                     mutex_exit(softnet_lock);
9694 temp_clean_up:
9695                     if (error) {
9696                               chk = TAILQ_FIRST(&tmp);
9697                               while (chk) {
9698                                         sctp_m_freem(chk->data);
9699                                         chk->data = NULL;
9700                                         TAILQ_REMOVE(&tmp, chk, sctp_next);
9701                                         SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_chunk, chk);
9702                                         sctppcbinfo.ipi_count_chunk--;
9703                                         asoc->chunks_on_out_queue--;
9704                                         if ((int)sctppcbinfo.ipi_count_chunk < 0) {
9705                                                   panic("Chunk count is negative");
9706                                         }
9707                                         sctppcbinfo.ipi_gencnt_chunk++;
9708                                         chk = TAILQ_FIRST(&tmp);
9709                               }
9710                               goto release;
9711                     }
9712           }
9713 zap_by_it_now:
9714 #ifdef SCTP_MBCNT_LOGGING
9715           sctp_log_mbcnt(SCTP_LOG_MBCNT_INCREASE,
9716                            asoc->total_output_queue_size,
9717                            dataout,
9718                            asoc->total_output_mbuf_queue_size,
9719                            mbcnt);
9720 #endif
9721           solock(so);
9722           asoc->total_output_queue_size += dataout;
9723           asoc->total_output_mbuf_queue_size += mbcnt;
9724           if ((stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE) ||
9725               (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL)) {
9726                     so->so_snd.sb_cc += dataout;
9727                     so->so_snd.sb_mbcnt += mbcnt;
9728           }
9729           if ((srcv->sinfo_flags & SCTP_EOF) &&
9730               (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_UDPTYPE)
9731                     ) {
9732                     int some_on_streamwheel = 0;
9733                     error = 0;
9734                     if (!TAILQ_EMPTY(&asoc->out_wheel)) {
9735                               /* Check to see if some data queued */
9736                               struct sctp_stream_out *outs;
9737                               TAILQ_FOREACH(outs, &asoc->out_wheel, next_spoke) {
9738                                         if (!TAILQ_EMPTY(&outs->outqueue)) {
9739                                                   some_on_streamwheel = 1;
9740                                                   break;
9741                                         }
9742                               }
9743                     }
9744                     if (TAILQ_EMPTY(&asoc->send_queue) &&
9745                         TAILQ_EMPTY(&asoc->sent_queue) &&
9746                         (some_on_streamwheel == 0)) {
9747                               /* there is nothing queued to send, so I'm done... */
9748                               if ((SCTP_GET_STATE(asoc) != SCTP_STATE_SHUTDOWN_SENT) &&
9749                                   (SCTP_GET_STATE(asoc) != SCTP_STATE_SHUTDOWN_ACK_SENT)) {
9750                                         /* only send SHUTDOWN the first time through */
9751 #ifdef SCTP_DEBUG
9752                                         if (sctp_debug_on & SCTP_DEBUG_OUTPUT4) {
9753                                                   printf("%s:%d sends a shutdown\n",
9754                                                          __FILE__,
9755                                                          __LINE__
9756                                                             );
9757                                         }
9758 #endif
9759                                         sctp_send_shutdown(stcb, stcb->asoc.primary_destination);
9760                                         asoc->state = SCTP_STATE_SHUTDOWN_SENT;
9761                                         sctp_timer_start(SCTP_TIMER_TYPE_SHUTDOWN, stcb->sctp_ep, stcb,
9762                                                              asoc->primary_destination);
9763                                         sctp_timer_start(SCTP_TIMER_TYPE_SHUTDOWNGUARD, stcb->sctp_ep, stcb,
9764                                                              asoc->primary_destination);
9765                               }
9766                     } else {
9767                               /*
9768                                * we still got (or just got) data to send, so set
9769                                * SHUTDOWN_PENDING
9770                                */
9771                               /*
9772                                * XXX sockets draft says that SCTP_EOF should be sent
9773                                * with no data.  currently, we will allow user data
9774                                * to be sent first and move to SHUTDOWN-PENDING
9775                                */
9776                               asoc->state |= SCTP_STATE_SHUTDOWN_PENDING;
9777                     }
9778           }
9779 #ifdef SCTP_DEBUG
9780           if (sctp_debug_on & SCTP_DEBUG_OUTPUT2) {
9781                     printf("++total out:%d total_mbuf_out:%d\n",
9782                            (int)asoc->total_output_queue_size,
9783                            (int)asoc->total_output_mbuf_queue_size);
9784           }
9785 #endif
9786 
9787 release:
9788           sbunlock(&so->so_snd);
9789 out_locked:
9790           sounlock(so);
9791 
9792           sctp_m_freem(mm);
9793           return (error);
9794 }
9795 
9796 
9797 int
9798 sctp_sosend(struct socket *so, struct sockaddr *addr, struct uio *uio,
9799               struct mbuf *top, struct mbuf *control, int flags, struct lwp *p)
9800 {
9801           int error, use_rcvinfo;
9802           int queue_only = 0, queue_only_for_init=0;
9803           int un_sent = 0;
9804           int now_filled=0;
9805           struct sctp_inpcb *inp;
9806           struct sctp_tcb *stcb=NULL;
9807           struct sctp_sndrcvinfo srcv;
9808           struct timeval now;
9809           struct sctp_nets *net;
9810           struct sctp_association *asoc;
9811           struct sctp_inpcb *t_inp;
9812           int create_lock_applied = 0;
9813 
9814           error = use_rcvinfo = 0;
9815           net = NULL;
9816           stcb = NULL;
9817           asoc = NULL;
9818           t_inp = inp = (struct sctp_inpcb *)so->so_pcb;
9819 
9820           solock(so);
9821           if ((inp->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE) &&
9822               (inp->sctp_flags & SCTP_PCB_FLAGS_ACCEPTING)) {
9823                     /* The listner can NOT send */
9824                     error = EFAULT;
9825                     sounlock(so);
9826                     goto out;
9827           }
9828           if (addr) {
9829                     SCTP_ASOC_CREATE_LOCK(inp);
9830                     if ((inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE) ||
9831                         (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE)) {
9832                               /* Should I really unlock ? */
9833                               error = EFAULT;
9834                               sounlock(so);
9835                               goto out;
9836 
9837                     }
9838                     create_lock_applied = 1;
9839                     if (((inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) == 0) &&
9840                         (addr->sa_family == AF_INET6)) {
9841                               error = EINVAL;
9842                               sounlock(so);
9843                               goto out;
9844                     }
9845           }
9846           /* now we must find the assoc */
9847           if (inp->sctp_flags & SCTP_PCB_FLAGS_CONNECTED) {
9848                     SCTP_INP_RLOCK(inp);
9849                     stcb = LIST_FIRST(&inp->sctp_asoc_list);
9850                     if (stcb == NULL) {
9851                               SCTP_INP_RUNLOCK(inp);
9852                               error = ENOTCONN;
9853                               sounlock(so);
9854                               goto out;
9855                     }
9856                     SCTP_TCB_LOCK(stcb);
9857                     SCTP_INP_RUNLOCK(inp);
9858                     net = stcb->asoc.primary_destination;
9859           }
9860 #ifdef SCTP_DEBUG
9861           printf("sctp_sosend: get control\n");
9862 #endif
9863           /* get control */
9864           if (control) {
9865                     /* process cmsg snd/rcv info (maybe a assoc-id) */
9866                     if (sctp_find_cmsg(SCTP_SNDRCV, (void *)&srcv, control,
9867                                            sizeof(srcv))) {
9868                               /* got one */
9869                               if (srcv.sinfo_flags & SCTP_SENDALL) {
9870                                         /* its a sendall */
9871                                         sctppcbinfo.mbuf_track--;
9872                                         sctp_m_freem(control);
9873 
9874                                         if (create_lock_applied) {
9875                                                   SCTP_ASOC_CREATE_UNLOCK(inp);
9876                                                   create_lock_applied = 0;
9877                                         }
9878                                         return (sctp_sendall(inp, uio, top, &srcv));
9879                               }
9880                               use_rcvinfo = 1;
9881                     }
9882           }
9883 #ifdef SCTP_DEBUG
9884           printf("sctp_sosend: doing lookup\n");
9885 #endif
9886           if (stcb == NULL) {
9887                     /* Need to do a lookup */
9888                     if (use_rcvinfo && srcv.sinfo_assoc_id) {
9889                               stcb = sctp_findassociation_ep_asocid(inp, srcv.sinfo_assoc_id);
9890                               /*
9891                                * Question: Should I error here if the assoc_id is
9892                                * no longer valid? i.e. I can't find it?
9893                                */
9894                               if ((stcb) &&
9895                                   (addr != NULL)) {
9896                                         /* Must locate the net structure */
9897                                         net = sctp_findnet(stcb, addr);
9898                               }
9899                     }
9900                     if (stcb == NULL) {
9901                               if (addr != NULL) {
9902                                         /* Since we did not use findep we must
9903                                          * increment it, and if we don't find a
9904                                          * tcb decrement it.
9905                                          */
9906                                         SCTP_INP_WLOCK(inp);
9907                                         SCTP_INP_INCR_REF(inp);
9908                                         SCTP_INP_WUNLOCK(inp);
9909                                         stcb = sctp_findassociation_ep_addr(&t_inp, addr, &net, NULL, NULL);
9910                                         if (stcb == NULL) {
9911                                                   SCTP_INP_WLOCK(inp);
9912                                                   SCTP_INP_DECR_REF(inp);
9913                                                   SCTP_INP_WUNLOCK(inp);
9914                                         }
9915                               }
9916                     }
9917           }
9918           if ((stcb == NULL) &&
9919               (inp->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE)) {
9920                     error = ENOTCONN;
9921                     sounlock(so);
9922                     goto out;
9923           } else if ((stcb == NULL) && (addr == NULL)) {
9924                     error = ENOENT;
9925                     sounlock(so);
9926                     goto out;
9927           } else if (stcb == NULL) {
9928                     /* UDP style, we must go ahead and start the INIT process */
9929                     if ((use_rcvinfo) &&
9930                         (srcv.sinfo_flags & SCTP_ABORT)) {
9931                               /* User asks to abort a non-existent asoc */
9932                               error = ENOENT;
9933                               sounlock(so);
9934                               goto out;
9935                     }
9936                     /* get an asoc/stcb struct */
9937                     stcb = sctp_aloc_assoc(inp, addr, 1, &error, 0);
9938                     if (stcb == NULL) {
9939                               /* Error is setup for us in the call */
9940                               sounlock(so);
9941                               goto out;
9942                     }
9943                     if (create_lock_applied) {
9944                               SCTP_ASOC_CREATE_UNLOCK(inp);
9945                               create_lock_applied = 0;
9946                     } else {
9947                               printf("Huh-3? create lock should have been on??\n");
9948                     }
9949                     /* Turn on queue only flag to prevent data from being sent */
9950                     queue_only = 1;
9951                     asoc = &stcb->asoc;
9952                     asoc->state = SCTP_STATE_COOKIE_WAIT;
9953                     SCTP_GETTIME_TIMEVAL(&asoc->time_entered);
9954                     if (control) {
9955                               /* see if a init structure exists in cmsg headers */
9956                               struct sctp_initmsg initm;
9957                               int i;
9958                               if (sctp_find_cmsg(SCTP_INIT, (void *)&initm, control, sizeof(initm))) {
9959                                         /* we have an INIT override of the default */
9960                                         if (initm.sinit_max_attempts)
9961                                                   asoc->max_init_times = initm.sinit_max_attempts;
9962                                         if (initm.sinit_num_ostreams)
9963                                                   asoc->pre_open_streams = initm.sinit_num_ostreams;
9964                                         if (initm.sinit_max_instreams)
9965                                                   asoc->max_inbound_streams = initm.sinit_max_instreams;
9966                                         if (initm.sinit_max_init_timeo)
9967                                                   asoc->initial_init_rto_max = initm.sinit_max_init_timeo;
9968                                         if (asoc->streamoutcnt < asoc->pre_open_streams) {
9969                                                   /* Default is NOT correct */
9970 #ifdef SCTP_DEBUG
9971                                                   if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
9972                                                             printf("Ok, defout:%d pre_open:%d\n",
9973                                                                    asoc->streamoutcnt, asoc->pre_open_streams);
9974                                                   }
9975 #endif
9976                                                   free(asoc->strmout, M_PCB);
9977                                                   asoc->strmout = NULL;
9978                                                   asoc->streamoutcnt = asoc->pre_open_streams;
9979 
9980                                                   /* What happesn if this fails? .. we panic ...*/
9981                                                   asoc->strmout = malloc(
9982                                                          asoc->streamoutcnt *
9983                                                          sizeof(struct sctp_stream_out),
9984                                                          M_PCB, M_WAIT);
9985                                                   for (i = 0; i < asoc->streamoutcnt; i++) {
9986                                                             /*
9987                                                              * inbound side must be set to 0xffff,
9988                                                              * also NOTE when we get the INIT-ACK
9989                                                              * back (for INIT sender) we MUST
9990                                                              * reduce the count (streamoutcnt) but
9991                                                              * first check if we sent to any of the
9992                                                              * upper streams that were dropped (if
9993                                                              * some were). Those that were dropped
9994                                                              * must be notified to the upper layer
9995                                                              * as failed to send.
9996                                                              */
9997                                                             asoc->strmout[i].next_sequence_sent = 0x0;
9998                                                             TAILQ_INIT(&asoc->strmout[i].outqueue);
9999                                                             asoc->strmout[i].stream_no = i;
10000                                                             asoc->strmout[i].next_spoke.tqe_next = 0;
10001                                                             asoc->strmout[i].next_spoke.tqe_prev = 0;
10002                                                   }
10003                                         }
10004                               }
10005 
10006                     }
10007                     /* out with the INIT */
10008                     queue_only_for_init = 1;
10009                     sctp_send_initiate(inp, stcb);
10010                     /*
10011                      * we may want to dig in after this call and adjust the MTU
10012                      * value. It defaulted to 1500 (constant) but the ro structure
10013                      * may now have an update and thus we may need to change it
10014                      * BEFORE we append the message.
10015                      */
10016                     net = stcb->asoc.primary_destination;
10017                     asoc = &stcb->asoc;
10018           } else {
10019                     asoc = &stcb->asoc;
10020           }
10021           if (create_lock_applied) {
10022                     SCTP_ASOC_CREATE_UNLOCK(inp);
10023                     create_lock_applied = 0;
10024           }
10025           if ((SCTP_GET_STATE(asoc) == SCTP_STATE_COOKIE_WAIT) ||
10026               (SCTP_GET_STATE(asoc) == SCTP_STATE_COOKIE_ECHOED)) {
10027                     queue_only = 1;
10028           }
10029           if (use_rcvinfo == 0) {
10030                     /* Grab the default stuff from the asoc */
10031                     srcv = stcb->asoc.def_send;
10032           }
10033           /* we are now done with all control */
10034           sctp_m_freem(control);
10035           control = NULL;
10036 
10037           if ((SCTP_GET_STATE(asoc) == SCTP_STATE_SHUTDOWN_SENT) ||
10038               (SCTP_GET_STATE(asoc) == SCTP_STATE_SHUTDOWN_RECEIVED) ||
10039               (SCTP_GET_STATE(asoc) == SCTP_STATE_SHUTDOWN_ACK_SENT) ||
10040               (asoc->state & SCTP_STATE_SHUTDOWN_PENDING)) {
10041                     if ((use_rcvinfo) &&
10042                         (srcv.sinfo_flags & SCTP_ABORT)) {
10043                               ;
10044                     } else {
10045                               error = ECONNRESET;
10046                               sounlock(so);
10047                               goto out;
10048                     }
10049           }
10050           /* Ok, we will attempt a msgsnd :> */
10051 #if 0     /* XXX */
10052           if (p)
10053                     p->p_stats->p_ru.ru_msgsnd++;
10054 #endif
10055 
10056           if (stcb) {
10057                     if (net && ((srcv.sinfo_flags & SCTP_ADDR_OVER))) {
10058                               /* we take the override or the unconfirmed */
10059                               ;
10060                     } else {
10061                               net = stcb->asoc.primary_destination;
10062                     }
10063           }
10064 
10065 #ifdef SCTP_DEBUG
10066           printf("sctp_sosend: before copying in %p\n", top);
10067 #endif
10068           if (top == NULL) {
10069                     /* Must copy it all in from user land. The
10070                      * socket buf is locked but we don't suspend
10071                      * protocol processing until we are ready to
10072                      * send/queue it.
10073                      */
10074                     sounlock(so);
10075 #ifdef SCTP_DEBUG
10076                     printf("sctp_sosend: before cii\n");
10077 #endif
10078                     error = sctp_copy_it_in(inp, stcb, asoc, net, &srcv, uio, flags);
10079 #ifdef SCTP_DEBUG
10080                     printf("sctp_sosend: after cii\n");
10081 #endif
10082                     if (error)
10083                               goto out;
10084           } else {
10085                     /* Here we must either pull in the user data to chunk
10086                      * buffers, or use top to do a msg_append.
10087                      */
10088                     error = sctp_msg_append(stcb, net, top, &srcv, flags);
10089                     sounlock(so);
10090                     if (error)
10091                               goto out;
10092                     /* zap the top since it is now being used */
10093                     top = 0;
10094           }
10095 #ifdef SCTP_DEBUG
10096           printf("sctp_sosend: after copying in\n");
10097 #endif
10098           if (net->flight_size > net->cwnd) {
10099                     sctp_pegs[SCTP_SENDTO_FULL_CWND]++;
10100                     queue_only = 1;
10101 
10102           } else if (asoc->ifp_had_enobuf) {
10103                     sctp_pegs[SCTP_QUEONLY_BURSTLMT]++;
10104                     queue_only = 1;
10105           } else {
10106                     un_sent = ((stcb->asoc.total_output_queue_size - stcb->asoc.total_flight) +
10107                                  ((stcb->asoc.chunks_on_out_queue - stcb->asoc.total_flight_count) * sizeof(struct sctp_data_chunk)) +
10108                                  SCTP_MED_OVERHEAD);
10109 
10110                     if (((inp->sctp_flags & SCTP_PCB_FLAGS_NODELAY) == 0) &&
10111                         (stcb->asoc.total_flight > 0) &&
10112                         (un_sent < (int)stcb->asoc.smallest_mtu)) {
10113 
10114                               /* Ok, Nagle is set on and we have data outstanding. Don't
10115                                * send anything and let SACKs drive out the data unless we
10116                                * have a "full" segment to send.
10117                                */
10118                               sctp_pegs[SCTP_NAGLE_NOQ]++;
10119                               queue_only = 1;
10120                     } else {
10121                               sctp_pegs[SCTP_NAGLE_OFF]++;
10122                     }
10123           }
10124           if (queue_only_for_init) {
10125                     /* It is possible to have a turn around of the
10126                      * INIT/INIT-ACK/COOKIE before I have a chance to
10127                      * copy in the data. In such a case I DO want to
10128                      * send it out by reversing the queue only flag.
10129                      */
10130                     if ((SCTP_GET_STATE(asoc) != SCTP_STATE_COOKIE_WAIT) ||
10131                         (SCTP_GET_STATE(asoc) != SCTP_STATE_COOKIE_ECHOED)) {
10132                               /* yep, reverse it */
10133                               queue_only = 0;
10134                     }
10135           }
10136 
10137 #ifdef SCTP_DEBUG
10138           printf("sctp_sosend: before sending chunk\n");
10139 #endif
10140           if ((queue_only == 0) && (stcb->asoc.peers_rwnd  && un_sent)) {
10141                     /* we can attempt to send too.*/
10142 #ifdef SCTP_DEBUG
10143                     if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
10144                               printf("USR Send calls sctp_chunk_output\n");
10145                     }
10146 #endif
10147                     solock(so);
10148                     sctp_pegs[SCTP_OUTPUT_FRM_SND]++;
10149                     sctp_chunk_output(inp, stcb, 0);
10150                     sounlock(so);
10151           } else if ((queue_only == 0) &&
10152                        (stcb->asoc.peers_rwnd == 0) &&
10153                        (stcb->asoc.total_flight == 0)) {
10154                     /* We get to have a probe outstanding */
10155                     solock(so);
10156                     sctp_from_user_send = 1;
10157                     sctp_chunk_output(inp, stcb, 0);
10158                     sctp_from_user_send = 0;
10159                     sounlock(so);
10160 
10161           } else if (!TAILQ_EMPTY(&stcb->asoc.control_send_queue)) {
10162                     int num_out, reason, cwnd_full;
10163                     /* Here we do control only */
10164                     solock(so);
10165                     sctp_med_chunk_output(inp, stcb, &stcb->asoc, &num_out,
10166                                               &reason, 1, &cwnd_full, 1, &now, &now_filled);
10167                     sounlock(so);
10168           }
10169 #ifdef SCTP_DEBUG
10170           if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
10171                     printf("USR Send complete qo:%d prw:%d unsent:%d tf:%d cooq:%d toqs:%d \n",
10172                            queue_only, stcb->asoc.peers_rwnd, un_sent,
10173                            stcb->asoc.total_flight, stcb->asoc.chunks_on_out_queue,
10174                            stcb->asoc.total_output_queue_size);
10175           }
10176 #endif
10177  out:
10178           if (create_lock_applied) {
10179                     SCTP_ASOC_CREATE_UNLOCK(inp);
10180                     create_lock_applied = 0;
10181           }
10182           if (stcb) {
10183                     SCTP_TCB_UNLOCK(stcb);
10184           }
10185           sctp_m_freem(top);
10186           sctp_m_freem(control);
10187           return (error);
10188 }
10189