sctp_input.c revision 164205
1/*-
2 * Copyright (c) 2001-2006, Cisco Systems, Inc. All rights reserved.
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions are met:
6 *
7 * a) Redistributions of source code must retain the above copyright notice,
8 *   this list of conditions and the following disclaimer.
9 *
10 * b) Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in
12 *   the documentation and/or other materials provided with the distribution.
13 *
14 * c) Neither the name of Cisco Systems, Inc. nor the names of its
15 *    contributors may be used to endorse or promote products derived
16 *    from this software without specific prior written permission.
17 *
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
20 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
22 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
23 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
24 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
26 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
28 * THE POSSIBILITY OF SUCH DAMAGE.
29 */
30
31/* $KAME: sctp_input.c,v 1.27 2005/03/06 16:04:17 itojun Exp $	 */
32
33#include <sys/cdefs.h>
34__FBSDID("$FreeBSD: head/sys/netinet/sctp_input.c 164205 2006-11-11 22:44:12Z rrs $");
35
36#include "opt_ipsec.h"
37#include "opt_compat.h"
38#include "opt_inet6.h"
39#include "opt_inet.h"
40#include "opt_sctp.h"
41
42#include <sys/param.h>
43#include <sys/systm.h>
44#include <sys/malloc.h>
45#include <sys/mbuf.h>
46#include <sys/socket.h>
47#include <sys/socketvar.h>
48#include <sys/sysctl.h>
49#include <sys/domain.h>
50#include <sys/protosw.h>
51#include <sys/kernel.h>
52#include <sys/errno.h>
53#include <sys/syslog.h>
54
55#include <sys/limits.h>
56#include <machine/cpu.h>
57
58#include <net/if.h>
59#include <net/route.h>
60#include <net/if_types.h>
61
62#include <netinet/in.h>
63#include <netinet/in_systm.h>
64#include <netinet/ip.h>
65#include <netinet/in_pcb.h>
66#include <netinet/in_var.h>
67#include <netinet/ip_var.h>
68
69#ifdef INET6
70#include <netinet/ip6.h>
71#include <netinet6/ip6_var.h>
72#endif				/* INET6 */
73
74#include <netinet/ip_icmp.h>
75#include <netinet/icmp_var.h>
76
77#include <netinet/sctp_os.h>
78#include <netinet/sctp_var.h>
79#include <netinet/sctp_pcb.h>
80#include <netinet/sctp_header.h>
81#include <netinet/sctputil.h>
82#include <netinet/sctp_output.h>
83#include <netinet/sctp_input.h>
84#include <netinet/sctp_auth.h>
85#include <netinet/sctp_indata.h>
86#include <netinet/sctp_asconf.h>
87
88#include <netinet/ip_options.h>
89
90
91#ifdef IPSEC
92#include <netinet6/ipsec.h>
93#include <netkey/key.h>
94#endif				/* IPSEC */
95
96
97#ifdef SCTP_DEBUG
98extern uint32_t sctp_debug_on;
99
100#endif
101
102
103static void
104sctp_stop_all_cookie_timers(struct sctp_tcb *stcb)
105{
106	struct sctp_nets *net;
107
108	SCTP_TCB_LOCK_ASSERT(stcb);
109	TAILQ_FOREACH(net, &stcb->asoc.nets, sctp_next) {
110		if ((callout_pending(&net->rxt_timer.timer)) &&
111		    (net->rxt_timer.type == SCTP_TIMER_TYPE_COOKIE)) {
112			sctp_timer_stop(SCTP_TIMER_TYPE_COOKIE,
113			    stcb->sctp_ep,
114			    stcb,
115			    net);
116		}
117	}
118}
119
120/* INIT handler */
121static void
122sctp_handle_init(struct mbuf *m, int iphlen, int offset, struct sctphdr *sh,
123    struct sctp_init_chunk *cp, struct sctp_inpcb *inp, struct sctp_tcb *stcb,
124    struct sctp_nets *net)
125{
126	struct sctp_init *init;
127	struct mbuf *op_err;
128	uint32_t init_limit;
129
130#ifdef SCTP_DEBUG
131	if (sctp_debug_on & SCTP_DEBUG_INPUT2) {
132		printf("sctp_handle_init: handling INIT tcb:%p\n", stcb);
133	}
134#endif
135	op_err = NULL;
136	init = &cp->init;
137	/* First are we accepting? */
138	if ((inp->sctp_socket->so_qlimit == 0) && (stcb == NULL)) {
139#ifdef SCTP_DEBUG
140		if (sctp_debug_on & SCTP_DEBUG_INPUT2) {
141			printf("sctp_handle_init: Abort, so_qlimit:%d\n", inp->sctp_socket->so_qlimit);
142		}
143#endif
144		/*
145		 * FIX ME ?? What about TCP model and we have a
146		 * match/restart case?
147		 */
148		sctp_abort_association(inp, stcb, m, iphlen, sh, op_err);
149		return;
150	}
151	if (ntohs(cp->ch.chunk_length) < sizeof(struct sctp_init_chunk)) {
152		/* Invalid length */
153		op_err = sctp_generate_invmanparam(SCTP_CAUSE_INVALID_PARAM);
154		sctp_abort_association(inp, stcb, m, iphlen, sh, op_err);
155		return;
156	}
157	/* validate parameters */
158	if (init->initiate_tag == 0) {
159		/* protocol error... send abort */
160		op_err = sctp_generate_invmanparam(SCTP_CAUSE_INVALID_PARAM);
161		sctp_abort_association(inp, stcb, m, iphlen, sh, op_err);
162		return;
163	}
164	if (ntohl(init->a_rwnd) < SCTP_MIN_RWND) {
165		/* invalid parameter... send abort */
166		op_err = sctp_generate_invmanparam(SCTP_CAUSE_INVALID_PARAM);
167		sctp_abort_association(inp, stcb, m, iphlen, sh, op_err);
168		return;
169	}
170	if (init->num_inbound_streams == 0) {
171		/* protocol error... send abort */
172		op_err = sctp_generate_invmanparam(SCTP_CAUSE_INVALID_PARAM);
173		sctp_abort_association(inp, stcb, m, iphlen, sh, op_err);
174		return;
175	}
176	if (init->num_outbound_streams == 0) {
177		/* protocol error... send abort */
178		op_err = sctp_generate_invmanparam(SCTP_CAUSE_INVALID_PARAM);
179		sctp_abort_association(inp, stcb, m, iphlen, sh, op_err);
180		return;
181	}
182	init_limit = offset + ntohs(cp->ch.chunk_length);
183	if (sctp_validate_init_auth_params(m, offset + sizeof(*cp),
184	    init_limit)) {
185		/* auth parameter(s) error... send abort */
186		sctp_abort_association(inp, stcb, m, iphlen, sh, NULL);
187		return;
188	}
189	/* send an INIT-ACK w/cookie */
190#ifdef SCTP_DEBUG
191	if (sctp_debug_on & SCTP_DEBUG_INPUT3) {
192		printf("sctp_handle_init: sending INIT-ACK\n");
193	}
194#endif
195	sctp_send_initiate_ack(inp, stcb, m, iphlen, offset, sh, cp);
196}
197
198/*
199 * process peer "INIT/INIT-ACK" chunk returns value < 0 on error
200 */
201static int
202sctp_process_init(struct sctp_init_chunk *cp, struct sctp_tcb *stcb,
203    struct sctp_nets *net)
204{
205	struct sctp_init *init;
206	struct sctp_association *asoc;
207	struct sctp_nets *lnet;
208	unsigned int i;
209
210	init = &cp->init;
211	asoc = &stcb->asoc;
212	/* save off parameters */
213	asoc->peer_vtag = ntohl(init->initiate_tag);
214	asoc->peers_rwnd = ntohl(init->a_rwnd);
215	if (TAILQ_FIRST(&asoc->nets)) {
216		/* update any ssthresh's that may have a default */
217		TAILQ_FOREACH(lnet, &asoc->nets, sctp_next) {
218			lnet->ssthresh = asoc->peers_rwnd;
219
220#if defined(SCTP_CWND_MONITOR) || defined(SCTP_CWND_LOGGING)
221			sctp_log_cwnd(stcb, lnet, 0, SCTP_CWND_INITIALIZATION);
222#endif
223
224		}
225	}
226	SCTP_TCB_SEND_LOCK(stcb);
227	if (asoc->pre_open_streams > ntohs(init->num_inbound_streams)) {
228		unsigned int newcnt;
229		struct sctp_stream_out *outs;
230		struct sctp_stream_queue_pending *sp;
231
232		/* cut back on number of streams */
233		newcnt = ntohs(init->num_inbound_streams);
234		/* This if is probably not needed but I am cautious */
235		if (asoc->strmout) {
236			/* First make sure no data chunks are trapped */
237			for (i = newcnt; i < asoc->pre_open_streams; i++) {
238				outs = &asoc->strmout[i];
239				sp = TAILQ_FIRST(&outs->outqueue);
240				while (sp) {
241					TAILQ_REMOVE(&outs->outqueue, sp,
242					    next);
243					asoc->stream_queue_cnt--;
244					sctp_ulp_notify(SCTP_NOTIFY_SPECIAL_SP_FAIL,
245					    stcb, SCTP_NOTIFY_DATAGRAM_UNSENT,
246					    sp);
247					if (sp->data) {
248						sctp_m_freem(sp->data);
249						sp->data = NULL;
250					}
251					sctp_free_remote_addr(sp->net);
252					sp->net = NULL;
253					/* Free the chunk */
254					printf("sp:%p tcb:%p weird free case\n",
255					    sp, stcb);
256
257					sctp_free_a_strmoq(stcb, sp);
258					sp = TAILQ_FIRST(&outs->outqueue);
259				}
260			}
261		}
262		/* cut back the count and abandon the upper streams */
263		asoc->pre_open_streams = newcnt;
264	}
265	SCTP_TCB_SEND_UNLOCK(stcb);
266	asoc->streamoutcnt = asoc->pre_open_streams;
267	/* init tsn's */
268	asoc->highest_tsn_inside_map = asoc->asconf_seq_in = ntohl(init->initial_tsn) - 1;
269#ifdef SCTP_MAP_LOGGING
270	sctp_log_map(0, 5, asoc->highest_tsn_inside_map, SCTP_MAP_SLIDE_RESULT);
271#endif
272	/* This is the next one we expect */
273	asoc->str_reset_seq_in = asoc->asconf_seq_in + 1;
274
275	asoc->mapping_array_base_tsn = ntohl(init->initial_tsn);
276	asoc->cumulative_tsn = asoc->asconf_seq_in;
277	asoc->last_echo_tsn = asoc->asconf_seq_in;
278	asoc->advanced_peer_ack_point = asoc->last_acked_seq;
279	/* open the requested streams */
280	if (asoc->strmin != NULL) {
281		/* Free the old ones */
282		struct sctp_queued_to_read *ctl;
283
284		for (i = 0; i < asoc->streamincnt; i++) {
285			ctl = TAILQ_FIRST(&asoc->strmin[i].inqueue);
286			while (ctl) {
287				TAILQ_REMOVE(&asoc->strmin[i].inqueue, ctl, next);
288				sctp_free_remote_addr(ctl->whoFrom);
289				sctp_m_freem(ctl->data);
290				ctl->data = NULL;
291				sctp_free_a_readq(stcb, ctl);
292				ctl = TAILQ_FIRST(&asoc->strmin[i].inqueue);
293			}
294		}
295		SCTP_FREE(asoc->strmin);
296	}
297	asoc->streamincnt = ntohs(init->num_outbound_streams);
298	if (asoc->streamincnt > MAX_SCTP_STREAMS) {
299		asoc->streamincnt = MAX_SCTP_STREAMS;
300	}
301	SCTP_MALLOC(asoc->strmin, struct sctp_stream_in *, asoc->streamincnt *
302	    sizeof(struct sctp_stream_in), "StreamsIn");
303	if (asoc->strmin == NULL) {
304		/* we didn't get memory for the streams! */
305#ifdef SCTP_DEBUG
306		if (sctp_debug_on & SCTP_DEBUG_INPUT2) {
307			printf("process_init: couldn't get memory for the streams!\n");
308		}
309#endif
310		return (-1);
311	}
312	for (i = 0; i < asoc->streamincnt; i++) {
313		asoc->strmin[i].stream_no = i;
314		asoc->strmin[i].last_sequence_delivered = 0xffff;
315		/*
316		 * U-stream ranges will be set when the cookie is unpacked.
317		 * Or for the INIT sender they are un set (if pr-sctp not
318		 * supported) when the INIT-ACK arrives.
319		 */
320		TAILQ_INIT(&asoc->strmin[i].inqueue);
321		/*
322		 * we are not on any wheel, pr-sctp streams will go on the
323		 * wheel when they have data waiting for reorder.
324		 */
325		asoc->strmin[i].next_spoke.tqe_next = 0;
326		asoc->strmin[i].next_spoke.tqe_prev = 0;
327	}
328
329	/*
330	 * load_address_from_init will put the addresses into the
331	 * association when the COOKIE is processed or the INIT-ACK is
332	 * processed. Both types of COOKIE's existing and new call this
333	 * routine. It will remove addresses that are no longer in the
334	 * association (for the restarting case where addresses are
335	 * removed). Up front when the INIT arrives we will discard it if it
336	 * is a restart and new addresses have been added.
337	 */
338	return (0);
339}
340
341/*
342 * INIT-ACK message processing/consumption returns value < 0 on error
343 */
344static int
345sctp_process_init_ack(struct mbuf *m, int iphlen, int offset,
346    struct sctphdr *sh, struct sctp_init_ack_chunk *cp, struct sctp_tcb *stcb,
347    struct sctp_nets *net)
348{
349	struct sctp_association *asoc;
350	struct mbuf *op_err;
351	int retval, abort_flag;
352	uint32_t initack_limit;
353
354	/* First verify that we have no illegal param's */
355	abort_flag = 0;
356	op_err = NULL;
357
358	op_err = sctp_arethere_unrecognized_parameters(m,
359	    (offset + sizeof(struct sctp_init_chunk)),
360	    &abort_flag, (struct sctp_chunkhdr *)cp);
361	if (abort_flag) {
362		/* Send an abort and notify peer */
363		if (op_err != NULL) {
364			sctp_send_operr_to(m, iphlen, op_err, cp->init.initiate_tag);
365		} else {
366			/*
367			 * Just notify (abort_assoc does this if we send an
368			 * abort).
369			 */
370			sctp_abort_notification(stcb, 0);
371			/*
372			 * No sense in further INIT's since we will get the
373			 * same param back
374			 */
375			sctp_free_assoc(stcb->sctp_ep, stcb, 0);
376		}
377		return (-1);
378	}
379	asoc = &stcb->asoc;
380	/* process the peer's parameters in the INIT-ACK */
381	retval = sctp_process_init((struct sctp_init_chunk *)cp, stcb, net);
382	if (retval < 0) {
383		return (retval);
384	}
385	initack_limit = offset + ntohs(cp->ch.chunk_length);
386	/* load all addresses */
387	if ((retval = sctp_load_addresses_from_init(stcb, m, iphlen,
388	    (offset + sizeof(struct sctp_init_chunk)), initack_limit, sh,
389	    NULL))) {
390		/* Huh, we should abort */
391#ifdef SCTP_DEBUG
392		if (sctp_debug_on & SCTP_DEBUG_INPUT1) {
393			printf("Load addresses from INIT causes an abort %d\n", retval);
394		}
395#endif
396		sctp_abort_association(stcb->sctp_ep, stcb, m, iphlen, sh,
397		    NULL);
398		return (-1);
399	}
400	stcb->asoc.peer_hmac_id = sctp_negotiate_hmacid(stcb->asoc.peer_hmacs,
401	    stcb->asoc.local_hmacs);
402	if (op_err) {
403		sctp_queue_op_err(stcb, op_err);
404		/* queuing will steal away the mbuf chain to the out queue */
405		op_err = NULL;
406	}
407	/* extract the cookie and queue it to "echo" it back... */
408	stcb->asoc.overall_error_count = 0;
409	net->error_count = 0;
410
411	/*
412	 * Cancel the INIT timer, We do this first before queueing the
413	 * cookie. We always cancel at the primary to assue that we are
414	 * canceling the timer started by the INIT which always goes to the
415	 * primary.
416	 */
417	sctp_timer_stop(SCTP_TIMER_TYPE_INIT, stcb->sctp_ep, stcb,
418	    asoc->primary_destination);
419
420	retval = sctp_send_cookie_echo(m, offset, stcb, net);
421	if (retval < 0) {
422		/*
423		 * No cookie, we probably should send a op error. But in any
424		 * case if there is no cookie in the INIT-ACK, we can
425		 * abandon the peer, its broke.
426		 */
427		if (retval == -3) {
428			/* We abort with an error of missing mandatory param */
429			struct mbuf *op_err;
430
431			op_err =
432			    sctp_generate_invmanparam(SCTP_CAUSE_MISSING_PARAM);
433			if (op_err) {
434				/*
435				 * Expand beyond to include the mandatory
436				 * param cookie
437				 */
438				struct sctp_inv_mandatory_param *mp;
439
440				op_err->m_len =
441				    sizeof(struct sctp_inv_mandatory_param);
442				mp = mtod(op_err,
443				    struct sctp_inv_mandatory_param *);
444				/* Subtract the reserved param */
445				mp->length =
446				    htons(sizeof(struct sctp_inv_mandatory_param) - 2);
447				mp->num_param = htonl(1);
448				mp->param = htons(SCTP_STATE_COOKIE);
449				mp->resv = 0;
450			}
451			sctp_abort_association(stcb->sctp_ep, stcb, m, iphlen,
452			    sh, op_err);
453		}
454		return (retval);
455	}
456	/* calculate the RTO */
457	net->RTO = sctp_calculate_rto(stcb, asoc, net, &asoc->time_entered);
458
459	return (0);
460}
461
462static void
463sctp_handle_heartbeat_ack(struct sctp_heartbeat_chunk *cp,
464    struct sctp_tcb *stcb, struct sctp_nets *net)
465{
466	struct sockaddr_storage store;
467	struct sockaddr_in *sin;
468	struct sockaddr_in6 *sin6;
469	struct sctp_nets *r_net;
470	struct timeval tv;
471
472	if (ntohs(cp->ch.chunk_length) != sizeof(struct sctp_heartbeat_chunk)) {
473		/* Invalid length */
474		return;
475	}
476	sin = (struct sockaddr_in *)&store;
477	sin6 = (struct sockaddr_in6 *)&store;
478
479	memset(&store, 0, sizeof(store));
480	if (cp->heartbeat.hb_info.addr_family == AF_INET &&
481	    cp->heartbeat.hb_info.addr_len == sizeof(struct sockaddr_in)) {
482		sin->sin_family = cp->heartbeat.hb_info.addr_family;
483		sin->sin_len = cp->heartbeat.hb_info.addr_len;
484		sin->sin_port = stcb->rport;
485		memcpy(&sin->sin_addr, cp->heartbeat.hb_info.address,
486		    sizeof(sin->sin_addr));
487	} else if (cp->heartbeat.hb_info.addr_family == AF_INET6 &&
488	    cp->heartbeat.hb_info.addr_len == sizeof(struct sockaddr_in6)) {
489		sin6->sin6_family = cp->heartbeat.hb_info.addr_family;
490		sin6->sin6_len = cp->heartbeat.hb_info.addr_len;
491		sin6->sin6_port = stcb->rport;
492		memcpy(&sin6->sin6_addr, cp->heartbeat.hb_info.address,
493		    sizeof(sin6->sin6_addr));
494	} else {
495		return;
496	}
497	r_net = sctp_findnet(stcb, (struct sockaddr *)sin);
498	if (r_net == NULL) {
499#ifdef SCTP_DEBUG
500		if (sctp_debug_on & SCTP_DEBUG_INPUT1) {
501			printf("Huh? I can't find the address I sent it to, discard\n");
502		}
503#endif
504		return;
505	}
506	if ((r_net && (r_net->dest_state & SCTP_ADDR_UNCONFIRMED)) &&
507	    (r_net->heartbeat_random1 == cp->heartbeat.hb_info.random_value1) &&
508	    (r_net->heartbeat_random2 == cp->heartbeat.hb_info.random_value2)) {
509		/*
510		 * If the its a HB and it's random value is correct when can
511		 * confirm the destination.
512		 */
513		r_net->dest_state &= ~SCTP_ADDR_UNCONFIRMED;
514		sctp_ulp_notify(SCTP_NOTIFY_INTERFACE_CONFIRMED,
515		    stcb, 0, (void *)r_net);
516	}
517	r_net->error_count = 0;
518	r_net->hb_responded = 1;
519	tv.tv_sec = cp->heartbeat.hb_info.time_value_1;
520	tv.tv_usec = cp->heartbeat.hb_info.time_value_2;
521	if (r_net->dest_state & SCTP_ADDR_NOT_REACHABLE) {
522		r_net->dest_state &= ~SCTP_ADDR_NOT_REACHABLE;
523		r_net->dest_state |= SCTP_ADDR_REACHABLE;
524		sctp_ulp_notify(SCTP_NOTIFY_INTERFACE_UP, stcb,
525		    SCTP_HEARTBEAT_SUCCESS, (void *)r_net);
526		/* now was it the primary? if so restore */
527		if (r_net->dest_state & SCTP_ADDR_WAS_PRIMARY) {
528			sctp_set_primary_addr(stcb, (struct sockaddr *)NULL, r_net);
529		}
530	}
531	/* Now lets do a RTO with this */
532	r_net->RTO = sctp_calculate_rto(stcb, &stcb->asoc, r_net, &tv);
533}
534
535static void
536sctp_handle_abort(struct sctp_abort_chunk *cp,
537    struct sctp_tcb *stcb, struct sctp_nets *net)
538{
539
540#ifdef SCTP_DEBUG
541	if (sctp_debug_on & SCTP_DEBUG_INPUT2) {
542		printf("sctp_handle_abort: handling ABORT\n");
543	}
544#endif
545	if (stcb == NULL)
546		return;
547	/* verify that the destination addr is in the association */
548	/* ignore abort for addresses being deleted */
549
550	/* stop any receive timers */
551	sctp_timer_stop(SCTP_TIMER_TYPE_RECV, stcb->sctp_ep, stcb, net);
552	/* notify user of the abort and clean up... */
553	sctp_abort_notification(stcb, 0);
554	/* free the tcb */
555	SCTP_STAT_INCR_COUNTER32(sctps_aborted);
556	if ((SCTP_GET_STATE(&stcb->asoc) == SCTP_STATE_OPEN) ||
557	    (SCTP_GET_STATE(&stcb->asoc) == SCTP_STATE_SHUTDOWN_RECEIVED)) {
558		SCTP_STAT_DECR_GAUGE32(sctps_currestab);
559	}
560	sctp_free_assoc(stcb->sctp_ep, stcb, 0);
561#ifdef SCTP_DEBUG
562	if (sctp_debug_on & SCTP_DEBUG_INPUT2) {
563		printf("sctp_handle_abort: finished\n");
564	}
565#endif
566}
567
568static void
569sctp_handle_shutdown(struct sctp_shutdown_chunk *cp,
570    struct sctp_tcb *stcb, struct sctp_nets *net, int *abort_flag)
571{
572	struct sctp_association *asoc;
573	int some_on_streamwheel;
574
575#ifdef SCTP_DEBUG
576	if (sctp_debug_on & SCTP_DEBUG_INPUT2) {
577		printf("sctp_handle_shutdown: handling SHUTDOWN\n");
578	}
579#endif
580	if (stcb == NULL)
581		return;
582
583	if ((SCTP_GET_STATE(&stcb->asoc) == SCTP_STATE_COOKIE_WAIT) ||
584	    (SCTP_GET_STATE(&stcb->asoc) == SCTP_STATE_COOKIE_ECHOED)) {
585		return;
586	}
587	if (ntohs(cp->ch.chunk_length) != sizeof(struct sctp_shutdown_chunk)) {
588		/* Shutdown NOT the expected size */
589		return;
590	} else {
591		sctp_update_acked(stcb, cp, net, abort_flag);
592	}
593	asoc = &stcb->asoc;
594	if (stcb->asoc.control_pdapi) {
595		/*
596		 * With a normal shutdown we assume the end of last record.
597		 */
598		SCTP_INP_READ_LOCK(stcb->sctp_ep);
599		stcb->asoc.control_pdapi->end_added = 1;
600		stcb->asoc.control_pdapi->pdapi_aborted = 1;
601		if (stcb->asoc.control_pdapi->tail_mbuf) {
602			stcb->asoc.control_pdapi->tail_mbuf->m_flags |= M_EOR;
603		}
604		stcb->asoc.control_pdapi = NULL;
605		SCTP_INP_READ_UNLOCK(stcb->sctp_ep);
606		sctp_sorwakeup(stcb->sctp_ep, stcb->sctp_socket);
607	}
608	/* goto SHUTDOWN_RECEIVED state to block new requests */
609	if (stcb->sctp_socket) {
610		if ((SCTP_GET_STATE(asoc) != SCTP_STATE_SHUTDOWN_RECEIVED) &&
611		    (SCTP_GET_STATE(asoc) != SCTP_STATE_SHUTDOWN_SENT)) {
612			asoc->state = SCTP_STATE_SHUTDOWN_RECEIVED;
613			/*
614			 * notify upper layer that peer has initiated a
615			 * shutdown
616			 */
617			sctp_ulp_notify(SCTP_NOTIFY_PEER_SHUTDOWN, stcb, 0, NULL);
618
619			/* reset time */
620			SCTP_GETTIME_TIMEVAL(&asoc->time_entered);
621		}
622	}
623	if (SCTP_GET_STATE(asoc) == SCTP_STATE_SHUTDOWN_SENT) {
624		/*
625		 * stop the shutdown timer, since we WILL move to
626		 * SHUTDOWN-ACK-SENT.
627		 */
628		sctp_timer_stop(SCTP_TIMER_TYPE_SHUTDOWN, stcb->sctp_ep, stcb, net);
629	}
630	/* Now are we there yet? */
631	some_on_streamwheel = 0;
632	if (!TAILQ_EMPTY(&asoc->out_wheel)) {
633		/* Check to see if some data queued */
634		struct sctp_stream_out *outs;
635
636		TAILQ_FOREACH(outs, &asoc->out_wheel, next_spoke) {
637			if (!TAILQ_EMPTY(&outs->outqueue)) {
638				some_on_streamwheel = 1;
639				break;
640			}
641		}
642	}
643	if (!TAILQ_EMPTY(&asoc->send_queue) ||
644	    !TAILQ_EMPTY(&asoc->sent_queue) ||
645	    some_on_streamwheel) {
646		/* By returning we will push more data out */
647		return;
648	} else {
649		/* no outstanding data to send, so move on... */
650		/* send SHUTDOWN-ACK */
651		sctp_send_shutdown_ack(stcb, stcb->asoc.primary_destination);
652		/* move to SHUTDOWN-ACK-SENT state */
653		if (asoc->state == SCTP_STATE_SHUTDOWN_RECEIVED) {
654			SCTP_STAT_DECR_GAUGE32(sctps_currestab);
655		}
656		asoc->state = SCTP_STATE_SHUTDOWN_ACK_SENT;
657
658		/* start SHUTDOWN timer */
659		sctp_timer_start(SCTP_TIMER_TYPE_SHUTDOWNACK, stcb->sctp_ep,
660		    stcb, net);
661	}
662}
663
664static void
665sctp_handle_shutdown_ack(struct sctp_shutdown_ack_chunk *cp,
666    struct sctp_tcb *stcb, struct sctp_nets *net)
667{
668	struct sctp_association *asoc;
669
670#ifdef SCTP_DEBUG
671	if (sctp_debug_on & SCTP_DEBUG_INPUT2) {
672		printf("sctp_handle_shutdown_ack: handling SHUTDOWN ACK\n");
673	}
674#endif
675	if (stcb == NULL)
676		return;
677
678	asoc = &stcb->asoc;
679	/* process according to association state */
680	if ((SCTP_GET_STATE(asoc) != SCTP_STATE_SHUTDOWN_SENT) &&
681	    (SCTP_GET_STATE(asoc) != SCTP_STATE_SHUTDOWN_ACK_SENT)) {
682		/* unexpected SHUTDOWN-ACK... so ignore... */
683		SCTP_TCB_UNLOCK(stcb);
684		return;
685	}
686	if (stcb->asoc.control_pdapi) {
687		/*
688		 * With a normal shutdown we assume the end of last record.
689		 */
690		SCTP_INP_READ_LOCK(stcb->sctp_ep);
691		stcb->asoc.control_pdapi->end_added = 1;
692		stcb->asoc.control_pdapi->pdapi_aborted = 1;
693		if (stcb->asoc.control_pdapi->tail_mbuf) {
694			stcb->asoc.control_pdapi->tail_mbuf->m_flags |= M_EOR;
695		}
696		stcb->asoc.control_pdapi = NULL;
697		SCTP_INP_READ_UNLOCK(stcb->sctp_ep);
698		sctp_sorwakeup(stcb->sctp_ep, stcb->sctp_socket);
699	}
700	/* are the queues empty? */
701	if (!TAILQ_EMPTY(&asoc->send_queue) ||
702	    !TAILQ_EMPTY(&asoc->sent_queue) ||
703	    !TAILQ_EMPTY(&asoc->out_wheel)) {
704		sctp_report_all_outbound(stcb, 0);
705	}
706	/* stop the timer */
707	sctp_timer_stop(SCTP_TIMER_TYPE_SHUTDOWN, stcb->sctp_ep, stcb, net);
708	/* send SHUTDOWN-COMPLETE */
709	sctp_send_shutdown_complete(stcb, net);
710	/* notify upper layer protocol */
711	if (stcb->sctp_socket) {
712		sctp_ulp_notify(SCTP_NOTIFY_ASSOC_DOWN, stcb, 0, NULL);
713		if ((stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE) ||
714		    (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL)) {
715			/* Set the connected flag to disconnected */
716			stcb->sctp_ep->sctp_socket->so_snd.sb_cc = 0;
717		}
718	}
719	SCTP_STAT_INCR_COUNTER32(sctps_shutdown);
720	/* free the TCB but first save off the ep */
721	sctp_free_assoc(stcb->sctp_ep, stcb, 0);
722}
723
724/*
725 * Skip past the param header and then we will find the chunk that caused the
726 * problem. There are two possiblities ASCONF or FWD-TSN other than that and
727 * our peer must be broken.
728 */
729static void
730sctp_process_unrecog_chunk(struct sctp_tcb *stcb, struct sctp_paramhdr *phdr,
731    struct sctp_nets *net)
732{
733	struct sctp_chunkhdr *chk;
734
735	chk = (struct sctp_chunkhdr *)((caddr_t)phdr + sizeof(*phdr));
736	switch (chk->chunk_type) {
737	case SCTP_ASCONF_ACK:
738	case SCTP_ASCONF:
739		sctp_asconf_cleanup(stcb, net);
740		break;
741	case SCTP_FORWARD_CUM_TSN:
742		stcb->asoc.peer_supports_prsctp = 0;
743		break;
744	default:
745#ifdef SCTP_DEBUG
746		if (sctp_debug_on & SCTP_DEBUG_INPUT2) {
747			printf("Peer does not support chunk type %d(%x)??\n",
748			    chk->chunk_type, (uint32_t) chk->chunk_type);
749		}
750#endif
751		break;
752	}
753}
754
755/*
756 * Skip past the param header and then we will find the param that caused the
757 * problem.  There are a number of param's in a ASCONF OR the prsctp param
758 * these will turn of specific features.
759 */
760static void
761sctp_process_unrecog_param(struct sctp_tcb *stcb, struct sctp_paramhdr *phdr)
762{
763	struct sctp_paramhdr *pbad;
764
765	pbad = phdr + 1;
766	switch (ntohs(pbad->param_type)) {
767		/* pr-sctp draft */
768	case SCTP_PRSCTP_SUPPORTED:
769		stcb->asoc.peer_supports_prsctp = 0;
770		break;
771	case SCTP_SUPPORTED_CHUNK_EXT:
772		break;
773		/* draft-ietf-tsvwg-addip-sctp */
774	case SCTP_ECN_NONCE_SUPPORTED:
775		stcb->asoc.peer_supports_ecn_nonce = 0;
776		stcb->asoc.ecn_nonce_allowed = 0;
777		stcb->asoc.ecn_allowed = 0;
778		break;
779	case SCTP_ADD_IP_ADDRESS:
780	case SCTP_DEL_IP_ADDRESS:
781	case SCTP_SET_PRIM_ADDR:
782		stcb->asoc.peer_supports_asconf = 0;
783		break;
784	case SCTP_SUCCESS_REPORT:
785	case SCTP_ERROR_CAUSE_IND:
786#ifdef SCTP_DEBUG
787		if (sctp_debug_on & SCTP_DEBUG_INPUT2) {
788			printf("Huh, the peer does not support success? or error cause?\n");
789			printf("Turning off ASCONF to this strange peer\n");
790		}
791#endif
792		stcb->asoc.peer_supports_asconf = 0;
793		break;
794	default:
795#ifdef SCTP_DEBUG
796		if (sctp_debug_on & SCTP_DEBUG_INPUT2) {
797			printf("Peer does not support param type %d(%x)??\n",
798			    pbad->param_type, (uint32_t) pbad->param_type);
799		}
800#endif
801		break;
802	}
803}
804
805static int
806sctp_handle_error(struct sctp_chunkhdr *ch,
807    struct sctp_tcb *stcb, struct sctp_nets *net)
808{
809	int chklen;
810	struct sctp_paramhdr *phdr;
811	uint16_t error_type;
812	uint16_t error_len;
813	struct sctp_association *asoc;
814
815	int adjust;
816
817	/* parse through all of the errors and process */
818	asoc = &stcb->asoc;
819	phdr = (struct sctp_paramhdr *)((caddr_t)ch +
820	    sizeof(struct sctp_chunkhdr));
821	chklen = ntohs(ch->chunk_length) - sizeof(struct sctp_chunkhdr);
822	while ((size_t)chklen >= sizeof(struct sctp_paramhdr)) {
823		/* Process an Error Cause */
824		error_type = ntohs(phdr->param_type);
825		error_len = ntohs(phdr->param_length);
826		if ((error_len > chklen) || (error_len == 0)) {
827			/* invalid param length for this param */
828#ifdef SCTP_DEBUG
829			if (sctp_debug_on & SCTP_DEBUG_INPUT1) {
830				printf("Bogus length in error param- chunk left:%d errorlen:%d\n",
831				    chklen, error_len);
832			}
833#endif				/* SCTP_DEBUG */
834			return (0);
835		}
836		switch (error_type) {
837		case SCTP_CAUSE_INVALID_STREAM:
838		case SCTP_CAUSE_MISSING_PARAM:
839		case SCTP_CAUSE_INVALID_PARAM:
840		case SCTP_CAUSE_NO_USER_DATA:
841#ifdef SCTP_DEBUG
842			if (sctp_debug_on & SCTP_DEBUG_INPUT1) {
843				printf("Software error we got a %d back? We have a bug :/ (or do they?)\n",
844				    error_type);
845			}
846#endif
847			break;
848		case SCTP_CAUSE_STALE_COOKIE:
849			/*
850			 * We only act if we have echoed a cookie and are
851			 * waiting.
852			 */
853			if (SCTP_GET_STATE(asoc) == SCTP_STATE_COOKIE_ECHOED) {
854				int *p;
855
856				p = (int *)((caddr_t)phdr + sizeof(*phdr));
857				/* Save the time doubled */
858				asoc->cookie_preserve_req = ntohl(*p) << 1;
859				asoc->stale_cookie_count++;
860				if (asoc->stale_cookie_count >
861				    asoc->max_init_times) {
862					sctp_abort_notification(stcb, 0);
863					/* now free the asoc */
864					sctp_free_assoc(stcb->sctp_ep, stcb, 0);
865					return (-1);
866				}
867				/* blast back to INIT state */
868				asoc->state &= ~SCTP_STATE_COOKIE_ECHOED;
869				asoc->state |= SCTP_STATE_COOKIE_WAIT;
870
871				sctp_stop_all_cookie_timers(stcb);
872				sctp_send_initiate(stcb->sctp_ep, stcb);
873			}
874			break;
875		case SCTP_CAUSE_UNRESOLVABLE_ADDR:
876			/*
877			 * Nothing we can do here, we don't do hostname
878			 * addresses so if the peer does not like my IPv6
879			 * (or IPv4 for that matter) it does not matter. If
880			 * they don't support that type of address, they can
881			 * NOT possibly get that packet type... i.e. with no
882			 * IPv6 you can't recieve a IPv6 packet. so we can
883			 * safely ignore this one. If we ever added support
884			 * for HOSTNAME Addresses, then we would need to do
885			 * something here.
886			 */
887			break;
888		case SCTP_CAUSE_UNRECOG_CHUNK:
889			sctp_process_unrecog_chunk(stcb, phdr, net);
890			break;
891		case SCTP_CAUSE_UNRECOG_PARAM:
892			sctp_process_unrecog_param(stcb, phdr);
893			break;
894		case SCTP_CAUSE_COOKIE_IN_SHUTDOWN:
895			/*
896			 * We ignore this since the timer will drive out a
897			 * new cookie anyway and there timer will drive us
898			 * to send a SHUTDOWN_COMPLETE. We can't send one
899			 * here since we don't have their tag.
900			 */
901			break;
902		case SCTP_CAUSE_DELETING_LAST_ADDR:
903		case SCTP_CAUSE_RESOURCE_SHORTAGE:
904		case SCTP_CAUSE_DELETING_SRC_ADDR:
905			/*
906			 * We should NOT get these here, but in a
907			 * ASCONF-ACK. n
908			 */
909#ifdef SCTP_DEBUG
910			if (sctp_debug_on & SCTP_DEBUG_INPUT2) {
911				printf("Peer sends ASCONF errors in a Operational Error?<%d>?\n",
912				    error_type);
913			}
914#endif
915			break;
916		case SCTP_CAUSE_OUT_OF_RESC:
917			/*
918			 * And what, pray tell do we do with the fact that
919			 * the peer is out of resources? Not really sure we
920			 * could do anything but abort. I suspect this n		 *
921			 * should have came WITH an abort instead of in a
922			 * OP-ERROR.
923			 */
924			break;
925		default:
926#ifdef SCTP_DEBUG
927			if (sctp_debug_on & SCTP_DEBUG_INPUT1) {
928				/* don't know what this error cause is... */
929				printf("sctp_handle_error: unknown error type = 0x%xh\n",
930				    error_type);
931			}
932#endif				/* SCTP_DEBUG */
933			break;
934		}
935		adjust = SCTP_SIZE32(error_len);
936		chklen -= adjust;
937		phdr = (struct sctp_paramhdr *)((caddr_t)phdr + adjust);
938	}
939	return (0);
940}
941
942static int
943sctp_handle_init_ack(struct mbuf *m, int iphlen, int offset, struct sctphdr *sh,
944    struct sctp_init_ack_chunk *cp, struct sctp_tcb *stcb,
945    struct sctp_nets *net)
946{
947	struct sctp_init_ack *init_ack;
948	int *state;
949	struct mbuf *op_err;
950
951#ifdef SCTP_DEBUG
952	if (sctp_debug_on & SCTP_DEBUG_INPUT2) {
953		printf("sctp_handle_init_ack: handling INIT-ACK\n");
954	}
955#endif
956	if (stcb == NULL) {
957#ifdef SCTP_DEBUG
958		if (sctp_debug_on & SCTP_DEBUG_INPUT2) {
959			printf("sctp_handle_init_ack: TCB is null\n");
960		}
961#endif
962		return (-1);
963	}
964	if (ntohs(cp->ch.chunk_length) < sizeof(struct sctp_init_ack_chunk)) {
965		/* Invalid length */
966		op_err = sctp_generate_invmanparam(SCTP_CAUSE_INVALID_PARAM);
967		sctp_abort_association(stcb->sctp_ep, stcb, m, iphlen, sh,
968		    op_err);
969		return (-1);
970	}
971	init_ack = &cp->init;
972	/* validate parameters */
973	if (init_ack->initiate_tag == 0) {
974		/* protocol error... send an abort */
975		op_err = sctp_generate_invmanparam(SCTP_CAUSE_INVALID_PARAM);
976		sctp_abort_association(stcb->sctp_ep, stcb, m, iphlen, sh,
977		    op_err);
978		return (-1);
979	}
980	if (ntohl(init_ack->a_rwnd) < SCTP_MIN_RWND) {
981		/* protocol error... send an abort */
982		op_err = sctp_generate_invmanparam(SCTP_CAUSE_INVALID_PARAM);
983		sctp_abort_association(stcb->sctp_ep, stcb, m, iphlen, sh,
984		    op_err);
985		return (-1);
986	}
987	if (init_ack->num_inbound_streams == 0) {
988		/* protocol error... send an abort */
989		op_err = sctp_generate_invmanparam(SCTP_CAUSE_INVALID_PARAM);
990		sctp_abort_association(stcb->sctp_ep, stcb, m, iphlen, sh,
991		    op_err);
992		return (-1);
993	}
994	if (init_ack->num_outbound_streams == 0) {
995		/* protocol error... send an abort */
996		op_err = sctp_generate_invmanparam(SCTP_CAUSE_INVALID_PARAM);
997		sctp_abort_association(stcb->sctp_ep, stcb, m, iphlen, sh,
998		    op_err);
999		return (-1);
1000	}
1001	/* process according to association state... */
1002	state = &stcb->asoc.state;
1003	switch (*state & SCTP_STATE_MASK) {
1004	case SCTP_STATE_COOKIE_WAIT:
1005		/* this is the expected state for this chunk */
1006		/* process the INIT-ACK parameters */
1007		if (stcb->asoc.primary_destination->dest_state &
1008		    SCTP_ADDR_UNCONFIRMED) {
1009			/*
1010			 * The primary is where we sent the INIT, we can
1011			 * always consider it confirmed when the INIT-ACK is
1012			 * returned. Do this before we load addresses
1013			 * though.
1014			 */
1015			stcb->asoc.primary_destination->dest_state &=
1016			    ~SCTP_ADDR_UNCONFIRMED;
1017			sctp_ulp_notify(SCTP_NOTIFY_INTERFACE_CONFIRMED,
1018			    stcb, 0, (void *)stcb->asoc.primary_destination);
1019		}
1020		if (sctp_process_init_ack(m, iphlen, offset, sh, cp, stcb, net
1021		    ) < 0) {
1022			/* error in parsing parameters */
1023			return (-1);
1024		}
1025		/* update our state */
1026#ifdef SCTP_DEBUG
1027		if (sctp_debug_on & SCTP_DEBUG_INPUT2) {
1028			printf("moving to COOKIE-ECHOED state\n");
1029		}
1030#endif
1031		if (*state & SCTP_STATE_SHUTDOWN_PENDING) {
1032			*state = SCTP_STATE_COOKIE_ECHOED |
1033			    SCTP_STATE_SHUTDOWN_PENDING;
1034		} else {
1035			*state = SCTP_STATE_COOKIE_ECHOED;
1036		}
1037
1038		/* reset the RTO calc */
1039		stcb->asoc.overall_error_count = 0;
1040		SCTP_GETTIME_TIMEVAL(&stcb->asoc.time_entered);
1041		/*
1042		 * collapse the init timer back in case of a exponential
1043		 * backoff n
1044		 */
1045		sctp_timer_start(SCTP_TIMER_TYPE_COOKIE, stcb->sctp_ep,
1046		    stcb, net);
1047		/*
1048		 * the send at the end of the inbound data processing will
1049		 * cause the cookie to be sent
1050		 */
1051		break;
1052	case SCTP_STATE_SHUTDOWN_SENT:
1053		/* incorrect state... discard */
1054		break;
1055	case SCTP_STATE_COOKIE_ECHOED:
1056		/* incorrect state... discard */
1057		break;
1058	case SCTP_STATE_OPEN:
1059		/* incorrect state... discard */
1060		break;
1061	case SCTP_STATE_EMPTY:
1062	case SCTP_STATE_INUSE:
1063	default:
1064		/* incorrect state... discard */
1065		return (-1);
1066		break;
1067	}			/* end switch asoc state */
1068#ifdef SCTP_DEBUG
1069	if (sctp_debug_on & SCTP_DEBUG_INPUT1) {
1070		printf("Leaving handle-init-ack end\n");
1071	}
1072#endif
1073	return (0);
1074}
1075
1076
1077/*
1078 * handle a state cookie for an existing association m: input packet mbuf
1079 * chain-- assumes a pullup on IP/SCTP/COOKIE-ECHO chunk note: this is a
1080 * "split" mbuf and the cookie signature does not exist offset: offset into
1081 * mbuf to the cookie-echo chunk
1082 */
1083static struct sctp_tcb *
1084sctp_process_cookie_existing(struct mbuf *m, int iphlen, int offset,
1085    struct sctphdr *sh, struct sctp_state_cookie *cookie, int cookie_len,
1086    struct sctp_inpcb *inp, struct sctp_tcb *stcb, struct sctp_nets *net,
1087    struct sockaddr *init_src, int *notification, sctp_assoc_t * sac_assoc_id)
1088{
1089	struct sctp_association *asoc;
1090	struct sctp_init_chunk *init_cp, init_buf;
1091	struct sctp_init_ack_chunk *initack_cp, initack_buf;
1092	int chk_length;
1093	int init_offset, initack_offset;
1094	int retval;
1095	int spec_flag = 0;
1096
1097	/* I know that the TCB is non-NULL from the caller */
1098	asoc = &stcb->asoc;
1099
1100	if (SCTP_GET_STATE(asoc) == SCTP_STATE_SHUTDOWN_ACK_SENT) {
1101		/* SHUTDOWN came in after sending INIT-ACK */
1102		struct mbuf *op_err;
1103		struct sctp_paramhdr *ph;
1104
1105		sctp_send_shutdown_ack(stcb, stcb->asoc.primary_destination);
1106		op_err = sctp_get_mbuf_for_msg(sizeof(struct sctp_paramhdr),
1107		    1, M_DONTWAIT, 1, MT_DATA);
1108		if (op_err == NULL) {
1109			/* FOOBAR */
1110			return (NULL);
1111		}
1112		/* pre-reserve some space */
1113		op_err->m_data += sizeof(struct ip6_hdr);
1114		op_err->m_data += sizeof(struct sctphdr);
1115		op_err->m_data += sizeof(struct sctp_chunkhdr);
1116		/* Set the len */
1117		op_err->m_len = op_err->m_pkthdr.len = sizeof(struct sctp_paramhdr);
1118		ph = mtod(op_err, struct sctp_paramhdr *);
1119		ph->param_type = htons(SCTP_CAUSE_COOKIE_IN_SHUTDOWN);
1120		ph->param_length = htons(sizeof(struct sctp_paramhdr));
1121		sctp_send_operr_to(m, iphlen, op_err, cookie->peers_vtag);
1122		return (NULL);
1123	}
1124	/*
1125	 * find and validate the INIT chunk in the cookie (peer's info) the
1126	 * INIT should start after the cookie-echo header struct (chunk
1127	 * header, state cookie header struct)
1128	 */
1129	init_offset = offset += sizeof(struct sctp_cookie_echo_chunk);
1130
1131	init_cp = (struct sctp_init_chunk *)
1132	    sctp_m_getptr(m, init_offset, sizeof(struct sctp_init_chunk),
1133	    (uint8_t *) & init_buf);
1134	if (init_cp == NULL) {
1135		/* could not pull a INIT chunk in cookie */
1136		return (NULL);
1137	}
1138	chk_length = ntohs(init_cp->ch.chunk_length);
1139	if (init_cp->ch.chunk_type != SCTP_INITIATION) {
1140		return (NULL);
1141	}
1142	/*
1143	 * find and validate the INIT-ACK chunk in the cookie (my info) the
1144	 * INIT-ACK follows the INIT chunk
1145	 */
1146	initack_offset = init_offset + SCTP_SIZE32(chk_length);
1147	initack_cp = (struct sctp_init_ack_chunk *)
1148	    sctp_m_getptr(m, initack_offset, sizeof(struct sctp_init_ack_chunk),
1149	    (uint8_t *) & initack_buf);
1150	if (initack_cp == NULL) {
1151		/* could not pull INIT-ACK chunk in cookie */
1152		return (NULL);
1153	}
1154	chk_length = ntohs(initack_cp->ch.chunk_length);
1155	if (initack_cp->ch.chunk_type != SCTP_INITIATION_ACK) {
1156		return (NULL);
1157	}
1158	if ((ntohl(initack_cp->init.initiate_tag) == asoc->my_vtag) &&
1159	    (ntohl(init_cp->init.initiate_tag) == asoc->peer_vtag)) {
1160		/*
1161		 * case D in Section 5.2.4 Table 2: MMAA process accordingly
1162		 * to get into the OPEN state
1163		 */
1164		switch SCTP_GET_STATE
1165			(asoc) {
1166		case SCTP_STATE_COOKIE_WAIT:
1167			/*
1168			 * INIT was sent, but got got a COOKIE_ECHO with the
1169			 * correct tags... just accept it...
1170			 */
1171			/* First we must process the INIT !! */
1172			retval = sctp_process_init(init_cp, stcb, net);
1173			if (retval < 0) {
1174				return (NULL);
1175			}
1176			/* intentional fall through to below... */
1177
1178		case SCTP_STATE_COOKIE_ECHOED:
1179			/* Duplicate INIT case */
1180			/* we have already processed the INIT so no problem */
1181			sctp_timer_stop(SCTP_TIMER_TYPE_HEARTBEAT, inp, stcb,
1182			    net);
1183			sctp_timer_stop(SCTP_TIMER_TYPE_INIT, inp, stcb, net);
1184			sctp_stop_all_cookie_timers(stcb);
1185			/* update current state */
1186			if (asoc->state & SCTP_STATE_SHUTDOWN_PENDING) {
1187				asoc->state = SCTP_STATE_OPEN |
1188				    SCTP_STATE_SHUTDOWN_PENDING;
1189				sctp_timer_start(SCTP_TIMER_TYPE_SHUTDOWNGUARD,
1190				    stcb->sctp_ep, stcb, asoc->primary_destination);
1191
1192			} else if ((asoc->state & SCTP_STATE_SHUTDOWN_SENT) == 0) {
1193				/* if ok, move to OPEN state */
1194				asoc->state = SCTP_STATE_OPEN;
1195			}
1196			if (((stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE) ||
1197			    (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL)) &&
1198			    (inp->sctp_socket->so_qlimit == 0)
1199			    ) {
1200				/*
1201				 * Here is where collision would go if we
1202				 * did a connect() and instead got a
1203				 * init/init-ack/cookie done before the
1204				 * init-ack came back..
1205				 */
1206				stcb->sctp_ep->sctp_flags |=
1207				    SCTP_PCB_FLAGS_CONNECTED;
1208				soisconnected(stcb->sctp_ep->sctp_socket);
1209			}
1210			/* notify upper layer */
1211			*notification = SCTP_NOTIFY_ASSOC_UP;
1212			/*
1213			 * since we did not send a HB make sure we don't
1214			 * double things
1215			 */
1216			net->hb_responded = 1;
1217
1218			if (stcb->asoc.sctp_autoclose_ticks &&
1219			    (sctp_is_feature_on(inp, SCTP_PCB_FLAGS_AUTOCLOSE))) {
1220				sctp_timer_start(SCTP_TIMER_TYPE_AUTOCLOSE,
1221				    inp, stcb, NULL);
1222			}
1223			break;
1224		default:
1225			/*
1226			 * we're in the OPEN state (or beyond), so peer must
1227			 * have simply lost the COOKIE-ACK
1228			 */
1229			break;
1230			}	/* end switch */
1231
1232		/*
1233		 * We ignore the return code here.. not sure if we should
1234		 * somehow abort.. but we do have an existing asoc. This
1235		 * really should not fail.
1236		 */
1237		if (sctp_load_addresses_from_init(stcb, m, iphlen,
1238		    init_offset + sizeof(struct sctp_init_chunk),
1239		    initack_offset, sh, init_src)) {
1240			return (NULL);
1241		}
1242		/* respond with a COOKIE-ACK */
1243		sctp_send_cookie_ack(stcb);
1244		return (stcb);
1245	}			/* end if */
1246	if (ntohl(initack_cp->init.initiate_tag) != asoc->my_vtag &&
1247	    ntohl(init_cp->init.initiate_tag) == asoc->peer_vtag &&
1248	    cookie->tie_tag_my_vtag == 0 &&
1249	    cookie->tie_tag_peer_vtag == 0) {
1250		/*
1251		 * case C in Section 5.2.4 Table 2: XMOO silently discard
1252		 */
1253		return (NULL);
1254	}
1255	if (ntohl(initack_cp->init.initiate_tag) == asoc->my_vtag &&
1256	    (ntohl(init_cp->init.initiate_tag) != asoc->peer_vtag ||
1257	    init_cp->init.initiate_tag == 0)) {
1258		/*
1259		 * case B in Section 5.2.4 Table 2: MXAA or MOAA my info
1260		 * should be ok, re-accept peer info
1261		 */
1262		sctp_timer_stop(SCTP_TIMER_TYPE_HEARTBEAT, inp, stcb, net);
1263		sctp_timer_stop(SCTP_TIMER_TYPE_INIT, inp, stcb, net);
1264		sctp_stop_all_cookie_timers(stcb);
1265		/*
1266		 * since we did not send a HB make sure we don't double
1267		 * things
1268		 */
1269		net->hb_responded = 1;
1270		if (stcb->asoc.sctp_autoclose_ticks &&
1271		    sctp_is_feature_on(inp, SCTP_PCB_FLAGS_AUTOCLOSE)) {
1272			sctp_timer_start(SCTP_TIMER_TYPE_AUTOCLOSE, inp, stcb,
1273			    NULL);
1274		}
1275		asoc->my_rwnd = ntohl(initack_cp->init.a_rwnd);
1276		asoc->pre_open_streams = ntohs(initack_cp->init.num_outbound_streams);
1277
1278		/* Note last_cwr_tsn? where is this used? */
1279		asoc->last_cwr_tsn = asoc->init_seq_number - 1;
1280		if (ntohl(init_cp->init.initiate_tag) != asoc->peer_vtag) {
1281			/*
1282			 * Ok the peer probably discarded our data (if we
1283			 * echoed a cookie+data). So anything on the
1284			 * sent_queue should be marked for retransmit, we
1285			 * may not get something to kick us so it COULD
1286			 * still take a timeout to move these.. but it can't
1287			 * hurt to mark them.
1288			 */
1289			struct sctp_tmit_chunk *chk;
1290
1291			TAILQ_FOREACH(chk, &stcb->asoc.sent_queue, sctp_next) {
1292				if (chk->sent < SCTP_DATAGRAM_RESEND) {
1293					chk->sent = SCTP_DATAGRAM_RESEND;
1294					stcb->asoc.sent_queue_retran_cnt++;
1295					spec_flag++;
1296				}
1297			}
1298
1299		}
1300		/* process the INIT info (peer's info) */
1301		retval = sctp_process_init(init_cp, stcb, net);
1302		if (retval < 0) {
1303			return (NULL);
1304		}
1305		if (sctp_load_addresses_from_init(stcb, m, iphlen,
1306		    init_offset + sizeof(struct sctp_init_chunk),
1307		    initack_offset, sh, init_src)) {
1308			return (NULL);
1309		}
1310		if ((asoc->state & SCTP_STATE_COOKIE_WAIT) ||
1311		    (asoc->state & SCTP_STATE_COOKIE_ECHOED)) {
1312			*notification = SCTP_NOTIFY_ASSOC_UP;
1313
1314			if (((stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE) ||
1315			    (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL)) &&
1316			    (inp->sctp_socket->so_qlimit == 0)) {
1317				stcb->sctp_ep->sctp_flags |=
1318				    SCTP_PCB_FLAGS_CONNECTED;
1319				soisconnected(stcb->sctp_ep->sctp_socket);
1320			}
1321		}
1322		if (asoc->state & SCTP_STATE_SHUTDOWN_PENDING) {
1323			asoc->state = SCTP_STATE_OPEN |
1324			    SCTP_STATE_SHUTDOWN_PENDING;
1325			sctp_timer_start(SCTP_TIMER_TYPE_SHUTDOWNGUARD,
1326			    stcb->sctp_ep, stcb, asoc->primary_destination);
1327
1328		} else {
1329			asoc->state = SCTP_STATE_OPEN;
1330		}
1331		sctp_stop_all_cookie_timers(stcb);
1332		sctp_send_cookie_ack(stcb);
1333		if (spec_flag) {
1334			/*
1335			 * only if we have retrans set do we do this. What
1336			 * this call does is get only the COOKIE-ACK out and
1337			 * then when we return the normal call to
1338			 * sctp_chunk_output will get the retrans out behind
1339			 * this.
1340			 */
1341			sctp_chunk_output(inp, stcb, SCTP_OUTPUT_FROM_COOKIE_ACK);
1342		}
1343		return (stcb);
1344	}
1345	if ((ntohl(initack_cp->init.initiate_tag) != asoc->my_vtag &&
1346	    ntohl(init_cp->init.initiate_tag) != asoc->peer_vtag) &&
1347	    cookie->tie_tag_my_vtag == asoc->my_vtag_nonce &&
1348	    cookie->tie_tag_peer_vtag == asoc->peer_vtag_nonce &&
1349	    cookie->tie_tag_peer_vtag != 0) {
1350		struct sctpasochead *head;
1351
1352		/*
1353		 * case A in Section 5.2.4 Table 2: XXMM (peer restarted)
1354		 */
1355		sctp_timer_stop(SCTP_TIMER_TYPE_INIT, inp, stcb, net);
1356		sctp_timer_stop(SCTP_TIMER_TYPE_HEARTBEAT, inp, stcb, net);
1357		*sac_assoc_id = sctp_get_associd(stcb);
1358		/* notify upper layer */
1359		*notification = SCTP_NOTIFY_ASSOC_RESTART;
1360
1361
1362		/* send up all the data */
1363		SCTP_TCB_SEND_LOCK(stcb);
1364		sctp_report_all_outbound(stcb, 1);
1365
1366		/* process the INIT-ACK info (my info) */
1367		asoc->my_vtag = ntohl(initack_cp->init.initiate_tag);
1368		asoc->my_rwnd = ntohl(initack_cp->init.a_rwnd);
1369
1370		/* pull from vtag hash */
1371		LIST_REMOVE(stcb, sctp_asocs);
1372		/* re-insert to new vtag position */
1373		head = &sctppcbinfo.sctp_asochash[SCTP_PCBHASH_ASOC(stcb->asoc.my_vtag,
1374		    sctppcbinfo.hashasocmark)];
1375		/*
1376		 * put it in the bucket in the vtag hash of assoc's for the
1377		 * system
1378		 */
1379		LIST_INSERT_HEAD(head, stcb, sctp_asocs);
1380
1381		/* Is this the first restart? */
1382		if (stcb->asoc.in_restart_hash == 0) {
1383			/* Ok add it to assoc_id vtag hash */
1384			head = &sctppcbinfo.sctp_restarthash[SCTP_PCBHASH_ASOC(stcb->asoc.assoc_id,
1385			    sctppcbinfo.hashrestartmark)];
1386			LIST_INSERT_HEAD(head, stcb, sctp_tcbrestarhash);
1387			stcb->asoc.in_restart_hash = 1;
1388		}
1389		asoc->pre_open_streams =
1390		    ntohs(initack_cp->init.num_outbound_streams);
1391		asoc->init_seq_number = ntohl(initack_cp->init.initial_tsn);
1392		asoc->sending_seq = asoc->asconf_seq_out = asoc->str_reset_seq_out = asoc->init_seq_number;
1393
1394		asoc->last_cwr_tsn = asoc->init_seq_number - 1;
1395		asoc->asconf_seq_in = asoc->last_acked_seq = asoc->init_seq_number - 1;
1396
1397		asoc->str_reset_seq_in = asoc->init_seq_number;
1398
1399		asoc->advanced_peer_ack_point = asoc->last_acked_seq;
1400		if (asoc->mapping_array)
1401			memset(asoc->mapping_array, 0,
1402			    asoc->mapping_array_size);
1403		/* process the INIT info (peer's info) */
1404		SCTP_TCB_SEND_UNLOCK(stcb);
1405		retval = sctp_process_init(init_cp, stcb, net);
1406		if (retval < 0) {
1407			return (NULL);
1408		}
1409		/*
1410		 * since we did not send a HB make sure we don't double
1411		 * things
1412		 */
1413		net->hb_responded = 1;
1414
1415		if (sctp_load_addresses_from_init(stcb, m, iphlen,
1416		    init_offset + sizeof(struct sctp_init_chunk),
1417		    initack_offset, sh, init_src)) {
1418			return (NULL);
1419		}
1420		if (asoc->state & SCTP_STATE_SHUTDOWN_PENDING) {
1421			asoc->state = SCTP_STATE_OPEN |
1422			    SCTP_STATE_SHUTDOWN_PENDING;
1423			sctp_timer_start(SCTP_TIMER_TYPE_SHUTDOWNGUARD,
1424			    stcb->sctp_ep, stcb, asoc->primary_destination);
1425
1426		} else if (!(asoc->state & SCTP_STATE_SHUTDOWN_SENT)) {
1427			/* move to OPEN state, if not in SHUTDOWN_SENT */
1428			asoc->state = SCTP_STATE_OPEN;
1429		}
1430		/* respond with a COOKIE-ACK */
1431		sctp_stop_all_cookie_timers(stcb);
1432		sctp_send_cookie_ack(stcb);
1433
1434		return (stcb);
1435	}
1436	/* if we are not a restart we need the assoc_id field pop'd */
1437	asoc->assoc_id = ntohl(initack_cp->init.initiate_tag);
1438
1439	/* all other cases... */
1440	return (NULL);
1441}
1442
1443/*
1444 * handle a state cookie for a new association m: input packet mbuf chain--
1445 * assumes a pullup on IP/SCTP/COOKIE-ECHO chunk note: this is a "split" mbuf
1446 * and the cookie signature does not exist offset: offset into mbuf to the
1447 * cookie-echo chunk length: length of the cookie chunk to: where the init
1448 * was from returns a new TCB
1449 */
1450static struct sctp_tcb *
1451sctp_process_cookie_new(struct mbuf *m, int iphlen, int offset,
1452    struct sctphdr *sh, struct sctp_state_cookie *cookie, int cookie_len,
1453    struct sctp_inpcb *inp, struct sctp_nets **netp,
1454    struct sockaddr *init_src, int *notification,
1455    int auth_skipped, uint32_t auth_offset, uint32_t auth_len)
1456{
1457	struct sctp_tcb *stcb;
1458	struct sctp_init_chunk *init_cp, init_buf;
1459	struct sctp_init_ack_chunk *initack_cp, initack_buf;
1460	struct sockaddr_storage sa_store;
1461	struct sockaddr *initack_src = (struct sockaddr *)&sa_store;
1462	struct sockaddr_in *sin;
1463	struct sockaddr_in6 *sin6;
1464	struct sctp_association *asoc;
1465	int chk_length;
1466	int init_offset, initack_offset, initack_limit;
1467	int retval;
1468	int error = 0;
1469	uint32_t old_tag;
1470	uint8_t chunk_buf[DEFAULT_CHUNK_BUFFER];
1471
1472	/*
1473	 * find and validate the INIT chunk in the cookie (peer's info) the
1474	 * INIT should start after the cookie-echo header struct (chunk
1475	 * header, state cookie header struct)
1476	 */
1477	init_offset = offset + sizeof(struct sctp_cookie_echo_chunk);
1478	init_cp = (struct sctp_init_chunk *)
1479	    sctp_m_getptr(m, init_offset, sizeof(struct sctp_init_chunk),
1480	    (uint8_t *) & init_buf);
1481	if (init_cp == NULL) {
1482		/* could not pull a INIT chunk in cookie */
1483#ifdef SCTP_DEBUG
1484		if (sctp_debug_on & SCTP_DEBUG_INPUT1) {
1485			printf("process_cookie_new: could not pull INIT chunk hdr\n");
1486		}
1487#endif				/* SCTP_DEBUG */
1488		return (NULL);
1489	}
1490	chk_length = ntohs(init_cp->ch.chunk_length);
1491	if (init_cp->ch.chunk_type != SCTP_INITIATION) {
1492#ifdef SCTP_DEBUG
1493		if (sctp_debug_on & SCTP_DEBUG_INPUT1) {
1494			printf("HUH? process_cookie_new: could not find INIT chunk!\n");
1495		}
1496#endif				/* SCTP_DEBUG */
1497		return (NULL);
1498	}
1499	initack_offset = init_offset + SCTP_SIZE32(chk_length);
1500	/*
1501	 * find and validate the INIT-ACK chunk in the cookie (my info) the
1502	 * INIT-ACK follows the INIT chunk
1503	 */
1504	initack_cp = (struct sctp_init_ack_chunk *)
1505	    sctp_m_getptr(m, initack_offset, sizeof(struct sctp_init_ack_chunk),
1506	    (uint8_t *) & initack_buf);
1507	if (initack_cp == NULL) {
1508		/* could not pull INIT-ACK chunk in cookie */
1509#ifdef SCTP_DEBUG
1510		if (sctp_debug_on & SCTP_DEBUG_INPUT1) {
1511			printf("process_cookie_new: could not pull INIT-ACK chunk hdr\n");
1512		}
1513#endif				/* SCTP_DEBUG */
1514		return (NULL);
1515	}
1516	chk_length = ntohs(initack_cp->ch.chunk_length);
1517	if (initack_cp->ch.chunk_type != SCTP_INITIATION_ACK) {
1518		return (NULL);
1519	}
1520	/*
1521	 * NOTE: We can't use the INIT_ACK's chk_length to determine the
1522	 * "initack_limit" value.  This is because the chk_length field
1523	 * includes the length of the cookie, but the cookie is omitted when
1524	 * the INIT and INIT_ACK are tacked onto the cookie...
1525	 */
1526	initack_limit = offset + cookie_len;
1527
1528	/*
1529	 * now that we know the INIT/INIT-ACK are in place, create a new TCB
1530	 * and popluate
1531	 */
1532	stcb = sctp_aloc_assoc(inp, init_src, 0, &error,
1533	    ntohl(initack_cp->init.initiate_tag));
1534	if (stcb == NULL) {
1535		struct mbuf *op_err;
1536
1537		/* memory problem? */
1538#ifdef SCTP_DEBUG
1539		if (sctp_debug_on & SCTP_DEBUG_INPUT1) {
1540			printf("process_cookie_new: no room for another TCB!\n");
1541		}
1542#endif				/* SCTP_DEBUG */
1543		op_err = sctp_generate_invmanparam(SCTP_CAUSE_OUT_OF_RESC);
1544		sctp_abort_association(inp, (struct sctp_tcb *)NULL, m, iphlen,
1545		    sh, op_err);
1546		return (NULL);
1547	}
1548	/* get the correct sctp_nets */
1549	*netp = sctp_findnet(stcb, init_src);
1550	asoc = &stcb->asoc;
1551	/* get scope variables out of cookie */
1552	asoc->ipv4_local_scope = cookie->ipv4_scope;
1553	asoc->site_scope = cookie->site_scope;
1554	asoc->local_scope = cookie->local_scope;
1555	asoc->loopback_scope = cookie->loopback_scope;
1556
1557	if ((asoc->ipv4_addr_legal != cookie->ipv4_addr_legal) ||
1558	    (asoc->ipv6_addr_legal != cookie->ipv6_addr_legal)) {
1559		struct mbuf *op_err;
1560
1561		/*
1562		 * Houston we have a problem. The EP changed while the
1563		 * cookie was in flight. Only recourse is to abort the
1564		 * association.
1565		 */
1566		op_err = sctp_generate_invmanparam(SCTP_CAUSE_OUT_OF_RESC);
1567		sctp_abort_association(inp, (struct sctp_tcb *)NULL, m, iphlen,
1568		    sh, op_err);
1569		return (NULL);
1570	}
1571	/* process the INIT-ACK info (my info) */
1572	old_tag = asoc->my_vtag;
1573	asoc->assoc_id = asoc->my_vtag = ntohl(initack_cp->init.initiate_tag);
1574	asoc->my_rwnd = ntohl(initack_cp->init.a_rwnd);
1575	asoc->pre_open_streams = ntohs(initack_cp->init.num_outbound_streams);
1576	asoc->init_seq_number = ntohl(initack_cp->init.initial_tsn);
1577	asoc->sending_seq = asoc->asconf_seq_out = asoc->str_reset_seq_out = asoc->init_seq_number;
1578	asoc->last_cwr_tsn = asoc->init_seq_number - 1;
1579	asoc->asconf_seq_in = asoc->last_acked_seq = asoc->init_seq_number - 1;
1580	asoc->str_reset_seq_in = asoc->init_seq_number;
1581
1582	asoc->advanced_peer_ack_point = asoc->last_acked_seq;
1583
1584	/* process the INIT info (peer's info) */
1585	retval = sctp_process_init(init_cp, stcb, *netp);
1586	if (retval < 0) {
1587		sctp_free_assoc(inp, stcb, 0);
1588		return (NULL);
1589	}
1590	/* load all addresses */
1591	if (sctp_load_addresses_from_init(stcb, m, iphlen,
1592	    init_offset + sizeof(struct sctp_init_chunk), initack_offset, sh,
1593	    init_src)) {
1594		sctp_free_assoc(inp, stcb, 0);
1595		return (NULL);
1596	}
1597	/*
1598	 * verify any preceding AUTH chunk that was skipped
1599	 */
1600	/* pull the local authentication parameters from the cookie/init-ack */
1601	sctp_auth_get_cookie_params(stcb, m,
1602	    initack_offset + sizeof(struct sctp_init_ack_chunk),
1603	    initack_limit - (initack_offset + sizeof(struct sctp_init_ack_chunk)));
1604	if (auth_skipped) {
1605		struct sctp_auth_chunk *auth;
1606
1607		auth = (struct sctp_auth_chunk *)
1608		    sctp_m_getptr(m, auth_offset, auth_len, chunk_buf);
1609		if (sctp_handle_auth(stcb, auth, m, auth_offset)) {
1610			/* auth HMAC failed, dump the assoc and packet */
1611#ifdef SCTP_DEBUG
1612			if (sctp_debug_on & SCTP_DEBUG_AUTH1)
1613				printf("COOKIE-ECHO: AUTH failed\n");
1614#endif				/* SCTP_DEBUG */
1615			sctp_free_assoc(inp, stcb, 0);
1616			return (NULL);
1617		} else {
1618			/* remaining chunks checked... good to go */
1619			stcb->asoc.authenticated = 1;
1620		}
1621	}
1622	/* update current state */
1623#ifdef SCTP_DEBUG
1624	if (sctp_debug_on & SCTP_DEBUG_INPUT1) {
1625		printf("moving to OPEN state\n");
1626	}
1627#endif
1628	if (asoc->state & SCTP_STATE_SHUTDOWN_PENDING) {
1629		asoc->state = SCTP_STATE_OPEN | SCTP_STATE_SHUTDOWN_PENDING;
1630		sctp_timer_start(SCTP_TIMER_TYPE_SHUTDOWNGUARD,
1631		    stcb->sctp_ep, stcb, asoc->primary_destination);
1632	} else {
1633		asoc->state = SCTP_STATE_OPEN;
1634	}
1635	SCTP_STAT_INCR_COUNTER32(sctps_passiveestab);
1636	SCTP_STAT_INCR_GAUGE32(sctps_currestab);
1637	sctp_stop_all_cookie_timers(stcb);
1638	/* calculate the RTT */
1639	(*netp)->RTO = sctp_calculate_rto(stcb, asoc, *netp,
1640	    &cookie->time_entered);
1641
1642	/*
1643	 * if we're doing ASCONFs, check to see if we have any new local
1644	 * addresses that need to get added to the peer (eg. addresses
1645	 * changed while cookie echo in flight).  This needs to be done
1646	 * after we go to the OPEN state to do the correct asconf
1647	 * processing. else, make sure we have the correct addresses in our
1648	 * lists
1649	 */
1650
1651	/* warning, we re-use sin, sin6, sa_store here! */
1652	/* pull in local_address (our "from" address) */
1653	if (cookie->laddr_type == SCTP_IPV4_ADDRESS) {
1654		/* source addr is IPv4 */
1655		sin = (struct sockaddr_in *)initack_src;
1656		memset(sin, 0, sizeof(*sin));
1657		sin->sin_family = AF_INET;
1658		sin->sin_len = sizeof(struct sockaddr_in);
1659		sin->sin_addr.s_addr = cookie->laddress[0];
1660	} else if (cookie->laddr_type == SCTP_IPV6_ADDRESS) {
1661		/* source addr is IPv6 */
1662		sin6 = (struct sockaddr_in6 *)initack_src;
1663		memset(sin6, 0, sizeof(*sin6));
1664		sin6->sin6_family = AF_INET6;
1665		sin6->sin6_len = sizeof(struct sockaddr_in6);
1666		sin6->sin6_scope_id = cookie->scope_id;
1667		memcpy(&sin6->sin6_addr, cookie->laddress,
1668		    sizeof(sin6->sin6_addr));
1669	} else {
1670		sctp_free_assoc(inp, stcb, 0);
1671		return (NULL);
1672	}
1673
1674	sctp_check_address_list(stcb, m,
1675	    initack_offset + sizeof(struct sctp_init_ack_chunk),
1676	    initack_limit - (initack_offset + sizeof(struct sctp_init_ack_chunk)),
1677	    initack_src, cookie->local_scope, cookie->site_scope,
1678	    cookie->ipv4_scope, cookie->loopback_scope);
1679
1680
1681	/* set up to notify upper layer */
1682	*notification = SCTP_NOTIFY_ASSOC_UP;
1683	if (((stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE) ||
1684	    (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL)) &&
1685	    (inp->sctp_socket->so_qlimit == 0)) {
1686		/*
1687		 * This is an endpoint that called connect() how it got a
1688		 * cookie that is NEW is a bit of a mystery. It must be that
1689		 * the INIT was sent, but before it got there.. a complete
1690		 * INIT/INIT-ACK/COOKIE arrived. But of course then it
1691		 * should have went to the other code.. not here.. oh well..
1692		 * a bit of protection is worth having..
1693		 */
1694		stcb->sctp_ep->sctp_flags |= SCTP_PCB_FLAGS_CONNECTED;
1695		soisconnected(stcb->sctp_ep->sctp_socket);
1696	} else if ((stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE) &&
1697	    (inp->sctp_socket->so_qlimit)) {
1698		/*
1699		 * We don't want to do anything with this one. Since it is
1700		 * the listening guy. The timer will get started for
1701		 * accepted connections in the caller.
1702		 */
1703		;
1704	}
1705	/* since we did not send a HB make sure we don't double things */
1706	(*netp)->hb_responded = 1;
1707
1708	if (stcb->asoc.sctp_autoclose_ticks &&
1709	    sctp_is_feature_on(inp, SCTP_PCB_FLAGS_AUTOCLOSE)) {
1710		sctp_timer_start(SCTP_TIMER_TYPE_AUTOCLOSE, inp, stcb, NULL);
1711	}
1712	/* respond with a COOKIE-ACK */
1713	sctp_send_cookie_ack(stcb);
1714	return (stcb);
1715}
1716
1717
1718/*
1719 * handles a COOKIE-ECHO message stcb: modified to either a new or left as
1720 * existing (non-NULL) TCB
1721 */
1722static struct mbuf *
1723sctp_handle_cookie_echo(struct mbuf *m, int iphlen, int offset,
1724    struct sctphdr *sh, struct sctp_cookie_echo_chunk *cp,
1725    struct sctp_inpcb **inp_p, struct sctp_tcb **stcb, struct sctp_nets **netp,
1726    int auth_skipped, uint32_t auth_offset, uint32_t auth_len)
1727{
1728	struct sctp_state_cookie *cookie;
1729	struct sockaddr_in6 sin6;
1730	struct sockaddr_in sin;
1731	struct sctp_tcb *l_stcb = *stcb;
1732	struct sctp_inpcb *l_inp;
1733	struct sockaddr *to;
1734	sctp_assoc_t sac_restart_id;
1735	struct sctp_pcb *ep;
1736	struct mbuf *m_sig;
1737	uint8_t calc_sig[SCTP_SIGNATURE_SIZE], tmp_sig[SCTP_SIGNATURE_SIZE];
1738	uint8_t *sig;
1739	uint8_t cookie_ok = 0;
1740	unsigned int size_of_pkt, sig_offset, cookie_offset;
1741	unsigned int cookie_len;
1742	struct timeval now;
1743	struct timeval time_expires;
1744	struct sockaddr_storage dest_store;
1745	struct sockaddr *localep_sa = (struct sockaddr *)&dest_store;
1746	struct ip *iph;
1747	int notification = 0;
1748	struct sctp_nets *netl;
1749	int had_a_existing_tcb = 0;
1750
1751#ifdef SCTP_DEBUG
1752	if (sctp_debug_on & SCTP_DEBUG_INPUT2) {
1753		printf("sctp_handle_cookie: handling COOKIE-ECHO\n");
1754	}
1755#endif
1756
1757	if (inp_p == NULL) {
1758		return (NULL);
1759	}
1760	/* First get the destination address setup too. */
1761	iph = mtod(m, struct ip *);
1762	if (iph->ip_v == IPVERSION) {
1763		/* its IPv4 */
1764		struct sockaddr_in *sin;
1765
1766		sin = (struct sockaddr_in *)(localep_sa);
1767		memset(sin, 0, sizeof(*sin));
1768		sin->sin_family = AF_INET;
1769		sin->sin_len = sizeof(*sin);
1770		sin->sin_port = sh->dest_port;
1771		sin->sin_addr.s_addr = iph->ip_dst.s_addr;
1772	} else if (iph->ip_v == (IPV6_VERSION >> 4)) {
1773		/* its IPv6 */
1774		struct ip6_hdr *ip6;
1775		struct sockaddr_in6 *sin6;
1776
1777		sin6 = (struct sockaddr_in6 *)(localep_sa);
1778		memset(sin6, 0, sizeof(*sin6));
1779		sin6->sin6_family = AF_INET6;
1780		sin6->sin6_len = sizeof(struct sockaddr_in6);
1781		ip6 = mtod(m, struct ip6_hdr *);
1782		sin6->sin6_port = sh->dest_port;
1783		sin6->sin6_addr = ip6->ip6_dst;
1784	} else {
1785		return (NULL);
1786	}
1787
1788	cookie = &cp->cookie;
1789	cookie_offset = offset + sizeof(struct sctp_chunkhdr);
1790	cookie_len = ntohs(cp->ch.chunk_length);
1791
1792	if ((cookie->peerport != sh->src_port) &&
1793	    (cookie->myport != sh->dest_port) &&
1794	    (cookie->my_vtag != sh->v_tag)) {
1795		/*
1796		 * invalid ports or bad tag.  Note that we always leave the
1797		 * v_tag in the header in network order and when we stored
1798		 * it in the my_vtag slot we also left it in network order.
1799		 * This maintians the match even though it may be in the
1800		 * opposite byte order of the machine :->
1801		 */
1802		return (NULL);
1803	}
1804	/* compute size of packet */
1805	if (m->m_flags & M_PKTHDR) {
1806		size_of_pkt = m->m_pkthdr.len;
1807	} else {
1808		/* Should have a pkt hdr really */
1809		struct mbuf *mat;
1810
1811		mat = m;
1812		size_of_pkt = 0;
1813		while (mat != NULL) {
1814			size_of_pkt += mat->m_len;
1815			mat = mat->m_next;
1816		}
1817	}
1818	if (cookie_len > size_of_pkt ||
1819	    cookie_len < sizeof(struct sctp_cookie_echo_chunk) +
1820	    sizeof(struct sctp_init_chunk) +
1821	    sizeof(struct sctp_init_ack_chunk) + SCTP_SIGNATURE_SIZE) {
1822		/* cookie too long!  or too small */
1823		return (NULL);
1824	}
1825	/*
1826	 * split off the signature into its own mbuf (since it should not be
1827	 * calculated in the sctp_hmac_m() call).
1828	 */
1829	sig_offset = offset + cookie_len - SCTP_SIGNATURE_SIZE;
1830	if (sig_offset > size_of_pkt) {
1831		/* packet not correct size! */
1832		/* XXX this may already be accounted for earlier... */
1833		return (NULL);
1834	}
1835	m_sig = m_split(m, sig_offset, M_DONTWAIT);
1836	if (m_sig == NULL) {
1837		/* out of memory or ?? */
1838		return (NULL);
1839	}
1840	/*
1841	 * compute the signature/digest for the cookie
1842	 */
1843	ep = &(*inp_p)->sctp_ep;
1844	l_inp = *inp_p;
1845	if (l_stcb) {
1846		SCTP_TCB_UNLOCK(l_stcb);
1847	}
1848	SCTP_INP_RLOCK(l_inp);
1849	if (l_stcb) {
1850		SCTP_TCB_LOCK(l_stcb);
1851	}
1852	/* which cookie is it? */
1853	if ((cookie->time_entered.tv_sec < (long)ep->time_of_secret_change) &&
1854	    (ep->current_secret_number != ep->last_secret_number)) {
1855		/* it's the old cookie */
1856		sctp_hmac_m(SCTP_HMAC,
1857		    (uint8_t *) ep->secret_key[(int)ep->last_secret_number],
1858		    SCTP_SECRET_SIZE, m, cookie_offset, calc_sig);
1859	} else {
1860		/* it's the current cookie */
1861		sctp_hmac_m(SCTP_HMAC,
1862		    (uint8_t *) ep->secret_key[(int)ep->current_secret_number],
1863		    SCTP_SECRET_SIZE, m, cookie_offset, calc_sig);
1864	}
1865	/* get the signature */
1866	SCTP_INP_RUNLOCK(l_inp);
1867	sig = (uint8_t *) sctp_m_getptr(m_sig, 0, SCTP_SIGNATURE_SIZE, (uint8_t *) & tmp_sig);
1868	if (sig == NULL) {
1869		/* couldn't find signature */
1870		sctp_m_freem(m_sig);
1871		return (NULL);
1872	}
1873	/* compare the received digest with the computed digest */
1874	if (memcmp(calc_sig, sig, SCTP_SIGNATURE_SIZE) != 0) {
1875		/* try the old cookie? */
1876		if ((cookie->time_entered.tv_sec == (long)ep->time_of_secret_change) &&
1877		    (ep->current_secret_number != ep->last_secret_number)) {
1878			/* compute digest with old */
1879			sctp_hmac_m(SCTP_HMAC,
1880			    (uint8_t *) ep->secret_key[(int)ep->last_secret_number],
1881			    SCTP_SECRET_SIZE, m, cookie_offset, calc_sig);
1882			/* compare */
1883			if (memcmp(calc_sig, sig, SCTP_SIGNATURE_SIZE) == 0)
1884				cookie_ok = 1;
1885		}
1886	} else {
1887		cookie_ok = 1;
1888	}
1889
1890	/*
1891	 * Now before we continue we must reconstruct our mbuf so that
1892	 * normal processing of any other chunks will work.
1893	 */
1894	{
1895		struct mbuf *m_at;
1896
1897		m_at = m;
1898		while (m_at->m_next != NULL) {
1899			m_at = m_at->m_next;
1900		}
1901		m_at->m_next = m_sig;
1902		if (m->m_flags & M_PKTHDR) {
1903			/*
1904			 * We should only do this if and only if the front
1905			 * mbuf has a m_pkthdr... it should in theory.
1906			 */
1907			if (m_sig->m_flags & M_PKTHDR) {
1908				/* Add back to the pkt hdr of main m chain */
1909				m->m_pkthdr.len += m_sig->m_pkthdr.len;
1910			} else {
1911				/*
1912				 * Got a problem, no pkthdr in split chain.
1913				 * TSNH but we will handle it just in case
1914				 */
1915				int mmlen = 0;
1916				struct mbuf *lat;
1917
1918				printf("Warning: Hitting m_split join TSNH code - fixed\n");
1919				lat = m_sig;
1920				while (lat) {
1921					mmlen += lat->m_len;
1922					lat = lat->m_next;
1923				}
1924				m->m_pkthdr.len += mmlen;
1925			}
1926		}
1927	}
1928
1929	if (cookie_ok == 0) {
1930#ifdef SCTP_DEBUG
1931		if (sctp_debug_on & SCTP_DEBUG_INPUT2) {
1932			printf("handle_cookie_echo: cookie signature validation failed!\n");
1933			printf("offset = %u, cookie_offset = %u, sig_offset = %u\n",
1934			    (uint32_t) offset, cookie_offset, sig_offset);
1935		}
1936#endif
1937		return (NULL);
1938	}
1939	/*
1940	 * check the cookie timestamps to be sure it's not stale
1941	 */
1942	SCTP_GETTIME_TIMEVAL(&now);
1943	/* Expire time is in Ticks, so we convert to seconds */
1944	time_expires.tv_sec = cookie->time_entered.tv_sec + cookie->cookie_life;
1945	time_expires.tv_usec = cookie->time_entered.tv_usec;
1946	if (timevalcmp(&now, &time_expires, >)) {
1947		/* cookie is stale! */
1948		struct mbuf *op_err;
1949		struct sctp_stale_cookie_msg *scm;
1950		uint32_t tim;
1951
1952		op_err = sctp_get_mbuf_for_msg(sizeof(struct sctp_stale_cookie_msg),
1953		    1, M_DONTWAIT, 1, MT_DATA);
1954		if (op_err == NULL) {
1955			/* FOOBAR */
1956			return (NULL);
1957		}
1958		/* pre-reserve some space */
1959		op_err->m_data += sizeof(struct ip6_hdr);
1960		op_err->m_data += sizeof(struct sctphdr);
1961		op_err->m_data += sizeof(struct sctp_chunkhdr);
1962
1963		/* Set the len */
1964		op_err->m_len = op_err->m_pkthdr.len = sizeof(struct sctp_stale_cookie_msg);
1965		scm = mtod(op_err, struct sctp_stale_cookie_msg *);
1966		scm->ph.param_type = htons(SCTP_CAUSE_STALE_COOKIE);
1967		scm->ph.param_length = htons((sizeof(struct sctp_paramhdr) +
1968		    (sizeof(uint32_t))));
1969		/* seconds to usec */
1970		tim = (now.tv_sec - time_expires.tv_sec) * 1000000;
1971		/* add in usec */
1972		if (tim == 0)
1973			tim = now.tv_usec - cookie->time_entered.tv_usec;
1974		scm->time_usec = htonl(tim);
1975		sctp_send_operr_to(m, iphlen, op_err, cookie->peers_vtag);
1976		return (NULL);
1977	}
1978	/*
1979	 * Now we must see with the lookup address if we have an existing
1980	 * asoc. This will only happen if we were in the COOKIE-WAIT state
1981	 * and a INIT collided with us and somewhere the peer sent the
1982	 * cookie on another address besides the single address our assoc
1983	 * had for him. In this case we will have one of the tie-tags set at
1984	 * least AND the address field in the cookie can be used to look it
1985	 * up.
1986	 */
1987	to = NULL;
1988	if (cookie->addr_type == SCTP_IPV6_ADDRESS) {
1989		memset(&sin6, 0, sizeof(sin6));
1990		sin6.sin6_family = AF_INET6;
1991		sin6.sin6_len = sizeof(sin6);
1992		sin6.sin6_port = sh->src_port;
1993		sin6.sin6_scope_id = cookie->scope_id;
1994		memcpy(&sin6.sin6_addr.s6_addr, cookie->address,
1995		    sizeof(sin6.sin6_addr.s6_addr));
1996		to = (struct sockaddr *)&sin6;
1997	} else if (cookie->addr_type == SCTP_IPV4_ADDRESS) {
1998		memset(&sin, 0, sizeof(sin));
1999		sin.sin_family = AF_INET;
2000		sin.sin_len = sizeof(sin);
2001		sin.sin_port = sh->src_port;
2002		sin.sin_addr.s_addr = cookie->address[0];
2003		to = (struct sockaddr *)&sin;
2004	}
2005	if ((*stcb == NULL) && to) {
2006		/* Yep, lets check */
2007		*stcb = sctp_findassociation_ep_addr(inp_p, to, netp, localep_sa, NULL);
2008		if (*stcb == NULL) {
2009			/*
2010			 * We should have only got back the same inp. If we
2011			 * got back a different ep we have a problem. The
2012			 * original findep got back l_inp and now
2013			 */
2014			if (l_inp != *inp_p) {
2015				printf("Bad problem find_ep got a diff inp then special_locate?\n");
2016			}
2017		}
2018	}
2019	cookie_len -= SCTP_SIGNATURE_SIZE;
2020	if (*stcb == NULL) {
2021		/* this is the "normal" case... get a new TCB */
2022		*stcb = sctp_process_cookie_new(m, iphlen, offset, sh, cookie,
2023		    cookie_len, *inp_p, netp, to, &notification,
2024		    auth_skipped, auth_offset, auth_len);
2025	} else {
2026		/* this is abnormal... cookie-echo on existing TCB */
2027		had_a_existing_tcb = 1;
2028		*stcb = sctp_process_cookie_existing(m, iphlen, offset, sh,
2029		    cookie, cookie_len, *inp_p, *stcb, *netp, to, &notification,
2030		    &sac_restart_id);
2031	}
2032
2033	if (*stcb == NULL) {
2034		/* still no TCB... must be bad cookie-echo */
2035		return (NULL);
2036	}
2037	/*
2038	 * Ok, we built an association so confirm the address we sent the
2039	 * INIT-ACK to.
2040	 */
2041	netl = sctp_findnet(*stcb, to);
2042	/*
2043	 * This code should in theory NOT run but
2044	 */
2045	if (netl == NULL) {
2046		/* TSNH! Huh, why do I need to add this address here? */
2047		int ret;
2048
2049		ret = sctp_add_remote_addr(*stcb, to, 0, 100);
2050		netl = sctp_findnet(*stcb, to);
2051	}
2052	if (netl) {
2053		if (netl->dest_state & SCTP_ADDR_UNCONFIRMED) {
2054			netl->dest_state &= ~SCTP_ADDR_UNCONFIRMED;
2055			sctp_set_primary_addr((*stcb), (struct sockaddr *)NULL,
2056			    netl);
2057			sctp_ulp_notify(SCTP_NOTIFY_INTERFACE_CONFIRMED,
2058			    (*stcb), 0, (void *)netl);
2059		}
2060	}
2061	if (*stcb) {
2062		sctp_timer_start(SCTP_TIMER_TYPE_HEARTBEAT, *inp_p,
2063		    *stcb, NULL);
2064	}
2065	if ((*inp_p)->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE) {
2066		if (!had_a_existing_tcb ||
2067		    (((*inp_p)->sctp_flags & SCTP_PCB_FLAGS_CONNECTED) == 0)) {
2068			/*
2069			 * If we have a NEW cookie or the connect never
2070			 * reached the connected state during collision we
2071			 * must do the TCP accept thing.
2072			 */
2073			struct socket *so, *oso;
2074			struct sctp_inpcb *inp;
2075
2076			if (notification == SCTP_NOTIFY_ASSOC_RESTART) {
2077				/*
2078				 * For a restart we will keep the same
2079				 * socket, no need to do anything. I THINK!!
2080				 */
2081				sctp_ulp_notify(notification, *stcb, 0, (void *)&sac_restart_id);
2082				return (m);
2083			}
2084			oso = (*inp_p)->sctp_socket;
2085			/*
2086			 * We do this to keep the sockets side happy durin
2087			 * the sonewcon ONLY.
2088			 */
2089			NET_LOCK_GIANT();
2090			SCTP_TCB_UNLOCK((*stcb));
2091			so = sonewconn(oso, SS_ISCONNECTED
2092			    );
2093			NET_UNLOCK_GIANT();
2094			SCTP_INP_WLOCK((*stcb)->sctp_ep);
2095			SCTP_TCB_LOCK((*stcb));
2096			SCTP_INP_WUNLOCK((*stcb)->sctp_ep);
2097			if (so == NULL) {
2098				struct mbuf *op_err;
2099
2100				/* Too many sockets */
2101#ifdef SCTP_DEBUG
2102				if (sctp_debug_on & SCTP_DEBUG_INPUT1) {
2103					printf("process_cookie_new: no room for another socket!\n");
2104				}
2105#endif				/* SCTP_DEBUG */
2106				op_err = sctp_generate_invmanparam(SCTP_CAUSE_OUT_OF_RESC);
2107				sctp_abort_association(*inp_p, NULL, m, iphlen,
2108				    sh, op_err);
2109				sctp_free_assoc(*inp_p, *stcb, 0);
2110				return (NULL);
2111			}
2112			inp = (struct sctp_inpcb *)so->so_pcb;
2113			inp->sctp_flags = (SCTP_PCB_FLAGS_TCPTYPE |
2114			    SCTP_PCB_FLAGS_CONNECTED |
2115			    SCTP_PCB_FLAGS_IN_TCPPOOL |
2116			    (SCTP_PCB_COPY_FLAGS & (*inp_p)->sctp_flags) |
2117			    SCTP_PCB_FLAGS_DONT_WAKE);
2118			inp->sctp_features = (*inp_p)->sctp_features;
2119			inp->sctp_socket = so;
2120			inp->sctp_frag_point = (*inp_p)->sctp_frag_point;
2121			inp->partial_delivery_point = (*inp_p)->partial_delivery_point;
2122			inp->sctp_context = (*inp_p)->sctp_context;
2123			inp->inp_starting_point_for_iterator = NULL;
2124			/*
2125			 * copy in the authentication parameters from the
2126			 * original endpoint
2127			 */
2128			if (inp->sctp_ep.local_hmacs)
2129				sctp_free_hmaclist(inp->sctp_ep.local_hmacs);
2130			inp->sctp_ep.local_hmacs =
2131			    sctp_copy_hmaclist((*inp_p)->sctp_ep.local_hmacs);
2132			if (inp->sctp_ep.local_auth_chunks)
2133				sctp_free_chunklist(inp->sctp_ep.local_auth_chunks);
2134			inp->sctp_ep.local_auth_chunks =
2135			    sctp_copy_chunklist((*inp_p)->sctp_ep.local_auth_chunks);
2136			(void)sctp_copy_skeylist(&(*inp_p)->sctp_ep.shared_keys,
2137			    &inp->sctp_ep.shared_keys);
2138
2139			/*
2140			 * Now we must move it from one hash table to
2141			 * another and get the tcb in the right place.
2142			 */
2143			sctp_move_pcb_and_assoc(*inp_p, inp, *stcb);
2144
2145			sctp_pull_off_control_to_new_inp((*inp_p), inp, *stcb);
2146
2147			/* Switch over to the new guy */
2148			*inp_p = inp;
2149
2150			sctp_ulp_notify(notification, *stcb, 0, NULL);
2151			return (m);
2152		}
2153	}
2154	if ((notification) && ((*inp_p)->sctp_flags & SCTP_PCB_FLAGS_UDPTYPE)) {
2155		sctp_ulp_notify(notification, *stcb, 0, NULL);
2156	}
2157	return (m);
2158}
2159
2160static void
2161sctp_handle_cookie_ack(struct sctp_cookie_ack_chunk *cp,
2162    struct sctp_tcb *stcb, struct sctp_nets *net)
2163{
2164	/* cp must not be used, others call this without a c-ack :-) */
2165	struct sctp_association *asoc;
2166
2167#ifdef SCTP_DEBUG
2168	if (sctp_debug_on & SCTP_DEBUG_INPUT2) {
2169		printf("sctp_handle_cookie_ack: handling COOKIE-ACK\n");
2170	}
2171#endif
2172	if (stcb == NULL)
2173		return;
2174
2175	asoc = &stcb->asoc;
2176
2177	sctp_stop_all_cookie_timers(stcb);
2178	/* process according to association state */
2179	if (SCTP_GET_STATE(asoc) == SCTP_STATE_COOKIE_ECHOED) {
2180		/* state change only needed when I am in right state */
2181#ifdef SCTP_DEBUG
2182		if (sctp_debug_on & SCTP_DEBUG_INPUT2) {
2183			printf("moving to OPEN state\n");
2184		}
2185#endif
2186		if (asoc->state & SCTP_STATE_SHUTDOWN_PENDING) {
2187			asoc->state = SCTP_STATE_OPEN | SCTP_STATE_SHUTDOWN_PENDING;
2188			sctp_timer_start(SCTP_TIMER_TYPE_SHUTDOWNGUARD,
2189			    stcb->sctp_ep, stcb, asoc->primary_destination);
2190
2191		} else {
2192			asoc->state = SCTP_STATE_OPEN;
2193		}
2194		/* update RTO */
2195		SCTP_STAT_INCR_COUNTER32(sctps_activeestab);
2196		SCTP_STAT_INCR_GAUGE32(sctps_currestab);
2197		if (asoc->overall_error_count == 0) {
2198			net->RTO = sctp_calculate_rto(stcb, asoc, net,
2199			    &asoc->time_entered);
2200		}
2201		SCTP_GETTIME_TIMEVAL(&asoc->time_entered);
2202		sctp_ulp_notify(SCTP_NOTIFY_ASSOC_UP, stcb, 0, NULL);
2203		if ((stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE) ||
2204		    (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL)) {
2205			stcb->sctp_ep->sctp_flags |= SCTP_PCB_FLAGS_CONNECTED;
2206			soisconnected(stcb->sctp_ep->sctp_socket);
2207		}
2208		sctp_timer_start(SCTP_TIMER_TYPE_HEARTBEAT, stcb->sctp_ep,
2209		    stcb, net);
2210		/*
2211		 * since we did not send a HB make sure we don't double
2212		 * things
2213		 */
2214		net->hb_responded = 1;
2215
2216		if (stcb->asoc.sctp_autoclose_ticks &&
2217		    sctp_is_feature_on(stcb->sctp_ep, SCTP_PCB_FLAGS_AUTOCLOSE)) {
2218			sctp_timer_start(SCTP_TIMER_TYPE_AUTOCLOSE,
2219			    stcb->sctp_ep, stcb, NULL);
2220		}
2221		/*
2222		 * set ASCONF timer if ASCONFs are pending and allowed (eg.
2223		 * addresses changed when init/cookie echo in flight)
2224		 */
2225		if ((sctp_is_feature_on(stcb->sctp_ep, SCTP_PCB_FLAGS_DO_ASCONF)) &&
2226		    (stcb->asoc.peer_supports_asconf) &&
2227		    (!TAILQ_EMPTY(&stcb->asoc.asconf_queue))) {
2228			sctp_timer_start(SCTP_TIMER_TYPE_ASCONF,
2229			    stcb->sctp_ep, stcb,
2230			    stcb->asoc.primary_destination);
2231		}
2232	}
2233	/* Toss the cookie if I can */
2234	sctp_toss_old_cookies(stcb, asoc);
2235	if (!TAILQ_EMPTY(&asoc->sent_queue)) {
2236		/* Restart the timer if we have pending data */
2237		struct sctp_tmit_chunk *chk;
2238
2239		chk = TAILQ_FIRST(&asoc->sent_queue);
2240		if (chk) {
2241			sctp_timer_start(SCTP_TIMER_TYPE_SEND, stcb->sctp_ep,
2242			    stcb, chk->whoTo);
2243		}
2244	}
2245}
2246
2247static void
2248sctp_handle_ecn_echo(struct sctp_ecne_chunk *cp,
2249    struct sctp_tcb *stcb)
2250{
2251	struct sctp_nets *net;
2252	struct sctp_tmit_chunk *lchk;
2253	uint32_t tsn;
2254
2255	if (ntohs(cp->ch.chunk_length) != sizeof(struct sctp_ecne_chunk)) {
2256		return;
2257	}
2258	SCTP_STAT_INCR(sctps_recvecne);
2259	tsn = ntohl(cp->tsn);
2260	/* ECN Nonce stuff: need a resync and disable the nonce sum check */
2261	/* Also we make sure we disable the nonce_wait */
2262	lchk = TAILQ_FIRST(&stcb->asoc.send_queue);
2263	if (lchk == NULL) {
2264		stcb->asoc.nonce_resync_tsn = stcb->asoc.sending_seq;
2265	} else {
2266		stcb->asoc.nonce_resync_tsn = lchk->rec.data.TSN_seq;
2267	}
2268	stcb->asoc.nonce_wait_for_ecne = 0;
2269	stcb->asoc.nonce_sum_check = 0;
2270
2271	/* Find where it was sent, if possible */
2272	net = NULL;
2273	lchk = TAILQ_FIRST(&stcb->asoc.sent_queue);
2274	while (lchk) {
2275		if (lchk->rec.data.TSN_seq == tsn) {
2276			net = lchk->whoTo;
2277			break;
2278		}
2279		if (compare_with_wrap(lchk->rec.data.TSN_seq, tsn, MAX_SEQ))
2280			break;
2281		lchk = TAILQ_NEXT(lchk, sctp_next);
2282	}
2283	if (net == NULL)
2284		/* default is we use the primary */
2285		net = stcb->asoc.primary_destination;
2286
2287	if (compare_with_wrap(tsn, stcb->asoc.last_cwr_tsn, MAX_TSN)) {
2288#ifdef SCTP_CWND_MONITOR
2289		int old_cwnd;
2290
2291		old_cwnd = net->cwnd;
2292#endif
2293		SCTP_STAT_INCR(sctps_ecnereducedcwnd);
2294		net->ssthresh = net->cwnd / 2;
2295		if (net->ssthresh < net->mtu) {
2296			net->ssthresh = net->mtu;
2297			/* here back off the timer as well, to slow us down */
2298			net->RTO <<= 2;
2299		}
2300		net->cwnd = net->ssthresh;
2301#ifdef SCTP_CWND_MONITOR
2302		sctp_log_cwnd(stcb, net, (net->cwnd - old_cwnd), SCTP_CWND_LOG_FROM_SAT);
2303#endif
2304		/*
2305		 * we reduce once every RTT. So we will only lower cwnd at
2306		 * the next sending seq i.e. the resync_tsn.
2307		 */
2308		stcb->asoc.last_cwr_tsn = stcb->asoc.nonce_resync_tsn;
2309	}
2310	/*
2311	 * We always send a CWR this way if our previous one was lost our
2312	 * peer will get an update, or if it is not time again to reduce we
2313	 * still get the cwr to the peer.
2314	 */
2315	sctp_send_cwr(stcb, net, tsn);
2316}
2317
2318static void
2319sctp_handle_ecn_cwr(struct sctp_cwr_chunk *cp, struct sctp_tcb *stcb)
2320{
2321	/*
2322	 * Here we get a CWR from the peer. We must look in the outqueue and
2323	 * make sure that we have a covered ECNE in teh control chunk part.
2324	 * If so remove it.
2325	 */
2326	struct sctp_tmit_chunk *chk;
2327	struct sctp_ecne_chunk *ecne;
2328
2329	TAILQ_FOREACH(chk, &stcb->asoc.control_send_queue, sctp_next) {
2330		if (chk->rec.chunk_id.id != SCTP_ECN_ECHO) {
2331			continue;
2332		}
2333		/*
2334		 * Look for and remove if it is the right TSN. Since there
2335		 * is only ONE ECNE on the control queue at any one time we
2336		 * don't need to worry about more than one!
2337		 */
2338		ecne = mtod(chk->data, struct sctp_ecne_chunk *);
2339		if (compare_with_wrap(ntohl(cp->tsn), ntohl(ecne->tsn),
2340		    MAX_TSN) || (cp->tsn == ecne->tsn)) {
2341			/* this covers this ECNE, we can remove it */
2342			stcb->asoc.ecn_echo_cnt_onq--;
2343			TAILQ_REMOVE(&stcb->asoc.control_send_queue, chk,
2344			    sctp_next);
2345			if (chk->data) {
2346				sctp_m_freem(chk->data);
2347				chk->data = NULL;
2348			}
2349			stcb->asoc.ctrl_queue_cnt--;
2350			sctp_free_remote_addr(chk->whoTo);
2351			sctp_free_a_chunk(stcb, chk);
2352			break;
2353		}
2354	}
2355}
2356
2357static void
2358sctp_handle_shutdown_complete(struct sctp_shutdown_complete_chunk *cp,
2359    struct sctp_tcb *stcb, struct sctp_nets *net)
2360{
2361	struct sctp_association *asoc;
2362
2363#ifdef SCTP_DEBUG
2364	if (sctp_debug_on & SCTP_DEBUG_INPUT2) {
2365		printf("sctp_handle_shutdown_complete: handling SHUTDOWN-COMPLETE\n");
2366	}
2367#endif
2368	if (stcb == NULL)
2369		return;
2370
2371	asoc = &stcb->asoc;
2372	/* process according to association state */
2373	if (SCTP_GET_STATE(asoc) != SCTP_STATE_SHUTDOWN_ACK_SENT) {
2374		/* unexpected SHUTDOWN-COMPLETE... so ignore... */
2375		SCTP_TCB_UNLOCK(stcb);
2376		return;
2377	}
2378	/* notify upper layer protocol */
2379	if (stcb->sctp_socket) {
2380		sctp_ulp_notify(SCTP_NOTIFY_ASSOC_DOWN, stcb, 0, NULL);
2381		/* are the queues empty? they should be */
2382		if (!TAILQ_EMPTY(&asoc->send_queue) ||
2383		    !TAILQ_EMPTY(&asoc->sent_queue) ||
2384		    !TAILQ_EMPTY(&asoc->out_wheel)) {
2385			sctp_report_all_outbound(stcb, 0);
2386		}
2387	}
2388	/* stop the timer */
2389	sctp_timer_stop(SCTP_TIMER_TYPE_SHUTDOWN, stcb->sctp_ep, stcb, net);
2390	SCTP_STAT_INCR_COUNTER32(sctps_shutdown);
2391	/* free the TCB */
2392	sctp_free_assoc(stcb->sctp_ep, stcb, 0);
2393	return;
2394}
2395
2396static int
2397process_chunk_drop(struct sctp_tcb *stcb, struct sctp_chunk_desc *desc,
2398    struct sctp_nets *net, uint8_t flg)
2399{
2400	switch (desc->chunk_type) {
2401		case SCTP_DATA:
2402		/* find the tsn to resend (possibly */
2403		{
2404			uint32_t tsn;
2405			struct sctp_tmit_chunk *tp1;
2406
2407			tsn = ntohl(desc->tsn_ifany);
2408			tp1 = TAILQ_FIRST(&stcb->asoc.sent_queue);
2409			while (tp1) {
2410				if (tp1->rec.data.TSN_seq == tsn) {
2411					/* found it */
2412					break;
2413				}
2414				if (compare_with_wrap(tp1->rec.data.TSN_seq, tsn,
2415				    MAX_TSN)) {
2416					/* not found */
2417					tp1 = NULL;
2418					break;
2419				}
2420				tp1 = TAILQ_NEXT(tp1, sctp_next);
2421			}
2422			if (tp1 == NULL) {
2423				/*
2424				 * Do it the other way , aka without paying
2425				 * attention to queue seq order.
2426				 */
2427				SCTP_STAT_INCR(sctps_pdrpdnfnd);
2428				tp1 = TAILQ_FIRST(&stcb->asoc.sent_queue);
2429				while (tp1) {
2430					if (tp1->rec.data.TSN_seq == tsn) {
2431						/* found it */
2432						break;
2433					}
2434					tp1 = TAILQ_NEXT(tp1, sctp_next);
2435				}
2436			}
2437			if (tp1 == NULL) {
2438				SCTP_STAT_INCR(sctps_pdrptsnnf);
2439			}
2440			if ((tp1) && (tp1->sent < SCTP_DATAGRAM_ACKED)) {
2441				uint8_t *ddp;
2442
2443				if ((stcb->asoc.peers_rwnd == 0) &&
2444				    ((flg & SCTP_FROM_MIDDLE_BOX) == 0)) {
2445					SCTP_STAT_INCR(sctps_pdrpdiwnp);
2446					return (0);
2447				}
2448				if (stcb->asoc.peers_rwnd == 0 &&
2449				    (flg & SCTP_FROM_MIDDLE_BOX)) {
2450					SCTP_STAT_INCR(sctps_pdrpdizrw);
2451					return (0);
2452				}
2453				ddp = (uint8_t *) (mtod(tp1->data, caddr_t)+
2454				    sizeof(struct sctp_data_chunk));
2455				{
2456					unsigned int iii;
2457
2458					for (iii = 0; iii < sizeof(desc->data_bytes);
2459					    iii++) {
2460						if (ddp[iii] != desc->data_bytes[iii]) {
2461							SCTP_STAT_INCR(sctps_pdrpbadd);
2462							return (-1);
2463						}
2464					}
2465				}
2466				/*
2467				 * We zero out the nonce so resync not
2468				 * needed
2469				 */
2470				tp1->rec.data.ect_nonce = 0;
2471
2472				if (tp1->do_rtt) {
2473					/*
2474					 * this guy had a RTO calculation
2475					 * pending on it, cancel it
2476					 */
2477					tp1->whoTo->rto_pending = 0;
2478					tp1->do_rtt = 0;
2479				}
2480				SCTP_STAT_INCR(sctps_pdrpmark);
2481				if (tp1->sent != SCTP_DATAGRAM_RESEND)
2482					sctp_ucount_incr(stcb->asoc.sent_queue_retran_cnt);
2483				tp1->sent = SCTP_DATAGRAM_RESEND;
2484				/*
2485				 * mark it as if we were doing a FR, since
2486				 * we will be getting gap ack reports behind
2487				 * the info from the router.
2488				 */
2489				tp1->rec.data.doing_fast_retransmit = 1;
2490				/*
2491				 * mark the tsn with what sequences can
2492				 * cause a new FR.
2493				 */
2494				if (TAILQ_EMPTY(&stcb->asoc.send_queue)) {
2495					tp1->rec.data.fast_retran_tsn = stcb->asoc.sending_seq;
2496				} else {
2497					tp1->rec.data.fast_retran_tsn = (TAILQ_FIRST(&stcb->asoc.send_queue))->rec.data.TSN_seq;
2498				}
2499
2500				/* restart the timer */
2501				sctp_timer_stop(SCTP_TIMER_TYPE_SEND, stcb->sctp_ep,
2502				    stcb, tp1->whoTo);
2503				sctp_timer_start(SCTP_TIMER_TYPE_SEND, stcb->sctp_ep,
2504				    stcb, tp1->whoTo);
2505
2506				/* fix counts and things */
2507				if (tp1->whoTo->flight_size >= tp1->book_size)
2508					tp1->whoTo->flight_size -= tp1->book_size;
2509				else
2510					tp1->whoTo->flight_size = 0;
2511
2512				if (stcb->asoc.total_flight >= tp1->book_size) {
2513					stcb->asoc.total_flight -= tp1->book_size;
2514					if (stcb->asoc.total_flight_count > 0)
2515						stcb->asoc.total_flight_count--;
2516				} else {
2517					stcb->asoc.total_flight = 0;
2518					stcb->asoc.total_flight_count = 0;
2519				}
2520				tp1->snd_count--;
2521			} {
2522				/* audit code */
2523				unsigned int audit;
2524
2525				audit = 0;
2526				TAILQ_FOREACH(tp1, &stcb->asoc.sent_queue, sctp_next) {
2527					if (tp1->sent == SCTP_DATAGRAM_RESEND)
2528						audit++;
2529				}
2530				TAILQ_FOREACH(tp1, &stcb->asoc.control_send_queue,
2531				    sctp_next) {
2532					if (tp1->sent == SCTP_DATAGRAM_RESEND)
2533						audit++;
2534				}
2535				if (audit != stcb->asoc.sent_queue_retran_cnt) {
2536					printf("**Local Audit finds cnt:%d asoc cnt:%d\n",
2537					    audit, stcb->asoc.sent_queue_retran_cnt);
2538#ifndef SCTP_AUDITING_ENABLED
2539					stcb->asoc.sent_queue_retran_cnt = audit;
2540#endif
2541				}
2542			}
2543		}
2544		break;
2545	case SCTP_ASCONF:
2546		{
2547			struct sctp_tmit_chunk *asconf;
2548
2549			TAILQ_FOREACH(asconf, &stcb->asoc.control_send_queue,
2550			    sctp_next) {
2551				if (asconf->rec.chunk_id.id == SCTP_ASCONF) {
2552					break;
2553				}
2554			}
2555			if (asconf) {
2556				if (asconf->sent != SCTP_DATAGRAM_RESEND)
2557					sctp_ucount_incr(stcb->asoc.sent_queue_retran_cnt);
2558				asconf->sent = SCTP_DATAGRAM_RESEND;
2559				asconf->snd_count--;
2560			}
2561		}
2562		break;
2563	case SCTP_INITIATION:
2564		/* resend the INIT */
2565		stcb->asoc.dropped_special_cnt++;
2566		if (stcb->asoc.dropped_special_cnt < SCTP_RETRY_DROPPED_THRESH) {
2567			/*
2568			 * If we can get it in, in a few attempts we do
2569			 * this, otherwise we let the timer fire.
2570			 */
2571			sctp_timer_stop(SCTP_TIMER_TYPE_INIT, stcb->sctp_ep,
2572			    stcb, net);
2573			sctp_send_initiate(stcb->sctp_ep, stcb);
2574		}
2575		break;
2576	case SCTP_SELECTIVE_ACK:
2577		/* resend the sack */
2578		sctp_send_sack(stcb);
2579		break;
2580	case SCTP_HEARTBEAT_REQUEST:
2581		/* resend a demand HB */
2582		sctp_send_hb(stcb, 1, net);
2583		break;
2584	case SCTP_SHUTDOWN:
2585		sctp_send_shutdown(stcb, net);
2586		break;
2587	case SCTP_SHUTDOWN_ACK:
2588		sctp_send_shutdown_ack(stcb, net);
2589		break;
2590	case SCTP_COOKIE_ECHO:
2591		{
2592			struct sctp_tmit_chunk *cookie;
2593
2594			cookie = NULL;
2595			TAILQ_FOREACH(cookie, &stcb->asoc.control_send_queue,
2596			    sctp_next) {
2597				if (cookie->rec.chunk_id.id == SCTP_COOKIE_ECHO) {
2598					break;
2599				}
2600			}
2601			if (cookie) {
2602				if (cookie->sent != SCTP_DATAGRAM_RESEND)
2603					sctp_ucount_incr(stcb->asoc.sent_queue_retran_cnt);
2604				cookie->sent = SCTP_DATAGRAM_RESEND;
2605				sctp_stop_all_cookie_timers(stcb);
2606			}
2607		}
2608		break;
2609	case SCTP_COOKIE_ACK:
2610		sctp_send_cookie_ack(stcb);
2611		break;
2612	case SCTP_ASCONF_ACK:
2613		/* resend last asconf ack */
2614		sctp_send_asconf_ack(stcb, 1);
2615		break;
2616	case SCTP_FORWARD_CUM_TSN:
2617		send_forward_tsn(stcb, &stcb->asoc);
2618		break;
2619		/* can't do anything with these */
2620	case SCTP_PACKET_DROPPED:
2621	case SCTP_INITIATION_ACK:	/* this should not happen */
2622	case SCTP_HEARTBEAT_ACK:
2623	case SCTP_ABORT_ASSOCIATION:
2624	case SCTP_OPERATION_ERROR:
2625	case SCTP_SHUTDOWN_COMPLETE:
2626	case SCTP_ECN_ECHO:
2627	case SCTP_ECN_CWR:
2628	default:
2629		break;
2630	}
2631	return (0);
2632}
2633
2634void
2635sctp_reset_in_stream(struct sctp_tcb *stcb, int number_entries, uint16_t * list)
2636{
2637	int i;
2638	uint16_t temp;
2639
2640	/*
2641	 * We set things to 0xffff since this is the last delivered sequence
2642	 * and we will be sending in 0 after the reset.
2643	 */
2644
2645	if (number_entries) {
2646		for (i = 0; i < number_entries; i++) {
2647			temp = ntohs(list[i]);
2648			if (temp >= stcb->asoc.streamincnt) {
2649				continue;
2650			}
2651			stcb->asoc.strmin[temp].last_sequence_delivered = 0xffff;
2652		}
2653	} else {
2654		list = NULL;
2655		for (i = 0; i < stcb->asoc.streamincnt; i++) {
2656			stcb->asoc.strmin[i].last_sequence_delivered = 0xffff;
2657		}
2658	}
2659	sctp_ulp_notify(SCTP_NOTIFY_STR_RESET_RECV, stcb, number_entries, (void *)list);
2660}
2661
2662static void
2663sctp_reset_out_streams(struct sctp_tcb *stcb, int number_entries, uint16_t * list)
2664{
2665	int i;
2666
2667	if (number_entries == 0) {
2668		for (i = 0; i < stcb->asoc.streamoutcnt; i++) {
2669			stcb->asoc.strmout[i].next_sequence_sent = 0;
2670		}
2671	} else if (number_entries) {
2672		for (i = 0; i < number_entries; i++) {
2673			uint16_t temp;
2674
2675			temp = ntohs(list[i]);
2676			if (temp >= stcb->asoc.streamoutcnt) {
2677				/* no such stream */
2678				continue;
2679			}
2680			stcb->asoc.strmout[temp].next_sequence_sent = 0;
2681		}
2682	}
2683	sctp_ulp_notify(SCTP_NOTIFY_STR_RESET_SEND, stcb, number_entries, (void *)list);
2684}
2685
2686
2687struct sctp_stream_reset_out_request *
2688sctp_find_stream_reset(struct sctp_tcb *stcb, uint32_t seq, struct sctp_tmit_chunk **bchk)
2689{
2690	struct sctp_association *asoc;
2691	struct sctp_stream_reset_out_req *req;
2692	struct sctp_stream_reset_out_request *r;
2693	struct sctp_tmit_chunk *chk;
2694	int len, clen;
2695
2696	asoc = &stcb->asoc;
2697	if (TAILQ_EMPTY(&stcb->asoc.control_send_queue)) {
2698		return (NULL);
2699	}
2700	if (stcb->asoc.str_reset == NULL) {
2701		return (NULL);
2702	}
2703	chk = stcb->asoc.str_reset;
2704	if (chk->data == NULL) {
2705		return (NULL);
2706	}
2707	if (bchk) {
2708		/* he wants a copy of the chk pointer */
2709		*bchk = chk;
2710	}
2711	clen = chk->send_size;
2712	req = mtod(chk->data, struct sctp_stream_reset_out_req *);
2713	r = &req->sr_req;
2714	if (ntohl(r->request_seq) == seq) {
2715		/* found it */
2716		return (r);
2717	}
2718	len = SCTP_SIZE32(ntohs(r->ph.param_length));
2719	if (clen > (len + (int)sizeof(struct sctp_chunkhdr))) {
2720		/* move to the next one, there can only be a max of two */
2721		r = (struct sctp_stream_reset_out_request *)((caddr_t)r + len);
2722		if (ntohl(r->request_seq) == seq) {
2723			return (r);
2724		}
2725	}
2726	/* that seq is not here */
2727	return (NULL);
2728}
2729
2730static void
2731sctp_clean_up_stream_reset(struct sctp_tcb *stcb)
2732{
2733	struct sctp_association *asoc;
2734
2735	asoc = &stcb->asoc;
2736	struct sctp_tmit_chunk *chk = stcb->asoc.str_reset;
2737
2738	if (stcb->asoc.str_reset == NULL) {
2739		return;
2740	}
2741	sctp_timer_stop(SCTP_TIMER_TYPE_STRRESET, stcb->sctp_ep, stcb, chk->whoTo);
2742	TAILQ_REMOVE(&asoc->control_send_queue,
2743	    chk,
2744	    sctp_next);
2745	if (chk->data) {
2746		sctp_m_freem(chk->data);
2747		chk->data = NULL;
2748	}
2749	asoc->ctrl_queue_cnt--;
2750	sctp_free_remote_addr(chk->whoTo);
2751
2752	sctp_free_a_chunk(stcb, chk);
2753	stcb->asoc.str_reset = NULL;
2754}
2755
2756
2757static int
2758sctp_handle_stream_reset_response(struct sctp_tcb *stcb,
2759    uint32_t seq, uint32_t action,
2760    struct sctp_stream_reset_response *respin)
2761{
2762	uint16_t type;
2763	int lparm_len;
2764	struct sctp_association *asoc = &stcb->asoc;
2765	struct sctp_tmit_chunk *chk;
2766	struct sctp_stream_reset_out_request *srparam;
2767	int number_entries;
2768
2769	if (asoc->stream_reset_outstanding == 0) {
2770		/* duplicate */
2771		return (0);
2772	}
2773	if (seq == stcb->asoc.str_reset_seq_out) {
2774		srparam = sctp_find_stream_reset(stcb, seq, &chk);
2775		if (srparam) {
2776			stcb->asoc.str_reset_seq_out++;
2777			type = ntohs(srparam->ph.param_type);
2778			lparm_len = ntohs(srparam->ph.param_length);
2779			if (type == SCTP_STR_RESET_OUT_REQUEST) {
2780				number_entries = (lparm_len - sizeof(struct sctp_stream_reset_out_request)) / sizeof(uint16_t);
2781				asoc->stream_reset_out_is_outstanding = 0;
2782				if (asoc->stream_reset_outstanding)
2783					asoc->stream_reset_outstanding--;
2784				if (action == SCTP_STREAM_RESET_PERFORMED) {
2785					/* do it */
2786					sctp_reset_out_streams(stcb, number_entries, srparam->list_of_streams);
2787				} else {
2788					sctp_ulp_notify(SCTP_NOTIFY_STR_RESET_FAILED_OUT, stcb, number_entries, srparam->list_of_streams);
2789				}
2790			} else if (type == SCTP_STR_RESET_IN_REQUEST) {
2791				/* Answered my request */
2792				number_entries = (lparm_len - sizeof(struct sctp_stream_reset_in_request)) / sizeof(uint16_t);
2793				if (asoc->stream_reset_outstanding)
2794					asoc->stream_reset_outstanding--;
2795				if (action != SCTP_STREAM_RESET_PERFORMED) {
2796					sctp_ulp_notify(SCTP_NOTIFY_STR_RESET_FAILED_IN, stcb, number_entries, srparam->list_of_streams);
2797				}
2798			} else if (type == SCTP_STR_RESET_TSN_REQUEST) {
2799				/**
2800				 * a) Adopt the new in tsn.
2801				 * b) reset the map
2802				 * c) Adopt the new out-tsn
2803				 */
2804				struct sctp_stream_reset_response_tsn *resp;
2805				struct sctp_forward_tsn_chunk fwdtsn;
2806				int abort_flag = 0;
2807
2808				if (respin == NULL) {
2809					/* huh ? */
2810					return (0);
2811				}
2812				if (action == SCTP_STREAM_RESET_PERFORMED) {
2813					resp = (struct sctp_stream_reset_response_tsn *)respin;
2814					asoc->stream_reset_outstanding--;
2815					fwdtsn.ch.chunk_length = htons(sizeof(struct sctp_forward_tsn_chunk));
2816					fwdtsn.ch.chunk_type = SCTP_FORWARD_CUM_TSN;
2817					fwdtsn.new_cumulative_tsn = htonl(ntohl(resp->senders_next_tsn) - 1);
2818					sctp_handle_forward_tsn(stcb, &fwdtsn, &abort_flag);
2819					if (abort_flag) {
2820						return (1);
2821					}
2822					stcb->asoc.highest_tsn_inside_map = (ntohl(resp->senders_next_tsn) - 1);
2823					stcb->asoc.cumulative_tsn = stcb->asoc.highest_tsn_inside_map;
2824					stcb->asoc.mapping_array_base_tsn = ntohl(resp->senders_next_tsn);
2825					memset(stcb->asoc.mapping_array, 0, stcb->asoc.mapping_array_size);
2826					stcb->asoc.sending_seq = ntohl(resp->receivers_next_tsn);
2827					stcb->asoc.last_acked_seq = stcb->asoc.cumulative_tsn;
2828
2829					sctp_reset_out_streams(stcb, 0, (uint16_t *) NULL);
2830					sctp_reset_in_stream(stcb, 0, (uint16_t *) NULL);
2831
2832				}
2833			}
2834			/* get rid of the request and get the request flags */
2835			if (asoc->stream_reset_outstanding == 0) {
2836				sctp_clean_up_stream_reset(stcb);
2837			}
2838		}
2839	}
2840	return (0);
2841}
2842
2843static void
2844sctp_handle_str_reset_request_in(struct sctp_tcb *stcb,
2845    struct sctp_tmit_chunk *chk,
2846    struct sctp_stream_reset_in_request *req)
2847{
2848	uint32_t seq;
2849	int len, i;
2850	int number_entries;
2851	uint16_t temp;
2852
2853	/*
2854	 * peer wants me to send a str-reset to him for my outgoing seq's if
2855	 * seq_in is right.
2856	 */
2857	struct sctp_association *asoc = &stcb->asoc;
2858
2859	seq = ntohl(req->request_seq);
2860	if (asoc->str_reset_seq_in == seq) {
2861		if (stcb->asoc.stream_reset_out_is_outstanding == 0) {
2862			len = ntohs(req->ph.param_length);
2863			number_entries = ((len - sizeof(struct sctp_stream_reset_in_request)) / sizeof(uint16_t));
2864			for (i = 0; i < number_entries; i++) {
2865				temp = ntohs(req->list_of_streams[i]);
2866				req->list_of_streams[i] = temp;
2867			}
2868			/* move the reset action back one */
2869			asoc->last_reset_action[1] = asoc->last_reset_action[0];
2870			asoc->last_reset_action[0] = SCTP_STREAM_RESET_PERFORMED;
2871			sctp_add_stream_reset_out(chk, number_entries, req->list_of_streams,
2872			    asoc->str_reset_seq_out,
2873			    seq, (asoc->sending_seq - 1));
2874			asoc->stream_reset_out_is_outstanding = 1;
2875			asoc->str_reset = chk;
2876			sctp_timer_start(SCTP_TIMER_TYPE_STRRESET, stcb->sctp_ep, stcb, chk->whoTo);
2877			stcb->asoc.stream_reset_outstanding++;
2878		} else {
2879			/* Can't do it, since we have sent one out */
2880			asoc->last_reset_action[1] = asoc->last_reset_action[0];
2881			asoc->last_reset_action[0] = SCTP_STREAM_RESET_TRY_LATER;
2882			sctp_add_stream_reset_result(chk, seq, asoc->last_reset_action[0]);
2883		}
2884		asoc->str_reset_seq_in++;
2885	} else if (asoc->str_reset_seq_in - 1 == seq) {
2886		sctp_add_stream_reset_result(chk, seq, asoc->last_reset_action[0]);
2887	} else if (asoc->str_reset_seq_in - 2 == seq) {
2888		sctp_add_stream_reset_result(chk, seq, asoc->last_reset_action[1]);
2889	} else {
2890		sctp_add_stream_reset_result(chk, seq, SCTP_STREAM_RESET_BAD_SEQNO);
2891	}
2892}
2893
2894static int
2895sctp_handle_str_reset_request_tsn(struct sctp_tcb *stcb,
2896    struct sctp_tmit_chunk *chk,
2897    struct sctp_stream_reset_tsn_request *req)
2898{
2899	/* reset all in and out and update the tsn */
2900	/*
2901	 * A) reset my str-seq's on in and out. B) Select a receive next,
2902	 * and set cum-ack to it. Also process this selected number as a
2903	 * fwd-tsn as well. C) set in the response my next sending seq.
2904	 */
2905	struct sctp_forward_tsn_chunk fwdtsn;
2906	struct sctp_association *asoc = &stcb->asoc;
2907	int abort_flag = 0;
2908	uint32_t seq;
2909
2910	seq = ntohl(req->request_seq);
2911	if (asoc->str_reset_seq_in == seq) {
2912		fwdtsn.ch.chunk_length = htons(sizeof(struct sctp_forward_tsn_chunk));
2913		fwdtsn.ch.chunk_type = SCTP_FORWARD_CUM_TSN;
2914		fwdtsn.ch.chunk_flags = 0;
2915		fwdtsn.new_cumulative_tsn = htonl(stcb->asoc.highest_tsn_inside_map + 1);
2916		sctp_handle_forward_tsn(stcb, &fwdtsn, &abort_flag);
2917		if (abort_flag) {
2918			return (1);
2919		}
2920		stcb->asoc.highest_tsn_inside_map += SCTP_STREAM_RESET_TSN_DELTA;
2921		stcb->asoc.cumulative_tsn = stcb->asoc.highest_tsn_inside_map;
2922		stcb->asoc.mapping_array_base_tsn = stcb->asoc.highest_tsn_inside_map + 1;
2923		memset(stcb->asoc.mapping_array, 0, stcb->asoc.mapping_array_size);
2924		atomic_add_int(&stcb->asoc.sending_seq, 1);
2925		/* save off historical data for retrans */
2926		stcb->asoc.last_sending_seq[1] = stcb->asoc.last_sending_seq[0];
2927		stcb->asoc.last_sending_seq[0] = stcb->asoc.sending_seq;
2928		stcb->asoc.last_base_tsnsent[1] = stcb->asoc.last_base_tsnsent[0];
2929		stcb->asoc.last_base_tsnsent[0] = stcb->asoc.mapping_array_base_tsn;
2930
2931		sctp_add_stream_reset_result_tsn(chk,
2932		    ntohl(req->request_seq),
2933		    SCTP_STREAM_RESET_PERFORMED,
2934		    stcb->asoc.sending_seq,
2935		    stcb->asoc.mapping_array_base_tsn);
2936		sctp_reset_out_streams(stcb, 0, (uint16_t *) NULL);
2937		sctp_reset_in_stream(stcb, 0, (uint16_t *) NULL);
2938		stcb->asoc.last_reset_action[1] = stcb->asoc.last_reset_action[0];
2939		stcb->asoc.last_reset_action[0] = SCTP_STREAM_RESET_PERFORMED;
2940
2941		asoc->str_reset_seq_in++;
2942	} else if (asoc->str_reset_seq_in - 1 == seq) {
2943		sctp_add_stream_reset_result_tsn(chk, seq, asoc->last_reset_action[0],
2944		    stcb->asoc.last_sending_seq[0],
2945		    stcb->asoc.last_base_tsnsent[0]
2946		    );
2947	} else if (asoc->str_reset_seq_in - 2 == seq) {
2948		sctp_add_stream_reset_result_tsn(chk, seq, asoc->last_reset_action[1],
2949		    stcb->asoc.last_sending_seq[1],
2950		    stcb->asoc.last_base_tsnsent[1]
2951		    );
2952	} else {
2953		sctp_add_stream_reset_result(chk, seq, SCTP_STREAM_RESET_BAD_SEQNO);
2954	}
2955	return (0);
2956}
2957
2958static void
2959sctp_handle_str_reset_request_out(struct sctp_tcb *stcb,
2960    struct sctp_tmit_chunk *chk,
2961    struct sctp_stream_reset_out_request *req)
2962{
2963	uint32_t seq, tsn;
2964	int number_entries, len;
2965	struct sctp_association *asoc = &stcb->asoc;
2966
2967	seq = ntohl(req->request_seq);
2968
2969	/* now if its not a duplicate we process it */
2970	if (asoc->str_reset_seq_in == seq) {
2971		len = ntohs(req->ph.param_length);
2972		number_entries = ((len - sizeof(struct sctp_stream_reset_out_request)) / sizeof(uint16_t));
2973		/*
2974		 * the sender is resetting, handle the list issue.. we must
2975		 * a) verify if we can do the reset, if so no problem b) If
2976		 * we can't do the reset we must copy the request. c) queue
2977		 * it, and setup the data in processor to trigger it off
2978		 * when needed and dequeue all the queued data.
2979		 */
2980		tsn = ntohl(req->send_reset_at_tsn);
2981
2982		/* move the reset action back one */
2983		asoc->last_reset_action[1] = asoc->last_reset_action[0];
2984		if ((tsn == asoc->cumulative_tsn) ||
2985		    (compare_with_wrap(asoc->cumulative_tsn, tsn, MAX_TSN))) {
2986			/* we can do it now */
2987			sctp_reset_in_stream(stcb, number_entries, req->list_of_streams);
2988			sctp_add_stream_reset_result(chk, seq, SCTP_STREAM_RESET_PERFORMED);
2989			asoc->last_reset_action[0] = SCTP_STREAM_RESET_PERFORMED;
2990		} else {
2991			/*
2992			 * we must queue it up and thus wait for the TSN's
2993			 * to arrive that are at or before tsn
2994			 */
2995			struct sctp_stream_reset_list *liste;
2996			int siz;
2997
2998			siz = sizeof(struct sctp_stream_reset_list) + (number_entries * sizeof(uint16_t));
2999			SCTP_MALLOC(liste, struct sctp_stream_reset_list *,
3000			    siz, "StrRstList");
3001			if (liste == NULL) {
3002				/* gak out of memory */
3003				sctp_add_stream_reset_result(chk, seq, SCTP_STREAM_RESET_DENIED);
3004				asoc->last_reset_action[0] = SCTP_STREAM_RESET_DENIED;
3005				return;
3006			}
3007			liste->tsn = tsn;
3008			liste->number_entries = number_entries;
3009			memcpy(&liste->req, req,
3010			    (sizeof(struct sctp_stream_reset_out_request) + (number_entries * sizeof(uint16_t))));
3011			TAILQ_INSERT_TAIL(&asoc->resetHead, liste, next_resp);
3012			sctp_add_stream_reset_result(chk, seq, SCTP_STREAM_RESET_PERFORMED);
3013			asoc->last_reset_action[0] = SCTP_STREAM_RESET_PERFORMED;
3014		}
3015		asoc->str_reset_seq_in++;
3016	} else if ((asoc->str_reset_seq_in - 1) == seq) {
3017		/*
3018		 * one seq back, just echo back last action since my
3019		 * response was lost.
3020		 */
3021		sctp_add_stream_reset_result(chk, seq, asoc->last_reset_action[0]);
3022	} else if ((asoc->str_reset_seq_in - 2) == seq) {
3023		/*
3024		 * two seq back, just echo back last action since my
3025		 * response was lost.
3026		 */
3027		sctp_add_stream_reset_result(chk, seq, asoc->last_reset_action[1]);
3028	} else {
3029		sctp_add_stream_reset_result(chk, seq, SCTP_STREAM_RESET_BAD_SEQNO);
3030	}
3031}
3032
3033static int
3034sctp_handle_stream_reset(struct sctp_tcb *stcb, struct sctp_stream_reset_out_req *sr_req)
3035{
3036	int chk_length, param_len, ptype;
3037	uint32_t seq;
3038	int num_req = 0;
3039	struct sctp_tmit_chunk *chk;
3040	struct sctp_chunkhdr *ch;
3041	struct sctp_paramhdr *ph;
3042
3043	/* now it may be a reset or a reset-response */
3044	chk_length = ntohs(sr_req->ch.chunk_length);
3045	int ret_code = 0;
3046	int num_param = 0;
3047
3048	/* setup for adding the response */
3049	sctp_alloc_a_chunk(stcb, chk);
3050	if (chk == NULL) {
3051		return (ret_code);
3052	}
3053	chk->rec.chunk_id.id = SCTP_STREAM_RESET;
3054	chk->asoc = &stcb->asoc;
3055	chk->no_fr_allowed = 0;
3056	chk->book_size = chk->send_size = sizeof(struct sctp_chunkhdr);
3057	chk->data = sctp_get_mbuf_for_msg(MCLBYTES, 1, M_DONTWAIT, 1, MT_DATA);
3058	if (chk->data == NULL) {
3059strres_nochunk:
3060		if (chk->data) {
3061			sctp_m_freem(chk->data);
3062			chk->data = NULL;
3063		}
3064		sctp_free_a_chunk(stcb, chk);
3065		return (ret_code);
3066	}
3067	chk->data->m_data += SCTP_MIN_OVERHEAD;
3068
3069	/* setup chunk parameters */
3070	chk->sent = SCTP_DATAGRAM_UNSENT;
3071	chk->snd_count = 0;
3072	chk->whoTo = stcb->asoc.primary_destination;
3073	atomic_add_int(&chk->whoTo->ref_count, 1);
3074
3075	ch = mtod(chk->data, struct sctp_chunkhdr *);
3076	ch->chunk_type = SCTP_STREAM_RESET;
3077	ch->chunk_flags = 0;
3078	ch->chunk_length = htons(chk->send_size);
3079	chk->data->m_pkthdr.len = chk->data->m_len = SCTP_SIZE32(chk->send_size);
3080
3081
3082	ph = (struct sctp_paramhdr *)&sr_req->sr_req;
3083	while ((size_t)chk_length >= sizeof(struct sctp_stream_reset_tsn_request)) {
3084		param_len = ntohs(ph->param_length);
3085		if (param_len < (int)sizeof(struct sctp_stream_reset_tsn_request)) {
3086			/* bad param */
3087			break;
3088		}
3089		ptype = ntohs(ph->param_type);
3090		num_param++;
3091		if (num_param > SCTP_MAX_RESET_PARAMS) {
3092			/* hit the max of parameters already sorry.. */
3093			break;
3094		}
3095		if (ptype == SCTP_STR_RESET_OUT_REQUEST) {
3096			struct sctp_stream_reset_out_request *req_out;
3097
3098			req_out = (struct sctp_stream_reset_out_request *)ph;
3099			num_req++;
3100			if (stcb->asoc.stream_reset_outstanding) {
3101				seq = ntohl(req_out->response_seq);
3102				if (seq == stcb->asoc.str_reset_seq_out) {
3103					/* implicit ack */
3104					sctp_handle_stream_reset_response(stcb, seq, SCTP_STREAM_RESET_PERFORMED, NULL);
3105				}
3106			}
3107			sctp_handle_str_reset_request_out(stcb, chk, req_out);
3108		} else if (ptype == SCTP_STR_RESET_IN_REQUEST) {
3109			struct sctp_stream_reset_in_request *req_in;
3110
3111			num_req++;
3112			req_in = (struct sctp_stream_reset_in_request *)ph;
3113			sctp_handle_str_reset_request_in(stcb, chk, req_in);
3114		} else if (ptype == SCTP_STR_RESET_TSN_REQUEST) {
3115			struct sctp_stream_reset_tsn_request *req_tsn;
3116
3117			num_req++;
3118			req_tsn = (struct sctp_stream_reset_tsn_request *)ph;
3119			if (sctp_handle_str_reset_request_tsn(stcb, chk, req_tsn)) {
3120				ret_code = 1;
3121				goto strres_nochunk;
3122			}
3123			/* no more */
3124			break;
3125		} else if (ptype == SCTP_STR_RESET_RESPONSE) {
3126			struct sctp_stream_reset_response *resp;
3127			uint32_t result;
3128
3129			resp = (struct sctp_stream_reset_response *)ph;
3130			seq = ntohl(resp->response_seq);
3131			result = ntohl(resp->result);
3132			if (sctp_handle_stream_reset_response(stcb, seq, result, resp)) {
3133				ret_code = 1;
3134				goto strres_nochunk;
3135			}
3136		} else {
3137			break;
3138		}
3139
3140		ph = (struct sctp_paramhdr *)((caddr_t)ph + SCTP_SIZE32(param_len));
3141		chk_length -= SCTP_SIZE32(param_len);
3142	}
3143	if (num_req == 0) {
3144		/* we have no response free the stuff */
3145		goto strres_nochunk;
3146	}
3147	/* ok we have a chunk to link in */
3148	TAILQ_INSERT_TAIL(&stcb->asoc.control_send_queue,
3149	    chk,
3150	    sctp_next);
3151	stcb->asoc.ctrl_queue_cnt++;
3152	return (ret_code);
3153}
3154
3155/*
3156 * Handle a router or endpoints report of a packet loss, there are two ways
3157 * to handle this, either we get the whole packet and must disect it
3158 * ourselves (possibly with truncation and or corruption) or it is a summary
3159 * from a middle box that did the disectting for us.
3160 */
3161static void
3162sctp_handle_packet_dropped(struct sctp_pktdrop_chunk *cp,
3163    struct sctp_tcb *stcb, struct sctp_nets *net)
3164{
3165	uint32_t bottle_bw, on_queue;
3166	uint16_t trunc_len;
3167	unsigned int chlen;
3168	unsigned int at;
3169	struct sctp_chunk_desc desc;
3170	struct sctp_chunkhdr *ch;
3171
3172	chlen = ntohs(cp->ch.chunk_length);
3173	chlen -= sizeof(struct sctp_pktdrop_chunk);
3174	/* XXX possible chlen underflow */
3175	if (chlen == 0) {
3176		ch = NULL;
3177		if (cp->ch.chunk_flags & SCTP_FROM_MIDDLE_BOX)
3178			SCTP_STAT_INCR(sctps_pdrpbwrpt);
3179	} else {
3180		ch = (struct sctp_chunkhdr *)(cp->data + sizeof(struct sctphdr));
3181		chlen -= sizeof(struct sctphdr);
3182		/* XXX possible chlen underflow */
3183		memset(&desc, 0, sizeof(desc));
3184	}
3185	trunc_len = (uint16_t) ntohs(cp->trunc_len);
3186	/* now the chunks themselves */
3187	while ((ch != NULL) && (chlen >= sizeof(struct sctp_chunkhdr))) {
3188		desc.chunk_type = ch->chunk_type;
3189		/* get amount we need to move */
3190		at = ntohs(ch->chunk_length);
3191		if (at < sizeof(struct sctp_chunkhdr)) {
3192			/* corrupt chunk, maybe at the end? */
3193			SCTP_STAT_INCR(sctps_pdrpcrupt);
3194			break;
3195		}
3196		if (trunc_len == 0) {
3197			/* we are supposed to have all of it */
3198			if (at > chlen) {
3199				/* corrupt skip it */
3200				SCTP_STAT_INCR(sctps_pdrpcrupt);
3201				break;
3202			}
3203		} else {
3204			/* is there enough of it left ? */
3205			if (desc.chunk_type == SCTP_DATA) {
3206				if (chlen < (sizeof(struct sctp_data_chunk) +
3207				    sizeof(desc.data_bytes))) {
3208					break;
3209				}
3210			} else {
3211				if (chlen < sizeof(struct sctp_chunkhdr)) {
3212					break;
3213				}
3214			}
3215		}
3216		if (desc.chunk_type == SCTP_DATA) {
3217			/* can we get out the tsn? */
3218			if ((cp->ch.chunk_flags & SCTP_FROM_MIDDLE_BOX))
3219				SCTP_STAT_INCR(sctps_pdrpmbda);
3220
3221			if (chlen >= (sizeof(struct sctp_data_chunk) + sizeof(uint32_t))) {
3222				/* yep */
3223				struct sctp_data_chunk *dcp;
3224				uint8_t *ddp;
3225				unsigned int iii;
3226
3227				dcp = (struct sctp_data_chunk *)ch;
3228				ddp = (uint8_t *) (dcp + 1);
3229				for (iii = 0; iii < sizeof(desc.data_bytes); iii++) {
3230					desc.data_bytes[iii] = ddp[iii];
3231				}
3232				desc.tsn_ifany = dcp->dp.tsn;
3233			} else {
3234				/* nope we are done. */
3235				SCTP_STAT_INCR(sctps_pdrpnedat);
3236				break;
3237			}
3238		} else {
3239			if ((cp->ch.chunk_flags & SCTP_FROM_MIDDLE_BOX))
3240				SCTP_STAT_INCR(sctps_pdrpmbct);
3241		}
3242
3243		if (process_chunk_drop(stcb, &desc, net, cp->ch.chunk_flags)) {
3244			SCTP_STAT_INCR(sctps_pdrppdbrk);
3245			break;
3246		}
3247		if (SCTP_SIZE32(at) > chlen) {
3248			break;
3249		}
3250		chlen -= SCTP_SIZE32(at);
3251		if (chlen < sizeof(struct sctp_chunkhdr)) {
3252			/* done, none left */
3253			break;
3254		}
3255		ch = (struct sctp_chunkhdr *)((caddr_t)ch + SCTP_SIZE32(at));
3256	}
3257	/* Now update any rwnd --- possibly */
3258	if ((cp->ch.chunk_flags & SCTP_FROM_MIDDLE_BOX) == 0) {
3259		/* From a peer, we get a rwnd report */
3260		uint32_t a_rwnd;
3261
3262		SCTP_STAT_INCR(sctps_pdrpfehos);
3263
3264		bottle_bw = ntohl(cp->bottle_bw);
3265		on_queue = ntohl(cp->current_onq);
3266		if (bottle_bw && on_queue) {
3267			/* a rwnd report is in here */
3268			if (bottle_bw > on_queue)
3269				a_rwnd = bottle_bw - on_queue;
3270			else
3271				a_rwnd = 0;
3272
3273			if (a_rwnd == 0)
3274				stcb->asoc.peers_rwnd = 0;
3275			else {
3276				if (a_rwnd > stcb->asoc.total_flight) {
3277					stcb->asoc.peers_rwnd =
3278					    a_rwnd - stcb->asoc.total_flight;
3279				} else {
3280					stcb->asoc.peers_rwnd = 0;
3281				}
3282				if (stcb->asoc.peers_rwnd <
3283				    stcb->sctp_ep->sctp_ep.sctp_sws_sender) {
3284					/* SWS sender side engages */
3285					stcb->asoc.peers_rwnd = 0;
3286				}
3287			}
3288		}
3289	} else {
3290		SCTP_STAT_INCR(sctps_pdrpfmbox);
3291	}
3292
3293	/* now middle boxes in sat networks get a cwnd bump */
3294	if ((cp->ch.chunk_flags & SCTP_FROM_MIDDLE_BOX) &&
3295	    (stcb->asoc.sat_t3_loss_recovery == 0) &&
3296	    (stcb->asoc.sat_network)) {
3297		/*
3298		 * This is debateable but for sat networks it makes sense
3299		 * Note if a T3 timer has went off, we will prohibit any
3300		 * changes to cwnd until we exit the t3 loss recovery.
3301		 */
3302		uint32_t bw_avail;
3303		int rtt, incr;
3304
3305#ifdef SCTP_CWND_MONITOR
3306		int old_cwnd = net->cwnd;
3307
3308#endif
3309		/* need real RTT for this calc */
3310		rtt = ((net->lastsa >> 2) + net->lastsv) >> 1;
3311		/* get bottle neck bw */
3312		bottle_bw = ntohl(cp->bottle_bw);
3313		/* and whats on queue */
3314		on_queue = ntohl(cp->current_onq);
3315		/*
3316		 * adjust the on-queue if our flight is more it could be
3317		 * that the router has not yet gotten data "in-flight" to it
3318		 */
3319		if (on_queue < net->flight_size)
3320			on_queue = net->flight_size;
3321
3322		/* calculate the available space */
3323		bw_avail = (bottle_bw * rtt) / 1000;
3324		if (bw_avail > bottle_bw) {
3325			/*
3326			 * Cap the growth to no more than the bottle neck.
3327			 * This can happen as RTT slides up due to queues.
3328			 * It also means if you have more than a 1 second
3329			 * RTT with a empty queue you will be limited to the
3330			 * bottle_bw per second no matter if other points
3331			 * have 1/2 the RTT and you could get more out...
3332			 */
3333			bw_avail = bottle_bw;
3334		}
3335		if (on_queue > bw_avail) {
3336			/*
3337			 * No room for anything else don't allow anything
3338			 * else to be "added to the fire".
3339			 */
3340			int seg_inflight, seg_onqueue, my_portion;
3341
3342			net->partial_bytes_acked = 0;
3343
3344			/* how much are we over queue size? */
3345			incr = on_queue - bw_avail;
3346			if (stcb->asoc.seen_a_sack_this_pkt) {
3347				/*
3348				 * undo any cwnd adjustment that the sack
3349				 * might have made
3350				 */
3351				net->cwnd = net->prev_cwnd;
3352			}
3353			/* Now how much of that is mine? */
3354			seg_inflight = net->flight_size / net->mtu;
3355			seg_onqueue = on_queue / net->mtu;
3356			my_portion = (incr * seg_inflight) / seg_onqueue;
3357
3358			/* Have I made an adjustment already */
3359			if (net->cwnd > net->flight_size) {
3360				/*
3361				 * for this flight I made an adjustment we
3362				 * need to decrease the portion by a share
3363				 * our previous adjustment.
3364				 */
3365				int diff_adj;
3366
3367				diff_adj = net->cwnd - net->flight_size;
3368				if (diff_adj > my_portion)
3369					my_portion = 0;
3370				else
3371					my_portion -= diff_adj;
3372			}
3373			/*
3374			 * back down to the previous cwnd (assume we have
3375			 * had a sack before this packet). minus what ever
3376			 * portion of the overage is my fault.
3377			 */
3378			net->cwnd -= my_portion;
3379
3380			/* we will NOT back down more than 1 MTU */
3381			if (net->cwnd <= net->mtu) {
3382				net->cwnd = net->mtu;
3383			}
3384			/* force into CA */
3385			net->ssthresh = net->cwnd - 1;
3386		} else {
3387			/*
3388			 * Take 1/4 of the space left or max burst up ..
3389			 * whichever is less.
3390			 */
3391			incr = min((bw_avail - on_queue) >> 2,
3392			    (int)stcb->asoc.max_burst * (int)net->mtu);
3393			net->cwnd += incr;
3394		}
3395		if (net->cwnd > bw_avail) {
3396			/* We can't exceed the pipe size */
3397			net->cwnd = bw_avail;
3398		}
3399		if (net->cwnd < net->mtu) {
3400			/* We always have 1 MTU */
3401			net->cwnd = net->mtu;
3402		}
3403#ifdef SCTP_CWND_MONITOR
3404		if (net->cwnd - old_cwnd != 0) {
3405			/* log only changes */
3406			sctp_log_cwnd(stcb, net, (net->cwnd - old_cwnd),
3407			    SCTP_CWND_LOG_FROM_SAT);
3408		}
3409#endif
3410	}
3411}
3412
3413extern int sctp_strict_init;
3414extern int sctp_abort_if_one_2_one_hits_limit;
3415
3416/*
3417 * handles all control chunks in a packet inputs: - m: mbuf chain, assumed to
3418 * still contain IP/SCTP header - stcb: is the tcb found for this packet -
3419 * offset: offset into the mbuf chain to first chunkhdr - length: is the
3420 * length of the complete packet outputs: - length: modified to remaining
3421 * length after control processing - netp: modified to new sctp_nets after
3422 * cookie-echo processing - return NULL to discard the packet (ie. no asoc,
3423 * bad packet,...) otherwise return the tcb for this packet
3424 */
3425static struct sctp_tcb *
3426sctp_process_control(struct mbuf *m, int iphlen, int *offset, int length,
3427    struct sctphdr *sh, struct sctp_chunkhdr *ch, struct sctp_inpcb *inp,
3428    struct sctp_tcb *stcb, struct sctp_nets **netp, int *fwd_tsn_seen)
3429{
3430	struct sctp_association *asoc;
3431	uint32_t vtag_in;
3432	int num_chunks = 0;	/* number of control chunks processed */
3433	int chk_length;
3434	int ret;
3435
3436	/*
3437	 * How big should this be, and should it be alloc'd? Lets try the
3438	 * d-mtu-ceiling for now (2k) and that should hopefully work ...
3439	 * until we get into jumbo grams and such..
3440	 */
3441	uint8_t chunk_buf[DEFAULT_CHUNK_BUFFER];
3442	struct sctp_tcb *locked_tcb = stcb;
3443	int got_auth = 0;
3444	uint32_t auth_offset = 0, auth_len = 0;
3445	int auth_skipped = 0;
3446
3447#ifdef SCTP_DEBUG
3448	if (sctp_debug_on & SCTP_DEBUG_INPUT1) {
3449		printf("sctp_process_control: iphlen=%u, offset=%u, length=%u stcb:%p\n",
3450		    iphlen, *offset, length, stcb);
3451	}
3452#endif				/* SCTP_DEBUG */
3453
3454	/* validate chunk header length... */
3455	if (ntohs(ch->chunk_length) < sizeof(*ch)) {
3456		return (NULL);
3457	}
3458	/*
3459	 * validate the verification tag
3460	 */
3461	vtag_in = ntohl(sh->v_tag);
3462
3463	if (ch->chunk_type == SCTP_INITIATION) {
3464		if (vtag_in != 0) {
3465			/* protocol error- silently discard... */
3466			SCTP_STAT_INCR(sctps_badvtag);
3467			if (locked_tcb)
3468				SCTP_TCB_UNLOCK(locked_tcb);
3469			return (NULL);
3470		}
3471	} else if (ch->chunk_type != SCTP_COOKIE_ECHO) {
3472		/*
3473		 * If there is no stcb, skip the AUTH chunk and process
3474		 * later after a stcb is found (to validate the lookup was
3475		 * valid.
3476		 */
3477		if ((ch->chunk_type == SCTP_AUTHENTICATION) &&
3478		    (stcb == NULL) && !sctp_auth_disable) {
3479			/* save this chunk for later processing */
3480			auth_skipped = 1;
3481			auth_offset = *offset;
3482			auth_len = ntohs(ch->chunk_length);
3483
3484			/* (temporarily) move past this chunk */
3485			*offset += SCTP_SIZE32(auth_len);
3486			if (*offset >= length) {
3487				/* no more data left in the mbuf chain */
3488				*offset = length;
3489				return (NULL);
3490			}
3491			ch = (struct sctp_chunkhdr *)sctp_m_getptr(m, *offset,
3492			    sizeof(struct sctp_chunkhdr), chunk_buf);
3493		}
3494		if (ch->chunk_type == SCTP_COOKIE_ECHO) {
3495			goto process_control_chunks;
3496		}
3497		/*
3498		 * first check if it's an ASCONF with an unknown src addr we
3499		 * need to look inside to find the association
3500		 */
3501		if (ch->chunk_type == SCTP_ASCONF && stcb == NULL) {
3502			/* inp's refcount may be reduced */
3503			SCTP_INP_INCR_REF(inp);
3504
3505			stcb = sctp_findassociation_ep_asconf(m, iphlen,
3506			    *offset, sh, &inp, netp);
3507			if (stcb == NULL) {
3508				/*
3509				 * reduce inp's refcount if not reduced in
3510				 * sctp_findassociation_ep_asconf().
3511				 */
3512				SCTP_INP_DECR_REF(inp);
3513			}
3514			/* now go back and verify any auth chunk to be sure */
3515			if (auth_skipped && (stcb != NULL)) {
3516				struct sctp_auth_chunk *auth;
3517
3518				auth = (struct sctp_auth_chunk *)
3519				    sctp_m_getptr(m, auth_offset,
3520				    auth_len, chunk_buf);
3521				got_auth = 1;
3522				auth_skipped = 0;
3523				if (sctp_handle_auth(stcb, auth, m,
3524				    auth_offset)) {
3525					/* auth HMAC failed so dump it */
3526					*offset = length;
3527					return (NULL);
3528				} else {
3529					/* remaining chunks are HMAC checked */
3530					stcb->asoc.authenticated = 1;
3531				}
3532			}
3533		}
3534		if (stcb == NULL) {
3535			/* no association, so it's out of the blue... */
3536			sctp_handle_ootb(m, iphlen, *offset, sh, inp, NULL);
3537			*offset = length;
3538			if (locked_tcb)
3539				SCTP_TCB_UNLOCK(locked_tcb);
3540			return (NULL);
3541		}
3542		asoc = &stcb->asoc;
3543		/* ABORT and SHUTDOWN can use either v_tag... */
3544		if ((ch->chunk_type == SCTP_ABORT_ASSOCIATION) ||
3545		    (ch->chunk_type == SCTP_SHUTDOWN_COMPLETE) ||
3546		    (ch->chunk_type == SCTP_PACKET_DROPPED)) {
3547			if ((vtag_in == asoc->my_vtag) ||
3548			    ((ch->chunk_flags & SCTP_HAD_NO_TCB) &&
3549			    (vtag_in == asoc->peer_vtag))) {
3550				/* this is valid */
3551			} else {
3552				/* drop this packet... */
3553				SCTP_STAT_INCR(sctps_badvtag);
3554				if (locked_tcb)
3555					SCTP_TCB_UNLOCK(locked_tcb);
3556				return (NULL);
3557			}
3558		} else if (ch->chunk_type == SCTP_SHUTDOWN_ACK) {
3559			if (vtag_in != asoc->my_vtag) {
3560				/*
3561				 * this could be a stale SHUTDOWN-ACK or the
3562				 * peer never got the SHUTDOWN-COMPLETE and
3563				 * is still hung; we have started a new asoc
3564				 * but it won't complete until the shutdown
3565				 * is completed
3566				 */
3567				if (locked_tcb)
3568					SCTP_TCB_UNLOCK(locked_tcb);
3569				sctp_handle_ootb(m, iphlen, *offset, sh, inp,
3570				    NULL);
3571				return (NULL);
3572			}
3573		} else {
3574			/* for all other chunks, vtag must match */
3575			if (vtag_in != asoc->my_vtag) {
3576				/* invalid vtag... */
3577#ifdef SCTP_DEBUG
3578				if (sctp_debug_on & SCTP_DEBUG_INPUT3) {
3579					printf("invalid vtag: %xh, expect %xh\n", vtag_in, asoc->my_vtag);
3580				}
3581#endif				/* SCTP_DEBUG */
3582				SCTP_STAT_INCR(sctps_badvtag);
3583				if (locked_tcb)
3584					SCTP_TCB_UNLOCK(locked_tcb);
3585				*offset = length;
3586				return (NULL);
3587			}
3588		}
3589	}			/* end if !SCTP_COOKIE_ECHO */
3590	/*
3591	 * process all control chunks...
3592	 */
3593	if (((ch->chunk_type == SCTP_SELECTIVE_ACK) ||
3594	    (ch->chunk_type == SCTP_HEARTBEAT_REQUEST)) &&
3595	    (SCTP_GET_STATE(&stcb->asoc) == SCTP_STATE_COOKIE_ECHOED)) {
3596		/* implied cookie-ack.. we must have lost the ack */
3597		stcb->asoc.overall_error_count = 0;
3598		sctp_handle_cookie_ack((struct sctp_cookie_ack_chunk *)ch, stcb,
3599		    *netp);
3600	}
3601process_control_chunks:
3602
3603	while (IS_SCTP_CONTROL(ch)) {
3604		/* validate chunk length */
3605		chk_length = ntohs(ch->chunk_length);
3606#ifdef SCTP_DEBUG
3607		if (sctp_debug_on & SCTP_DEBUG_INPUT2) {
3608			printf("sctp_process_control: processing a chunk type=%u, len=%u\n",
3609			    ch->chunk_type, chk_length);
3610		}
3611#endif				/* SCTP_DEBUG */
3612		if ((size_t)chk_length < sizeof(*ch) ||
3613		    (*offset + chk_length) > length) {
3614			*offset = length;
3615			if (locked_tcb)
3616				SCTP_TCB_UNLOCK(locked_tcb);
3617			return (NULL);
3618		}
3619		SCTP_STAT_INCR_COUNTER64(sctps_incontrolchunks);
3620		/*
3621		 * INIT-ACK only gets the init ack "header" portion only
3622		 * because we don't have to process the peer's COOKIE. All
3623		 * others get a complete chunk.
3624		 */
3625		if (ch->chunk_type == SCTP_INITIATION_ACK) {
3626			/* get an init-ack chunk */
3627			ch = (struct sctp_chunkhdr *)sctp_m_getptr(m, *offset,
3628			    sizeof(struct sctp_init_ack_chunk), chunk_buf);
3629			if (ch == NULL) {
3630				*offset = length;
3631				if (locked_tcb)
3632					SCTP_TCB_UNLOCK(locked_tcb);
3633				return (NULL);
3634			}
3635		} else {
3636			/* get a complete chunk... */
3637			if ((size_t)chk_length > sizeof(chunk_buf)) {
3638				struct mbuf *oper;
3639				struct sctp_paramhdr *phdr;
3640
3641				oper = NULL;
3642				oper = sctp_get_mbuf_for_msg(sizeof(struct sctp_paramhdr),
3643				    1, M_DONTWAIT, 1, MT_DATA);
3644				if (oper) {
3645					/* pre-reserve some space */
3646					oper->m_data += sizeof(struct sctp_chunkhdr);
3647					oper->m_len = sizeof(struct sctp_paramhdr);
3648					oper->m_pkthdr.len = oper->m_len;
3649					phdr = mtod(oper, struct sctp_paramhdr *);
3650					phdr->param_type = htons(SCTP_CAUSE_OUT_OF_RESC);
3651					phdr->param_length = htons(sizeof(struct sctp_paramhdr));
3652					sctp_queue_op_err(stcb, oper);
3653				}
3654				if (locked_tcb)
3655					SCTP_TCB_UNLOCK(locked_tcb);
3656				return (NULL);
3657			}
3658			ch = (struct sctp_chunkhdr *)sctp_m_getptr(m, *offset,
3659			    chk_length, chunk_buf);
3660			if (ch == NULL) {
3661				printf("sctp_process_control: Can't get the all data....\n");
3662				*offset = length;
3663				if (locked_tcb)
3664					SCTP_TCB_UNLOCK(locked_tcb);
3665				return (NULL);
3666			}
3667		}
3668		num_chunks++;
3669		/* Save off the last place we got a control from */
3670		if (stcb != NULL) {
3671			if ((*netp != NULL) || (ch->chunk_type == SCTP_ASCONF)) {
3672				/*
3673				 * allow last_control to be NULL if
3674				 * ASCONF... ASCONF processing will find the
3675				 * right net later
3676				 */
3677				stcb->asoc.last_control_chunk_from = *netp;
3678			}
3679		}
3680#ifdef SCTP_AUDITING_ENABLED
3681		sctp_audit_log(0xB0, ch->chunk_type);
3682#endif
3683
3684		/* check to see if this chunk required auth, but isn't */
3685		if ((stcb != NULL) && !sctp_auth_disable &&
3686		    sctp_auth_is_required_chunk(ch->chunk_type,
3687		    stcb->asoc.local_auth_chunks) &&
3688		    !stcb->asoc.authenticated) {
3689			/* "silently" ignore */
3690			SCTP_STAT_INCR(sctps_recvauthmissing);
3691			goto next_chunk;
3692		}
3693		switch (ch->chunk_type) {
3694		case SCTP_INITIATION:
3695			/* must be first and only chunk */
3696#ifdef SCTP_DEBUG
3697			if (sctp_debug_on & SCTP_DEBUG_INPUT3) {
3698				printf("SCTP_INIT\n");
3699			}
3700#endif				/* SCTP_DEBUG */
3701			if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE) {
3702				/* We are not interested anymore? */
3703				if ((stcb) && (stcb->asoc.total_output_queue_size)) {
3704					/*
3705					 * collision case where we are
3706					 * sending to them too
3707					 */
3708					;
3709				} else {
3710					if (locked_tcb)
3711						SCTP_TCB_UNLOCK(locked_tcb);
3712					*offset = length;
3713					return (NULL);
3714				}
3715			}
3716			if ((num_chunks > 1) ||
3717			    (sctp_strict_init && (length - *offset > SCTP_SIZE32(chk_length)))) {
3718				*offset = length;
3719				if (locked_tcb)
3720					SCTP_TCB_UNLOCK(locked_tcb);
3721				return (NULL);
3722			}
3723			if ((stcb != NULL) &&
3724			    (SCTP_GET_STATE(&stcb->asoc) ==
3725			    SCTP_STATE_SHUTDOWN_ACK_SENT)) {
3726				sctp_send_shutdown_ack(stcb,
3727				    stcb->asoc.primary_destination);
3728				*offset = length;
3729				sctp_chunk_output(inp, stcb, SCTP_OUTPUT_FROM_CONTROL_PROC);
3730				if (locked_tcb)
3731					SCTP_TCB_UNLOCK(locked_tcb);
3732				return (NULL);
3733			}
3734			sctp_handle_init(m, iphlen, *offset, sh,
3735			    (struct sctp_init_chunk *)ch, inp, stcb, *netp);
3736			*offset = length;
3737			if (locked_tcb)
3738				SCTP_TCB_UNLOCK(locked_tcb);
3739			return (NULL);
3740			break;
3741		case SCTP_INITIATION_ACK:
3742			/* must be first and only chunk */
3743#ifdef SCTP_DEBUG
3744			if (sctp_debug_on & SCTP_DEBUG_INPUT3) {
3745				printf("SCTP_INIT-ACK\n");
3746			}
3747#endif				/* SCTP_DEBUG */
3748			if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE) {
3749				/* We are not interested anymore */
3750				if ((stcb) && (stcb->asoc.total_output_queue_size)) {
3751					;
3752				} else {
3753					if (locked_tcb)
3754						SCTP_TCB_UNLOCK(locked_tcb);
3755					*offset = length;
3756					if (stcb) {
3757						sctp_free_assoc(inp, stcb, 0);
3758					}
3759					return (NULL);
3760				}
3761			}
3762			if ((num_chunks > 1) ||
3763			    (sctp_strict_init && (length - *offset > SCTP_SIZE32(chk_length)))) {
3764				*offset = length;
3765				if (locked_tcb)
3766					SCTP_TCB_UNLOCK(locked_tcb);
3767				return (NULL);
3768			}
3769			ret = sctp_handle_init_ack(m, iphlen, *offset, sh,
3770			    (struct sctp_init_ack_chunk *)ch, stcb, *netp);
3771			/*
3772			 * Special case, I must call the output routine to
3773			 * get the cookie echoed
3774			 */
3775			if ((stcb) && ret == 0)
3776				sctp_chunk_output(stcb->sctp_ep, stcb, SCTP_OUTPUT_FROM_CONTROL_PROC);
3777			*offset = length;
3778			if (locked_tcb)
3779				SCTP_TCB_UNLOCK(locked_tcb);
3780			return (NULL);
3781			break;
3782		case SCTP_SELECTIVE_ACK:
3783#ifdef SCTP_DEBUG
3784			if (sctp_debug_on & SCTP_DEBUG_INPUT3) {
3785				printf("SCTP_SACK\n");
3786			}
3787#endif				/* SCTP_DEBUG */
3788			SCTP_STAT_INCR(sctps_recvsacks);
3789			{
3790				struct sctp_sack_chunk *sack;
3791				int abort_now = 0;
3792				uint32_t a_rwnd, cum_ack;
3793				uint16_t num_seg;
3794				int nonce_sum_flag;
3795
3796				sack = (struct sctp_sack_chunk *)ch;
3797
3798				nonce_sum_flag = ch->chunk_flags & SCTP_SACK_NONCE_SUM;
3799				cum_ack = ntohl(sack->sack.cum_tsn_ack);
3800				num_seg = ntohs(sack->sack.num_gap_ack_blks);
3801				a_rwnd = (uint32_t) ntohl(sack->sack.a_rwnd);
3802				stcb->asoc.seen_a_sack_this_pkt = 1;
3803				if ((stcb->asoc.pr_sctp_cnt == 0) &&
3804				    (num_seg == 0) &&
3805				    ((compare_with_wrap(cum_ack, stcb->asoc.last_acked_seq, MAX_TSN)) ||
3806				    (cum_ack == stcb->asoc.last_acked_seq)) &&
3807				    (stcb->asoc.saw_sack_with_frags == 0) &&
3808				    (!TAILQ_EMPTY(&stcb->asoc.sent_queue))
3809				    ) {
3810					/*
3811					 * We have a SIMPLE sack having no
3812					 * prior segments and data on sent
3813					 * queue to be acked.. Use the
3814					 * faster path sack processing. We
3815					 * also allow window update sacks
3816					 * with no missing segments to go
3817					 * this way too.
3818					 */
3819					sctp_express_handle_sack(stcb, cum_ack, a_rwnd, nonce_sum_flag, &abort_now);
3820				} else {
3821					sctp_handle_sack(sack, stcb, *netp, &abort_now);
3822				}
3823				if (abort_now) {
3824					/* ABORT signal from sack processing */
3825					*offset = length;
3826					return (NULL);
3827				}
3828			}
3829			break;
3830		case SCTP_HEARTBEAT_REQUEST:
3831#ifdef SCTP_DEBUG
3832			if (sctp_debug_on & SCTP_DEBUG_INPUT3) {
3833				printf("SCTP_HEARTBEAT\n");
3834			}
3835#endif				/* SCTP_DEBUG */
3836			SCTP_STAT_INCR(sctps_recvheartbeat);
3837			sctp_send_heartbeat_ack(stcb, m, *offset, chk_length,
3838			    *netp);
3839
3840			/* He's alive so give him credit */
3841			stcb->asoc.overall_error_count = 0;
3842			break;
3843		case SCTP_HEARTBEAT_ACK:
3844#ifdef SCTP_DEBUG
3845			if (sctp_debug_on & SCTP_DEBUG_INPUT3) {
3846				printf("SCTP_HEARTBEAT-ACK\n");
3847			}
3848#endif				/* SCTP_DEBUG */
3849
3850			/* He's alive so give him credit */
3851			stcb->asoc.overall_error_count = 0;
3852			SCTP_STAT_INCR(sctps_recvheartbeatack);
3853			sctp_handle_heartbeat_ack((struct sctp_heartbeat_chunk *)ch,
3854			    stcb, *netp);
3855			break;
3856		case SCTP_ABORT_ASSOCIATION:
3857#ifdef SCTP_DEBUG
3858			if (sctp_debug_on & SCTP_DEBUG_INPUT3) {
3859				printf("SCTP_ABORT\n");
3860			}
3861#endif				/* SCTP_DEBUG */
3862			sctp_handle_abort((struct sctp_abort_chunk *)ch,
3863			    stcb, *netp);
3864			*offset = length;
3865			return (NULL);
3866			break;
3867		case SCTP_SHUTDOWN:
3868#ifdef SCTP_DEBUG
3869			if (sctp_debug_on & SCTP_DEBUG_INPUT3) {
3870				printf("SCTP_SHUTDOWN\n");
3871			}
3872#endif				/* SCTP_DEBUG */
3873			{
3874				int abort_flag = 0;
3875
3876				sctp_handle_shutdown((struct sctp_shutdown_chunk *)ch,
3877				    stcb, *netp, &abort_flag);
3878				if (abort_flag) {
3879					*offset = length;
3880					return (NULL);
3881				}
3882			}
3883			break;
3884		case SCTP_SHUTDOWN_ACK:
3885#ifdef SCTP_DEBUG
3886			if (sctp_debug_on & SCTP_DEBUG_INPUT3) {
3887				printf("SCTP_SHUTDOWN-ACK\n");
3888			}
3889#endif				/* SCTP_DEBUG */
3890			sctp_handle_shutdown_ack((struct sctp_shutdown_ack_chunk *)ch, stcb, *netp);
3891			*offset = length;
3892			return (NULL);
3893			break;
3894		case SCTP_OPERATION_ERROR:
3895#ifdef SCTP_DEBUG
3896			if (sctp_debug_on & SCTP_DEBUG_INPUT3) {
3897				printf("SCTP_OP-ERR\n");
3898			}
3899#endif				/* SCTP_DEBUG */
3900			if (sctp_handle_error(ch, stcb, *netp) < 0) {
3901				*offset = length;
3902				return (NULL);
3903			}
3904			break;
3905		case SCTP_COOKIE_ECHO:
3906#ifdef SCTP_DEBUG
3907			if (sctp_debug_on & SCTP_DEBUG_INPUT3) {
3908				printf("SCTP_COOKIE-ECHO stcb is %p\n", stcb);
3909			}
3910#endif				/* SCTP_DEBUG */
3911			if ((stcb) && (stcb->asoc.total_output_queue_size)) {
3912				;
3913			} else {
3914				if ((inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE) &&
3915				    (stcb == NULL)) {
3916					/* We are not interested anymore */
3917					*offset = length;
3918					return (NULL);
3919				}
3920			}
3921			/*
3922			 * First are we accepting? We do this again here
3923			 * since it is possible that a previous endpoint WAS
3924			 * listening responded to a INIT-ACK and then
3925			 * closed. We opened and bound.. and are now no
3926			 * longer listening.
3927			 */
3928			if (inp->sctp_socket->so_qlimit == 0) {
3929				if ((stcb) && (inp->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL)) {
3930					/*
3931					 * special case, is this a retran'd
3932					 * COOKIE-ECHO or a restarting assoc
3933					 * that is a peeled off or
3934					 * one-to-one style socket.
3935					 */
3936					goto process_cookie_anyway;
3937				}
3938				sctp_abort_association(inp, stcb, m, iphlen, sh,
3939				    NULL);
3940				*offset = length;
3941				return (NULL);
3942			} else if (inp->sctp_socket->so_qlimit) {
3943				/* we are accepting so check limits like TCP */
3944				if (inp->sctp_socket->so_qlen >
3945				    inp->sctp_socket->so_qlimit) {
3946					/* no space */
3947					struct mbuf *oper;
3948					struct sctp_paramhdr *phdr;
3949
3950					if (sctp_abort_if_one_2_one_hits_limit) {
3951						oper = NULL;
3952						oper = sctp_get_mbuf_for_msg(sizeof(struct sctp_paramhdr),
3953						    1, M_DONTWAIT, 1, MT_DATA);
3954						if (oper) {
3955							oper->m_len =
3956							    oper->m_pkthdr.len =
3957							    sizeof(struct sctp_paramhdr);
3958							phdr = mtod(oper,
3959							    struct sctp_paramhdr *);
3960							phdr->param_type =
3961							    htons(SCTP_CAUSE_OUT_OF_RESC);
3962							phdr->param_length =
3963							    htons(sizeof(struct sctp_paramhdr));
3964						}
3965						sctp_abort_association(inp, stcb, m,
3966						    iphlen, sh, oper);
3967					}
3968					*offset = length;
3969					return (NULL);
3970				}
3971			}
3972	process_cookie_anyway:
3973			{
3974				struct mbuf *ret_buf;
3975
3976				ret_buf =
3977				    sctp_handle_cookie_echo(m, iphlen,
3978				    *offset, sh,
3979				    (struct sctp_cookie_echo_chunk *)ch,
3980				    &inp, &stcb, netp,
3981				    auth_skipped,
3982				    auth_offset,
3983				    auth_len);
3984
3985				if (ret_buf == NULL) {
3986					if (locked_tcb) {
3987						SCTP_TCB_UNLOCK(locked_tcb);
3988					}
3989#ifdef SCTP_DEBUG
3990					if (sctp_debug_on & SCTP_DEBUG_INPUT3) {
3991						printf("GAK, null buffer\n");
3992					}
3993#endif				/* SCTP_DEBUG */
3994					auth_skipped = 0;
3995					*offset = length;
3996					return (NULL);
3997				}
3998				/* if AUTH skipped, see if it verified... */
3999				if (auth_skipped) {
4000					got_auth = 1;
4001					auth_skipped = 0;
4002				}
4003				if (!TAILQ_EMPTY(&stcb->asoc.sent_queue)) {
4004					/*
4005					 * Restart the timer if we have
4006					 * pending data
4007					 */
4008					struct sctp_tmit_chunk *chk;
4009
4010					chk = TAILQ_FIRST(&stcb->asoc.sent_queue);
4011					if (chk) {
4012						sctp_timer_start(SCTP_TIMER_TYPE_SEND,
4013						    stcb->sctp_ep, stcb,
4014						    chk->whoTo);
4015					}
4016				}
4017			}
4018			break;
4019		case SCTP_COOKIE_ACK:
4020#ifdef SCTP_DEBUG
4021			if (sctp_debug_on & SCTP_DEBUG_INPUT3) {
4022				printf("SCTP_COOKIE-ACK\n");
4023			}
4024#endif				/* SCTP_DEBUG */
4025
4026			if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE) {
4027				/* We are not interested anymore */
4028				if ((stcb) && (stcb->asoc.total_output_queue_size)) {
4029					;
4030				} else {
4031					sctp_free_assoc(inp, stcb, 0);
4032					*offset = length;
4033					return (NULL);
4034				}
4035			}
4036			/* He's alive so give him credit */
4037			stcb->asoc.overall_error_count = 0;
4038			sctp_handle_cookie_ack((struct sctp_cookie_ack_chunk *)ch, stcb, *netp);
4039			break;
4040		case SCTP_ECN_ECHO:
4041#ifdef SCTP_DEBUG
4042			if (sctp_debug_on & SCTP_DEBUG_INPUT3) {
4043				printf("SCTP_ECN-ECHO\n");
4044			}
4045#endif				/* SCTP_DEBUG */
4046			/* He's alive so give him credit */
4047			stcb->asoc.overall_error_count = 0;
4048			sctp_handle_ecn_echo((struct sctp_ecne_chunk *)ch,
4049			    stcb);
4050			break;
4051		case SCTP_ECN_CWR:
4052#ifdef SCTP_DEBUG
4053			if (sctp_debug_on & SCTP_DEBUG_INPUT3) {
4054				printf("SCTP_ECN-CWR\n");
4055			}
4056#endif				/* SCTP_DEBUG */
4057			/* He's alive so give him credit */
4058			stcb->asoc.overall_error_count = 0;
4059
4060			sctp_handle_ecn_cwr((struct sctp_cwr_chunk *)ch, stcb);
4061			break;
4062		case SCTP_SHUTDOWN_COMPLETE:
4063#ifdef SCTP_DEBUG
4064			if (sctp_debug_on & SCTP_DEBUG_INPUT3) {
4065				printf("SCTP_SHUTDOWN-COMPLETE\n");
4066			}
4067#endif				/* SCTP_DEBUG */
4068			/* must be first and only chunk */
4069			if ((num_chunks > 1) ||
4070			    (length - *offset > SCTP_SIZE32(chk_length))) {
4071				*offset = length;
4072				if (locked_tcb)
4073					SCTP_TCB_UNLOCK(locked_tcb);
4074
4075				return (NULL);
4076			}
4077			sctp_handle_shutdown_complete((struct sctp_shutdown_complete_chunk *)ch,
4078			    stcb, *netp);
4079			*offset = length;
4080			return (NULL);
4081			break;
4082		case SCTP_ASCONF:
4083#ifdef SCTP_DEBUG
4084			if (sctp_debug_on & SCTP_DEBUG_INPUT3) {
4085				printf("SCTP_ASCONF\n");
4086			}
4087#endif				/* SCTP_DEBUG */
4088			/* He's alive so give him credit */
4089			stcb->asoc.overall_error_count = 0;
4090
4091			sctp_handle_asconf(m, *offset,
4092			    (struct sctp_asconf_chunk *)ch, stcb);
4093			break;
4094		case SCTP_ASCONF_ACK:
4095#ifdef SCTP_DEBUG
4096			if (sctp_debug_on & SCTP_DEBUG_INPUT3) {
4097				printf("SCTP_ASCONF-ACK\n");
4098			}
4099#endif				/* SCTP_DEBUG */
4100			/* He's alive so give him credit */
4101			stcb->asoc.overall_error_count = 0;
4102
4103			sctp_handle_asconf_ack(m, *offset,
4104			    (struct sctp_asconf_ack_chunk *)ch, stcb, *netp);
4105			break;
4106		case SCTP_FORWARD_CUM_TSN:
4107#ifdef SCTP_DEBUG
4108			if (sctp_debug_on & SCTP_DEBUG_INPUT3) {
4109				printf("SCTP_FWD-TSN\n");
4110			}
4111#endif				/* SCTP_DEBUG */
4112			/* He's alive so give him credit */
4113			{
4114				int abort_flag = 0;
4115
4116				stcb->asoc.overall_error_count = 0;
4117				*fwd_tsn_seen = 1;
4118				if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE) {
4119					/* We are not interested anymore */
4120					sctp_free_assoc(inp, stcb, 0);
4121					*offset = length;
4122					return (NULL);
4123				}
4124				sctp_handle_forward_tsn(stcb,
4125				    (struct sctp_forward_tsn_chunk *)ch, &abort_flag);
4126				if (abort_flag) {
4127					*offset = length;
4128					return (NULL);
4129				} else {
4130					stcb->asoc.overall_error_count = 0;
4131				}
4132
4133			}
4134			break;
4135		case SCTP_STREAM_RESET:
4136#ifdef SCTP_DEBUG
4137			if (sctp_debug_on & SCTP_DEBUG_INPUT3) {
4138				printf("SCTP_STREAM_RESET\n");
4139			}
4140#endif				/* SCTP_DEBUG */
4141			ch = (struct sctp_chunkhdr *)sctp_m_getptr(m, *offset,
4142			    chk_length, chunk_buf);
4143			if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE) {
4144				/* We are not interested anymore */
4145				sctp_free_assoc(inp, stcb, 0);
4146				*offset = length;
4147				return (NULL);
4148			}
4149			if (stcb->asoc.peer_supports_strreset == 0) {
4150				/*
4151				 * hmm, peer should have announced this, but
4152				 * we will turn it on since he is sending us
4153				 * a stream reset.
4154				 */
4155				stcb->asoc.peer_supports_strreset = 1;
4156			}
4157			if (sctp_handle_stream_reset(stcb, (struct sctp_stream_reset_out_req *)ch)) {
4158				/* stop processing */
4159				*offset = length;
4160				return (NULL);
4161			}
4162			break;
4163		case SCTP_PACKET_DROPPED:
4164#ifdef SCTP_DEBUG
4165			if (sctp_debug_on & SCTP_DEBUG_INPUT3) {
4166				printf("SCTP_PACKET_DROPPED\n");
4167			}
4168#endif				/* SCTP_DEBUG */
4169			/* re-get it all please */
4170			ch = (struct sctp_chunkhdr *)sctp_m_getptr(m, *offset,
4171			    chk_length, chunk_buf);
4172
4173			sctp_handle_packet_dropped((struct sctp_pktdrop_chunk *)ch,
4174			    stcb, *netp);
4175
4176			break;
4177
4178		case SCTP_AUTHENTICATION:
4179#ifdef SCTP_DEBUG
4180			if (sctp_debug_on & SCTP_DEBUG_INPUT3) {
4181				printf("SCTP_AUTHENTICATION\n");
4182			}
4183#endif				/* SCTP_DEBUG */
4184			if (sctp_auth_disable)
4185				goto unknown_chunk;
4186
4187			if (stcb == NULL) {
4188				/* save the first AUTH for later processing */
4189				if (auth_skipped == 0) {
4190					auth_offset = *offset;
4191					auth_len = chk_length;
4192					auth_skipped = 1;
4193				}
4194				/* skip this chunk (temporarily) */
4195				goto next_chunk;
4196			}
4197			if (got_auth == 1) {
4198				/* skip this chunk... it's already auth'd */
4199				goto next_chunk;
4200			}
4201			ch = (struct sctp_chunkhdr *)sctp_m_getptr(m, *offset,
4202			    chk_length, chunk_buf);
4203			got_auth = 1;
4204			if (sctp_handle_auth(stcb, (struct sctp_auth_chunk *)ch,
4205			    m, *offset)) {
4206				/* auth HMAC failed so dump the packet */
4207				*offset = length;
4208				return (stcb);
4209			} else {
4210				/* remaining chunks are HMAC checked */
4211				stcb->asoc.authenticated = 1;
4212			}
4213			break;
4214
4215		default:
4216	unknown_chunk:
4217			/* it's an unknown chunk! */
4218			if ((ch->chunk_type & 0x40) && (stcb != NULL)) {
4219				struct mbuf *mm;
4220				struct sctp_paramhdr *phd;
4221
4222				mm = sctp_get_mbuf_for_msg(sizeof(struct sctp_paramhdr),
4223				    1, M_DONTWAIT, 1, MT_DATA);
4224				if (mm) {
4225					phd = mtod(mm, struct sctp_paramhdr *);
4226					/*
4227					 * We cheat and use param type since
4228					 * we did not bother to define a
4229					 * error cause struct. They are the
4230					 * same basic format with different
4231					 * names.
4232					 */
4233					phd->param_type = htons(SCTP_CAUSE_UNRECOG_CHUNK);
4234					phd->param_length = htons(chk_length + sizeof(*phd));
4235					mm->m_len = sizeof(*phd);
4236					mm->m_next = sctp_m_copym(m, *offset, SCTP_SIZE32(chk_length),
4237					    M_DONTWAIT);
4238					if (mm->m_next) {
4239						mm->m_pkthdr.len = SCTP_SIZE32(chk_length) + sizeof(*phd);
4240						sctp_queue_op_err(stcb, mm);
4241					} else {
4242						sctp_m_freem(mm);
4243					}
4244				}
4245			}
4246			if ((ch->chunk_type & 0x80) == 0) {
4247				/* discard this packet */
4248				*offset = length;
4249				return (stcb);
4250			}	/* else skip this bad chunk and continue... */
4251			break;
4252		}		/* switch (ch->chunk_type) */
4253
4254
4255next_chunk:
4256		/* get the next chunk */
4257		*offset += SCTP_SIZE32(chk_length);
4258		if (*offset >= length) {
4259			/* no more data left in the mbuf chain */
4260			break;
4261		}
4262		ch = (struct sctp_chunkhdr *)sctp_m_getptr(m, *offset,
4263		    sizeof(struct sctp_chunkhdr), chunk_buf);
4264		if (ch == NULL) {
4265			if (locked_tcb)
4266				SCTP_TCB_UNLOCK(locked_tcb);
4267			*offset = length;
4268			return (NULL);
4269		}
4270	}			/* while */
4271	return (stcb);
4272}
4273
4274
4275/*
4276 * Process the ECN bits we have something set so we must look to see if it is
4277 * ECN(0) or ECN(1) or CE
4278 */
4279static __inline void
4280sctp_process_ecn_marked_a(struct sctp_tcb *stcb, struct sctp_nets *net,
4281    uint8_t ecn_bits)
4282{
4283	if ((ecn_bits & SCTP_CE_BITS) == SCTP_CE_BITS) {
4284		;
4285	} else if ((ecn_bits & SCTP_ECT1_BIT) == SCTP_ECT1_BIT) {
4286		/*
4287		 * we only add to the nonce sum for ECT1, ECT0 does not
4288		 * change the NS bit (that we have yet to find a way to send
4289		 * it yet).
4290		 */
4291
4292		/* ECN Nonce stuff */
4293		stcb->asoc.receiver_nonce_sum++;
4294		stcb->asoc.receiver_nonce_sum &= SCTP_SACK_NONCE_SUM;
4295
4296		/*
4297		 * Drag up the last_echo point if cumack is larger since we
4298		 * don't want the point falling way behind by more than
4299		 * 2^^31 and then having it be incorrect.
4300		 */
4301		if (compare_with_wrap(stcb->asoc.cumulative_tsn,
4302		    stcb->asoc.last_echo_tsn, MAX_TSN)) {
4303			stcb->asoc.last_echo_tsn = stcb->asoc.cumulative_tsn;
4304		}
4305	} else if ((ecn_bits & SCTP_ECT0_BIT) == SCTP_ECT0_BIT) {
4306		/*
4307		 * Drag up the last_echo point if cumack is larger since we
4308		 * don't want the point falling way behind by more than
4309		 * 2^^31 and then having it be incorrect.
4310		 */
4311		if (compare_with_wrap(stcb->asoc.cumulative_tsn,
4312		    stcb->asoc.last_echo_tsn, MAX_TSN)) {
4313			stcb->asoc.last_echo_tsn = stcb->asoc.cumulative_tsn;
4314		}
4315	}
4316}
4317
4318static __inline void
4319sctp_process_ecn_marked_b(struct sctp_tcb *stcb, struct sctp_nets *net,
4320    uint32_t high_tsn, uint8_t ecn_bits)
4321{
4322	if ((ecn_bits & SCTP_CE_BITS) == SCTP_CE_BITS) {
4323		/*
4324		 * we possibly must notify the sender that a congestion
4325		 * window reduction is in order. We do this by adding a ECNE
4326		 * chunk to the output chunk queue. The incoming CWR will
4327		 * remove this chunk.
4328		 */
4329		if (compare_with_wrap(high_tsn, stcb->asoc.last_echo_tsn,
4330		    MAX_TSN)) {
4331			/* Yep, we need to add a ECNE */
4332			sctp_send_ecn_echo(stcb, net, high_tsn);
4333			stcb->asoc.last_echo_tsn = high_tsn;
4334		}
4335	}
4336}
4337
4338/*
4339 * common input chunk processing (v4 and v6)
4340 */
4341int
4342sctp_common_input_processing(struct mbuf **mm, int iphlen, int offset,
4343    int length, struct sctphdr *sh, struct sctp_chunkhdr *ch,
4344    struct sctp_inpcb *inp, struct sctp_tcb *stcb, struct sctp_nets *net,
4345    uint8_t ecn_bits)
4346{
4347	/*
4348	 * Control chunk processing
4349	 */
4350	uint32_t high_tsn;
4351	int fwd_tsn_seen = 0, data_processed = 0;
4352	struct mbuf *m = *mm;
4353	int abort_flag = 0;
4354	int un_sent;
4355
4356	SCTP_STAT_INCR(sctps_recvdatagrams);
4357#ifdef SCTP_AUDITING_ENABLED
4358	sctp_audit_log(0xE0, 1);
4359	sctp_auditing(0, inp, stcb, net);
4360#endif
4361
4362#ifdef SCTP_DEBUG
4363	if (sctp_debug_on & SCTP_DEBUG_INPUT1) {
4364		printf("Ok, Common input processing called, m:%p iphlen:%d offset:%d\n",
4365		    m, iphlen, offset);
4366	}
4367#endif				/* SCTP_DEBUG */
4368
4369	if (stcb) {
4370		/* always clear this before beginning a packet */
4371		stcb->asoc.authenticated = 0;
4372		stcb->asoc.seen_a_sack_this_pkt = 0;
4373	}
4374	if (IS_SCTP_CONTROL(ch)) {
4375		/* process the control portion of the SCTP packet */
4376		stcb = sctp_process_control(m, iphlen, &offset, length, sh, ch,
4377		    inp, stcb, &net, &fwd_tsn_seen);
4378		if (stcb) {
4379			/*
4380			 * This covers us if the cookie-echo was there and
4381			 * it changes our INP.
4382			 */
4383			inp = stcb->sctp_ep;
4384		}
4385	} else {
4386		/*
4387		 * no control chunks, so pre-process DATA chunks (these
4388		 * checks are taken care of by control processing)
4389		 */
4390
4391		/*
4392		 * if DATA only packet, and auth is required, then punt...
4393		 * can't have authenticated without any AUTH (control)
4394		 * chunks
4395		 */
4396		if ((stcb != NULL) && !sctp_auth_disable &&
4397		    sctp_auth_is_required_chunk(SCTP_DATA,
4398		    stcb->asoc.local_auth_chunks)) {
4399			/* "silently" ignore */
4400			SCTP_STAT_INCR(sctps_recvauthmissing);
4401			SCTP_TCB_UNLOCK(stcb);
4402			return (1);
4403		}
4404		if (stcb == NULL) {
4405			/* out of the blue DATA chunk */
4406			sctp_handle_ootb(m, iphlen, offset, sh, inp, NULL);
4407			return (1);
4408		}
4409		if (stcb->asoc.my_vtag != ntohl(sh->v_tag)) {
4410			/* v_tag mismatch! */
4411			SCTP_STAT_INCR(sctps_badvtag);
4412			SCTP_TCB_UNLOCK(stcb);
4413			return (1);
4414		}
4415	}
4416
4417	if (stcb == NULL) {
4418		/*
4419		 * no valid TCB for this packet, or we found it's a bad
4420		 * packet while processing control, or we're done with this
4421		 * packet (done or skip rest of data), so we drop it...
4422		 */
4423		return (1);
4424	}
4425	/*
4426	 * DATA chunk processing
4427	 */
4428	/* plow through the data chunks while length > offset */
4429
4430	/*
4431	 * Rest should be DATA only.  Check authentication state if AUTH for
4432	 * DATA is required.
4433	 */
4434	if ((stcb != NULL) && !sctp_auth_disable &&
4435	    sctp_auth_is_required_chunk(SCTP_DATA,
4436	    stcb->asoc.local_auth_chunks) &&
4437	    !stcb->asoc.authenticated) {
4438		/* "silently" ignore */
4439		SCTP_STAT_INCR(sctps_recvauthmissing);
4440#ifdef SCTP_DEBUG
4441		if (sctp_debug_on & SCTP_DEBUG_AUTH1)
4442			printf("Data chunk requires AUTH, skipped\n");
4443#endif
4444		SCTP_TCB_UNLOCK(stcb);
4445		return (1);
4446	}
4447	if (length > offset) {
4448		int retval;
4449
4450		/*
4451		 * First check to make sure our state is correct. We would
4452		 * not get here unless we really did have a tag, so we don't
4453		 * abort if this happens, just dump the chunk silently.
4454		 */
4455		switch (SCTP_GET_STATE(&stcb->asoc)) {
4456		case SCTP_STATE_COOKIE_ECHOED:
4457			/*
4458			 * we consider data with valid tags in this state
4459			 * shows us the cookie-ack was lost. Imply it was
4460			 * there.
4461			 */
4462			stcb->asoc.overall_error_count = 0;
4463			sctp_handle_cookie_ack((struct sctp_cookie_ack_chunk *)ch, stcb, net);
4464			break;
4465		case SCTP_STATE_COOKIE_WAIT:
4466			/*
4467			 * We consider OOTB any data sent during asoc setup.
4468			 */
4469			sctp_handle_ootb(m, iphlen, offset, sh, inp, NULL);
4470			SCTP_TCB_UNLOCK(stcb);
4471			return (1);
4472			break;
4473		case SCTP_STATE_EMPTY:	/* should not happen */
4474		case SCTP_STATE_INUSE:	/* should not happen */
4475		case SCTP_STATE_SHUTDOWN_RECEIVED:	/* This is a peer error */
4476		case SCTP_STATE_SHUTDOWN_ACK_SENT:
4477		default:
4478			SCTP_TCB_UNLOCK(stcb);
4479			return (1);
4480			break;
4481		case SCTP_STATE_OPEN:
4482		case SCTP_STATE_SHUTDOWN_SENT:
4483			break;
4484		}
4485		/* take care of ECN, part 1. */
4486		if (stcb->asoc.ecn_allowed &&
4487		    (ecn_bits & (SCTP_ECT0_BIT | SCTP_ECT1_BIT))) {
4488			sctp_process_ecn_marked_a(stcb, net, ecn_bits);
4489		}
4490		/* plow through the data chunks while length > offset */
4491		retval = sctp_process_data(mm, iphlen, &offset, length, sh,
4492		    inp, stcb, net, &high_tsn);
4493		if (retval == 2) {
4494			/*
4495			 * The association aborted, NO UNLOCK needed since
4496			 * the association is destroyed.
4497			 */
4498			return (0);
4499		}
4500		data_processed = 1;
4501		if (retval == 0) {
4502			/* take care of ecn part 2. */
4503			if (stcb->asoc.ecn_allowed &&
4504			    (ecn_bits & (SCTP_ECT0_BIT | SCTP_ECT1_BIT))) {
4505				sctp_process_ecn_marked_b(stcb, net, high_tsn,
4506				    ecn_bits);
4507			}
4508		}
4509		/*
4510		 * Anything important needs to have been m_copy'ed in
4511		 * process_data
4512		 */
4513	}
4514	if ((data_processed == 0) && (fwd_tsn_seen)) {
4515		int was_a_gap = 0;
4516
4517		if (compare_with_wrap(stcb->asoc.highest_tsn_inside_map,
4518		    stcb->asoc.cumulative_tsn, MAX_TSN)) {
4519			/* there was a gap before this data was processed */
4520			was_a_gap = 1;
4521		}
4522		sctp_sack_check(stcb, 1, was_a_gap, &abort_flag);
4523		if (abort_flag) {
4524			/* Again, we aborted so NO UNLOCK needed */
4525			return (0);
4526		}
4527	}
4528	/* trigger send of any chunks in queue... */
4529#ifdef SCTP_AUDITING_ENABLED
4530	sctp_audit_log(0xE0, 2);
4531	sctp_auditing(1, inp, stcb, net);
4532#endif
4533#ifdef SCTP_DEBUG
4534	if (sctp_debug_on & SCTP_DEBUG_INPUT1) {
4535		printf("Check for chunk output prw:%d tqe:%d tf=%d\n",
4536		    stcb->asoc.peers_rwnd,
4537		    TAILQ_EMPTY(&stcb->asoc.control_send_queue),
4538		    stcb->asoc.total_flight);
4539	}
4540#endif
4541	un_sent = (stcb->asoc.total_output_queue_size - stcb->asoc.total_flight);
4542
4543	if (!TAILQ_EMPTY(&stcb->asoc.control_send_queue) ||
4544	    ((un_sent) &&
4545	    (stcb->asoc.peers_rwnd > 0 ||
4546	    (stcb->asoc.peers_rwnd <= 0 && stcb->asoc.total_flight == 0)))) {
4547#ifdef SCTP_DEBUG
4548		if (sctp_debug_on & SCTP_DEBUG_INPUT3) {
4549			printf("Calling chunk OUTPUT\n");
4550		}
4551#endif
4552		sctp_chunk_output(inp, stcb, SCTP_OUTPUT_FROM_CONTROL_PROC);
4553#ifdef SCTP_DEBUG
4554		if (sctp_debug_on & SCTP_DEBUG_INPUT3) {
4555			printf("chunk OUTPUT returns\n");
4556		}
4557#endif
4558	}
4559#ifdef SCTP_AUDITING_ENABLED
4560	sctp_audit_log(0xE0, 3);
4561	sctp_auditing(2, inp, stcb, net);
4562#endif
4563	SCTP_TCB_UNLOCK(stcb);
4564	return (0);
4565}
4566
4567extern int sctp_no_csum_on_loopback;
4568
4569
4570void
4571sctp_input(m, off)
4572	struct mbuf *m;
4573	int off;
4574
4575{
4576#ifdef SCTP_MBUF_LOGGING
4577	struct mbuf *mat;
4578
4579#endif
4580	int iphlen;
4581	int s;
4582	uint8_t ecn_bits;
4583	struct ip *ip;
4584	struct sctphdr *sh;
4585	struct sctp_inpcb *inp = NULL;
4586
4587	uint32_t check, calc_check;
4588	struct sctp_nets *net;
4589	struct sctp_tcb *stcb = NULL;
4590	struct sctp_chunkhdr *ch;
4591	int refcount_up = 0;
4592	int length, mlen, offset;
4593
4594
4595	iphlen = off;
4596	net = NULL;
4597	SCTP_STAT_INCR(sctps_recvpackets);
4598	SCTP_STAT_INCR_COUNTER64(sctps_inpackets);
4599
4600	/*
4601	 * Strip IP options, we don't allow any in or out.
4602	 */
4603#ifdef SCTP_MBUF_LOGGING
4604	/* Log in any input mbufs */
4605	mat = m;
4606	while (mat) {
4607		if (mat->m_flags & M_EXT) {
4608			sctp_log_mb(mat, SCTP_MBUF_INPUT);
4609		}
4610		mat = mat->m_next;
4611	}
4612#endif
4613	if ((size_t)iphlen > sizeof(struct ip)) {
4614		ip_stripoptions(m, (struct mbuf *)0);
4615		iphlen = sizeof(struct ip);
4616	}
4617	/*
4618	 * Get IP, SCTP, and first chunk header together in first mbuf.
4619	 */
4620	ip = mtod(m, struct ip *);
4621	offset = iphlen + sizeof(*sh) + sizeof(*ch);
4622	if (m->m_len < offset) {
4623		if ((m = m_pullup(m, offset)) == 0) {
4624			SCTP_STAT_INCR(sctps_hdrops);
4625			return;
4626		}
4627		ip = mtod(m, struct ip *);
4628	}
4629	sh = (struct sctphdr *)((caddr_t)ip + iphlen);
4630	ch = (struct sctp_chunkhdr *)((caddr_t)sh + sizeof(*sh));
4631
4632	/* SCTP does not allow broadcasts or multicasts */
4633	if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr))) {
4634		goto bad;
4635	}
4636	if (((ch->chunk_type == SCTP_INITIATION) ||
4637	    (ch->chunk_type == SCTP_INITIATION_ACK) ||
4638	    (ch->chunk_type == SCTP_COOKIE_ECHO)) &&
4639	    (in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))) {
4640		/*
4641		 * We only look at broadcast if its a front state, All
4642		 * others we will not have a tcb for anyway.
4643		 */
4644		goto bad;
4645	}
4646	/* destination port of 0 is illegal, based on RFC2960. */
4647	if (sh->dest_port == 0) {
4648		SCTP_STAT_INCR(sctps_hdrops);
4649		goto bad;
4650	}
4651	/* validate SCTP checksum */
4652	if ((sctp_no_csum_on_loopback == 0) ||
4653	    (m->m_pkthdr.rcvif == NULL) ||
4654	    (m->m_pkthdr.rcvif->if_type != IFT_LOOP)) {
4655		/*
4656		 * we do NOT validate things from the loopback if the sysctl
4657		 * is set to 1.
4658		 */
4659		check = sh->checksum;	/* save incoming checksum */
4660		if ((check == 0) && (sctp_no_csum_on_loopback)) {
4661			/*
4662			 * special hook for where we got a local address
4663			 * somehow routed across a non IFT_LOOP type
4664			 * interface
4665			 */
4666			if (ip->ip_src.s_addr == ip->ip_dst.s_addr)
4667				goto sctp_skip_csum_4;
4668		}
4669		sh->checksum = 0;	/* prepare for calc */
4670		calc_check = sctp_calculate_sum(m, &mlen, iphlen);
4671		if (calc_check != check) {
4672#ifdef SCTP_DEBUG
4673			if (sctp_debug_on & SCTP_DEBUG_INPUT1) {
4674				printf("Bad CSUM on SCTP packet calc_check:%x check:%x  m:%p mlen:%d iphlen:%d\n",
4675				    calc_check, check, m, mlen, iphlen);
4676			}
4677#endif
4678
4679			stcb = sctp_findassociation_addr(m, iphlen,
4680			    offset - sizeof(*ch),
4681			    sh, ch, &inp, &net);
4682			if ((inp) && (stcb)) {
4683				sctp_send_packet_dropped(stcb, net, m, iphlen, 1);
4684				sctp_chunk_output(inp, stcb, SCTP_OUTPUT_FROM_INPUT_ERROR);
4685			} else if ((inp != NULL) && (stcb == NULL)) {
4686				refcount_up = 1;
4687			}
4688			SCTP_STAT_INCR(sctps_badsum);
4689			SCTP_STAT_INCR_COUNTER32(sctps_checksumerrors);
4690			goto bad;
4691		}
4692		sh->checksum = calc_check;
4693	} else {
4694sctp_skip_csum_4:
4695		mlen = m->m_pkthdr.len;
4696	}
4697	/* validate mbuf chain length with IP payload length */
4698	if (mlen < (ip->ip_len - iphlen)) {
4699		SCTP_STAT_INCR(sctps_hdrops);
4700		goto bad;
4701	}
4702	/*
4703	 * Locate pcb and tcb for datagram sctp_findassociation_addr() wants
4704	 * IP/SCTP/first chunk header...
4705	 */
4706	stcb = sctp_findassociation_addr(m, iphlen, offset - sizeof(*ch),
4707	    sh, ch, &inp, &net);
4708	/* inp's ref-count increased && stcb locked */
4709	if (inp == NULL) {
4710		struct sctp_init_chunk *init_chk, chunk_buf;
4711
4712		SCTP_STAT_INCR(sctps_noport);
4713#ifdef ICMP_BANDLIM
4714		/*
4715		 * we use the bandwidth limiting to protect against sending
4716		 * too many ABORTS all at once. In this case these count the
4717		 * same as an ICMP message.
4718		 */
4719		if (badport_bandlim(0) < 0)
4720			goto bad;
4721#endif				/* ICMP_BANDLIM */
4722#ifdef SCTP_DEBUG
4723		if (sctp_debug_on & SCTP_DEBUG_INPUT1) {
4724			printf("Sending a ABORT from packet entry!\n");
4725		}
4726#endif
4727		if (ch->chunk_type == SCTP_INITIATION) {
4728			/*
4729			 * we do a trick here to get the INIT tag, dig in
4730			 * and get the tag from the INIT and put it in the
4731			 * common header.
4732			 */
4733			init_chk = (struct sctp_init_chunk *)sctp_m_getptr(m,
4734			    iphlen + sizeof(*sh), sizeof(*init_chk),
4735			    (uint8_t *) & chunk_buf);
4736			if (init_chk != NULL)
4737				sh->v_tag = init_chk->init.initiate_tag;
4738		}
4739		sctp_send_abort(m, iphlen, sh, 0, NULL);
4740		goto bad;
4741	} else if (stcb == NULL) {
4742		refcount_up = 1;
4743	}
4744#ifdef IPSEC
4745	/*
4746	 * I very much doubt any of the IPSEC stuff will work but I have no
4747	 * idea, so I will leave it in place.
4748	 */
4749
4750	if (inp && ipsec4_in_reject(m, &inp->ip_inp.inp)) {
4751		ipsecstat.in_polvio++;
4752		SCTP_STAT_INCR(sctps_hdrops);
4753		goto bad;
4754	}
4755#endif				/* IPSEC */
4756
4757
4758
4759	/*
4760	 * common chunk processing
4761	 */
4762	length = ip->ip_len + iphlen;
4763	offset -= sizeof(struct sctp_chunkhdr);
4764
4765	ecn_bits = ip->ip_tos;
4766	s = splnet();
4767
4768	sctp_common_input_processing(&m, iphlen, offset, length, sh, ch,
4769	    inp, stcb, net, ecn_bits);
4770	/* inp's ref-count reduced && stcb unlocked */
4771	splx(s);
4772	if (m) {
4773		sctp_m_freem(m);
4774	}
4775	if ((inp) && (refcount_up)) {
4776		/* reduce ref-count */
4777		SCTP_INP_WLOCK(inp);
4778		SCTP_INP_DECR_REF(inp);
4779		SCTP_INP_WUNLOCK(inp);
4780	}
4781	return;
4782bad:
4783	if (stcb)
4784		SCTP_TCB_UNLOCK(stcb);
4785
4786	if ((inp) && (refcount_up)) {
4787		/* reduce ref-count */
4788		SCTP_INP_WLOCK(inp);
4789		SCTP_INP_DECR_REF(inp);
4790		SCTP_INP_WUNLOCK(inp);
4791	}
4792	if (m) {
4793		sctp_m_freem(m);
4794	}
4795	return;
4796}
4797