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