sctp_input.c revision 235416
1/*-
2 * Copyright (c) 2001-2008, by Cisco Systems, Inc. All rights reserved.
3 * Copyright (c) 2008-2011, by Randall Stewart. All rights reserved.
4 * Copyright (c) 2008-2011, by Michael Tuexen. All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions are met:
8 *
9 * a) Redistributions of source code must retain the above copyright notice,
10 *    this list of conditions and the following disclaimer.
11 *
12 * b) Redistributions in binary form must reproduce the above copyright
13 *    notice, this list of conditions and the following disclaimer in
14 *    the documentation and/or other materials provided with the distribution.
15 *
16 * c) Neither the name of Cisco Systems, Inc. nor the names of its
17 *    contributors may be used to endorse or promote products derived
18 *    from this software without specific prior written permission.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
22 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
24 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
30 * THE POSSIBILITY OF SUCH DAMAGE.
31 */
32
33/* $KAME: sctp_input.c,v 1.27 2005/03/06 16:04:17 itojun Exp $	 */
34
35#include <sys/cdefs.h>
36__FBSDID("$FreeBSD: head/sys/netinet/sctp_input.c 235416 2012-05-13 19:32:49Z tuexen $");
37
38#include <netinet/sctp_os.h>
39#include <netinet/sctp_var.h>
40#include <netinet/sctp_sysctl.h>
41#include <netinet/sctp_pcb.h>
42#include <netinet/sctp_header.h>
43#include <netinet/sctputil.h>
44#include <netinet/sctp_output.h>
45#include <netinet/sctp_input.h>
46#include <netinet/sctp_auth.h>
47#include <netinet/sctp_indata.h>
48#include <netinet/sctp_asconf.h>
49#include <netinet/sctp_bsd_addr.h>
50#include <netinet/sctp_timer.h>
51#include <netinet/sctp_crc32.h>
52#include <netinet/udp.h>
53#include <sys/smp.h>
54
55
56
57static void
58sctp_stop_all_cookie_timers(struct sctp_tcb *stcb)
59{
60	struct sctp_nets *net;
61
62	/*
63	 * This now not only stops all cookie timers it also stops any INIT
64	 * timers as well. This will make sure that the timers are stopped
65	 * in all collision cases.
66	 */
67	SCTP_TCB_LOCK_ASSERT(stcb);
68	TAILQ_FOREACH(net, &stcb->asoc.nets, sctp_next) {
69		if (net->rxt_timer.type == SCTP_TIMER_TYPE_COOKIE) {
70			sctp_timer_stop(SCTP_TIMER_TYPE_COOKIE,
71			    stcb->sctp_ep,
72			    stcb,
73			    net, SCTP_FROM_SCTP_INPUT + SCTP_LOC_1);
74		} else if (net->rxt_timer.type == SCTP_TIMER_TYPE_INIT) {
75			sctp_timer_stop(SCTP_TIMER_TYPE_INIT,
76			    stcb->sctp_ep,
77			    stcb,
78			    net, SCTP_FROM_SCTP_INPUT + SCTP_LOC_2);
79		}
80	}
81}
82
83/* INIT handler */
84static void
85sctp_handle_init(struct mbuf *m, int iphlen, int offset, struct sctphdr *sh,
86    struct sctp_init_chunk *cp, struct sctp_inpcb *inp, struct sctp_tcb *stcb,
87    int *abort_no_unlock, uint32_t vrf_id, uint16_t port)
88{
89	struct sctp_init *init;
90	struct mbuf *op_err;
91
92	SCTPDBG(SCTP_DEBUG_INPUT2, "sctp_handle_init: handling INIT tcb:%p\n",
93	    stcb);
94	if (stcb == NULL) {
95		SCTP_INP_RLOCK(inp);
96	}
97	/* validate length */
98	if (ntohs(cp->ch.chunk_length) < sizeof(struct sctp_init_chunk)) {
99		op_err = sctp_generate_invmanparam(SCTP_CAUSE_INVALID_PARAM);
100		sctp_abort_association(inp, stcb, m, iphlen, sh, op_err,
101		    vrf_id, port);
102		if (stcb)
103			*abort_no_unlock = 1;
104		goto outnow;
105	}
106	/* validate parameters */
107	init = &cp->init;
108	if (init->initiate_tag == 0) {
109		/* protocol error... send abort */
110		op_err = sctp_generate_invmanparam(SCTP_CAUSE_INVALID_PARAM);
111		sctp_abort_association(inp, stcb, m, iphlen, sh, op_err,
112		    vrf_id, port);
113		if (stcb)
114			*abort_no_unlock = 1;
115		goto outnow;
116	}
117	if (ntohl(init->a_rwnd) < SCTP_MIN_RWND) {
118		/* invalid parameter... send abort */
119		op_err = sctp_generate_invmanparam(SCTP_CAUSE_INVALID_PARAM);
120		sctp_abort_association(inp, stcb, m, iphlen, sh, op_err,
121		    vrf_id, port);
122		if (stcb)
123			*abort_no_unlock = 1;
124		goto outnow;
125	}
126	if (init->num_inbound_streams == 0) {
127		/* protocol error... send abort */
128		op_err = sctp_generate_invmanparam(SCTP_CAUSE_INVALID_PARAM);
129		sctp_abort_association(inp, stcb, m, iphlen, sh, op_err,
130		    vrf_id, port);
131		if (stcb)
132			*abort_no_unlock = 1;
133		goto outnow;
134	}
135	if (init->num_outbound_streams == 0) {
136		/* protocol error... send abort */
137		op_err = sctp_generate_invmanparam(SCTP_CAUSE_INVALID_PARAM);
138		sctp_abort_association(inp, stcb, m, iphlen, sh, op_err,
139		    vrf_id, port);
140		if (stcb)
141			*abort_no_unlock = 1;
142		goto outnow;
143	}
144	if (sctp_validate_init_auth_params(m, offset + sizeof(*cp),
145	    offset + ntohs(cp->ch.chunk_length))) {
146		/* auth parameter(s) error... send abort */
147		sctp_abort_association(inp, stcb, m, iphlen, sh, NULL, vrf_id, port);
148		if (stcb)
149			*abort_no_unlock = 1;
150		goto outnow;
151	}
152	/*
153	 * We are only accepting if we have a socket with positive
154	 * so_qlimit.
155	 */
156	if ((stcb == NULL) &&
157	    ((inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE) ||
158	    (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) ||
159	    (inp->sctp_socket == NULL) ||
160	    (inp->sctp_socket->so_qlimit == 0))) {
161		/*
162		 * FIX ME ?? What about TCP model and we have a
163		 * match/restart case? Actually no fix is needed. the lookup
164		 * will always find the existing assoc so stcb would not be
165		 * NULL. It may be questionable to do this since we COULD
166		 * just send back the INIT-ACK and hope that the app did
167		 * accept()'s by the time the COOKIE was sent. But there is
168		 * a price to pay for COOKIE generation and I don't want to
169		 * pay it on the chance that the app will actually do some
170		 * accepts(). The App just looses and should NOT be in this
171		 * state :-)
172		 */
173		if (SCTP_BASE_SYSCTL(sctp_blackhole) == 0) {
174			sctp_send_abort(m, iphlen, sh, 0, NULL, vrf_id, port);
175		}
176		goto outnow;
177	}
178	if ((stcb != NULL) &&
179	    (SCTP_GET_STATE(&stcb->asoc) == SCTP_STATE_SHUTDOWN_ACK_SENT)) {
180		SCTPDBG(SCTP_DEBUG_INPUT3, "sctp_handle_init: sending SHUTDOWN-ACK\n");
181		sctp_send_shutdown_ack(stcb, NULL);
182		sctp_chunk_output(inp, stcb, SCTP_OUTPUT_FROM_CONTROL_PROC, SCTP_SO_NOT_LOCKED);
183	} else {
184		SCTPDBG(SCTP_DEBUG_INPUT3, "sctp_handle_init: sending INIT-ACK\n");
185		sctp_send_initiate_ack(inp, stcb, m, iphlen, offset, sh, cp, vrf_id, port,
186		    ((stcb == NULL) ? SCTP_HOLDS_LOCK : SCTP_NOT_LOCKED));
187	}
188outnow:
189	if (stcb == NULL) {
190		SCTP_INP_RUNLOCK(inp);
191	}
192}
193
194/*
195 * process peer "INIT/INIT-ACK" chunk returns value < 0 on error
196 */
197
198int
199sctp_is_there_unsent_data(struct sctp_tcb *stcb, int so_locked
200#if !defined(__APPLE__) && !defined(SCTP_SO_LOCK_TESTING)
201    SCTP_UNUSED
202#endif
203)
204{
205	int unsent_data = 0;
206	unsigned int i;
207	struct sctp_stream_queue_pending *sp;
208	struct sctp_association *asoc;
209
210	/*
211	 * This function returns the number of streams that have true unsent
212	 * data on them. Note that as it looks through it will clean up any
213	 * places that have old data that has been sent but left at top of
214	 * stream queue.
215	 */
216	asoc = &stcb->asoc;
217	SCTP_TCB_SEND_LOCK(stcb);
218	if (!stcb->asoc.ss_functions.sctp_ss_is_empty(stcb, asoc)) {
219		/* Check to see if some data queued */
220		for (i = 0; i < stcb->asoc.streamoutcnt; i++) {
221			/* sa_ignore FREED_MEMORY */
222			sp = TAILQ_FIRST(&stcb->asoc.strmout[i].outqueue);
223			if (sp == NULL) {
224				continue;
225			}
226			if ((sp->msg_is_complete) &&
227			    (sp->length == 0) &&
228			    (sp->sender_all_done)) {
229				/*
230				 * We are doing differed cleanup. Last time
231				 * through when we took all the data the
232				 * sender_all_done was not set.
233				 */
234				if (sp->put_last_out == 0) {
235					SCTP_PRINTF("Gak, put out entire msg with NO end!-1\n");
236					SCTP_PRINTF("sender_done:%d len:%d msg_comp:%d put_last_out:%d\n",
237					    sp->sender_all_done,
238					    sp->length,
239					    sp->msg_is_complete,
240					    sp->put_last_out);
241				}
242				atomic_subtract_int(&stcb->asoc.stream_queue_cnt, 1);
243				TAILQ_REMOVE(&stcb->asoc.strmout[i].outqueue, sp, next);
244				if (sp->net) {
245					sctp_free_remote_addr(sp->net);
246					sp->net = NULL;
247				}
248				if (sp->data) {
249					sctp_m_freem(sp->data);
250					sp->data = NULL;
251				}
252				sctp_free_a_strmoq(stcb, sp, so_locked);
253			} else {
254				unsent_data++;
255				break;
256			}
257		}
258	}
259	SCTP_TCB_SEND_UNLOCK(stcb);
260	return (unsent_data);
261}
262
263static int
264sctp_process_init(struct sctp_init_chunk *cp, struct sctp_tcb *stcb)
265{
266	struct sctp_init *init;
267	struct sctp_association *asoc;
268	struct sctp_nets *lnet;
269	unsigned int i;
270
271	init = &cp->init;
272	asoc = &stcb->asoc;
273	/* save off parameters */
274	asoc->peer_vtag = ntohl(init->initiate_tag);
275	asoc->peers_rwnd = ntohl(init->a_rwnd);
276	/* init tsn's */
277	asoc->highest_tsn_inside_map = asoc->asconf_seq_in = ntohl(init->initial_tsn) - 1;
278
279	if (!TAILQ_EMPTY(&asoc->nets)) {
280		/* update any ssthresh's that may have a default */
281		TAILQ_FOREACH(lnet, &asoc->nets, sctp_next) {
282			lnet->ssthresh = asoc->peers_rwnd;
283			if (SCTP_BASE_SYSCTL(sctp_logging_level) & (SCTP_CWND_MONITOR_ENABLE | SCTP_CWND_LOGGING_ENABLE)) {
284				sctp_log_cwnd(stcb, lnet, 0, SCTP_CWND_INITIALIZATION);
285			}
286		}
287	}
288	SCTP_TCB_SEND_LOCK(stcb);
289	if (asoc->pre_open_streams > ntohs(init->num_inbound_streams)) {
290		unsigned int newcnt;
291		struct sctp_stream_out *outs;
292		struct sctp_stream_queue_pending *sp, *nsp;
293		struct sctp_tmit_chunk *chk, *nchk;
294
295		/* abandon the upper streams */
296		newcnt = ntohs(init->num_inbound_streams);
297		TAILQ_FOREACH_SAFE(chk, &asoc->send_queue, sctp_next, nchk) {
298			if (chk->rec.data.stream_number >= newcnt) {
299				TAILQ_REMOVE(&asoc->send_queue, chk, sctp_next);
300				asoc->send_queue_cnt--;
301				if (chk->data != NULL) {
302					sctp_free_bufspace(stcb, asoc, chk, 1);
303					sctp_ulp_notify(SCTP_NOTIFY_UNSENT_DG_FAIL, stcb,
304					    0, chk, SCTP_SO_NOT_LOCKED);
305					if (chk->data) {
306						sctp_m_freem(chk->data);
307						chk->data = NULL;
308					}
309				}
310				sctp_free_a_chunk(stcb, chk, SCTP_SO_NOT_LOCKED);
311				/* sa_ignore FREED_MEMORY */
312			}
313		}
314		if (asoc->strmout) {
315			for (i = newcnt; i < asoc->pre_open_streams; i++) {
316				outs = &asoc->strmout[i];
317				TAILQ_FOREACH_SAFE(sp, &outs->outqueue, next, nsp) {
318					TAILQ_REMOVE(&outs->outqueue, sp, next);
319					asoc->stream_queue_cnt--;
320					sctp_ulp_notify(SCTP_NOTIFY_SPECIAL_SP_FAIL,
321					    stcb, 0, sp, SCTP_SO_NOT_LOCKED);
322					if (sp->data) {
323						sctp_m_freem(sp->data);
324						sp->data = NULL;
325					}
326					if (sp->net) {
327						sctp_free_remote_addr(sp->net);
328						sp->net = NULL;
329					}
330					/* Free the chunk */
331					sctp_free_a_strmoq(stcb, sp, SCTP_SO_NOT_LOCKED);
332					/* sa_ignore FREED_MEMORY */
333				}
334			}
335		}
336		/* cut back the count */
337		asoc->pre_open_streams = newcnt;
338	}
339	SCTP_TCB_SEND_UNLOCK(stcb);
340	asoc->strm_realoutsize = asoc->streamoutcnt = asoc->pre_open_streams;
341
342	/* EY - nr_sack: initialize highest tsn in nr_mapping_array */
343	asoc->highest_tsn_inside_nr_map = asoc->highest_tsn_inside_map;
344	if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_MAP_LOGGING_ENABLE) {
345		sctp_log_map(0, 5, asoc->highest_tsn_inside_map, SCTP_MAP_SLIDE_RESULT);
346	}
347	/* This is the next one we expect */
348	asoc->str_reset_seq_in = asoc->asconf_seq_in + 1;
349
350	asoc->mapping_array_base_tsn = ntohl(init->initial_tsn);
351	asoc->tsn_last_delivered = asoc->cumulative_tsn = asoc->asconf_seq_in;
352
353	asoc->advanced_peer_ack_point = asoc->last_acked_seq;
354	/* open the requested streams */
355
356	if (asoc->strmin != NULL) {
357		/* Free the old ones */
358		struct sctp_queued_to_read *ctl, *nctl;
359
360		for (i = 0; i < asoc->streamincnt; i++) {
361			TAILQ_FOREACH_SAFE(ctl, &asoc->strmin[i].inqueue, next, nctl) {
362				TAILQ_REMOVE(&asoc->strmin[i].inqueue, ctl, next);
363				sctp_free_remote_addr(ctl->whoFrom);
364				ctl->whoFrom = NULL;
365				sctp_m_freem(ctl->data);
366				ctl->data = NULL;
367				sctp_free_a_readq(stcb, ctl);
368			}
369		}
370		SCTP_FREE(asoc->strmin, SCTP_M_STRMI);
371	}
372	asoc->streamincnt = ntohs(init->num_outbound_streams);
373	if (asoc->streamincnt > MAX_SCTP_STREAMS) {
374		asoc->streamincnt = MAX_SCTP_STREAMS;
375	}
376	SCTP_MALLOC(asoc->strmin, struct sctp_stream_in *, asoc->streamincnt *
377	    sizeof(struct sctp_stream_in), SCTP_M_STRMI);
378	if (asoc->strmin == NULL) {
379		/* we didn't get memory for the streams! */
380		SCTPDBG(SCTP_DEBUG_INPUT2, "process_init: couldn't get memory for the streams!\n");
381		return (-1);
382	}
383	for (i = 0; i < asoc->streamincnt; i++) {
384		asoc->strmin[i].stream_no = i;
385		asoc->strmin[i].last_sequence_delivered = 0xffff;
386		/*
387		 * U-stream ranges will be set when the cookie is unpacked.
388		 * Or for the INIT sender they are un set (if pr-sctp not
389		 * supported) when the INIT-ACK arrives.
390		 */
391		TAILQ_INIT(&asoc->strmin[i].inqueue);
392		asoc->strmin[i].delivery_started = 0;
393	}
394	/*
395	 * load_address_from_init will put the addresses into the
396	 * association when the COOKIE is processed or the INIT-ACK is
397	 * processed. Both types of COOKIE's existing and new call this
398	 * routine. It will remove addresses that are no longer in the
399	 * association (for the restarting case where addresses are
400	 * removed). Up front when the INIT arrives we will discard it if it
401	 * is a restart and new addresses have been added.
402	 */
403	/* sa_ignore MEMLEAK */
404	return (0);
405}
406
407/*
408 * INIT-ACK message processing/consumption returns value < 0 on error
409 */
410static int
411sctp_process_init_ack(struct mbuf *m, int iphlen, int offset,
412    struct sctphdr *sh, struct sctp_init_ack_chunk *cp, struct sctp_tcb *stcb,
413    struct sctp_nets *net, int *abort_no_unlock, uint32_t vrf_id)
414{
415	struct sctp_association *asoc;
416	struct mbuf *op_err;
417	int retval, abort_flag;
418	uint32_t initack_limit;
419	int nat_friendly = 0;
420
421	/* First verify that we have no illegal param's */
422	abort_flag = 0;
423	op_err = NULL;
424
425	op_err = sctp_arethere_unrecognized_parameters(m,
426	    (offset + sizeof(struct sctp_init_chunk)),
427	    &abort_flag, (struct sctp_chunkhdr *)cp, &nat_friendly);
428	if (abort_flag) {
429		/* Send an abort and notify peer */
430		sctp_abort_an_association(stcb->sctp_ep, stcb, op_err, SCTP_SO_NOT_LOCKED);
431		*abort_no_unlock = 1;
432		return (-1);
433	}
434	asoc = &stcb->asoc;
435	asoc->peer_supports_nat = (uint8_t) nat_friendly;
436	/* process the peer's parameters in the INIT-ACK */
437	retval = sctp_process_init((struct sctp_init_chunk *)cp, stcb);
438	if (retval < 0) {
439		return (retval);
440	}
441	initack_limit = offset + ntohs(cp->ch.chunk_length);
442	/* load all addresses */
443	if ((retval = sctp_load_addresses_from_init(stcb, m,
444	    (offset + sizeof(struct sctp_init_chunk)), initack_limit, sh,
445	    NULL))) {
446		/* Huh, we should abort */
447		SCTPDBG(SCTP_DEBUG_INPUT1,
448		    "Load addresses from INIT causes an abort %d\n",
449		    retval);
450		sctp_abort_association(stcb->sctp_ep, stcb, m, iphlen, sh,
451		    NULL, 0, net->port);
452		*abort_no_unlock = 1;
453		return (-1);
454	}
455	/* if the peer doesn't support asconf, flush the asconf queue */
456	if (asoc->peer_supports_asconf == 0) {
457		struct sctp_asconf_addr *param, *nparam;
458
459		TAILQ_FOREACH_SAFE(param, &asoc->asconf_queue, next, nparam) {
460			TAILQ_REMOVE(&asoc->asconf_queue, param, next);
461			SCTP_FREE(param, SCTP_M_ASC_ADDR);
462		}
463	}
464	stcb->asoc.peer_hmac_id = sctp_negotiate_hmacid(stcb->asoc.peer_hmacs,
465	    stcb->asoc.local_hmacs);
466	if (op_err) {
467		sctp_queue_op_err(stcb, op_err);
468		/* queuing will steal away the mbuf chain to the out queue */
469		op_err = NULL;
470	}
471	/* extract the cookie and queue it to "echo" it back... */
472	if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_THRESHOLD_LOGGING) {
473		sctp_misc_ints(SCTP_THRESHOLD_CLEAR,
474		    stcb->asoc.overall_error_count,
475		    0,
476		    SCTP_FROM_SCTP_INPUT,
477		    __LINE__);
478	}
479	stcb->asoc.overall_error_count = 0;
480	net->error_count = 0;
481
482	/*
483	 * Cancel the INIT timer, We do this first before queueing the
484	 * cookie. We always cancel at the primary to assue that we are
485	 * canceling the timer started by the INIT which always goes to the
486	 * primary.
487	 */
488	sctp_timer_stop(SCTP_TIMER_TYPE_INIT, stcb->sctp_ep, stcb,
489	    asoc->primary_destination, SCTP_FROM_SCTP_INPUT + SCTP_LOC_4);
490
491	/* calculate the RTO */
492	net->RTO = sctp_calculate_rto(stcb, asoc, net, &asoc->time_entered, sctp_align_safe_nocopy,
493	    SCTP_RTT_FROM_NON_DATA);
494
495	retval = sctp_send_cookie_echo(m, offset, stcb, net);
496	if (retval < 0) {
497		/*
498		 * No cookie, we probably should send a op error. But in any
499		 * case if there is no cookie in the INIT-ACK, we can
500		 * abandon the peer, its broke.
501		 */
502		if (retval == -3) {
503			/* We abort with an error of missing mandatory param */
504			op_err =
505			    sctp_generate_invmanparam(SCTP_CAUSE_MISSING_PARAM);
506			if (op_err) {
507				/*
508				 * Expand beyond to include the mandatory
509				 * param cookie
510				 */
511				struct sctp_inv_mandatory_param *mp;
512
513				SCTP_BUF_LEN(op_err) =
514				    sizeof(struct sctp_inv_mandatory_param);
515				mp = mtod(op_err,
516				    struct sctp_inv_mandatory_param *);
517				/* Subtract the reserved param */
518				mp->length =
519				    htons(sizeof(struct sctp_inv_mandatory_param) - 2);
520				mp->num_param = htonl(1);
521				mp->param = htons(SCTP_STATE_COOKIE);
522				mp->resv = 0;
523			}
524			sctp_abort_association(stcb->sctp_ep, stcb, m, iphlen,
525			    sh, op_err, vrf_id, net->port);
526			*abort_no_unlock = 1;
527		}
528		return (retval);
529	}
530	return (0);
531}
532
533static void
534sctp_handle_heartbeat_ack(struct sctp_heartbeat_chunk *cp,
535    struct sctp_tcb *stcb, struct sctp_nets *net)
536{
537	struct sockaddr_storage store;
538	struct sctp_nets *r_net, *f_net;
539	struct timeval tv;
540	int req_prim = 0;
541	uint16_t old_error_counter;
542
543#ifdef INET
544	struct sockaddr_in *sin;
545
546#endif
547#ifdef INET6
548	struct sockaddr_in6 *sin6;
549
550#endif
551
552	if (ntohs(cp->ch.chunk_length) != sizeof(struct sctp_heartbeat_chunk)) {
553		/* Invalid length */
554		return;
555	}
556	memset(&store, 0, sizeof(store));
557	switch (cp->heartbeat.hb_info.addr_family) {
558#ifdef INET
559	case AF_INET:
560		if (cp->heartbeat.hb_info.addr_len == sizeof(struct sockaddr_in)) {
561			sin = (struct sockaddr_in *)&store;
562			sin->sin_family = cp->heartbeat.hb_info.addr_family;
563			sin->sin_len = cp->heartbeat.hb_info.addr_len;
564			sin->sin_port = stcb->rport;
565			memcpy(&sin->sin_addr, cp->heartbeat.hb_info.address,
566			    sizeof(sin->sin_addr));
567		} else {
568			return;
569		}
570		break;
571#endif
572#ifdef INET6
573	case AF_INET6:
574		if (cp->heartbeat.hb_info.addr_len == sizeof(struct sockaddr_in6)) {
575			sin6 = (struct sockaddr_in6 *)&store;
576			sin6->sin6_family = cp->heartbeat.hb_info.addr_family;
577			sin6->sin6_len = cp->heartbeat.hb_info.addr_len;
578			sin6->sin6_port = stcb->rport;
579			memcpy(&sin6->sin6_addr, cp->heartbeat.hb_info.address,
580			    sizeof(sin6->sin6_addr));
581		} else {
582			return;
583		}
584		break;
585#endif
586	default:
587		return;
588	}
589	r_net = sctp_findnet(stcb, (struct sockaddr *)&store);
590	if (r_net == NULL) {
591		SCTPDBG(SCTP_DEBUG_INPUT1, "Huh? I can't find the address I sent it to, discard\n");
592		return;
593	}
594	if ((r_net && (r_net->dest_state & SCTP_ADDR_UNCONFIRMED)) &&
595	    (r_net->heartbeat_random1 == cp->heartbeat.hb_info.random_value1) &&
596	    (r_net->heartbeat_random2 == cp->heartbeat.hb_info.random_value2)) {
597		/*
598		 * If the its a HB and it's random value is correct when can
599		 * confirm the destination.
600		 */
601		r_net->dest_state &= ~SCTP_ADDR_UNCONFIRMED;
602		if (r_net->dest_state & SCTP_ADDR_REQ_PRIMARY) {
603			stcb->asoc.primary_destination = r_net;
604			r_net->dest_state &= ~SCTP_ADDR_REQ_PRIMARY;
605			f_net = TAILQ_FIRST(&stcb->asoc.nets);
606			if (f_net != r_net) {
607				/*
608				 * first one on the list is NOT the primary
609				 * sctp_cmpaddr() is much more efficent if
610				 * the primary is the first on the list,
611				 * make it so.
612				 */
613				TAILQ_REMOVE(&stcb->asoc.nets, r_net, sctp_next);
614				TAILQ_INSERT_HEAD(&stcb->asoc.nets, r_net, sctp_next);
615			}
616			req_prim = 1;
617		}
618		sctp_ulp_notify(SCTP_NOTIFY_INTERFACE_CONFIRMED,
619		    stcb, 0, (void *)r_net, SCTP_SO_NOT_LOCKED);
620		sctp_timer_stop(SCTP_TIMER_TYPE_HEARTBEAT, stcb->sctp_ep, stcb, r_net, SCTP_FROM_SCTP_INPUT + SCTP_LOC_3);
621		sctp_timer_start(SCTP_TIMER_TYPE_HEARTBEAT, stcb->sctp_ep, stcb, r_net);
622	}
623	old_error_counter = r_net->error_count;
624	r_net->error_count = 0;
625	r_net->hb_responded = 1;
626	tv.tv_sec = cp->heartbeat.hb_info.time_value_1;
627	tv.tv_usec = cp->heartbeat.hb_info.time_value_2;
628	/* Now lets do a RTO with this */
629	r_net->RTO = sctp_calculate_rto(stcb, &stcb->asoc, r_net, &tv, sctp_align_safe_nocopy,
630	    SCTP_RTT_FROM_NON_DATA);
631	if (!(r_net->dest_state & SCTP_ADDR_REACHABLE)) {
632		r_net->dest_state |= SCTP_ADDR_REACHABLE;
633		sctp_ulp_notify(SCTP_NOTIFY_INTERFACE_UP, stcb,
634		    0, (void *)r_net, SCTP_SO_NOT_LOCKED);
635	}
636	if (r_net->dest_state & SCTP_ADDR_PF) {
637		r_net->dest_state &= ~SCTP_ADDR_PF;
638		stcb->asoc.cc_functions.sctp_cwnd_update_exit_pf(stcb, net);
639	}
640	if (old_error_counter > 0) {
641		sctp_timer_stop(SCTP_TIMER_TYPE_HEARTBEAT, stcb->sctp_ep, stcb, r_net, SCTP_FROM_SCTP_INPUT + SCTP_LOC_3);
642		sctp_timer_start(SCTP_TIMER_TYPE_HEARTBEAT, stcb->sctp_ep, stcb, r_net);
643	}
644	if (r_net == stcb->asoc.primary_destination) {
645		if (stcb->asoc.alternate) {
646			/* release the alternate, primary is good */
647			sctp_free_remote_addr(stcb->asoc.alternate);
648			stcb->asoc.alternate = NULL;
649		}
650	}
651	/* Mobility adaptation */
652	if (req_prim) {
653		if ((sctp_is_mobility_feature_on(stcb->sctp_ep,
654		    SCTP_MOBILITY_BASE) ||
655		    sctp_is_mobility_feature_on(stcb->sctp_ep,
656		    SCTP_MOBILITY_FASTHANDOFF)) &&
657		    sctp_is_mobility_feature_on(stcb->sctp_ep,
658		    SCTP_MOBILITY_PRIM_DELETED)) {
659
660			sctp_timer_stop(SCTP_TIMER_TYPE_PRIM_DELETED, stcb->sctp_ep, stcb, NULL, SCTP_FROM_SCTP_TIMER + SCTP_LOC_7);
661			if (sctp_is_mobility_feature_on(stcb->sctp_ep,
662			    SCTP_MOBILITY_FASTHANDOFF)) {
663				sctp_assoc_immediate_retrans(stcb,
664				    stcb->asoc.primary_destination);
665			}
666			if (sctp_is_mobility_feature_on(stcb->sctp_ep,
667			    SCTP_MOBILITY_BASE)) {
668				sctp_move_chunks_from_net(stcb,
669				    stcb->asoc.deleted_primary);
670			}
671			sctp_delete_prim_timer(stcb->sctp_ep, stcb,
672			    stcb->asoc.deleted_primary);
673		}
674	}
675}
676
677static int
678sctp_handle_nat_colliding_state(struct sctp_tcb *stcb)
679{
680	/*
681	 * return 0 means we want you to proceed with the abort non-zero
682	 * means no abort processing
683	 */
684	struct sctpasochead *head;
685
686	if (SCTP_GET_STATE(&stcb->asoc) == SCTP_STATE_COOKIE_WAIT) {
687		/* generate a new vtag and send init */
688		LIST_REMOVE(stcb, sctp_asocs);
689		stcb->asoc.my_vtag = sctp_select_a_tag(stcb->sctp_ep, stcb->sctp_ep->sctp_lport, stcb->rport, 1);
690		head = &SCTP_BASE_INFO(sctp_asochash)[SCTP_PCBHASH_ASOC(stcb->asoc.my_vtag, SCTP_BASE_INFO(hashasocmark))];
691		/*
692		 * put it in the bucket in the vtag hash of assoc's for the
693		 * system
694		 */
695		LIST_INSERT_HEAD(head, stcb, sctp_asocs);
696		sctp_send_initiate(stcb->sctp_ep, stcb, SCTP_SO_NOT_LOCKED);
697		return (1);
698	}
699	if (SCTP_GET_STATE(&stcb->asoc) == SCTP_STATE_COOKIE_ECHOED) {
700		/*
701		 * treat like a case where the cookie expired i.e.: - dump
702		 * current cookie. - generate a new vtag. - resend init.
703		 */
704		/* generate a new vtag and send init */
705		LIST_REMOVE(stcb, sctp_asocs);
706		stcb->asoc.state &= ~SCTP_STATE_COOKIE_ECHOED;
707		stcb->asoc.state |= SCTP_STATE_COOKIE_WAIT;
708		sctp_stop_all_cookie_timers(stcb);
709		sctp_toss_old_cookies(stcb, &stcb->asoc);
710		stcb->asoc.my_vtag = sctp_select_a_tag(stcb->sctp_ep, stcb->sctp_ep->sctp_lport, stcb->rport, 1);
711		head = &SCTP_BASE_INFO(sctp_asochash)[SCTP_PCBHASH_ASOC(stcb->asoc.my_vtag, SCTP_BASE_INFO(hashasocmark))];
712		/*
713		 * put it in the bucket in the vtag hash of assoc's for the
714		 * system
715		 */
716		LIST_INSERT_HEAD(head, stcb, sctp_asocs);
717		sctp_send_initiate(stcb->sctp_ep, stcb, SCTP_SO_NOT_LOCKED);
718		return (1);
719	}
720	return (0);
721}
722
723static int
724sctp_handle_nat_missing_state(struct sctp_tcb *stcb,
725    struct sctp_nets *net)
726{
727	/*
728	 * return 0 means we want you to proceed with the abort non-zero
729	 * means no abort processing
730	 */
731	if (stcb->asoc.peer_supports_auth == 0) {
732		SCTPDBG(SCTP_DEBUG_INPUT2, "sctp_handle_nat_missing_state: Peer does not support AUTH, cannot send an asconf\n");
733		return (0);
734	}
735	sctp_asconf_send_nat_state_update(stcb, net);
736	return (1);
737}
738
739
740static void
741sctp_handle_abort(struct sctp_abort_chunk *abort,
742    struct sctp_tcb *stcb, struct sctp_nets *net)
743{
744#if defined (__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
745	struct socket *so;
746
747#endif
748	uint16_t len;
749	uint16_t error;
750
751	SCTPDBG(SCTP_DEBUG_INPUT2, "sctp_handle_abort: handling ABORT\n");
752	if (stcb == NULL)
753		return;
754
755	len = ntohs(abort->ch.chunk_length);
756	if (len > sizeof(struct sctp_chunkhdr)) {
757		/*
758		 * Need to check the cause codes for our two magic nat
759		 * aborts which don't kill the assoc necessarily.
760		 */
761		struct sctp_missing_nat_state *natc;
762
763		natc = (struct sctp_missing_nat_state *)(abort + 1);
764		error = ntohs(natc->cause);
765		if (error == SCTP_CAUSE_NAT_COLLIDING_STATE) {
766			SCTPDBG(SCTP_DEBUG_INPUT2, "Received Colliding state abort flags:%x\n",
767			    abort->ch.chunk_flags);
768			if (sctp_handle_nat_colliding_state(stcb)) {
769				return;
770			}
771		} else if (error == SCTP_CAUSE_NAT_MISSING_STATE) {
772			SCTPDBG(SCTP_DEBUG_INPUT2, "Received missing state abort flags:%x\n",
773			    abort->ch.chunk_flags);
774			if (sctp_handle_nat_missing_state(stcb, net)) {
775				return;
776			}
777		}
778	} else {
779		error = 0;
780	}
781	/* stop any receive timers */
782	sctp_timer_stop(SCTP_TIMER_TYPE_RECV, stcb->sctp_ep, stcb, net, SCTP_FROM_SCTP_INPUT + SCTP_LOC_6);
783	/* notify user of the abort and clean up... */
784	sctp_abort_notification(stcb, 1, error, abort, SCTP_SO_NOT_LOCKED);
785	/* free the tcb */
786	SCTP_STAT_INCR_COUNTER32(sctps_aborted);
787	if ((SCTP_GET_STATE(&stcb->asoc) == SCTP_STATE_OPEN) ||
788	    (SCTP_GET_STATE(&stcb->asoc) == SCTP_STATE_SHUTDOWN_RECEIVED)) {
789		SCTP_STAT_DECR_GAUGE32(sctps_currestab);
790	}
791#ifdef SCTP_ASOCLOG_OF_TSNS
792	sctp_print_out_track_log(stcb);
793#endif
794#if defined (__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
795	so = SCTP_INP_SO(stcb->sctp_ep);
796	atomic_add_int(&stcb->asoc.refcnt, 1);
797	SCTP_TCB_UNLOCK(stcb);
798	SCTP_SOCKET_LOCK(so, 1);
799	SCTP_TCB_LOCK(stcb);
800	atomic_subtract_int(&stcb->asoc.refcnt, 1);
801#endif
802	stcb->asoc.state |= SCTP_STATE_WAS_ABORTED;
803	(void)sctp_free_assoc(stcb->sctp_ep, stcb, SCTP_NORMAL_PROC,
804	    SCTP_FROM_SCTP_INPUT + SCTP_LOC_6);
805#if defined (__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
806	SCTP_SOCKET_UNLOCK(so, 1);
807#endif
808	SCTPDBG(SCTP_DEBUG_INPUT2, "sctp_handle_abort: finished\n");
809}
810
811static void
812sctp_start_net_timers(struct sctp_tcb *stcb)
813{
814	uint32_t cnt_hb_sent;
815	struct sctp_nets *net;
816
817	cnt_hb_sent = 0;
818	TAILQ_FOREACH(net, &stcb->asoc.nets, sctp_next) {
819		/*
820		 * For each network start: 1) A pmtu timer. 2) A HB timer 3)
821		 * If the dest in unconfirmed send a hb as well if under
822		 * max_hb_burst have been sent.
823		 */
824		sctp_timer_start(SCTP_TIMER_TYPE_PATHMTURAISE, stcb->sctp_ep, stcb, net);
825		sctp_timer_start(SCTP_TIMER_TYPE_HEARTBEAT, stcb->sctp_ep, stcb, net);
826		if ((net->dest_state & SCTP_ADDR_UNCONFIRMED) &&
827		    (cnt_hb_sent < SCTP_BASE_SYSCTL(sctp_hb_maxburst))) {
828			sctp_send_hb(stcb, net, SCTP_SO_NOT_LOCKED);
829			cnt_hb_sent++;
830		}
831	}
832	if (cnt_hb_sent) {
833		sctp_chunk_output(stcb->sctp_ep, stcb,
834		    SCTP_OUTPUT_FROM_COOKIE_ACK,
835		    SCTP_SO_NOT_LOCKED);
836	}
837}
838
839
840static void
841sctp_handle_shutdown(struct sctp_shutdown_chunk *cp,
842    struct sctp_tcb *stcb, struct sctp_nets *net, int *abort_flag)
843{
844	struct sctp_association *asoc;
845	int some_on_streamwheel;
846
847#if defined (__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
848	struct socket *so;
849
850#endif
851
852	SCTPDBG(SCTP_DEBUG_INPUT2,
853	    "sctp_handle_shutdown: handling SHUTDOWN\n");
854	if (stcb == NULL)
855		return;
856	asoc = &stcb->asoc;
857	if ((SCTP_GET_STATE(asoc) == SCTP_STATE_COOKIE_WAIT) ||
858	    (SCTP_GET_STATE(asoc) == SCTP_STATE_COOKIE_ECHOED)) {
859		return;
860	}
861	if (ntohs(cp->ch.chunk_length) != sizeof(struct sctp_shutdown_chunk)) {
862		/* Shutdown NOT the expected size */
863		return;
864	} else {
865		sctp_update_acked(stcb, cp, abort_flag);
866		if (*abort_flag) {
867			return;
868		}
869	}
870	if (asoc->control_pdapi) {
871		/*
872		 * With a normal shutdown we assume the end of last record.
873		 */
874		SCTP_INP_READ_LOCK(stcb->sctp_ep);
875		asoc->control_pdapi->end_added = 1;
876		asoc->control_pdapi->pdapi_aborted = 1;
877		asoc->control_pdapi = NULL;
878		SCTP_INP_READ_UNLOCK(stcb->sctp_ep);
879#if defined (__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
880		so = SCTP_INP_SO(stcb->sctp_ep);
881		atomic_add_int(&stcb->asoc.refcnt, 1);
882		SCTP_TCB_UNLOCK(stcb);
883		SCTP_SOCKET_LOCK(so, 1);
884		SCTP_TCB_LOCK(stcb);
885		atomic_subtract_int(&stcb->asoc.refcnt, 1);
886		if (stcb->asoc.state & SCTP_STATE_CLOSED_SOCKET) {
887			/* assoc was freed while we were unlocked */
888			SCTP_SOCKET_UNLOCK(so, 1);
889			return;
890		}
891#endif
892		sctp_sorwakeup(stcb->sctp_ep, stcb->sctp_socket);
893#if defined (__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
894		SCTP_SOCKET_UNLOCK(so, 1);
895#endif
896	}
897	/* goto SHUTDOWN_RECEIVED state to block new requests */
898	if (stcb->sctp_socket) {
899		if ((SCTP_GET_STATE(asoc) != SCTP_STATE_SHUTDOWN_RECEIVED) &&
900		    (SCTP_GET_STATE(asoc) != SCTP_STATE_SHUTDOWN_ACK_SENT) &&
901		    (SCTP_GET_STATE(asoc) != SCTP_STATE_SHUTDOWN_SENT)) {
902			SCTP_SET_STATE(asoc, SCTP_STATE_SHUTDOWN_RECEIVED);
903			SCTP_CLEAR_SUBSTATE(asoc, SCTP_STATE_SHUTDOWN_PENDING);
904			/*
905			 * notify upper layer that peer has initiated a
906			 * shutdown
907			 */
908			sctp_ulp_notify(SCTP_NOTIFY_PEER_SHUTDOWN, stcb, 0, NULL, SCTP_SO_NOT_LOCKED);
909
910			/* reset time */
911			(void)SCTP_GETTIME_TIMEVAL(&asoc->time_entered);
912		}
913	}
914	if (SCTP_GET_STATE(asoc) == SCTP_STATE_SHUTDOWN_SENT) {
915		/*
916		 * stop the shutdown timer, since we WILL move to
917		 * SHUTDOWN-ACK-SENT.
918		 */
919		sctp_timer_stop(SCTP_TIMER_TYPE_SHUTDOWN, stcb->sctp_ep, stcb, net, SCTP_FROM_SCTP_INPUT + SCTP_LOC_8);
920	}
921	/* Now is there unsent data on a stream somewhere? */
922	some_on_streamwheel = sctp_is_there_unsent_data(stcb, SCTP_SO_NOT_LOCKED);
923
924	if (!TAILQ_EMPTY(&asoc->send_queue) ||
925	    !TAILQ_EMPTY(&asoc->sent_queue) ||
926	    some_on_streamwheel) {
927		/* By returning we will push more data out */
928		return;
929	} else {
930		/* no outstanding data to send, so move on... */
931		/* send SHUTDOWN-ACK */
932		sctp_send_shutdown_ack(stcb, net);
933		/* move to SHUTDOWN-ACK-SENT state */
934		if ((SCTP_GET_STATE(asoc) == SCTP_STATE_OPEN) ||
935		    (SCTP_GET_STATE(asoc) == SCTP_STATE_SHUTDOWN_RECEIVED)) {
936			SCTP_STAT_DECR_GAUGE32(sctps_currestab);
937		}
938		SCTP_SET_STATE(asoc, SCTP_STATE_SHUTDOWN_ACK_SENT);
939		SCTP_CLEAR_SUBSTATE(asoc, SCTP_STATE_SHUTDOWN_PENDING);
940		sctp_stop_timers_for_shutdown(stcb);
941		sctp_timer_start(SCTP_TIMER_TYPE_SHUTDOWNACK, stcb->sctp_ep,
942		    stcb, net);
943	}
944}
945
946static void
947sctp_handle_shutdown_ack(struct sctp_shutdown_ack_chunk *cp SCTP_UNUSED,
948    struct sctp_tcb *stcb,
949    struct sctp_nets *net)
950{
951	struct sctp_association *asoc;
952
953#if defined (__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
954	struct socket *so;
955
956	so = SCTP_INP_SO(stcb->sctp_ep);
957#endif
958	SCTPDBG(SCTP_DEBUG_INPUT2,
959	    "sctp_handle_shutdown_ack: handling SHUTDOWN ACK\n");
960	if (stcb == NULL)
961		return;
962
963	asoc = &stcb->asoc;
964	/* process according to association state */
965	if ((SCTP_GET_STATE(asoc) == SCTP_STATE_COOKIE_WAIT) ||
966	    (SCTP_GET_STATE(asoc) == SCTP_STATE_COOKIE_ECHOED)) {
967		/* unexpected SHUTDOWN-ACK... do OOTB handling... */
968		sctp_send_shutdown_complete(stcb, net, 1);
969		SCTP_TCB_UNLOCK(stcb);
970		return;
971	}
972	if ((SCTP_GET_STATE(asoc) != SCTP_STATE_SHUTDOWN_SENT) &&
973	    (SCTP_GET_STATE(asoc) != SCTP_STATE_SHUTDOWN_ACK_SENT)) {
974		/* unexpected SHUTDOWN-ACK... so ignore... */
975		SCTP_TCB_UNLOCK(stcb);
976		return;
977	}
978	if (asoc->control_pdapi) {
979		/*
980		 * With a normal shutdown we assume the end of last record.
981		 */
982		SCTP_INP_READ_LOCK(stcb->sctp_ep);
983		asoc->control_pdapi->end_added = 1;
984		asoc->control_pdapi->pdapi_aborted = 1;
985		asoc->control_pdapi = NULL;
986		SCTP_INP_READ_UNLOCK(stcb->sctp_ep);
987#if defined (__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
988		atomic_add_int(&stcb->asoc.refcnt, 1);
989		SCTP_TCB_UNLOCK(stcb);
990		SCTP_SOCKET_LOCK(so, 1);
991		SCTP_TCB_LOCK(stcb);
992		atomic_subtract_int(&stcb->asoc.refcnt, 1);
993		if (stcb->asoc.state & SCTP_STATE_CLOSED_SOCKET) {
994			/* assoc was freed while we were unlocked */
995			SCTP_SOCKET_UNLOCK(so, 1);
996			return;
997		}
998#endif
999		sctp_sorwakeup(stcb->sctp_ep, stcb->sctp_socket);
1000#if defined (__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
1001		SCTP_SOCKET_UNLOCK(so, 1);
1002#endif
1003	}
1004	/* are the queues empty? */
1005	if (!TAILQ_EMPTY(&asoc->send_queue) ||
1006	    !TAILQ_EMPTY(&asoc->sent_queue) ||
1007	    !stcb->asoc.ss_functions.sctp_ss_is_empty(stcb, asoc)) {
1008		sctp_report_all_outbound(stcb, 0, 0, SCTP_SO_NOT_LOCKED);
1009	}
1010	/* stop the timer */
1011	sctp_timer_stop(SCTP_TIMER_TYPE_SHUTDOWN, stcb->sctp_ep, stcb, net, SCTP_FROM_SCTP_INPUT + SCTP_LOC_9);
1012	/* send SHUTDOWN-COMPLETE */
1013	sctp_send_shutdown_complete(stcb, net, 0);
1014	/* notify upper layer protocol */
1015	if (stcb->sctp_socket) {
1016		if ((stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE) ||
1017		    (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL)) {
1018			stcb->sctp_socket->so_snd.sb_cc = 0;
1019		}
1020		sctp_ulp_notify(SCTP_NOTIFY_ASSOC_DOWN, stcb, 0, NULL, SCTP_SO_NOT_LOCKED);
1021	}
1022	SCTP_STAT_INCR_COUNTER32(sctps_shutdown);
1023	/* free the TCB but first save off the ep */
1024#if defined (__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
1025	atomic_add_int(&stcb->asoc.refcnt, 1);
1026	SCTP_TCB_UNLOCK(stcb);
1027	SCTP_SOCKET_LOCK(so, 1);
1028	SCTP_TCB_LOCK(stcb);
1029	atomic_subtract_int(&stcb->asoc.refcnt, 1);
1030#endif
1031	(void)sctp_free_assoc(stcb->sctp_ep, stcb, SCTP_NORMAL_PROC,
1032	    SCTP_FROM_SCTP_INPUT + SCTP_LOC_10);
1033#if defined (__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
1034	SCTP_SOCKET_UNLOCK(so, 1);
1035#endif
1036}
1037
1038/*
1039 * Skip past the param header and then we will find the chunk that caused the
1040 * problem. There are two possiblities ASCONF or FWD-TSN other than that and
1041 * our peer must be broken.
1042 */
1043static void
1044sctp_process_unrecog_chunk(struct sctp_tcb *stcb, struct sctp_paramhdr *phdr,
1045    struct sctp_nets *net)
1046{
1047	struct sctp_chunkhdr *chk;
1048
1049	chk = (struct sctp_chunkhdr *)((caddr_t)phdr + sizeof(*phdr));
1050	switch (chk->chunk_type) {
1051	case SCTP_ASCONF_ACK:
1052	case SCTP_ASCONF:
1053		sctp_asconf_cleanup(stcb, net);
1054		break;
1055	case SCTP_FORWARD_CUM_TSN:
1056		stcb->asoc.peer_supports_prsctp = 0;
1057		break;
1058	default:
1059		SCTPDBG(SCTP_DEBUG_INPUT2,
1060		    "Peer does not support chunk type %d(%x)??\n",
1061		    chk->chunk_type, (uint32_t) chk->chunk_type);
1062		break;
1063	}
1064}
1065
1066/*
1067 * Skip past the param header and then we will find the param that caused the
1068 * problem.  There are a number of param's in a ASCONF OR the prsctp param
1069 * these will turn of specific features.
1070 */
1071static void
1072sctp_process_unrecog_param(struct sctp_tcb *stcb, struct sctp_paramhdr *phdr)
1073{
1074	struct sctp_paramhdr *pbad;
1075
1076	pbad = phdr + 1;
1077	switch (ntohs(pbad->param_type)) {
1078		/* pr-sctp draft */
1079	case SCTP_PRSCTP_SUPPORTED:
1080		stcb->asoc.peer_supports_prsctp = 0;
1081		break;
1082	case SCTP_SUPPORTED_CHUNK_EXT:
1083		break;
1084		/* draft-ietf-tsvwg-addip-sctp */
1085	case SCTP_HAS_NAT_SUPPORT:
1086		stcb->asoc.peer_supports_nat = 0;
1087		break;
1088	case SCTP_ADD_IP_ADDRESS:
1089	case SCTP_DEL_IP_ADDRESS:
1090	case SCTP_SET_PRIM_ADDR:
1091		stcb->asoc.peer_supports_asconf = 0;
1092		break;
1093	case SCTP_SUCCESS_REPORT:
1094	case SCTP_ERROR_CAUSE_IND:
1095		SCTPDBG(SCTP_DEBUG_INPUT2, "Huh, the peer does not support success? or error cause?\n");
1096		SCTPDBG(SCTP_DEBUG_INPUT2,
1097		    "Turning off ASCONF to this strange peer\n");
1098		stcb->asoc.peer_supports_asconf = 0;
1099		break;
1100	default:
1101		SCTPDBG(SCTP_DEBUG_INPUT2,
1102		    "Peer does not support param type %d(%x)??\n",
1103		    pbad->param_type, (uint32_t) pbad->param_type);
1104		break;
1105	}
1106}
1107
1108static int
1109sctp_handle_error(struct sctp_chunkhdr *ch,
1110    struct sctp_tcb *stcb, struct sctp_nets *net)
1111{
1112	int chklen;
1113	struct sctp_paramhdr *phdr;
1114	uint16_t error_type;
1115	uint16_t error_len;
1116	struct sctp_association *asoc;
1117	int adjust;
1118
1119#if defined (__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
1120	struct socket *so;
1121
1122#endif
1123
1124	/* parse through all of the errors and process */
1125	asoc = &stcb->asoc;
1126	phdr = (struct sctp_paramhdr *)((caddr_t)ch +
1127	    sizeof(struct sctp_chunkhdr));
1128	chklen = ntohs(ch->chunk_length) - sizeof(struct sctp_chunkhdr);
1129	while ((size_t)chklen >= sizeof(struct sctp_paramhdr)) {
1130		/* Process an Error Cause */
1131		error_type = ntohs(phdr->param_type);
1132		error_len = ntohs(phdr->param_length);
1133		if ((error_len > chklen) || (error_len == 0)) {
1134			/* invalid param length for this param */
1135			SCTPDBG(SCTP_DEBUG_INPUT1, "Bogus length in error param- chunk left:%d errorlen:%d\n",
1136			    chklen, error_len);
1137			return (0);
1138		}
1139		switch (error_type) {
1140		case SCTP_CAUSE_INVALID_STREAM:
1141		case SCTP_CAUSE_MISSING_PARAM:
1142		case SCTP_CAUSE_INVALID_PARAM:
1143		case SCTP_CAUSE_NO_USER_DATA:
1144			SCTPDBG(SCTP_DEBUG_INPUT1, "Software error we got a %d back? We have a bug :/ (or do they?)\n",
1145			    error_type);
1146			break;
1147		case SCTP_CAUSE_NAT_COLLIDING_STATE:
1148			SCTPDBG(SCTP_DEBUG_INPUT2, "Received Colliding state abort flags:%x\n",
1149			    ch->chunk_flags);
1150			if (sctp_handle_nat_colliding_state(stcb)) {
1151				return (0);
1152			}
1153			break;
1154		case SCTP_CAUSE_NAT_MISSING_STATE:
1155			SCTPDBG(SCTP_DEBUG_INPUT2, "Received missing state abort flags:%x\n",
1156			    ch->chunk_flags);
1157			if (sctp_handle_nat_missing_state(stcb, net)) {
1158				return (0);
1159			}
1160			break;
1161		case SCTP_CAUSE_STALE_COOKIE:
1162			/*
1163			 * We only act if we have echoed a cookie and are
1164			 * waiting.
1165			 */
1166			if (SCTP_GET_STATE(asoc) == SCTP_STATE_COOKIE_ECHOED) {
1167				int *p;
1168
1169				p = (int *)((caddr_t)phdr + sizeof(*phdr));
1170				/* Save the time doubled */
1171				asoc->cookie_preserve_req = ntohl(*p) << 1;
1172				asoc->stale_cookie_count++;
1173				if (asoc->stale_cookie_count >
1174				    asoc->max_init_times) {
1175					sctp_abort_notification(stcb, 0, 0, NULL, SCTP_SO_NOT_LOCKED);
1176					/* now free the asoc */
1177#if defined (__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
1178					so = SCTP_INP_SO(stcb->sctp_ep);
1179					atomic_add_int(&stcb->asoc.refcnt, 1);
1180					SCTP_TCB_UNLOCK(stcb);
1181					SCTP_SOCKET_LOCK(so, 1);
1182					SCTP_TCB_LOCK(stcb);
1183					atomic_subtract_int(&stcb->asoc.refcnt, 1);
1184#endif
1185					(void)sctp_free_assoc(stcb->sctp_ep, stcb, SCTP_NORMAL_PROC,
1186					    SCTP_FROM_SCTP_INPUT + SCTP_LOC_11);
1187#if defined (__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
1188					SCTP_SOCKET_UNLOCK(so, 1);
1189#endif
1190					return (-1);
1191				}
1192				/* blast back to INIT state */
1193				sctp_toss_old_cookies(stcb, &stcb->asoc);
1194				asoc->state &= ~SCTP_STATE_COOKIE_ECHOED;
1195				asoc->state |= SCTP_STATE_COOKIE_WAIT;
1196				sctp_stop_all_cookie_timers(stcb);
1197				sctp_send_initiate(stcb->sctp_ep, stcb, SCTP_SO_NOT_LOCKED);
1198			}
1199			break;
1200		case SCTP_CAUSE_UNRESOLVABLE_ADDR:
1201			/*
1202			 * Nothing we can do here, we don't do hostname
1203			 * addresses so if the peer does not like my IPv6
1204			 * (or IPv4 for that matter) it does not matter. If
1205			 * they don't support that type of address, they can
1206			 * NOT possibly get that packet type... i.e. with no
1207			 * IPv6 you can't recieve a IPv6 packet. so we can
1208			 * safely ignore this one. If we ever added support
1209			 * for HOSTNAME Addresses, then we would need to do
1210			 * something here.
1211			 */
1212			break;
1213		case SCTP_CAUSE_UNRECOG_CHUNK:
1214			sctp_process_unrecog_chunk(stcb, phdr, net);
1215			break;
1216		case SCTP_CAUSE_UNRECOG_PARAM:
1217			sctp_process_unrecog_param(stcb, phdr);
1218			break;
1219		case SCTP_CAUSE_COOKIE_IN_SHUTDOWN:
1220			/*
1221			 * We ignore this since the timer will drive out a
1222			 * new cookie anyway and there timer will drive us
1223			 * to send a SHUTDOWN_COMPLETE. We can't send one
1224			 * here since we don't have their tag.
1225			 */
1226			break;
1227		case SCTP_CAUSE_DELETING_LAST_ADDR:
1228		case SCTP_CAUSE_RESOURCE_SHORTAGE:
1229		case SCTP_CAUSE_DELETING_SRC_ADDR:
1230			/*
1231			 * We should NOT get these here, but in a
1232			 * ASCONF-ACK.
1233			 */
1234			SCTPDBG(SCTP_DEBUG_INPUT2, "Peer sends ASCONF errors in a Operational Error?<%d>?\n",
1235			    error_type);
1236			break;
1237		case SCTP_CAUSE_OUT_OF_RESC:
1238			/*
1239			 * And what, pray tell do we do with the fact that
1240			 * the peer is out of resources? Not really sure we
1241			 * could do anything but abort. I suspect this
1242			 * should have came WITH an abort instead of in a
1243			 * OP-ERROR.
1244			 */
1245			break;
1246		default:
1247			SCTPDBG(SCTP_DEBUG_INPUT1, "sctp_handle_error: unknown error type = 0x%xh\n",
1248			    error_type);
1249			break;
1250		}
1251		adjust = SCTP_SIZE32(error_len);
1252		chklen -= adjust;
1253		phdr = (struct sctp_paramhdr *)((caddr_t)phdr + adjust);
1254	}
1255	return (0);
1256}
1257
1258static int
1259sctp_handle_init_ack(struct mbuf *m, int iphlen, int offset,
1260    struct sctphdr *sh, struct sctp_init_ack_chunk *cp, struct sctp_tcb *stcb,
1261    struct sctp_nets *net, int *abort_no_unlock, uint32_t vrf_id)
1262{
1263	struct sctp_init_ack *init_ack;
1264	struct mbuf *op_err;
1265
1266	SCTPDBG(SCTP_DEBUG_INPUT2,
1267	    "sctp_handle_init_ack: handling INIT-ACK\n");
1268
1269	if (stcb == NULL) {
1270		SCTPDBG(SCTP_DEBUG_INPUT2,
1271		    "sctp_handle_init_ack: TCB is null\n");
1272		return (-1);
1273	}
1274	if (ntohs(cp->ch.chunk_length) < sizeof(struct sctp_init_ack_chunk)) {
1275		/* Invalid length */
1276		op_err = sctp_generate_invmanparam(SCTP_CAUSE_INVALID_PARAM);
1277		sctp_abort_association(stcb->sctp_ep, stcb, m, iphlen, sh,
1278		    op_err, 0, net->port);
1279		*abort_no_unlock = 1;
1280		return (-1);
1281	}
1282	init_ack = &cp->init;
1283	/* validate parameters */
1284	if (init_ack->initiate_tag == 0) {
1285		/* protocol error... send an abort */
1286		op_err = sctp_generate_invmanparam(SCTP_CAUSE_INVALID_PARAM);
1287		sctp_abort_association(stcb->sctp_ep, stcb, m, iphlen, sh,
1288		    op_err, 0, net->port);
1289		*abort_no_unlock = 1;
1290		return (-1);
1291	}
1292	if (ntohl(init_ack->a_rwnd) < SCTP_MIN_RWND) {
1293		/* protocol error... send an abort */
1294		op_err = sctp_generate_invmanparam(SCTP_CAUSE_INVALID_PARAM);
1295		sctp_abort_association(stcb->sctp_ep, stcb, m, iphlen, sh,
1296		    op_err, 0, net->port);
1297		*abort_no_unlock = 1;
1298		return (-1);
1299	}
1300	if (init_ack->num_inbound_streams == 0) {
1301		/* protocol error... send an abort */
1302		op_err = sctp_generate_invmanparam(SCTP_CAUSE_INVALID_PARAM);
1303		sctp_abort_association(stcb->sctp_ep, stcb, m, iphlen, sh,
1304		    op_err, 0, net->port);
1305		*abort_no_unlock = 1;
1306		return (-1);
1307	}
1308	if (init_ack->num_outbound_streams == 0) {
1309		/* protocol error... send an abort */
1310		op_err = sctp_generate_invmanparam(SCTP_CAUSE_INVALID_PARAM);
1311		sctp_abort_association(stcb->sctp_ep, stcb, m, iphlen, sh,
1312		    op_err, 0, net->port);
1313		*abort_no_unlock = 1;
1314		return (-1);
1315	}
1316	/* process according to association state... */
1317	switch (stcb->asoc.state & SCTP_STATE_MASK) {
1318	case SCTP_STATE_COOKIE_WAIT:
1319		/* this is the expected state for this chunk */
1320		/* process the INIT-ACK parameters */
1321		if (stcb->asoc.primary_destination->dest_state &
1322		    SCTP_ADDR_UNCONFIRMED) {
1323			/*
1324			 * The primary is where we sent the INIT, we can
1325			 * always consider it confirmed when the INIT-ACK is
1326			 * returned. Do this before we load addresses
1327			 * though.
1328			 */
1329			stcb->asoc.primary_destination->dest_state &=
1330			    ~SCTP_ADDR_UNCONFIRMED;
1331			sctp_ulp_notify(SCTP_NOTIFY_INTERFACE_CONFIRMED,
1332			    stcb, 0, (void *)stcb->asoc.primary_destination, SCTP_SO_NOT_LOCKED);
1333		}
1334		if (sctp_process_init_ack(m, iphlen, offset, sh, cp, stcb,
1335		    net, abort_no_unlock, vrf_id) < 0) {
1336			/* error in parsing parameters */
1337			return (-1);
1338		}
1339		/* update our state */
1340		SCTPDBG(SCTP_DEBUG_INPUT2, "moving to COOKIE-ECHOED state\n");
1341		SCTP_SET_STATE(&stcb->asoc, SCTP_STATE_COOKIE_ECHOED);
1342
1343		/* reset the RTO calc */
1344		if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_THRESHOLD_LOGGING) {
1345			sctp_misc_ints(SCTP_THRESHOLD_CLEAR,
1346			    stcb->asoc.overall_error_count,
1347			    0,
1348			    SCTP_FROM_SCTP_INPUT,
1349			    __LINE__);
1350		}
1351		stcb->asoc.overall_error_count = 0;
1352		(void)SCTP_GETTIME_TIMEVAL(&stcb->asoc.time_entered);
1353		/*
1354		 * collapse the init timer back in case of a exponential
1355		 * backoff
1356		 */
1357		sctp_timer_start(SCTP_TIMER_TYPE_COOKIE, stcb->sctp_ep,
1358		    stcb, net);
1359		/*
1360		 * the send at the end of the inbound data processing will
1361		 * cause the cookie to be sent
1362		 */
1363		break;
1364	case SCTP_STATE_SHUTDOWN_SENT:
1365		/* incorrect state... discard */
1366		break;
1367	case SCTP_STATE_COOKIE_ECHOED:
1368		/* incorrect state... discard */
1369		break;
1370	case SCTP_STATE_OPEN:
1371		/* incorrect state... discard */
1372		break;
1373	case SCTP_STATE_EMPTY:
1374	case SCTP_STATE_INUSE:
1375	default:
1376		/* incorrect state... discard */
1377		return (-1);
1378		break;
1379	}
1380	SCTPDBG(SCTP_DEBUG_INPUT1, "Leaving handle-init-ack end\n");
1381	return (0);
1382}
1383
1384static struct sctp_tcb *
1385sctp_process_cookie_new(struct mbuf *m, int iphlen, int offset,
1386    struct sctphdr *sh, struct sctp_state_cookie *cookie, int cookie_len,
1387    struct sctp_inpcb *inp, struct sctp_nets **netp,
1388    struct sockaddr *init_src, int *notification,
1389    int auth_skipped, uint32_t auth_offset, uint32_t auth_len,
1390    uint32_t vrf_id, uint16_t port);
1391
1392
1393/*
1394 * handle a state cookie for an existing association m: input packet mbuf
1395 * chain-- assumes a pullup on IP/SCTP/COOKIE-ECHO chunk note: this is a
1396 * "split" mbuf and the cookie signature does not exist offset: offset into
1397 * mbuf to the cookie-echo chunk
1398 */
1399static struct sctp_tcb *
1400sctp_process_cookie_existing(struct mbuf *m, int iphlen, int offset,
1401    struct sctphdr *sh, struct sctp_state_cookie *cookie, int cookie_len,
1402    struct sctp_inpcb *inp, struct sctp_tcb *stcb, struct sctp_nets **netp,
1403    struct sockaddr *init_src, int *notification,
1404    uint32_t vrf_id, int auth_skipped, uint32_t auth_offset, uint32_t auth_len, uint16_t port)
1405{
1406	struct sctp_association *asoc;
1407	struct sctp_init_chunk *init_cp, init_buf;
1408	struct sctp_init_ack_chunk *initack_cp, initack_buf;
1409	struct sctp_nets *net;
1410	struct mbuf *op_err;
1411	struct sctp_paramhdr *ph;
1412	int init_offset, initack_offset, i;
1413	int retval;
1414	int spec_flag = 0;
1415	uint32_t how_indx;
1416
1417	net = *netp;
1418	/* I know that the TCB is non-NULL from the caller */
1419	asoc = &stcb->asoc;
1420	for (how_indx = 0; how_indx < sizeof(asoc->cookie_how); how_indx++) {
1421		if (asoc->cookie_how[how_indx] == 0)
1422			break;
1423	}
1424	if (how_indx < sizeof(asoc->cookie_how)) {
1425		asoc->cookie_how[how_indx] = 1;
1426	}
1427	if (SCTP_GET_STATE(asoc) == SCTP_STATE_SHUTDOWN_ACK_SENT) {
1428		/* SHUTDOWN came in after sending INIT-ACK */
1429		sctp_send_shutdown_ack(stcb, stcb->asoc.primary_destination);
1430		op_err = sctp_get_mbuf_for_msg(sizeof(struct sctp_paramhdr),
1431		    0, M_DONTWAIT, 1, MT_DATA);
1432		if (op_err == NULL) {
1433			/* FOOBAR */
1434			return (NULL);
1435		}
1436		/* Set the len */
1437		SCTP_BUF_LEN(op_err) = sizeof(struct sctp_paramhdr);
1438		ph = mtod(op_err, struct sctp_paramhdr *);
1439		ph->param_type = htons(SCTP_CAUSE_COOKIE_IN_SHUTDOWN);
1440		ph->param_length = htons(sizeof(struct sctp_paramhdr));
1441		sctp_send_operr_to(m, iphlen, op_err, cookie->peers_vtag,
1442		    vrf_id, net->port);
1443		if (how_indx < sizeof(asoc->cookie_how))
1444			asoc->cookie_how[how_indx] = 2;
1445		return (NULL);
1446	}
1447	/*
1448	 * find and validate the INIT chunk in the cookie (peer's info) the
1449	 * INIT should start after the cookie-echo header struct (chunk
1450	 * header, state cookie header struct)
1451	 */
1452	init_offset = offset += sizeof(struct sctp_cookie_echo_chunk);
1453
1454	init_cp = (struct sctp_init_chunk *)
1455	    sctp_m_getptr(m, init_offset, sizeof(struct sctp_init_chunk),
1456	    (uint8_t *) & init_buf);
1457	if (init_cp == NULL) {
1458		/* could not pull a INIT chunk in cookie */
1459		return (NULL);
1460	}
1461	if (init_cp->ch.chunk_type != SCTP_INITIATION) {
1462		return (NULL);
1463	}
1464	/*
1465	 * find and validate the INIT-ACK chunk in the cookie (my info) the
1466	 * INIT-ACK follows the INIT chunk
1467	 */
1468	initack_offset = init_offset + SCTP_SIZE32(ntohs(init_cp->ch.chunk_length));
1469	initack_cp = (struct sctp_init_ack_chunk *)
1470	    sctp_m_getptr(m, initack_offset, sizeof(struct sctp_init_ack_chunk),
1471	    (uint8_t *) & initack_buf);
1472	if (initack_cp == NULL) {
1473		/* could not pull INIT-ACK chunk in cookie */
1474		return (NULL);
1475	}
1476	if (initack_cp->ch.chunk_type != SCTP_INITIATION_ACK) {
1477		return (NULL);
1478	}
1479	if ((ntohl(initack_cp->init.initiate_tag) == asoc->my_vtag) &&
1480	    (ntohl(init_cp->init.initiate_tag) == asoc->peer_vtag)) {
1481		/*
1482		 * case D in Section 5.2.4 Table 2: MMAA process accordingly
1483		 * to get into the OPEN state
1484		 */
1485		if (ntohl(initack_cp->init.initial_tsn) != asoc->init_seq_number) {
1486			/*-
1487			 * Opps, this means that we somehow generated two vtag's
1488			 * the same. I.e. we did:
1489			 *  Us               Peer
1490			 *   <---INIT(tag=a)------
1491			 *   ----INIT-ACK(tag=t)-->
1492			 *   ----INIT(tag=t)------> *1
1493			 *   <---INIT-ACK(tag=a)---
1494                         *   <----CE(tag=t)------------- *2
1495			 *
1496			 * At point *1 we should be generating a different
1497			 * tag t'. Which means we would throw away the CE and send
1498			 * ours instead. Basically this is case C (throw away side).
1499			 */
1500			if (how_indx < sizeof(asoc->cookie_how))
1501				asoc->cookie_how[how_indx] = 17;
1502			return (NULL);
1503
1504		}
1505		switch SCTP_GET_STATE
1506			(asoc) {
1507		case SCTP_STATE_COOKIE_WAIT:
1508		case SCTP_STATE_COOKIE_ECHOED:
1509			/*
1510			 * INIT was sent but got a COOKIE_ECHO with the
1511			 * correct tags... just accept it...but we must
1512			 * process the init so that we can make sure we have
1513			 * the right seq no's.
1514			 */
1515			/* First we must process the INIT !! */
1516			retval = sctp_process_init(init_cp, stcb);
1517			if (retval < 0) {
1518				if (how_indx < sizeof(asoc->cookie_how))
1519					asoc->cookie_how[how_indx] = 3;
1520				return (NULL);
1521			}
1522			/* we have already processed the INIT so no problem */
1523			sctp_timer_stop(SCTP_TIMER_TYPE_HEARTBEAT, inp, stcb,
1524			    net, SCTP_FROM_SCTP_INPUT + SCTP_LOC_12);
1525			sctp_timer_stop(SCTP_TIMER_TYPE_INIT, inp, stcb, net, SCTP_FROM_SCTP_INPUT + SCTP_LOC_13);
1526			/* update current state */
1527			if (SCTP_GET_STATE(asoc) == SCTP_STATE_COOKIE_ECHOED)
1528				SCTP_STAT_INCR_COUNTER32(sctps_activeestab);
1529			else
1530				SCTP_STAT_INCR_COUNTER32(sctps_collisionestab);
1531
1532			SCTP_SET_STATE(asoc, SCTP_STATE_OPEN);
1533			if (asoc->state & SCTP_STATE_SHUTDOWN_PENDING) {
1534				sctp_timer_start(SCTP_TIMER_TYPE_SHUTDOWNGUARD,
1535				    stcb->sctp_ep, stcb, asoc->primary_destination);
1536			}
1537			SCTP_STAT_INCR_GAUGE32(sctps_currestab);
1538			sctp_stop_all_cookie_timers(stcb);
1539			if (((stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE) ||
1540			    (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL)) &&
1541			    (inp->sctp_socket->so_qlimit == 0)
1542			    ) {
1543#if defined (__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
1544				struct socket *so;
1545
1546#endif
1547				/*
1548				 * Here is where collision would go if we
1549				 * did a connect() and instead got a
1550				 * init/init-ack/cookie done before the
1551				 * init-ack came back..
1552				 */
1553				stcb->sctp_ep->sctp_flags |=
1554				    SCTP_PCB_FLAGS_CONNECTED;
1555#if defined (__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
1556				so = SCTP_INP_SO(stcb->sctp_ep);
1557				atomic_add_int(&stcb->asoc.refcnt, 1);
1558				SCTP_TCB_UNLOCK(stcb);
1559				SCTP_SOCKET_LOCK(so, 1);
1560				SCTP_TCB_LOCK(stcb);
1561				atomic_add_int(&stcb->asoc.refcnt, -1);
1562				if (stcb->asoc.state & SCTP_STATE_CLOSED_SOCKET) {
1563					SCTP_SOCKET_UNLOCK(so, 1);
1564					return (NULL);
1565				}
1566#endif
1567				soisconnected(stcb->sctp_socket);
1568#if defined (__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
1569				SCTP_SOCKET_UNLOCK(so, 1);
1570#endif
1571			}
1572			/* notify upper layer */
1573			*notification = SCTP_NOTIFY_ASSOC_UP;
1574			/*
1575			 * since we did not send a HB make sure we don't
1576			 * double things
1577			 */
1578			net->hb_responded = 1;
1579			net->RTO = sctp_calculate_rto(stcb, asoc, net,
1580			    &cookie->time_entered,
1581			    sctp_align_unsafe_makecopy,
1582			    SCTP_RTT_FROM_NON_DATA);
1583
1584			if (stcb->asoc.sctp_autoclose_ticks &&
1585			    (sctp_is_feature_on(inp, SCTP_PCB_FLAGS_AUTOCLOSE))) {
1586				sctp_timer_start(SCTP_TIMER_TYPE_AUTOCLOSE,
1587				    inp, stcb, NULL);
1588			}
1589			break;
1590		default:
1591			/*
1592			 * we're in the OPEN state (or beyond), so peer must
1593			 * have simply lost the COOKIE-ACK
1594			 */
1595			break;
1596			}	/* end switch */
1597		sctp_stop_all_cookie_timers(stcb);
1598		/*
1599		 * We ignore the return code here.. not sure if we should
1600		 * somehow abort.. but we do have an existing asoc. This
1601		 * really should not fail.
1602		 */
1603		if (sctp_load_addresses_from_init(stcb, m,
1604		    init_offset + sizeof(struct sctp_init_chunk),
1605		    initack_offset, sh, init_src)) {
1606			if (how_indx < sizeof(asoc->cookie_how))
1607				asoc->cookie_how[how_indx] = 4;
1608			return (NULL);
1609		}
1610		/* respond with a COOKIE-ACK */
1611		sctp_toss_old_cookies(stcb, asoc);
1612		sctp_send_cookie_ack(stcb);
1613		if (how_indx < sizeof(asoc->cookie_how))
1614			asoc->cookie_how[how_indx] = 5;
1615		return (stcb);
1616	}
1617	if (ntohl(initack_cp->init.initiate_tag) != asoc->my_vtag &&
1618	    ntohl(init_cp->init.initiate_tag) == asoc->peer_vtag &&
1619	    cookie->tie_tag_my_vtag == 0 &&
1620	    cookie->tie_tag_peer_vtag == 0) {
1621		/*
1622		 * case C in Section 5.2.4 Table 2: XMOO silently discard
1623		 */
1624		if (how_indx < sizeof(asoc->cookie_how))
1625			asoc->cookie_how[how_indx] = 6;
1626		return (NULL);
1627	}
1628	/*
1629	 * If nat support, and the below and stcb is established, send back
1630	 * a ABORT(colliding state) if we are established.
1631	 */
1632	if ((SCTP_GET_STATE(asoc) == SCTP_STATE_OPEN) &&
1633	    (asoc->peer_supports_nat) &&
1634	    ((ntohl(initack_cp->init.initiate_tag) == asoc->my_vtag) &&
1635	    ((ntohl(init_cp->init.initiate_tag) != asoc->peer_vtag) ||
1636	    (asoc->peer_vtag == 0)))) {
1637		/*
1638		 * Special case - Peer's support nat. We may have two init's
1639		 * that we gave out the same tag on since one was not
1640		 * established.. i.e. we get INIT from host-1 behind the nat
1641		 * and we respond tag-a, we get a INIT from host-2 behind
1642		 * the nat and we get tag-a again. Then we bring up host-1
1643		 * (or 2's) assoc, Then comes the cookie from hsot-2 (or 1).
1644		 * Now we have colliding state. We must send an abort here
1645		 * with colliding state indication.
1646		 */
1647		op_err = sctp_get_mbuf_for_msg(sizeof(struct sctp_paramhdr),
1648		    0, M_DONTWAIT, 1, MT_DATA);
1649		if (op_err == NULL) {
1650			/* FOOBAR */
1651			return (NULL);
1652		}
1653		/* pre-reserve some space */
1654#ifdef INET6
1655		SCTP_BUF_RESV_UF(op_err, sizeof(struct ip6_hdr));
1656#else
1657		SCTP_BUF_RESV_UF(op_err, sizeof(struct ip));
1658#endif
1659		SCTP_BUF_RESV_UF(op_err, sizeof(struct sctphdr));
1660		SCTP_BUF_RESV_UF(op_err, sizeof(struct sctp_chunkhdr));
1661		/* Set the len */
1662		SCTP_BUF_LEN(op_err) = sizeof(struct sctp_paramhdr);
1663		ph = mtod(op_err, struct sctp_paramhdr *);
1664		ph->param_type = htons(SCTP_CAUSE_NAT_COLLIDING_STATE);
1665		ph->param_length = htons(sizeof(struct sctp_paramhdr));
1666		sctp_send_abort(m, iphlen, sh, 0, op_err, vrf_id, port);
1667		return (NULL);
1668	}
1669	if ((ntohl(initack_cp->init.initiate_tag) == asoc->my_vtag) &&
1670	    ((ntohl(init_cp->init.initiate_tag) != asoc->peer_vtag) ||
1671	    (asoc->peer_vtag == 0))) {
1672		/*
1673		 * case B in Section 5.2.4 Table 2: MXAA or MOAA my info
1674		 * should be ok, re-accept peer info
1675		 */
1676		if (ntohl(initack_cp->init.initial_tsn) != asoc->init_seq_number) {
1677			/*
1678			 * Extension of case C. If we hit this, then the
1679			 * random number generator returned the same vtag
1680			 * when we first sent our INIT-ACK and when we later
1681			 * sent our INIT. The side with the seq numbers that
1682			 * are different will be the one that normnally
1683			 * would have hit case C. This in effect "extends"
1684			 * our vtags in this collision case to be 64 bits.
1685			 * The same collision could occur aka you get both
1686			 * vtag and seq number the same twice in a row.. but
1687			 * is much less likely. If it did happen then we
1688			 * would proceed through and bring up the assoc.. we
1689			 * may end up with the wrong stream setup however..
1690			 * which would be bad.. but there is no way to
1691			 * tell.. until we send on a stream that does not
1692			 * exist :-)
1693			 */
1694			if (how_indx < sizeof(asoc->cookie_how))
1695				asoc->cookie_how[how_indx] = 7;
1696
1697			return (NULL);
1698		}
1699		if (how_indx < sizeof(asoc->cookie_how))
1700			asoc->cookie_how[how_indx] = 8;
1701		sctp_timer_stop(SCTP_TIMER_TYPE_HEARTBEAT, inp, stcb, net, SCTP_FROM_SCTP_INPUT + SCTP_LOC_14);
1702		sctp_stop_all_cookie_timers(stcb);
1703		/*
1704		 * since we did not send a HB make sure we don't double
1705		 * things
1706		 */
1707		net->hb_responded = 1;
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,
1711			    NULL);
1712		}
1713		asoc->my_rwnd = ntohl(initack_cp->init.a_rwnd);
1714		asoc->pre_open_streams = ntohs(initack_cp->init.num_outbound_streams);
1715
1716		if (ntohl(init_cp->init.initiate_tag) != asoc->peer_vtag) {
1717			/*
1718			 * Ok the peer probably discarded our data (if we
1719			 * echoed a cookie+data). So anything on the
1720			 * sent_queue should be marked for retransmit, we
1721			 * may not get something to kick us so it COULD
1722			 * still take a timeout to move these.. but it can't
1723			 * hurt to mark them.
1724			 */
1725			struct sctp_tmit_chunk *chk;
1726
1727			TAILQ_FOREACH(chk, &stcb->asoc.sent_queue, sctp_next) {
1728				if (chk->sent < SCTP_DATAGRAM_RESEND) {
1729					chk->sent = SCTP_DATAGRAM_RESEND;
1730					sctp_flight_size_decrease(chk);
1731					sctp_total_flight_decrease(stcb, chk);
1732					sctp_ucount_incr(stcb->asoc.sent_queue_retran_cnt);
1733					spec_flag++;
1734				}
1735			}
1736
1737		}
1738		/* process the INIT info (peer's info) */
1739		retval = sctp_process_init(init_cp, stcb);
1740		if (retval < 0) {
1741			if (how_indx < sizeof(asoc->cookie_how))
1742				asoc->cookie_how[how_indx] = 9;
1743			return (NULL);
1744		}
1745		if (sctp_load_addresses_from_init(stcb, m,
1746		    init_offset + sizeof(struct sctp_init_chunk),
1747		    initack_offset, sh, init_src)) {
1748			if (how_indx < sizeof(asoc->cookie_how))
1749				asoc->cookie_how[how_indx] = 10;
1750			return (NULL);
1751		}
1752		if ((asoc->state & SCTP_STATE_COOKIE_WAIT) ||
1753		    (asoc->state & SCTP_STATE_COOKIE_ECHOED)) {
1754			*notification = SCTP_NOTIFY_ASSOC_UP;
1755
1756			if (((stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE) ||
1757			    (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL)) &&
1758			    (inp->sctp_socket->so_qlimit == 0)) {
1759#if defined (__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
1760				struct socket *so;
1761
1762#endif
1763				stcb->sctp_ep->sctp_flags |=
1764				    SCTP_PCB_FLAGS_CONNECTED;
1765#if defined (__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
1766				so = SCTP_INP_SO(stcb->sctp_ep);
1767				atomic_add_int(&stcb->asoc.refcnt, 1);
1768				SCTP_TCB_UNLOCK(stcb);
1769				SCTP_SOCKET_LOCK(so, 1);
1770				SCTP_TCB_LOCK(stcb);
1771				atomic_add_int(&stcb->asoc.refcnt, -1);
1772				if (stcb->asoc.state & SCTP_STATE_CLOSED_SOCKET) {
1773					SCTP_SOCKET_UNLOCK(so, 1);
1774					return (NULL);
1775				}
1776#endif
1777				soisconnected(stcb->sctp_socket);
1778#if defined (__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
1779				SCTP_SOCKET_UNLOCK(so, 1);
1780#endif
1781			}
1782			if (SCTP_GET_STATE(asoc) == SCTP_STATE_COOKIE_ECHOED)
1783				SCTP_STAT_INCR_COUNTER32(sctps_activeestab);
1784			else
1785				SCTP_STAT_INCR_COUNTER32(sctps_collisionestab);
1786			SCTP_STAT_INCR_GAUGE32(sctps_currestab);
1787		} else if (SCTP_GET_STATE(asoc) == SCTP_STATE_OPEN) {
1788			SCTP_STAT_INCR_COUNTER32(sctps_restartestab);
1789		} else {
1790			SCTP_STAT_INCR_COUNTER32(sctps_collisionestab);
1791		}
1792		SCTP_SET_STATE(asoc, SCTP_STATE_OPEN);
1793		if (asoc->state & SCTP_STATE_SHUTDOWN_PENDING) {
1794			sctp_timer_start(SCTP_TIMER_TYPE_SHUTDOWNGUARD,
1795			    stcb->sctp_ep, stcb, asoc->primary_destination);
1796		}
1797		sctp_stop_all_cookie_timers(stcb);
1798		sctp_toss_old_cookies(stcb, asoc);
1799		sctp_send_cookie_ack(stcb);
1800		if (spec_flag) {
1801			/*
1802			 * only if we have retrans set do we do this. What
1803			 * this call does is get only the COOKIE-ACK out and
1804			 * then when we return the normal call to
1805			 * sctp_chunk_output will get the retrans out behind
1806			 * this.
1807			 */
1808			sctp_chunk_output(inp, stcb, SCTP_OUTPUT_FROM_COOKIE_ACK, SCTP_SO_NOT_LOCKED);
1809		}
1810		if (how_indx < sizeof(asoc->cookie_how))
1811			asoc->cookie_how[how_indx] = 11;
1812
1813		return (stcb);
1814	}
1815	if ((ntohl(initack_cp->init.initiate_tag) != asoc->my_vtag &&
1816	    ntohl(init_cp->init.initiate_tag) != asoc->peer_vtag) &&
1817	    cookie->tie_tag_my_vtag == asoc->my_vtag_nonce &&
1818	    cookie->tie_tag_peer_vtag == asoc->peer_vtag_nonce &&
1819	    cookie->tie_tag_peer_vtag != 0) {
1820		struct sctpasochead *head;
1821
1822		if (asoc->peer_supports_nat) {
1823			/*
1824			 * This is a gross gross hack. just call the
1825			 * cookie_new code since we are allowing a duplicate
1826			 * association. I hope this works...
1827			 */
1828			return (sctp_process_cookie_new(m, iphlen, offset, sh, cookie, cookie_len,
1829			    inp, netp, init_src, notification,
1830			    auth_skipped, auth_offset, auth_len,
1831			    vrf_id, port));
1832		}
1833		/*
1834		 * case A in Section 5.2.4 Table 2: XXMM (peer restarted)
1835		 */
1836		/* temp code */
1837		if (how_indx < sizeof(asoc->cookie_how))
1838			asoc->cookie_how[how_indx] = 12;
1839		sctp_timer_stop(SCTP_TIMER_TYPE_INIT, inp, stcb, net, SCTP_FROM_SCTP_INPUT + SCTP_LOC_15);
1840		sctp_timer_stop(SCTP_TIMER_TYPE_HEARTBEAT, inp, stcb, net, SCTP_FROM_SCTP_INPUT + SCTP_LOC_16);
1841
1842		/* notify upper layer */
1843		*notification = SCTP_NOTIFY_ASSOC_RESTART;
1844		atomic_add_int(&stcb->asoc.refcnt, 1);
1845		if ((SCTP_GET_STATE(asoc) != SCTP_STATE_OPEN) &&
1846		    (SCTP_GET_STATE(asoc) != SCTP_STATE_SHUTDOWN_RECEIVED) &&
1847		    (SCTP_GET_STATE(asoc) != SCTP_STATE_SHUTDOWN_SENT)) {
1848			SCTP_STAT_INCR_GAUGE32(sctps_currestab);
1849		}
1850		if (SCTP_GET_STATE(asoc) == SCTP_STATE_OPEN) {
1851			SCTP_STAT_INCR_GAUGE32(sctps_restartestab);
1852		} else if (SCTP_GET_STATE(asoc) != SCTP_STATE_SHUTDOWN_SENT) {
1853			SCTP_STAT_INCR_GAUGE32(sctps_collisionestab);
1854		}
1855		if (asoc->state & SCTP_STATE_SHUTDOWN_PENDING) {
1856			SCTP_SET_STATE(asoc, SCTP_STATE_OPEN);
1857			sctp_timer_start(SCTP_TIMER_TYPE_SHUTDOWNGUARD,
1858			    stcb->sctp_ep, stcb, asoc->primary_destination);
1859
1860		} else if (!(asoc->state & SCTP_STATE_SHUTDOWN_SENT)) {
1861			/* move to OPEN state, if not in SHUTDOWN_SENT */
1862			SCTP_SET_STATE(asoc, SCTP_STATE_OPEN);
1863		}
1864		asoc->pre_open_streams =
1865		    ntohs(initack_cp->init.num_outbound_streams);
1866		asoc->init_seq_number = ntohl(initack_cp->init.initial_tsn);
1867		asoc->sending_seq = asoc->asconf_seq_out = asoc->str_reset_seq_out = asoc->init_seq_number;
1868		asoc->asconf_seq_out_acked = asoc->asconf_seq_out - 1;
1869
1870		asoc->asconf_seq_in = asoc->last_acked_seq = asoc->init_seq_number - 1;
1871
1872		asoc->str_reset_seq_in = asoc->init_seq_number;
1873
1874		asoc->advanced_peer_ack_point = asoc->last_acked_seq;
1875		if (asoc->mapping_array) {
1876			memset(asoc->mapping_array, 0,
1877			    asoc->mapping_array_size);
1878		}
1879		if (asoc->nr_mapping_array) {
1880			memset(asoc->nr_mapping_array, 0,
1881			    asoc->mapping_array_size);
1882		}
1883		SCTP_TCB_UNLOCK(stcb);
1884		SCTP_INP_INFO_WLOCK();
1885		SCTP_INP_WLOCK(stcb->sctp_ep);
1886		SCTP_TCB_LOCK(stcb);
1887		atomic_add_int(&stcb->asoc.refcnt, -1);
1888		/* send up all the data */
1889		SCTP_TCB_SEND_LOCK(stcb);
1890
1891		sctp_report_all_outbound(stcb, 0, 1, SCTP_SO_NOT_LOCKED);
1892		for (i = 0; i < stcb->asoc.streamoutcnt; i++) {
1893			stcb->asoc.strmout[i].stream_no = i;
1894			stcb->asoc.strmout[i].next_sequence_sent = 0;
1895			stcb->asoc.strmout[i].last_msg_incomplete = 0;
1896		}
1897		/* process the INIT-ACK info (my info) */
1898		asoc->my_vtag = ntohl(initack_cp->init.initiate_tag);
1899		asoc->my_rwnd = ntohl(initack_cp->init.a_rwnd);
1900
1901		/* pull from vtag hash */
1902		LIST_REMOVE(stcb, sctp_asocs);
1903		/* re-insert to new vtag position */
1904		head = &SCTP_BASE_INFO(sctp_asochash)[SCTP_PCBHASH_ASOC(stcb->asoc.my_vtag,
1905		    SCTP_BASE_INFO(hashasocmark))];
1906		/*
1907		 * put it in the bucket in the vtag hash of assoc's for the
1908		 * system
1909		 */
1910		LIST_INSERT_HEAD(head, stcb, sctp_asocs);
1911
1912		/* process the INIT info (peer's info) */
1913		SCTP_TCB_SEND_UNLOCK(stcb);
1914		SCTP_INP_WUNLOCK(stcb->sctp_ep);
1915		SCTP_INP_INFO_WUNLOCK();
1916
1917		retval = sctp_process_init(init_cp, stcb);
1918		if (retval < 0) {
1919			if (how_indx < sizeof(asoc->cookie_how))
1920				asoc->cookie_how[how_indx] = 13;
1921
1922			return (NULL);
1923		}
1924		/*
1925		 * since we did not send a HB make sure we don't double
1926		 * things
1927		 */
1928		net->hb_responded = 1;
1929
1930		if (sctp_load_addresses_from_init(stcb, m,
1931		    init_offset + sizeof(struct sctp_init_chunk),
1932		    initack_offset, sh, init_src)) {
1933			if (how_indx < sizeof(asoc->cookie_how))
1934				asoc->cookie_how[how_indx] = 14;
1935
1936			return (NULL);
1937		}
1938		/* respond with a COOKIE-ACK */
1939		sctp_stop_all_cookie_timers(stcb);
1940		sctp_toss_old_cookies(stcb, asoc);
1941		sctp_send_cookie_ack(stcb);
1942		if (how_indx < sizeof(asoc->cookie_how))
1943			asoc->cookie_how[how_indx] = 15;
1944
1945		return (stcb);
1946	}
1947	if (how_indx < sizeof(asoc->cookie_how))
1948		asoc->cookie_how[how_indx] = 16;
1949	/* all other cases... */
1950	return (NULL);
1951}
1952
1953
1954/*
1955 * handle a state cookie for a new association m: input packet mbuf chain--
1956 * assumes a pullup on IP/SCTP/COOKIE-ECHO chunk note: this is a "split" mbuf
1957 * and the cookie signature does not exist offset: offset into mbuf to the
1958 * cookie-echo chunk length: length of the cookie chunk to: where the init
1959 * was from returns a new TCB
1960 */
1961struct sctp_tcb *
1962sctp_process_cookie_new(struct mbuf *m, int iphlen, int offset,
1963    struct sctphdr *sh, struct sctp_state_cookie *cookie, int cookie_len,
1964    struct sctp_inpcb *inp, struct sctp_nets **netp,
1965    struct sockaddr *init_src, int *notification,
1966    int auth_skipped, uint32_t auth_offset, uint32_t auth_len,
1967    uint32_t vrf_id, uint16_t port)
1968{
1969	struct sctp_tcb *stcb;
1970	struct sctp_init_chunk *init_cp, init_buf;
1971	struct sctp_init_ack_chunk *initack_cp, initack_buf;
1972	struct sockaddr_storage sa_store;
1973	struct sockaddr *initack_src = (struct sockaddr *)&sa_store;
1974	struct sctp_association *asoc;
1975	int init_offset, initack_offset, initack_limit;
1976	int retval;
1977	int error = 0;
1978	uint8_t auth_chunk_buf[SCTP_PARAM_BUFFER_SIZE];
1979
1980#ifdef INET
1981	struct sockaddr_in *sin;
1982
1983#endif
1984#ifdef INET6
1985	struct sockaddr_in6 *sin6;
1986
1987#endif
1988#if defined (__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
1989	struct socket *so;
1990
1991	so = SCTP_INP_SO(inp);
1992#endif
1993
1994	/*
1995	 * find and validate the INIT chunk in the cookie (peer's info) the
1996	 * INIT should start after the cookie-echo header struct (chunk
1997	 * header, state cookie header struct)
1998	 */
1999	init_offset = offset + sizeof(struct sctp_cookie_echo_chunk);
2000	init_cp = (struct sctp_init_chunk *)
2001	    sctp_m_getptr(m, init_offset, sizeof(struct sctp_init_chunk),
2002	    (uint8_t *) & init_buf);
2003	if (init_cp == NULL) {
2004		/* could not pull a INIT chunk in cookie */
2005		SCTPDBG(SCTP_DEBUG_INPUT1,
2006		    "process_cookie_new: could not pull INIT chunk hdr\n");
2007		return (NULL);
2008	}
2009	if (init_cp->ch.chunk_type != SCTP_INITIATION) {
2010		SCTPDBG(SCTP_DEBUG_INPUT1, "HUH? process_cookie_new: could not find INIT chunk!\n");
2011		return (NULL);
2012	}
2013	initack_offset = init_offset + SCTP_SIZE32(ntohs(init_cp->ch.chunk_length));
2014	/*
2015	 * find and validate the INIT-ACK chunk in the cookie (my info) the
2016	 * INIT-ACK follows the INIT chunk
2017	 */
2018	initack_cp = (struct sctp_init_ack_chunk *)
2019	    sctp_m_getptr(m, initack_offset, sizeof(struct sctp_init_ack_chunk),
2020	    (uint8_t *) & initack_buf);
2021	if (initack_cp == NULL) {
2022		/* could not pull INIT-ACK chunk in cookie */
2023		SCTPDBG(SCTP_DEBUG_INPUT1, "process_cookie_new: could not pull INIT-ACK chunk hdr\n");
2024		return (NULL);
2025	}
2026	if (initack_cp->ch.chunk_type != SCTP_INITIATION_ACK) {
2027		return (NULL);
2028	}
2029	/*
2030	 * NOTE: We can't use the INIT_ACK's chk_length to determine the
2031	 * "initack_limit" value.  This is because the chk_length field
2032	 * includes the length of the cookie, but the cookie is omitted when
2033	 * the INIT and INIT_ACK are tacked onto the cookie...
2034	 */
2035	initack_limit = offset + cookie_len;
2036
2037	/*
2038	 * now that we know the INIT/INIT-ACK are in place, create a new TCB
2039	 * and popluate
2040	 */
2041
2042	/*
2043	 * Here we do a trick, we set in NULL for the proc/thread argument.
2044	 * We do this since in effect we only use the p argument when the
2045	 * socket is unbound and we must do an implicit bind. Since we are
2046	 * getting a cookie, we cannot be unbound.
2047	 */
2048	stcb = sctp_aloc_assoc(inp, init_src, &error,
2049	    ntohl(initack_cp->init.initiate_tag), vrf_id,
2050	    (struct thread *)NULL
2051	    );
2052	if (stcb == NULL) {
2053		struct mbuf *op_err;
2054
2055		/* memory problem? */
2056		SCTPDBG(SCTP_DEBUG_INPUT1,
2057		    "process_cookie_new: no room for another TCB!\n");
2058		op_err = sctp_generate_invmanparam(SCTP_CAUSE_OUT_OF_RESC);
2059
2060		sctp_abort_association(inp, (struct sctp_tcb *)NULL, m, iphlen,
2061		    sh, op_err, vrf_id, port);
2062		return (NULL);
2063	}
2064	/* get the correct sctp_nets */
2065	if (netp)
2066		*netp = sctp_findnet(stcb, init_src);
2067
2068	asoc = &stcb->asoc;
2069	/* get scope variables out of cookie */
2070	asoc->ipv4_local_scope = cookie->ipv4_scope;
2071	asoc->site_scope = cookie->site_scope;
2072	asoc->local_scope = cookie->local_scope;
2073	asoc->loopback_scope = cookie->loopback_scope;
2074
2075	if ((asoc->ipv4_addr_legal != cookie->ipv4_addr_legal) ||
2076	    (asoc->ipv6_addr_legal != cookie->ipv6_addr_legal)) {
2077		struct mbuf *op_err;
2078
2079		/*
2080		 * Houston we have a problem. The EP changed while the
2081		 * cookie was in flight. Only recourse is to abort the
2082		 * association.
2083		 */
2084		atomic_add_int(&stcb->asoc.refcnt, 1);
2085		op_err = sctp_generate_invmanparam(SCTP_CAUSE_OUT_OF_RESC);
2086		sctp_abort_association(inp, (struct sctp_tcb *)NULL, m, iphlen,
2087		    sh, op_err, vrf_id, port);
2088#if defined (__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
2089		SCTP_TCB_UNLOCK(stcb);
2090		SCTP_SOCKET_LOCK(so, 1);
2091		SCTP_TCB_LOCK(stcb);
2092#endif
2093		(void)sctp_free_assoc(inp, stcb, SCTP_NORMAL_PROC,
2094		    SCTP_FROM_SCTP_INPUT + SCTP_LOC_16);
2095#if defined (__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
2096		SCTP_SOCKET_UNLOCK(so, 1);
2097#endif
2098		atomic_subtract_int(&stcb->asoc.refcnt, 1);
2099		return (NULL);
2100	}
2101	/* process the INIT-ACK info (my info) */
2102	asoc->my_vtag = ntohl(initack_cp->init.initiate_tag);
2103	asoc->my_rwnd = ntohl(initack_cp->init.a_rwnd);
2104	asoc->pre_open_streams = ntohs(initack_cp->init.num_outbound_streams);
2105	asoc->init_seq_number = ntohl(initack_cp->init.initial_tsn);
2106	asoc->sending_seq = asoc->asconf_seq_out = asoc->str_reset_seq_out = asoc->init_seq_number;
2107	asoc->asconf_seq_out_acked = asoc->asconf_seq_out - 1;
2108	asoc->asconf_seq_in = asoc->last_acked_seq = asoc->init_seq_number - 1;
2109	asoc->str_reset_seq_in = asoc->init_seq_number;
2110
2111	asoc->advanced_peer_ack_point = asoc->last_acked_seq;
2112
2113	/* process the INIT info (peer's info) */
2114	if (netp)
2115		retval = sctp_process_init(init_cp, stcb);
2116	else
2117		retval = 0;
2118	if (retval < 0) {
2119		atomic_add_int(&stcb->asoc.refcnt, 1);
2120#if defined (__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
2121		SCTP_TCB_UNLOCK(stcb);
2122		SCTP_SOCKET_LOCK(so, 1);
2123		SCTP_TCB_LOCK(stcb);
2124#endif
2125		(void)sctp_free_assoc(inp, stcb, SCTP_NORMAL_PROC, SCTP_FROM_SCTP_INPUT + SCTP_LOC_16);
2126#if defined (__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
2127		SCTP_SOCKET_UNLOCK(so, 1);
2128#endif
2129		atomic_subtract_int(&stcb->asoc.refcnt, 1);
2130		return (NULL);
2131	}
2132	/* load all addresses */
2133	if (sctp_load_addresses_from_init(stcb, m,
2134	    init_offset + sizeof(struct sctp_init_chunk), initack_offset, sh,
2135	    init_src)) {
2136		atomic_add_int(&stcb->asoc.refcnt, 1);
2137#if defined (__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
2138		SCTP_TCB_UNLOCK(stcb);
2139		SCTP_SOCKET_LOCK(so, 1);
2140		SCTP_TCB_LOCK(stcb);
2141#endif
2142		(void)sctp_free_assoc(inp, stcb, SCTP_NORMAL_PROC, SCTP_FROM_SCTP_INPUT + SCTP_LOC_17);
2143#if defined (__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
2144		SCTP_SOCKET_UNLOCK(so, 1);
2145#endif
2146		atomic_subtract_int(&stcb->asoc.refcnt, 1);
2147		return (NULL);
2148	}
2149	/*
2150	 * verify any preceding AUTH chunk that was skipped
2151	 */
2152	/* pull the local authentication parameters from the cookie/init-ack */
2153	sctp_auth_get_cookie_params(stcb, m,
2154	    initack_offset + sizeof(struct sctp_init_ack_chunk),
2155	    initack_limit - (initack_offset + sizeof(struct sctp_init_ack_chunk)));
2156	if (auth_skipped) {
2157		struct sctp_auth_chunk *auth;
2158
2159		auth = (struct sctp_auth_chunk *)
2160		    sctp_m_getptr(m, auth_offset, auth_len, auth_chunk_buf);
2161		if ((auth == NULL) || sctp_handle_auth(stcb, auth, m, auth_offset)) {
2162			/* auth HMAC failed, dump the assoc and packet */
2163			SCTPDBG(SCTP_DEBUG_AUTH1,
2164			    "COOKIE-ECHO: AUTH failed\n");
2165			atomic_add_int(&stcb->asoc.refcnt, 1);
2166#if defined (__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
2167			SCTP_TCB_UNLOCK(stcb);
2168			SCTP_SOCKET_LOCK(so, 1);
2169			SCTP_TCB_LOCK(stcb);
2170#endif
2171			(void)sctp_free_assoc(inp, stcb, SCTP_NORMAL_PROC, SCTP_FROM_SCTP_INPUT + SCTP_LOC_18);
2172#if defined (__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
2173			SCTP_SOCKET_UNLOCK(so, 1);
2174#endif
2175			atomic_subtract_int(&stcb->asoc.refcnt, 1);
2176			return (NULL);
2177		} else {
2178			/* remaining chunks checked... good to go */
2179			stcb->asoc.authenticated = 1;
2180		}
2181	}
2182	/* update current state */
2183	SCTPDBG(SCTP_DEBUG_INPUT2, "moving to OPEN state\n");
2184	SCTP_SET_STATE(asoc, SCTP_STATE_OPEN);
2185	if (asoc->state & SCTP_STATE_SHUTDOWN_PENDING) {
2186		sctp_timer_start(SCTP_TIMER_TYPE_SHUTDOWNGUARD,
2187		    stcb->sctp_ep, stcb, asoc->primary_destination);
2188	}
2189	sctp_stop_all_cookie_timers(stcb);
2190	SCTP_STAT_INCR_COUNTER32(sctps_passiveestab);
2191	SCTP_STAT_INCR_GAUGE32(sctps_currestab);
2192
2193	/*
2194	 * if we're doing ASCONFs, check to see if we have any new local
2195	 * addresses that need to get added to the peer (eg. addresses
2196	 * changed while cookie echo in flight).  This needs to be done
2197	 * after we go to the OPEN state to do the correct asconf
2198	 * processing. else, make sure we have the correct addresses in our
2199	 * lists
2200	 */
2201
2202	/* warning, we re-use sin, sin6, sa_store here! */
2203	/* pull in local_address (our "from" address) */
2204	switch (cookie->laddr_type) {
2205#ifdef INET
2206	case SCTP_IPV4_ADDRESS:
2207		/* source addr is IPv4 */
2208		sin = (struct sockaddr_in *)initack_src;
2209		memset(sin, 0, sizeof(*sin));
2210		sin->sin_family = AF_INET;
2211		sin->sin_len = sizeof(struct sockaddr_in);
2212		sin->sin_addr.s_addr = cookie->laddress[0];
2213		break;
2214#endif
2215#ifdef INET6
2216	case SCTP_IPV6_ADDRESS:
2217		/* source addr is IPv6 */
2218		sin6 = (struct sockaddr_in6 *)initack_src;
2219		memset(sin6, 0, sizeof(*sin6));
2220		sin6->sin6_family = AF_INET6;
2221		sin6->sin6_len = sizeof(struct sockaddr_in6);
2222		sin6->sin6_scope_id = cookie->scope_id;
2223		memcpy(&sin6->sin6_addr, cookie->laddress,
2224		    sizeof(sin6->sin6_addr));
2225		break;
2226#endif
2227	default:
2228		atomic_add_int(&stcb->asoc.refcnt, 1);
2229#if defined (__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
2230		SCTP_TCB_UNLOCK(stcb);
2231		SCTP_SOCKET_LOCK(so, 1);
2232		SCTP_TCB_LOCK(stcb);
2233#endif
2234		(void)sctp_free_assoc(inp, stcb, SCTP_NORMAL_PROC, SCTP_FROM_SCTP_INPUT + SCTP_LOC_19);
2235#if defined (__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
2236		SCTP_SOCKET_UNLOCK(so, 1);
2237#endif
2238		atomic_subtract_int(&stcb->asoc.refcnt, 1);
2239		return (NULL);
2240	}
2241
2242	/* set up to notify upper layer */
2243	*notification = SCTP_NOTIFY_ASSOC_UP;
2244	if (((stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE) ||
2245	    (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL)) &&
2246	    (inp->sctp_socket->so_qlimit == 0)) {
2247		/*
2248		 * This is an endpoint that called connect() how it got a
2249		 * cookie that is NEW is a bit of a mystery. It must be that
2250		 * the INIT was sent, but before it got there.. a complete
2251		 * INIT/INIT-ACK/COOKIE arrived. But of course then it
2252		 * should have went to the other code.. not here.. oh well..
2253		 * a bit of protection is worth having..
2254		 */
2255		stcb->sctp_ep->sctp_flags |= SCTP_PCB_FLAGS_CONNECTED;
2256#if defined (__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
2257		atomic_add_int(&stcb->asoc.refcnt, 1);
2258		SCTP_TCB_UNLOCK(stcb);
2259		SCTP_SOCKET_LOCK(so, 1);
2260		SCTP_TCB_LOCK(stcb);
2261		atomic_subtract_int(&stcb->asoc.refcnt, 1);
2262		if (stcb->asoc.state & SCTP_STATE_CLOSED_SOCKET) {
2263			SCTP_SOCKET_UNLOCK(so, 1);
2264			return (NULL);
2265		}
2266#endif
2267		soisconnected(stcb->sctp_socket);
2268#if defined (__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
2269		SCTP_SOCKET_UNLOCK(so, 1);
2270#endif
2271	} else if ((stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE) &&
2272	    (inp->sctp_socket->so_qlimit)) {
2273		/*
2274		 * We don't want to do anything with this one. Since it is
2275		 * the listening guy. The timer will get started for
2276		 * accepted connections in the caller.
2277		 */
2278		;
2279	}
2280	/* since we did not send a HB make sure we don't double things */
2281	if ((netp) && (*netp))
2282		(*netp)->hb_responded = 1;
2283
2284	if (stcb->asoc.sctp_autoclose_ticks &&
2285	    sctp_is_feature_on(inp, SCTP_PCB_FLAGS_AUTOCLOSE)) {
2286		sctp_timer_start(SCTP_TIMER_TYPE_AUTOCLOSE, inp, stcb, NULL);
2287	}
2288	/* calculate the RTT */
2289	(void)SCTP_GETTIME_TIMEVAL(&stcb->asoc.time_entered);
2290	if ((netp) && (*netp)) {
2291		(*netp)->RTO = sctp_calculate_rto(stcb, asoc, *netp,
2292		    &cookie->time_entered, sctp_align_unsafe_makecopy,
2293		    SCTP_RTT_FROM_NON_DATA);
2294	}
2295	/* respond with a COOKIE-ACK */
2296	sctp_send_cookie_ack(stcb);
2297
2298	/*
2299	 * check the address lists for any ASCONFs that need to be sent
2300	 * AFTER the cookie-ack is sent
2301	 */
2302	sctp_check_address_list(stcb, m,
2303	    initack_offset + sizeof(struct sctp_init_ack_chunk),
2304	    initack_limit - (initack_offset + sizeof(struct sctp_init_ack_chunk)),
2305	    initack_src, cookie->local_scope, cookie->site_scope,
2306	    cookie->ipv4_scope, cookie->loopback_scope);
2307
2308
2309	return (stcb);
2310}
2311
2312/*
2313 * CODE LIKE THIS NEEDS TO RUN IF the peer supports the NAT extension, i.e
2314 * we NEED to make sure we are not already using the vtag. If so we
2315 * need to send back an ABORT-TRY-AGAIN-WITH-NEW-TAG No middle box bit!
2316	head = &SCTP_BASE_INFO(sctp_asochash)[SCTP_PCBHASH_ASOC(tag,
2317							    SCTP_BASE_INFO(hashasocmark))];
2318	LIST_FOREACH(stcb, head, sctp_asocs) {
2319	        if ((stcb->asoc.my_vtag == tag) && (stcb->rport == rport) && (inp == stcb->sctp_ep))  {
2320		       -- SEND ABORT - TRY AGAIN --
2321		}
2322	}
2323*/
2324
2325/*
2326 * handles a COOKIE-ECHO message stcb: modified to either a new or left as
2327 * existing (non-NULL) TCB
2328 */
2329static struct mbuf *
2330sctp_handle_cookie_echo(struct mbuf *m, int iphlen, int offset,
2331    struct sctphdr *sh, struct sctp_cookie_echo_chunk *cp,
2332    struct sctp_inpcb **inp_p, struct sctp_tcb **stcb, struct sctp_nets **netp,
2333    int auth_skipped, uint32_t auth_offset, uint32_t auth_len,
2334    struct sctp_tcb **locked_tcb, uint32_t vrf_id, uint16_t port)
2335{
2336	struct sctp_state_cookie *cookie;
2337	struct sctp_tcb *l_stcb = *stcb;
2338	struct sctp_inpcb *l_inp;
2339	struct sockaddr *to;
2340	struct sctp_pcb *ep;
2341	struct mbuf *m_sig;
2342	uint8_t calc_sig[SCTP_SIGNATURE_SIZE], tmp_sig[SCTP_SIGNATURE_SIZE];
2343	uint8_t *sig;
2344	uint8_t cookie_ok = 0;
2345	unsigned int size_of_pkt, sig_offset, cookie_offset;
2346	unsigned int cookie_len;
2347	struct timeval now;
2348	struct timeval time_expires;
2349	struct sockaddr_storage dest_store;
2350	struct sockaddr *localep_sa = (struct sockaddr *)&dest_store;
2351	struct ip *iph;
2352	int notification = 0;
2353	struct sctp_nets *netl;
2354	int had_a_existing_tcb = 0;
2355	int send_int_conf = 0;
2356
2357#ifdef INET
2358	struct sockaddr_in sin;
2359
2360#endif
2361#ifdef INET6
2362	struct sockaddr_in6 sin6;
2363
2364#endif
2365
2366	SCTPDBG(SCTP_DEBUG_INPUT2,
2367	    "sctp_handle_cookie: handling COOKIE-ECHO\n");
2368
2369	if (inp_p == NULL) {
2370		return (NULL);
2371	}
2372	/* First get the destination address setup too. */
2373	iph = mtod(m, struct ip *);
2374	switch (iph->ip_v) {
2375#ifdef INET
2376	case IPVERSION:
2377		{
2378			/* its IPv4 */
2379			struct sockaddr_in *lsin;
2380
2381			lsin = (struct sockaddr_in *)(localep_sa);
2382			memset(lsin, 0, sizeof(*lsin));
2383			lsin->sin_family = AF_INET;
2384			lsin->sin_len = sizeof(*lsin);
2385			lsin->sin_port = sh->dest_port;
2386			lsin->sin_addr.s_addr = iph->ip_dst.s_addr;
2387			size_of_pkt = SCTP_GET_IPV4_LENGTH(iph);
2388			break;
2389		}
2390#endif
2391#ifdef INET6
2392	case IPV6_VERSION >> 4:
2393		{
2394			/* its IPv6 */
2395			struct ip6_hdr *ip6;
2396			struct sockaddr_in6 *lsin6;
2397
2398			lsin6 = (struct sockaddr_in6 *)(localep_sa);
2399			memset(lsin6, 0, sizeof(*lsin6));
2400			lsin6->sin6_family = AF_INET6;
2401			lsin6->sin6_len = sizeof(struct sockaddr_in6);
2402			ip6 = mtod(m, struct ip6_hdr *);
2403			lsin6->sin6_port = sh->dest_port;
2404			lsin6->sin6_addr = ip6->ip6_dst;
2405			size_of_pkt = SCTP_GET_IPV6_LENGTH(ip6) + iphlen;
2406			break;
2407		}
2408#endif
2409	default:
2410		return (NULL);
2411	}
2412
2413	cookie = &cp->cookie;
2414	cookie_offset = offset + sizeof(struct sctp_chunkhdr);
2415	cookie_len = ntohs(cp->ch.chunk_length);
2416
2417	if ((cookie->peerport != sh->src_port) &&
2418	    (cookie->myport != sh->dest_port) &&
2419	    (cookie->my_vtag != sh->v_tag)) {
2420		/*
2421		 * invalid ports or bad tag.  Note that we always leave the
2422		 * v_tag in the header in network order and when we stored
2423		 * it in the my_vtag slot we also left it in network order.
2424		 * This maintains the match even though it may be in the
2425		 * opposite byte order of the machine :->
2426		 */
2427		return (NULL);
2428	}
2429	if (cookie_len > size_of_pkt ||
2430	    cookie_len < sizeof(struct sctp_cookie_echo_chunk) +
2431	    sizeof(struct sctp_init_chunk) +
2432	    sizeof(struct sctp_init_ack_chunk) + SCTP_SIGNATURE_SIZE) {
2433		/* cookie too long!  or too small */
2434		return (NULL);
2435	}
2436	/*
2437	 * split off the signature into its own mbuf (since it should not be
2438	 * calculated in the sctp_hmac_m() call).
2439	 */
2440	sig_offset = offset + cookie_len - SCTP_SIGNATURE_SIZE;
2441	if (sig_offset > size_of_pkt) {
2442		/* packet not correct size! */
2443		/* XXX this may already be accounted for earlier... */
2444		return (NULL);
2445	}
2446	m_sig = m_split(m, sig_offset, M_DONTWAIT);
2447	if (m_sig == NULL) {
2448		/* out of memory or ?? */
2449		return (NULL);
2450	}
2451#ifdef SCTP_MBUF_LOGGING
2452	if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_MBUF_LOGGING_ENABLE) {
2453		struct mbuf *mat;
2454
2455		for (mat = m_sig; mat; mat = SCTP_BUF_NEXT(mat)) {
2456			if (SCTP_BUF_IS_EXTENDED(mat)) {
2457				sctp_log_mb(mat, SCTP_MBUF_SPLIT);
2458			}
2459		}
2460	}
2461#endif
2462
2463	/*
2464	 * compute the signature/digest for the cookie
2465	 */
2466	ep = &(*inp_p)->sctp_ep;
2467	l_inp = *inp_p;
2468	if (l_stcb) {
2469		SCTP_TCB_UNLOCK(l_stcb);
2470	}
2471	SCTP_INP_RLOCK(l_inp);
2472	if (l_stcb) {
2473		SCTP_TCB_LOCK(l_stcb);
2474	}
2475	/* which cookie is it? */
2476	if ((cookie->time_entered.tv_sec < (long)ep->time_of_secret_change) &&
2477	    (ep->current_secret_number != ep->last_secret_number)) {
2478		/* it's the old cookie */
2479		(void)sctp_hmac_m(SCTP_HMAC,
2480		    (uint8_t *) ep->secret_key[(int)ep->last_secret_number],
2481		    SCTP_SECRET_SIZE, m, cookie_offset, calc_sig, 0);
2482	} else {
2483		/* it's the current cookie */
2484		(void)sctp_hmac_m(SCTP_HMAC,
2485		    (uint8_t *) ep->secret_key[(int)ep->current_secret_number],
2486		    SCTP_SECRET_SIZE, m, cookie_offset, calc_sig, 0);
2487	}
2488	/* get the signature */
2489	SCTP_INP_RUNLOCK(l_inp);
2490	sig = (uint8_t *) sctp_m_getptr(m_sig, 0, SCTP_SIGNATURE_SIZE, (uint8_t *) & tmp_sig);
2491	if (sig == NULL) {
2492		/* couldn't find signature */
2493		sctp_m_freem(m_sig);
2494		return (NULL);
2495	}
2496	/* compare the received digest with the computed digest */
2497	if (memcmp(calc_sig, sig, SCTP_SIGNATURE_SIZE) != 0) {
2498		/* try the old cookie? */
2499		if ((cookie->time_entered.tv_sec == (long)ep->time_of_secret_change) &&
2500		    (ep->current_secret_number != ep->last_secret_number)) {
2501			/* compute digest with old */
2502			(void)sctp_hmac_m(SCTP_HMAC,
2503			    (uint8_t *) ep->secret_key[(int)ep->last_secret_number],
2504			    SCTP_SECRET_SIZE, m, cookie_offset, calc_sig, 0);
2505			/* compare */
2506			if (memcmp(calc_sig, sig, SCTP_SIGNATURE_SIZE) == 0)
2507				cookie_ok = 1;
2508		}
2509	} else {
2510		cookie_ok = 1;
2511	}
2512
2513	/*
2514	 * Now before we continue we must reconstruct our mbuf so that
2515	 * normal processing of any other chunks will work.
2516	 */
2517	{
2518		struct mbuf *m_at;
2519
2520		m_at = m;
2521		while (SCTP_BUF_NEXT(m_at) != NULL) {
2522			m_at = SCTP_BUF_NEXT(m_at);
2523		}
2524		SCTP_BUF_NEXT(m_at) = m_sig;
2525	}
2526
2527	if (cookie_ok == 0) {
2528		SCTPDBG(SCTP_DEBUG_INPUT2, "handle_cookie_echo: cookie signature validation failed!\n");
2529		SCTPDBG(SCTP_DEBUG_INPUT2,
2530		    "offset = %u, cookie_offset = %u, sig_offset = %u\n",
2531		    (uint32_t) offset, cookie_offset, sig_offset);
2532		return (NULL);
2533	}
2534	/*
2535	 * check the cookie timestamps to be sure it's not stale
2536	 */
2537	(void)SCTP_GETTIME_TIMEVAL(&now);
2538	/* Expire time is in Ticks, so we convert to seconds */
2539	time_expires.tv_sec = cookie->time_entered.tv_sec + TICKS_TO_SEC(cookie->cookie_life);
2540	time_expires.tv_usec = cookie->time_entered.tv_usec;
2541	/*
2542	 * TODO sctp_constants.h needs alternative time macros when _KERNEL
2543	 * is undefined.
2544	 */
2545	if (timevalcmp(&now, &time_expires, >)) {
2546		/* cookie is stale! */
2547		struct mbuf *op_err;
2548		struct sctp_stale_cookie_msg *scm;
2549		uint32_t tim;
2550
2551		op_err = sctp_get_mbuf_for_msg(sizeof(struct sctp_stale_cookie_msg),
2552		    0, M_DONTWAIT, 1, MT_DATA);
2553		if (op_err == NULL) {
2554			/* FOOBAR */
2555			return (NULL);
2556		}
2557		/* Set the len */
2558		SCTP_BUF_LEN(op_err) = sizeof(struct sctp_stale_cookie_msg);
2559		scm = mtod(op_err, struct sctp_stale_cookie_msg *);
2560		scm->ph.param_type = htons(SCTP_CAUSE_STALE_COOKIE);
2561		scm->ph.param_length = htons((sizeof(struct sctp_paramhdr) +
2562		    (sizeof(uint32_t))));
2563		/* seconds to usec */
2564		tim = (now.tv_sec - time_expires.tv_sec) * 1000000;
2565		/* add in usec */
2566		if (tim == 0)
2567			tim = now.tv_usec - cookie->time_entered.tv_usec;
2568		scm->time_usec = htonl(tim);
2569		sctp_send_operr_to(m, iphlen, op_err, cookie->peers_vtag,
2570		    vrf_id, port);
2571		return (NULL);
2572	}
2573	/*
2574	 * Now we must see with the lookup address if we have an existing
2575	 * asoc. This will only happen if we were in the COOKIE-WAIT state
2576	 * and a INIT collided with us and somewhere the peer sent the
2577	 * cookie on another address besides the single address our assoc
2578	 * had for him. In this case we will have one of the tie-tags set at
2579	 * least AND the address field in the cookie can be used to look it
2580	 * up.
2581	 */
2582	to = NULL;
2583	switch (cookie->addr_type) {
2584#ifdef INET6
2585	case SCTP_IPV6_ADDRESS:
2586		memset(&sin6, 0, sizeof(sin6));
2587		sin6.sin6_family = AF_INET6;
2588		sin6.sin6_len = sizeof(sin6);
2589		sin6.sin6_port = sh->src_port;
2590		sin6.sin6_scope_id = cookie->scope_id;
2591		memcpy(&sin6.sin6_addr.s6_addr, cookie->address,
2592		    sizeof(sin6.sin6_addr.s6_addr));
2593		to = (struct sockaddr *)&sin6;
2594		break;
2595#endif
2596#ifdef INET
2597	case SCTP_IPV4_ADDRESS:
2598		memset(&sin, 0, sizeof(sin));
2599		sin.sin_family = AF_INET;
2600		sin.sin_len = sizeof(sin);
2601		sin.sin_port = sh->src_port;
2602		sin.sin_addr.s_addr = cookie->address[0];
2603		to = (struct sockaddr *)&sin;
2604		break;
2605#endif
2606	default:
2607		/* This should not happen */
2608		return (NULL);
2609	}
2610	if ((*stcb == NULL) && to) {
2611		/* Yep, lets check */
2612		*stcb = sctp_findassociation_ep_addr(inp_p, to, netp, localep_sa, NULL);
2613		if (*stcb == NULL) {
2614			/*
2615			 * We should have only got back the same inp. If we
2616			 * got back a different ep we have a problem. The
2617			 * original findep got back l_inp and now
2618			 */
2619			if (l_inp != *inp_p) {
2620				SCTP_PRINTF("Bad problem find_ep got a diff inp then special_locate?\n");
2621			}
2622		} else {
2623			if (*locked_tcb == NULL) {
2624				/*
2625				 * In this case we found the assoc only
2626				 * after we locked the create lock. This
2627				 * means we are in a colliding case and we
2628				 * must make sure that we unlock the tcb if
2629				 * its one of the cases where we throw away
2630				 * the incoming packets.
2631				 */
2632				*locked_tcb = *stcb;
2633
2634				/*
2635				 * We must also increment the inp ref count
2636				 * since the ref_count flags was set when we
2637				 * did not find the TCB, now we found it
2638				 * which reduces the refcount.. we must
2639				 * raise it back out to balance it all :-)
2640				 */
2641				SCTP_INP_INCR_REF((*stcb)->sctp_ep);
2642				if ((*stcb)->sctp_ep != l_inp) {
2643					SCTP_PRINTF("Huh? ep:%p diff then l_inp:%p?\n",
2644					    (*stcb)->sctp_ep, l_inp);
2645				}
2646			}
2647		}
2648	}
2649	if (to == NULL) {
2650		return (NULL);
2651	}
2652	cookie_len -= SCTP_SIGNATURE_SIZE;
2653	if (*stcb == NULL) {
2654		/* this is the "normal" case... get a new TCB */
2655		*stcb = sctp_process_cookie_new(m, iphlen, offset, sh, cookie,
2656		    cookie_len, *inp_p, netp, to, &notification,
2657		    auth_skipped, auth_offset, auth_len, vrf_id, port);
2658	} else {
2659		/* this is abnormal... cookie-echo on existing TCB */
2660		had_a_existing_tcb = 1;
2661		*stcb = sctp_process_cookie_existing(m, iphlen, offset, sh,
2662		    cookie, cookie_len, *inp_p, *stcb, netp, to,
2663		    &notification, vrf_id, auth_skipped, auth_offset, auth_len, port);
2664	}
2665
2666	if (*stcb == NULL) {
2667		/* still no TCB... must be bad cookie-echo */
2668		return (NULL);
2669	}
2670	if ((*netp != NULL) && (m->m_flags & M_FLOWID)) {
2671		(*netp)->flowid = m->m_pkthdr.flowid;
2672#ifdef INVARIANTS
2673		(*netp)->flowidset = 1;
2674#endif
2675	}
2676	/*
2677	 * Ok, we built an association so confirm the address we sent the
2678	 * INIT-ACK to.
2679	 */
2680	netl = sctp_findnet(*stcb, to);
2681	/*
2682	 * This code should in theory NOT run but
2683	 */
2684	if (netl == NULL) {
2685		/* TSNH! Huh, why do I need to add this address here? */
2686		if (sctp_add_remote_addr(*stcb, to, NULL, SCTP_DONOT_SETSCOPE, SCTP_IN_COOKIE_PROC)) {
2687			return (NULL);
2688		}
2689		netl = sctp_findnet(*stcb, to);
2690	}
2691	if (netl) {
2692		if (netl->dest_state & SCTP_ADDR_UNCONFIRMED) {
2693			netl->dest_state &= ~SCTP_ADDR_UNCONFIRMED;
2694			(void)sctp_set_primary_addr((*stcb), (struct sockaddr *)NULL,
2695			    netl);
2696			send_int_conf = 1;
2697		}
2698	}
2699	sctp_start_net_timers(*stcb);
2700	if ((*inp_p)->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE) {
2701		if (!had_a_existing_tcb ||
2702		    (((*inp_p)->sctp_flags & SCTP_PCB_FLAGS_CONNECTED) == 0)) {
2703			/*
2704			 * If we have a NEW cookie or the connect never
2705			 * reached the connected state during collision we
2706			 * must do the TCP accept thing.
2707			 */
2708			struct socket *so, *oso;
2709			struct sctp_inpcb *inp;
2710
2711			if (notification == SCTP_NOTIFY_ASSOC_RESTART) {
2712				/*
2713				 * For a restart we will keep the same
2714				 * socket, no need to do anything. I THINK!!
2715				 */
2716				sctp_ulp_notify(notification, *stcb, 0, NULL, SCTP_SO_NOT_LOCKED);
2717				if (send_int_conf) {
2718					sctp_ulp_notify(SCTP_NOTIFY_INTERFACE_CONFIRMED,
2719					    (*stcb), 0, (void *)netl, SCTP_SO_NOT_LOCKED);
2720				}
2721				return (m);
2722			}
2723			oso = (*inp_p)->sctp_socket;
2724			atomic_add_int(&(*stcb)->asoc.refcnt, 1);
2725			SCTP_TCB_UNLOCK((*stcb));
2726			CURVNET_SET(oso->so_vnet);
2727			so = sonewconn(oso, 0
2728			    );
2729			CURVNET_RESTORE();
2730			SCTP_TCB_LOCK((*stcb));
2731			atomic_subtract_int(&(*stcb)->asoc.refcnt, 1);
2732
2733			if (so == NULL) {
2734				struct mbuf *op_err;
2735
2736#if defined (__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
2737				struct socket *pcb_so;
2738
2739#endif
2740				/* Too many sockets */
2741				SCTPDBG(SCTP_DEBUG_INPUT1, "process_cookie_new: no room for another socket!\n");
2742				op_err = sctp_generate_invmanparam(SCTP_CAUSE_OUT_OF_RESC);
2743				sctp_abort_association(*inp_p, NULL, m, iphlen,
2744				    sh, op_err, vrf_id, port);
2745#if defined (__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
2746				pcb_so = SCTP_INP_SO(*inp_p);
2747				atomic_add_int(&(*stcb)->asoc.refcnt, 1);
2748				SCTP_TCB_UNLOCK((*stcb));
2749				SCTP_SOCKET_LOCK(pcb_so, 1);
2750				SCTP_TCB_LOCK((*stcb));
2751				atomic_subtract_int(&(*stcb)->asoc.refcnt, 1);
2752#endif
2753				(void)sctp_free_assoc(*inp_p, *stcb, SCTP_NORMAL_PROC, SCTP_FROM_SCTP_INPUT + SCTP_LOC_20);
2754#if defined (__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
2755				SCTP_SOCKET_UNLOCK(pcb_so, 1);
2756#endif
2757				return (NULL);
2758			}
2759			inp = (struct sctp_inpcb *)so->so_pcb;
2760			SCTP_INP_INCR_REF(inp);
2761			/*
2762			 * We add the unbound flag here so that if we get an
2763			 * soabort() before we get the move_pcb done, we
2764			 * will properly cleanup.
2765			 */
2766			inp->sctp_flags = (SCTP_PCB_FLAGS_TCPTYPE |
2767			    SCTP_PCB_FLAGS_CONNECTED |
2768			    SCTP_PCB_FLAGS_IN_TCPPOOL |
2769			    SCTP_PCB_FLAGS_UNBOUND |
2770			    (SCTP_PCB_COPY_FLAGS & (*inp_p)->sctp_flags) |
2771			    SCTP_PCB_FLAGS_DONT_WAKE);
2772			inp->sctp_features = (*inp_p)->sctp_features;
2773			inp->sctp_mobility_features = (*inp_p)->sctp_mobility_features;
2774			inp->sctp_socket = so;
2775			inp->sctp_frag_point = (*inp_p)->sctp_frag_point;
2776			inp->sctp_cmt_on_off = (*inp_p)->sctp_cmt_on_off;
2777			inp->sctp_ecn_enable = (*inp_p)->sctp_ecn_enable;
2778			inp->partial_delivery_point = (*inp_p)->partial_delivery_point;
2779			inp->sctp_context = (*inp_p)->sctp_context;
2780			inp->local_strreset_support = (*inp_p)->local_strreset_support;
2781			inp->inp_starting_point_for_iterator = NULL;
2782			/*
2783			 * copy in the authentication parameters from the
2784			 * original endpoint
2785			 */
2786			if (inp->sctp_ep.local_hmacs)
2787				sctp_free_hmaclist(inp->sctp_ep.local_hmacs);
2788			inp->sctp_ep.local_hmacs =
2789			    sctp_copy_hmaclist((*inp_p)->sctp_ep.local_hmacs);
2790			if (inp->sctp_ep.local_auth_chunks)
2791				sctp_free_chunklist(inp->sctp_ep.local_auth_chunks);
2792			inp->sctp_ep.local_auth_chunks =
2793			    sctp_copy_chunklist((*inp_p)->sctp_ep.local_auth_chunks);
2794
2795			/*
2796			 * Now we must move it from one hash table to
2797			 * another and get the tcb in the right place.
2798			 */
2799
2800			/*
2801			 * This is where the one-2-one socket is put into
2802			 * the accept state waiting for the accept!
2803			 */
2804			if (*stcb) {
2805				(*stcb)->asoc.state |= SCTP_STATE_IN_ACCEPT_QUEUE;
2806			}
2807			sctp_move_pcb_and_assoc(*inp_p, inp, *stcb);
2808
2809			atomic_add_int(&(*stcb)->asoc.refcnt, 1);
2810			SCTP_TCB_UNLOCK((*stcb));
2811
2812			sctp_pull_off_control_to_new_inp((*inp_p), inp, *stcb,
2813			    0);
2814			SCTP_TCB_LOCK((*stcb));
2815			atomic_subtract_int(&(*stcb)->asoc.refcnt, 1);
2816
2817
2818			/*
2819			 * now we must check to see if we were aborted while
2820			 * the move was going on and the lock/unlock
2821			 * happened.
2822			 */
2823			if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE) {
2824				/*
2825				 * yep it was, we leave the assoc attached
2826				 * to the socket since the sctp_inpcb_free()
2827				 * call will send an abort for us.
2828				 */
2829				SCTP_INP_DECR_REF(inp);
2830				return (NULL);
2831			}
2832			SCTP_INP_DECR_REF(inp);
2833			/* Switch over to the new guy */
2834			*inp_p = inp;
2835			sctp_ulp_notify(notification, *stcb, 0, NULL, SCTP_SO_NOT_LOCKED);
2836			if (send_int_conf) {
2837				sctp_ulp_notify(SCTP_NOTIFY_INTERFACE_CONFIRMED,
2838				    (*stcb), 0, (void *)netl, SCTP_SO_NOT_LOCKED);
2839			}
2840			/*
2841			 * Pull it from the incomplete queue and wake the
2842			 * guy
2843			 */
2844#if defined (__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
2845			atomic_add_int(&(*stcb)->asoc.refcnt, 1);
2846			SCTP_TCB_UNLOCK((*stcb));
2847			SCTP_SOCKET_LOCK(so, 1);
2848#endif
2849			soisconnected(so);
2850#if defined (__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
2851			SCTP_TCB_LOCK((*stcb));
2852			atomic_subtract_int(&(*stcb)->asoc.refcnt, 1);
2853			SCTP_SOCKET_UNLOCK(so, 1);
2854#endif
2855			return (m);
2856		}
2857	}
2858	if ((*inp_p)->sctp_flags & SCTP_PCB_FLAGS_UDPTYPE) {
2859		if (notification) {
2860			sctp_ulp_notify(notification, *stcb, 0, NULL, SCTP_SO_NOT_LOCKED);
2861		}
2862		if (send_int_conf) {
2863			sctp_ulp_notify(SCTP_NOTIFY_INTERFACE_CONFIRMED,
2864			    (*stcb), 0, (void *)netl, SCTP_SO_NOT_LOCKED);
2865		}
2866	}
2867	return (m);
2868}
2869
2870static void
2871sctp_handle_cookie_ack(struct sctp_cookie_ack_chunk *cp SCTP_UNUSED,
2872    struct sctp_tcb *stcb, struct sctp_nets *net)
2873{
2874	/* cp must not be used, others call this without a c-ack :-) */
2875	struct sctp_association *asoc;
2876
2877	SCTPDBG(SCTP_DEBUG_INPUT2,
2878	    "sctp_handle_cookie_ack: handling COOKIE-ACK\n");
2879	if (stcb == NULL)
2880		return;
2881
2882	asoc = &stcb->asoc;
2883
2884	sctp_stop_all_cookie_timers(stcb);
2885	/* process according to association state */
2886	if (SCTP_GET_STATE(asoc) == SCTP_STATE_COOKIE_ECHOED) {
2887		/* state change only needed when I am in right state */
2888		SCTPDBG(SCTP_DEBUG_INPUT2, "moving to OPEN state\n");
2889		SCTP_SET_STATE(asoc, SCTP_STATE_OPEN);
2890		sctp_start_net_timers(stcb);
2891		if (asoc->state & SCTP_STATE_SHUTDOWN_PENDING) {
2892			sctp_timer_start(SCTP_TIMER_TYPE_SHUTDOWNGUARD,
2893			    stcb->sctp_ep, stcb, asoc->primary_destination);
2894
2895		}
2896		/* update RTO */
2897		SCTP_STAT_INCR_COUNTER32(sctps_activeestab);
2898		SCTP_STAT_INCR_GAUGE32(sctps_currestab);
2899		if (asoc->overall_error_count == 0) {
2900			net->RTO = sctp_calculate_rto(stcb, asoc, net,
2901			    &asoc->time_entered, sctp_align_safe_nocopy,
2902			    SCTP_RTT_FROM_NON_DATA);
2903		}
2904		(void)SCTP_GETTIME_TIMEVAL(&asoc->time_entered);
2905		sctp_ulp_notify(SCTP_NOTIFY_ASSOC_UP, stcb, 0, NULL, SCTP_SO_NOT_LOCKED);
2906		if ((stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE) ||
2907		    (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL)) {
2908#if defined (__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
2909			struct socket *so;
2910
2911#endif
2912			stcb->sctp_ep->sctp_flags |= SCTP_PCB_FLAGS_CONNECTED;
2913#if defined (__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
2914			so = SCTP_INP_SO(stcb->sctp_ep);
2915			atomic_add_int(&stcb->asoc.refcnt, 1);
2916			SCTP_TCB_UNLOCK(stcb);
2917			SCTP_SOCKET_LOCK(so, 1);
2918			SCTP_TCB_LOCK(stcb);
2919			atomic_subtract_int(&stcb->asoc.refcnt, 1);
2920#endif
2921			if ((stcb->asoc.state & SCTP_STATE_CLOSED_SOCKET) == 0) {
2922				soisconnected(stcb->sctp_socket);
2923			}
2924#if defined (__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
2925			SCTP_SOCKET_UNLOCK(so, 1);
2926#endif
2927		}
2928		/*
2929		 * since we did not send a HB make sure we don't double
2930		 * things
2931		 */
2932		net->hb_responded = 1;
2933
2934		if (stcb->asoc.state & SCTP_STATE_CLOSED_SOCKET) {
2935			/*
2936			 * We don't need to do the asconf thing, nor hb or
2937			 * autoclose if the socket is closed.
2938			 */
2939			goto closed_socket;
2940		}
2941		sctp_timer_start(SCTP_TIMER_TYPE_HEARTBEAT, stcb->sctp_ep,
2942		    stcb, net);
2943
2944
2945		if (stcb->asoc.sctp_autoclose_ticks &&
2946		    sctp_is_feature_on(stcb->sctp_ep, SCTP_PCB_FLAGS_AUTOCLOSE)) {
2947			sctp_timer_start(SCTP_TIMER_TYPE_AUTOCLOSE,
2948			    stcb->sctp_ep, stcb, NULL);
2949		}
2950		/*
2951		 * send ASCONF if parameters are pending and ASCONFs are
2952		 * allowed (eg. addresses changed when init/cookie echo were
2953		 * in flight)
2954		 */
2955		if ((sctp_is_feature_on(stcb->sctp_ep, SCTP_PCB_FLAGS_DO_ASCONF)) &&
2956		    (stcb->asoc.peer_supports_asconf) &&
2957		    (!TAILQ_EMPTY(&stcb->asoc.asconf_queue))) {
2958#ifdef SCTP_TIMER_BASED_ASCONF
2959			sctp_timer_start(SCTP_TIMER_TYPE_ASCONF,
2960			    stcb->sctp_ep, stcb,
2961			    stcb->asoc.primary_destination);
2962#else
2963			sctp_send_asconf(stcb, stcb->asoc.primary_destination,
2964			    SCTP_ADDR_NOT_LOCKED);
2965#endif
2966		}
2967	}
2968closed_socket:
2969	/* Toss the cookie if I can */
2970	sctp_toss_old_cookies(stcb, asoc);
2971	if (!TAILQ_EMPTY(&asoc->sent_queue)) {
2972		/* Restart the timer if we have pending data */
2973		struct sctp_tmit_chunk *chk;
2974
2975		chk = TAILQ_FIRST(&asoc->sent_queue);
2976		sctp_timer_start(SCTP_TIMER_TYPE_SEND, stcb->sctp_ep, stcb, chk->whoTo);
2977	}
2978}
2979
2980static void
2981sctp_handle_ecn_echo(struct sctp_ecne_chunk *cp,
2982    struct sctp_tcb *stcb)
2983{
2984	struct sctp_nets *net;
2985	struct sctp_tmit_chunk *lchk;
2986	struct sctp_ecne_chunk bkup;
2987	uint8_t override_bit;
2988	uint32_t tsn, window_data_tsn;
2989	int len;
2990	unsigned int pkt_cnt;
2991
2992	len = ntohs(cp->ch.chunk_length);
2993	if ((len != sizeof(struct sctp_ecne_chunk)) &&
2994	    (len != sizeof(struct old_sctp_ecne_chunk))) {
2995		return;
2996	}
2997	if (len == sizeof(struct old_sctp_ecne_chunk)) {
2998		/* Its the old format */
2999		memcpy(&bkup, cp, sizeof(struct old_sctp_ecne_chunk));
3000		bkup.num_pkts_since_cwr = htonl(1);
3001		cp = &bkup;
3002	}
3003	SCTP_STAT_INCR(sctps_recvecne);
3004	tsn = ntohl(cp->tsn);
3005	pkt_cnt = ntohl(cp->num_pkts_since_cwr);
3006	lchk = TAILQ_LAST(&stcb->asoc.send_queue, sctpchunk_listhead);
3007	if (lchk == NULL) {
3008		window_data_tsn = stcb->asoc.sending_seq - 1;
3009	} else {
3010		window_data_tsn = lchk->rec.data.TSN_seq;
3011	}
3012
3013	/* Find where it was sent to if possible. */
3014	net = NULL;
3015	TAILQ_FOREACH(lchk, &stcb->asoc.sent_queue, sctp_next) {
3016		if (lchk->rec.data.TSN_seq == tsn) {
3017			net = lchk->whoTo;
3018			net->ecn_prev_cwnd = lchk->rec.data.cwnd_at_send;
3019			break;
3020		}
3021		if (SCTP_TSN_GT(lchk->rec.data.TSN_seq, tsn)) {
3022			break;
3023		}
3024	}
3025	if (net == NULL) {
3026		/*
3027		 * What to do. A previous send of a CWR was possibly lost.
3028		 * See how old it is, we may have it marked on the actual
3029		 * net.
3030		 */
3031		TAILQ_FOREACH(net, &stcb->asoc.nets, sctp_next) {
3032			if (tsn == net->last_cwr_tsn) {
3033				/* Found him, send it off */
3034				break;
3035			}
3036		}
3037		if (net == NULL) {
3038			/*
3039			 * If we reach here, we need to send a special CWR
3040			 * that says hey, we did this a long time ago and
3041			 * you lost the response.
3042			 */
3043			net = TAILQ_FIRST(&stcb->asoc.nets);
3044			if (net == NULL) {
3045				/* TSNH */
3046				return;
3047			}
3048			override_bit = SCTP_CWR_REDUCE_OVERRIDE;
3049		} else {
3050			override_bit = 0;
3051		}
3052	} else {
3053		override_bit = 0;
3054	}
3055	if (SCTP_TSN_GT(tsn, net->cwr_window_tsn) &&
3056	    ((override_bit & SCTP_CWR_REDUCE_OVERRIDE) == 0)) {
3057		/*
3058		 * JRS - Use the congestion control given in the pluggable
3059		 * CC module
3060		 */
3061		stcb->asoc.cc_functions.sctp_cwnd_update_after_ecn_echo(stcb, net, 0, pkt_cnt);
3062		/*
3063		 * We reduce once every RTT. So we will only lower cwnd at
3064		 * the next sending seq i.e. the window_data_tsn
3065		 */
3066		net->cwr_window_tsn = window_data_tsn;
3067		net->ecn_ce_pkt_cnt += pkt_cnt;
3068		net->lost_cnt = pkt_cnt;
3069		net->last_cwr_tsn = tsn;
3070	} else {
3071		override_bit |= SCTP_CWR_IN_SAME_WINDOW;
3072		if (SCTP_TSN_GT(tsn, net->last_cwr_tsn) &&
3073		    ((override_bit & SCTP_CWR_REDUCE_OVERRIDE) == 0)) {
3074			/*
3075			 * Another loss in the same window update how many
3076			 * marks/packets lost we have had.
3077			 */
3078			int cnt = 1;
3079
3080			if (pkt_cnt > net->lost_cnt) {
3081				/* Should be the case */
3082				cnt = (pkt_cnt - net->lost_cnt);
3083				net->ecn_ce_pkt_cnt += cnt;
3084			}
3085			net->lost_cnt = pkt_cnt;
3086			net->last_cwr_tsn = tsn;
3087			/*
3088			 * Most CC functions will ignore this call, since we
3089			 * are in-window yet of the initial CE the peer saw.
3090			 */
3091			stcb->asoc.cc_functions.sctp_cwnd_update_after_ecn_echo(stcb, net, 1, cnt);
3092		}
3093	}
3094	/*
3095	 * We always send a CWR this way if our previous one was lost our
3096	 * peer will get an update, or if it is not time again to reduce we
3097	 * still get the cwr to the peer. Note we set the override when we
3098	 * could not find the TSN on the chunk or the destination network.
3099	 */
3100	sctp_send_cwr(stcb, net, net->last_cwr_tsn, override_bit);
3101}
3102
3103static void
3104sctp_handle_ecn_cwr(struct sctp_cwr_chunk *cp, struct sctp_tcb *stcb, struct sctp_nets *net)
3105{
3106	/*
3107	 * Here we get a CWR from the peer. We must look in the outqueue and
3108	 * make sure that we have a covered ECNE in teh control chunk part.
3109	 * If so remove it.
3110	 */
3111	struct sctp_tmit_chunk *chk;
3112	struct sctp_ecne_chunk *ecne;
3113	int override;
3114	uint32_t cwr_tsn;
3115
3116	cwr_tsn = ntohl(cp->tsn);
3117
3118	override = cp->ch.chunk_flags & SCTP_CWR_REDUCE_OVERRIDE;
3119	TAILQ_FOREACH(chk, &stcb->asoc.control_send_queue, sctp_next) {
3120		if (chk->rec.chunk_id.id != SCTP_ECN_ECHO) {
3121			continue;
3122		}
3123		if ((override == 0) && (chk->whoTo != net)) {
3124			/* Must be from the right src unless override is set */
3125			continue;
3126		}
3127		ecne = mtod(chk->data, struct sctp_ecne_chunk *);
3128		if (SCTP_TSN_GE(cwr_tsn, ntohl(ecne->tsn))) {
3129			/* this covers this ECNE, we can remove it */
3130			stcb->asoc.ecn_echo_cnt_onq--;
3131			TAILQ_REMOVE(&stcb->asoc.control_send_queue, chk,
3132			    sctp_next);
3133			if (chk->data) {
3134				sctp_m_freem(chk->data);
3135				chk->data = NULL;
3136			}
3137			stcb->asoc.ctrl_queue_cnt--;
3138			sctp_free_a_chunk(stcb, chk, SCTP_SO_NOT_LOCKED);
3139			if (override == 0) {
3140				break;
3141			}
3142		}
3143	}
3144}
3145
3146static void
3147sctp_handle_shutdown_complete(struct sctp_shutdown_complete_chunk *cp SCTP_UNUSED,
3148    struct sctp_tcb *stcb, struct sctp_nets *net)
3149{
3150	struct sctp_association *asoc;
3151
3152#if defined (__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
3153	struct socket *so;
3154
3155#endif
3156
3157	SCTPDBG(SCTP_DEBUG_INPUT2,
3158	    "sctp_handle_shutdown_complete: handling SHUTDOWN-COMPLETE\n");
3159	if (stcb == NULL)
3160		return;
3161
3162	asoc = &stcb->asoc;
3163	/* process according to association state */
3164	if (SCTP_GET_STATE(asoc) != SCTP_STATE_SHUTDOWN_ACK_SENT) {
3165		/* unexpected SHUTDOWN-COMPLETE... so ignore... */
3166		SCTPDBG(SCTP_DEBUG_INPUT2,
3167		    "sctp_handle_shutdown_complete: not in SCTP_STATE_SHUTDOWN_ACK_SENT --- ignore\n");
3168		SCTP_TCB_UNLOCK(stcb);
3169		return;
3170	}
3171	/* notify upper layer protocol */
3172	if (stcb->sctp_socket) {
3173		sctp_ulp_notify(SCTP_NOTIFY_ASSOC_DOWN, stcb, 0, NULL, SCTP_SO_NOT_LOCKED);
3174		/* are the queues empty? they should be */
3175		if (!TAILQ_EMPTY(&asoc->send_queue) ||
3176		    !TAILQ_EMPTY(&asoc->sent_queue) ||
3177		    !stcb->asoc.ss_functions.sctp_ss_is_empty(stcb, asoc)) {
3178			sctp_report_all_outbound(stcb, 0, 0, SCTP_SO_NOT_LOCKED);
3179		}
3180	}
3181	/* stop the timer */
3182	sctp_timer_stop(SCTP_TIMER_TYPE_SHUTDOWNACK, stcb->sctp_ep, stcb, net, SCTP_FROM_SCTP_INPUT + SCTP_LOC_22);
3183	SCTP_STAT_INCR_COUNTER32(sctps_shutdown);
3184	/* free the TCB */
3185	SCTPDBG(SCTP_DEBUG_INPUT2,
3186	    "sctp_handle_shutdown_complete: calls free-asoc\n");
3187#if defined (__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
3188	so = SCTP_INP_SO(stcb->sctp_ep);
3189	atomic_add_int(&stcb->asoc.refcnt, 1);
3190	SCTP_TCB_UNLOCK(stcb);
3191	SCTP_SOCKET_LOCK(so, 1);
3192	SCTP_TCB_LOCK(stcb);
3193	atomic_subtract_int(&stcb->asoc.refcnt, 1);
3194#endif
3195	(void)sctp_free_assoc(stcb->sctp_ep, stcb, SCTP_NORMAL_PROC, SCTP_FROM_SCTP_INPUT + SCTP_LOC_23);
3196#if defined (__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
3197	SCTP_SOCKET_UNLOCK(so, 1);
3198#endif
3199	return;
3200}
3201
3202static int
3203process_chunk_drop(struct sctp_tcb *stcb, struct sctp_chunk_desc *desc,
3204    struct sctp_nets *net, uint8_t flg)
3205{
3206	switch (desc->chunk_type) {
3207	case SCTP_DATA:
3208		/* find the tsn to resend (possibly */
3209		{
3210			uint32_t tsn;
3211			struct sctp_tmit_chunk *tp1;
3212
3213			tsn = ntohl(desc->tsn_ifany);
3214			TAILQ_FOREACH(tp1, &stcb->asoc.sent_queue, sctp_next) {
3215				if (tp1->rec.data.TSN_seq == tsn) {
3216					/* found it */
3217					break;
3218				}
3219				if (SCTP_TSN_GT(tp1->rec.data.TSN_seq, tsn)) {
3220					/* not found */
3221					tp1 = NULL;
3222					break;
3223				}
3224			}
3225			if (tp1 == NULL) {
3226				/*
3227				 * Do it the other way , aka without paying
3228				 * attention to queue seq order.
3229				 */
3230				SCTP_STAT_INCR(sctps_pdrpdnfnd);
3231				TAILQ_FOREACH(tp1, &stcb->asoc.sent_queue, sctp_next) {
3232					if (tp1->rec.data.TSN_seq == tsn) {
3233						/* found it */
3234						break;
3235					}
3236				}
3237			}
3238			if (tp1 == NULL) {
3239				SCTP_STAT_INCR(sctps_pdrptsnnf);
3240			}
3241			if ((tp1) && (tp1->sent < SCTP_DATAGRAM_ACKED)) {
3242				uint8_t *ddp;
3243
3244				if (((flg & SCTP_BADCRC) == 0) &&
3245				    ((flg & SCTP_FROM_MIDDLE_BOX) == 0)) {
3246					return (0);
3247				}
3248				if ((stcb->asoc.peers_rwnd == 0) &&
3249				    ((flg & SCTP_FROM_MIDDLE_BOX) == 0)) {
3250					SCTP_STAT_INCR(sctps_pdrpdiwnp);
3251					return (0);
3252				}
3253				if (stcb->asoc.peers_rwnd == 0 &&
3254				    (flg & SCTP_FROM_MIDDLE_BOX)) {
3255					SCTP_STAT_INCR(sctps_pdrpdizrw);
3256					return (0);
3257				}
3258				ddp = (uint8_t *) (mtod(tp1->data, caddr_t)+
3259				    sizeof(struct sctp_data_chunk));
3260				{
3261					unsigned int iii;
3262
3263					for (iii = 0; iii < sizeof(desc->data_bytes);
3264					    iii++) {
3265						if (ddp[iii] != desc->data_bytes[iii]) {
3266							SCTP_STAT_INCR(sctps_pdrpbadd);
3267							return (-1);
3268						}
3269					}
3270				}
3271
3272				if (tp1->do_rtt) {
3273					/*
3274					 * this guy had a RTO calculation
3275					 * pending on it, cancel it
3276					 */
3277					if (tp1->whoTo->rto_needed == 0) {
3278						tp1->whoTo->rto_needed = 1;
3279					}
3280					tp1->do_rtt = 0;
3281				}
3282				SCTP_STAT_INCR(sctps_pdrpmark);
3283				if (tp1->sent != SCTP_DATAGRAM_RESEND)
3284					sctp_ucount_incr(stcb->asoc.sent_queue_retran_cnt);
3285				/*
3286				 * mark it as if we were doing a FR, since
3287				 * we will be getting gap ack reports behind
3288				 * the info from the router.
3289				 */
3290				tp1->rec.data.doing_fast_retransmit = 1;
3291				/*
3292				 * mark the tsn with what sequences can
3293				 * cause a new FR.
3294				 */
3295				if (TAILQ_EMPTY(&stcb->asoc.send_queue)) {
3296					tp1->rec.data.fast_retran_tsn = stcb->asoc.sending_seq;
3297				} else {
3298					tp1->rec.data.fast_retran_tsn = (TAILQ_FIRST(&stcb->asoc.send_queue))->rec.data.TSN_seq;
3299				}
3300
3301				/* restart the timer */
3302				sctp_timer_stop(SCTP_TIMER_TYPE_SEND, stcb->sctp_ep,
3303				    stcb, tp1->whoTo, SCTP_FROM_SCTP_INPUT + SCTP_LOC_24);
3304				sctp_timer_start(SCTP_TIMER_TYPE_SEND, stcb->sctp_ep,
3305				    stcb, tp1->whoTo);
3306
3307				/* fix counts and things */
3308				if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_FLIGHT_LOGGING_ENABLE) {
3309					sctp_misc_ints(SCTP_FLIGHT_LOG_DOWN_PDRP,
3310					    tp1->whoTo->flight_size,
3311					    tp1->book_size,
3312					    (uintptr_t) stcb,
3313					    tp1->rec.data.TSN_seq);
3314				}
3315				if (tp1->sent < SCTP_DATAGRAM_RESEND) {
3316					sctp_flight_size_decrease(tp1);
3317					sctp_total_flight_decrease(stcb, tp1);
3318				}
3319				tp1->sent = SCTP_DATAGRAM_RESEND;
3320			} {
3321				/* audit code */
3322				unsigned int audit;
3323
3324				audit = 0;
3325				TAILQ_FOREACH(tp1, &stcb->asoc.sent_queue, sctp_next) {
3326					if (tp1->sent == SCTP_DATAGRAM_RESEND)
3327						audit++;
3328				}
3329				TAILQ_FOREACH(tp1, &stcb->asoc.control_send_queue,
3330				    sctp_next) {
3331					if (tp1->sent == SCTP_DATAGRAM_RESEND)
3332						audit++;
3333				}
3334				if (audit != stcb->asoc.sent_queue_retran_cnt) {
3335					SCTP_PRINTF("**Local Audit finds cnt:%d asoc cnt:%d\n",
3336					    audit, stcb->asoc.sent_queue_retran_cnt);
3337#ifndef SCTP_AUDITING_ENABLED
3338					stcb->asoc.sent_queue_retran_cnt = audit;
3339#endif
3340				}
3341			}
3342		}
3343		break;
3344	case SCTP_ASCONF:
3345		{
3346			struct sctp_tmit_chunk *asconf;
3347
3348			TAILQ_FOREACH(asconf, &stcb->asoc.control_send_queue,
3349			    sctp_next) {
3350				if (asconf->rec.chunk_id.id == SCTP_ASCONF) {
3351					break;
3352				}
3353			}
3354			if (asconf) {
3355				if (asconf->sent != SCTP_DATAGRAM_RESEND)
3356					sctp_ucount_incr(stcb->asoc.sent_queue_retran_cnt);
3357				asconf->sent = SCTP_DATAGRAM_RESEND;
3358				asconf->snd_count--;
3359			}
3360		}
3361		break;
3362	case SCTP_INITIATION:
3363		/* resend the INIT */
3364		stcb->asoc.dropped_special_cnt++;
3365		if (stcb->asoc.dropped_special_cnt < SCTP_RETRY_DROPPED_THRESH) {
3366			/*
3367			 * If we can get it in, in a few attempts we do
3368			 * this, otherwise we let the timer fire.
3369			 */
3370			sctp_timer_stop(SCTP_TIMER_TYPE_INIT, stcb->sctp_ep,
3371			    stcb, net, SCTP_FROM_SCTP_INPUT + SCTP_LOC_25);
3372			sctp_send_initiate(stcb->sctp_ep, stcb, SCTP_SO_NOT_LOCKED);
3373		}
3374		break;
3375	case SCTP_SELECTIVE_ACK:
3376	case SCTP_NR_SELECTIVE_ACK:
3377		/* resend the sack */
3378		sctp_send_sack(stcb, SCTP_SO_NOT_LOCKED);
3379		break;
3380	case SCTP_HEARTBEAT_REQUEST:
3381		/* resend a demand HB */
3382		if ((stcb->asoc.overall_error_count + 3) < stcb->asoc.max_send_times) {
3383			/*
3384			 * Only retransmit if we KNOW we wont destroy the
3385			 * tcb
3386			 */
3387			sctp_send_hb(stcb, net, SCTP_SO_NOT_LOCKED);
3388		}
3389		break;
3390	case SCTP_SHUTDOWN:
3391		sctp_send_shutdown(stcb, net);
3392		break;
3393	case SCTP_SHUTDOWN_ACK:
3394		sctp_send_shutdown_ack(stcb, net);
3395		break;
3396	case SCTP_COOKIE_ECHO:
3397		{
3398			struct sctp_tmit_chunk *cookie;
3399
3400			cookie = NULL;
3401			TAILQ_FOREACH(cookie, &stcb->asoc.control_send_queue,
3402			    sctp_next) {
3403				if (cookie->rec.chunk_id.id == SCTP_COOKIE_ECHO) {
3404					break;
3405				}
3406			}
3407			if (cookie) {
3408				if (cookie->sent != SCTP_DATAGRAM_RESEND)
3409					sctp_ucount_incr(stcb->asoc.sent_queue_retran_cnt);
3410				cookie->sent = SCTP_DATAGRAM_RESEND;
3411				sctp_stop_all_cookie_timers(stcb);
3412			}
3413		}
3414		break;
3415	case SCTP_COOKIE_ACK:
3416		sctp_send_cookie_ack(stcb);
3417		break;
3418	case SCTP_ASCONF_ACK:
3419		/* resend last asconf ack */
3420		sctp_send_asconf_ack(stcb);
3421		break;
3422	case SCTP_FORWARD_CUM_TSN:
3423		send_forward_tsn(stcb, &stcb->asoc);
3424		break;
3425		/* can't do anything with these */
3426	case SCTP_PACKET_DROPPED:
3427	case SCTP_INITIATION_ACK:	/* this should not happen */
3428	case SCTP_HEARTBEAT_ACK:
3429	case SCTP_ABORT_ASSOCIATION:
3430	case SCTP_OPERATION_ERROR:
3431	case SCTP_SHUTDOWN_COMPLETE:
3432	case SCTP_ECN_ECHO:
3433	case SCTP_ECN_CWR:
3434	default:
3435		break;
3436	}
3437	return (0);
3438}
3439
3440void
3441sctp_reset_in_stream(struct sctp_tcb *stcb, int number_entries, uint16_t * list)
3442{
3443	int i;
3444	uint16_t temp;
3445
3446	/*
3447	 * We set things to 0xffff since this is the last delivered sequence
3448	 * and we will be sending in 0 after the reset.
3449	 */
3450
3451	if (number_entries) {
3452		for (i = 0; i < number_entries; i++) {
3453			temp = ntohs(list[i]);
3454			if (temp >= stcb->asoc.streamincnt) {
3455				continue;
3456			}
3457			stcb->asoc.strmin[temp].last_sequence_delivered = 0xffff;
3458		}
3459	} else {
3460		list = NULL;
3461		for (i = 0; i < stcb->asoc.streamincnt; i++) {
3462			stcb->asoc.strmin[i].last_sequence_delivered = 0xffff;
3463		}
3464	}
3465	sctp_ulp_notify(SCTP_NOTIFY_STR_RESET_RECV, stcb, number_entries, (void *)list, SCTP_SO_NOT_LOCKED);
3466}
3467
3468static void
3469sctp_reset_out_streams(struct sctp_tcb *stcb, int number_entries, uint16_t * list)
3470{
3471	int i;
3472
3473	if (number_entries == 0) {
3474		for (i = 0; i < stcb->asoc.streamoutcnt; i++) {
3475			stcb->asoc.strmout[i].next_sequence_sent = 0;
3476		}
3477	} else if (number_entries) {
3478		for (i = 0; i < number_entries; i++) {
3479			uint16_t temp;
3480
3481			temp = ntohs(list[i]);
3482			if (temp >= stcb->asoc.streamoutcnt) {
3483				/* no such stream */
3484				continue;
3485			}
3486			stcb->asoc.strmout[temp].next_sequence_sent = 0;
3487		}
3488	}
3489	sctp_ulp_notify(SCTP_NOTIFY_STR_RESET_SEND, stcb, number_entries, (void *)list, SCTP_SO_NOT_LOCKED);
3490}
3491
3492
3493struct sctp_stream_reset_out_request *
3494sctp_find_stream_reset(struct sctp_tcb *stcb, uint32_t seq, struct sctp_tmit_chunk **bchk)
3495{
3496	struct sctp_association *asoc;
3497	struct sctp_stream_reset_out_req *req;
3498	struct sctp_stream_reset_out_request *r;
3499	struct sctp_tmit_chunk *chk;
3500	int len, clen;
3501
3502	asoc = &stcb->asoc;
3503	if (TAILQ_EMPTY(&stcb->asoc.control_send_queue)) {
3504		asoc->stream_reset_outstanding = 0;
3505		return (NULL);
3506	}
3507	if (stcb->asoc.str_reset == NULL) {
3508		asoc->stream_reset_outstanding = 0;
3509		return (NULL);
3510	}
3511	chk = stcb->asoc.str_reset;
3512	if (chk->data == NULL) {
3513		return (NULL);
3514	}
3515	if (bchk) {
3516		/* he wants a copy of the chk pointer */
3517		*bchk = chk;
3518	}
3519	clen = chk->send_size;
3520	req = mtod(chk->data, struct sctp_stream_reset_out_req *);
3521	r = &req->sr_req;
3522	if (ntohl(r->request_seq) == seq) {
3523		/* found it */
3524		return (r);
3525	}
3526	len = SCTP_SIZE32(ntohs(r->ph.param_length));
3527	if (clen > (len + (int)sizeof(struct sctp_chunkhdr))) {
3528		/* move to the next one, there can only be a max of two */
3529		r = (struct sctp_stream_reset_out_request *)((caddr_t)r + len);
3530		if (ntohl(r->request_seq) == seq) {
3531			return (r);
3532		}
3533	}
3534	/* that seq is not here */
3535	return (NULL);
3536}
3537
3538static void
3539sctp_clean_up_stream_reset(struct sctp_tcb *stcb)
3540{
3541	struct sctp_association *asoc;
3542	struct sctp_tmit_chunk *chk = stcb->asoc.str_reset;
3543
3544	if (stcb->asoc.str_reset == NULL) {
3545		return;
3546	}
3547	asoc = &stcb->asoc;
3548
3549	sctp_timer_stop(SCTP_TIMER_TYPE_STRRESET, stcb->sctp_ep, stcb, chk->whoTo, SCTP_FROM_SCTP_INPUT + SCTP_LOC_26);
3550	TAILQ_REMOVE(&asoc->control_send_queue,
3551	    chk,
3552	    sctp_next);
3553	if (chk->data) {
3554		sctp_m_freem(chk->data);
3555		chk->data = NULL;
3556	}
3557	asoc->ctrl_queue_cnt--;
3558	sctp_free_a_chunk(stcb, chk, SCTP_SO_NOT_LOCKED);
3559	/* sa_ignore NO_NULL_CHK */
3560	stcb->asoc.str_reset = NULL;
3561}
3562
3563
3564static int
3565sctp_handle_stream_reset_response(struct sctp_tcb *stcb,
3566    uint32_t seq, uint32_t action,
3567    struct sctp_stream_reset_response *respin)
3568{
3569	uint16_t type;
3570	int lparm_len;
3571	struct sctp_association *asoc = &stcb->asoc;
3572	struct sctp_tmit_chunk *chk;
3573	struct sctp_stream_reset_out_request *srparam;
3574	int number_entries;
3575
3576	if (asoc->stream_reset_outstanding == 0) {
3577		/* duplicate */
3578		return (0);
3579	}
3580	if (seq == stcb->asoc.str_reset_seq_out) {
3581		srparam = sctp_find_stream_reset(stcb, seq, &chk);
3582		if (srparam) {
3583			stcb->asoc.str_reset_seq_out++;
3584			type = ntohs(srparam->ph.param_type);
3585			lparm_len = ntohs(srparam->ph.param_length);
3586			if (type == SCTP_STR_RESET_OUT_REQUEST) {
3587				number_entries = (lparm_len - sizeof(struct sctp_stream_reset_out_request)) / sizeof(uint16_t);
3588				asoc->stream_reset_out_is_outstanding = 0;
3589				if (asoc->stream_reset_outstanding)
3590					asoc->stream_reset_outstanding--;
3591				if (action == SCTP_STREAM_RESET_RESULT_PERFORMED) {
3592					/* do it */
3593					sctp_reset_out_streams(stcb, number_entries, srparam->list_of_streams);
3594				} else if (action == SCTP_STREAM_RESET_RESULT_DENIED) {
3595					sctp_ulp_notify(SCTP_NOTIFY_STR_RESET_DENIED_OUT, stcb, number_entries, srparam->list_of_streams, SCTP_SO_NOT_LOCKED);
3596				} else {
3597					sctp_ulp_notify(SCTP_NOTIFY_STR_RESET_FAILED_OUT, stcb, number_entries, srparam->list_of_streams, SCTP_SO_NOT_LOCKED);
3598				}
3599			} else if (type == SCTP_STR_RESET_IN_REQUEST) {
3600				/* Answered my request */
3601				number_entries = (lparm_len - sizeof(struct sctp_stream_reset_in_request)) / sizeof(uint16_t);
3602				if (asoc->stream_reset_outstanding)
3603					asoc->stream_reset_outstanding--;
3604				if (action == SCTP_STREAM_RESET_RESULT_DENIED) {
3605					sctp_ulp_notify(SCTP_NOTIFY_STR_RESET_DENIED_IN, stcb,
3606					    number_entries, srparam->list_of_streams, SCTP_SO_NOT_LOCKED);
3607				} else if (action != SCTP_STREAM_RESET_RESULT_PERFORMED) {
3608					sctp_ulp_notify(SCTP_NOTIFY_STR_RESET_FAILED_IN, stcb,
3609					    number_entries, srparam->list_of_streams, SCTP_SO_NOT_LOCKED);
3610				}
3611			} else if (type == SCTP_STR_RESET_ADD_OUT_STREAMS) {
3612				/* Ok we now may have more streams */
3613				int num_stream;
3614
3615				num_stream = stcb->asoc.strm_pending_add_size;
3616				if (num_stream > (stcb->asoc.strm_realoutsize - stcb->asoc.streamoutcnt)) {
3617					/* TSNH */
3618					num_stream = stcb->asoc.strm_realoutsize - stcb->asoc.streamoutcnt;
3619				}
3620				stcb->asoc.strm_pending_add_size = 0;
3621				if (asoc->stream_reset_outstanding)
3622					asoc->stream_reset_outstanding--;
3623				if (action == SCTP_STREAM_RESET_RESULT_PERFORMED) {
3624					/* Put the new streams into effect */
3625					stcb->asoc.streamoutcnt += num_stream;
3626					sctp_notify_stream_reset_add(stcb, stcb->asoc.streamincnt, stcb->asoc.streamoutcnt, 0);
3627				} else if (action == SCTP_STREAM_RESET_RESULT_DENIED) {
3628					sctp_notify_stream_reset_add(stcb, stcb->asoc.streamincnt, stcb->asoc.streamoutcnt,
3629					    SCTP_STREAM_CHANGE_DENIED);
3630				} else {
3631					sctp_notify_stream_reset_add(stcb, stcb->asoc.streamincnt, stcb->asoc.streamoutcnt,
3632					    SCTP_STREAM_CHANGE_FAILED);
3633				}
3634			} else if (type == SCTP_STR_RESET_ADD_IN_STREAMS) {
3635				if (asoc->stream_reset_outstanding)
3636					asoc->stream_reset_outstanding--;
3637				if (action == SCTP_STREAM_RESET_RESULT_DENIED) {
3638					sctp_notify_stream_reset_add(stcb, stcb->asoc.streamincnt, stcb->asoc.streamoutcnt,
3639					    SCTP_STREAM_CHANGE_DENIED);
3640				} else if (action != SCTP_STREAM_RESET_RESULT_PERFORMED) {
3641					sctp_notify_stream_reset_add(stcb, stcb->asoc.streamincnt, stcb->asoc.streamoutcnt,
3642					    SCTP_STREAM_CHANGE_FAILED);
3643				}
3644			} else if (type == SCTP_STR_RESET_TSN_REQUEST) {
3645				/**
3646				 * a) Adopt the new in tsn.
3647				 * b) reset the map
3648				 * c) Adopt the new out-tsn
3649				 */
3650				struct sctp_stream_reset_response_tsn *resp;
3651				struct sctp_forward_tsn_chunk fwdtsn;
3652				int abort_flag = 0;
3653
3654				if (respin == NULL) {
3655					/* huh ? */
3656					return (0);
3657				}
3658				if (action == SCTP_STREAM_RESET_RESULT_PERFORMED) {
3659					resp = (struct sctp_stream_reset_response_tsn *)respin;
3660					asoc->stream_reset_outstanding--;
3661					fwdtsn.ch.chunk_length = htons(sizeof(struct sctp_forward_tsn_chunk));
3662					fwdtsn.ch.chunk_type = SCTP_FORWARD_CUM_TSN;
3663					fwdtsn.new_cumulative_tsn = htonl(ntohl(resp->senders_next_tsn) - 1);
3664					sctp_handle_forward_tsn(stcb, &fwdtsn, &abort_flag, NULL, 0);
3665					if (abort_flag) {
3666						return (1);
3667					}
3668					stcb->asoc.highest_tsn_inside_map = (ntohl(resp->senders_next_tsn) - 1);
3669					if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_MAP_LOGGING_ENABLE) {
3670						sctp_log_map(0, 7, asoc->highest_tsn_inside_map, SCTP_MAP_SLIDE_RESULT);
3671					}
3672					stcb->asoc.tsn_last_delivered = stcb->asoc.cumulative_tsn = stcb->asoc.highest_tsn_inside_map;
3673					stcb->asoc.mapping_array_base_tsn = ntohl(resp->senders_next_tsn);
3674					memset(stcb->asoc.mapping_array, 0, stcb->asoc.mapping_array_size);
3675
3676					stcb->asoc.highest_tsn_inside_nr_map = stcb->asoc.highest_tsn_inside_map;
3677					memset(stcb->asoc.nr_mapping_array, 0, stcb->asoc.mapping_array_size);
3678
3679					stcb->asoc.sending_seq = ntohl(resp->receivers_next_tsn);
3680					stcb->asoc.last_acked_seq = stcb->asoc.cumulative_tsn;
3681
3682					sctp_reset_out_streams(stcb, 0, (uint16_t *) NULL);
3683					sctp_reset_in_stream(stcb, 0, (uint16_t *) NULL);
3684					sctp_notify_stream_reset_tsn(stcb, stcb->asoc.sending_seq, (stcb->asoc.mapping_array_base_tsn + 1), 0);
3685				} else if (action == SCTP_STREAM_RESET_RESULT_DENIED) {
3686					sctp_notify_stream_reset_tsn(stcb, stcb->asoc.sending_seq, (stcb->asoc.mapping_array_base_tsn + 1),
3687					    SCTP_ASSOC_RESET_DENIED);
3688				} else {
3689					sctp_notify_stream_reset_tsn(stcb, stcb->asoc.sending_seq, (stcb->asoc.mapping_array_base_tsn + 1),
3690					    SCTP_ASSOC_RESET_FAILED);
3691				}
3692			}
3693			/* get rid of the request and get the request flags */
3694			if (asoc->stream_reset_outstanding == 0) {
3695				sctp_clean_up_stream_reset(stcb);
3696			}
3697		}
3698	}
3699	return (0);
3700}
3701
3702static void
3703sctp_handle_str_reset_request_in(struct sctp_tcb *stcb,
3704    struct sctp_tmit_chunk *chk,
3705    struct sctp_stream_reset_in_request *req, int trunc)
3706{
3707	uint32_t seq;
3708	int len, i;
3709	int number_entries;
3710	uint16_t temp;
3711
3712	/*
3713	 * peer wants me to send a str-reset to him for my outgoing seq's if
3714	 * seq_in is right.
3715	 */
3716	struct sctp_association *asoc = &stcb->asoc;
3717
3718	seq = ntohl(req->request_seq);
3719	if (asoc->str_reset_seq_in == seq) {
3720		asoc->last_reset_action[1] = asoc->last_reset_action[0];
3721		if (!(asoc->local_strreset_support & SCTP_ENABLE_RESET_STREAM_REQ)) {
3722			asoc->last_reset_action[0] = SCTP_STREAM_RESET_RESULT_DENIED;
3723		} else if (trunc) {
3724			/* Can't do it, since they exceeded our buffer size  */
3725			asoc->last_reset_action[0] = SCTP_STREAM_RESET_RESULT_DENIED;
3726		} else if (stcb->asoc.stream_reset_out_is_outstanding == 0) {
3727			len = ntohs(req->ph.param_length);
3728			number_entries = ((len - sizeof(struct sctp_stream_reset_in_request)) / sizeof(uint16_t));
3729			for (i = 0; i < number_entries; i++) {
3730				temp = ntohs(req->list_of_streams[i]);
3731				req->list_of_streams[i] = temp;
3732			}
3733			asoc->last_reset_action[0] = SCTP_STREAM_RESET_RESULT_PERFORMED;
3734			sctp_add_stream_reset_out(chk, number_entries, req->list_of_streams,
3735			    asoc->str_reset_seq_out,
3736			    seq, (asoc->sending_seq - 1));
3737			asoc->stream_reset_out_is_outstanding = 1;
3738			asoc->str_reset = chk;
3739			sctp_timer_start(SCTP_TIMER_TYPE_STRRESET, stcb->sctp_ep, stcb, chk->whoTo);
3740			stcb->asoc.stream_reset_outstanding++;
3741		} else {
3742			/* Can't do it, since we have sent one out */
3743			asoc->last_reset_action[0] = SCTP_STREAM_RESET_RESULT_ERR_IN_PROGRESS;
3744		}
3745		sctp_add_stream_reset_result(chk, seq, asoc->last_reset_action[0]);
3746		asoc->str_reset_seq_in++;
3747	} else if (asoc->str_reset_seq_in - 1 == seq) {
3748		sctp_add_stream_reset_result(chk, seq, asoc->last_reset_action[0]);
3749	} else if (asoc->str_reset_seq_in - 2 == seq) {
3750		sctp_add_stream_reset_result(chk, seq, asoc->last_reset_action[1]);
3751	} else {
3752		sctp_add_stream_reset_result(chk, seq, SCTP_STREAM_RESET_RESULT_ERR_BAD_SEQNO);
3753	}
3754}
3755
3756static int
3757sctp_handle_str_reset_request_tsn(struct sctp_tcb *stcb,
3758    struct sctp_tmit_chunk *chk,
3759    struct sctp_stream_reset_tsn_request *req)
3760{
3761	/* reset all in and out and update the tsn */
3762	/*
3763	 * A) reset my str-seq's on in and out. B) Select a receive next,
3764	 * and set cum-ack to it. Also process this selected number as a
3765	 * fwd-tsn as well. C) set in the response my next sending seq.
3766	 */
3767	struct sctp_forward_tsn_chunk fwdtsn;
3768	struct sctp_association *asoc = &stcb->asoc;
3769	int abort_flag = 0;
3770	uint32_t seq;
3771
3772	seq = ntohl(req->request_seq);
3773	if (asoc->str_reset_seq_in == seq) {
3774		asoc->last_reset_action[1] = stcb->asoc.last_reset_action[0];
3775		if (!(asoc->local_strreset_support & SCTP_ENABLE_CHANGE_ASSOC_REQ)) {
3776			asoc->last_reset_action[0] = SCTP_STREAM_RESET_RESULT_DENIED;
3777		} else {
3778			fwdtsn.ch.chunk_length = htons(sizeof(struct sctp_forward_tsn_chunk));
3779			fwdtsn.ch.chunk_type = SCTP_FORWARD_CUM_TSN;
3780			fwdtsn.ch.chunk_flags = 0;
3781			fwdtsn.new_cumulative_tsn = htonl(stcb->asoc.highest_tsn_inside_map + 1);
3782			sctp_handle_forward_tsn(stcb, &fwdtsn, &abort_flag, NULL, 0);
3783			if (abort_flag) {
3784				return (1);
3785			}
3786			asoc->highest_tsn_inside_map += SCTP_STREAM_RESET_TSN_DELTA;
3787			if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_MAP_LOGGING_ENABLE) {
3788				sctp_log_map(0, 10, asoc->highest_tsn_inside_map, SCTP_MAP_SLIDE_RESULT);
3789			}
3790			asoc->tsn_last_delivered = asoc->cumulative_tsn = asoc->highest_tsn_inside_map;
3791			asoc->mapping_array_base_tsn = asoc->highest_tsn_inside_map + 1;
3792			memset(asoc->mapping_array, 0, asoc->mapping_array_size);
3793			asoc->highest_tsn_inside_nr_map = asoc->highest_tsn_inside_map;
3794			memset(asoc->nr_mapping_array, 0, asoc->mapping_array_size);
3795			atomic_add_int(&asoc->sending_seq, 1);
3796			/* save off historical data for retrans */
3797			asoc->last_sending_seq[1] = asoc->last_sending_seq[0];
3798			asoc->last_sending_seq[0] = asoc->sending_seq;
3799			asoc->last_base_tsnsent[1] = asoc->last_base_tsnsent[0];
3800			asoc->last_base_tsnsent[0] = asoc->mapping_array_base_tsn;
3801			sctp_reset_out_streams(stcb, 0, (uint16_t *) NULL);
3802			sctp_reset_in_stream(stcb, 0, (uint16_t *) NULL);
3803			asoc->last_reset_action[0] = SCTP_STREAM_RESET_RESULT_PERFORMED;
3804			sctp_notify_stream_reset_tsn(stcb, asoc->sending_seq, (asoc->mapping_array_base_tsn + 1), 0);
3805		}
3806		sctp_add_stream_reset_result_tsn(chk, seq, asoc->last_reset_action[0],
3807		    asoc->last_sending_seq[0], asoc->last_base_tsnsent[0]);
3808		asoc->str_reset_seq_in++;
3809	} else if (asoc->str_reset_seq_in - 1 == seq) {
3810		sctp_add_stream_reset_result_tsn(chk, seq, asoc->last_reset_action[0],
3811		    asoc->last_sending_seq[0], asoc->last_base_tsnsent[0]);
3812	} else if (asoc->str_reset_seq_in - 2 == seq) {
3813		sctp_add_stream_reset_result_tsn(chk, seq, asoc->last_reset_action[1],
3814		    asoc->last_sending_seq[1], asoc->last_base_tsnsent[1]);
3815	} else {
3816		sctp_add_stream_reset_result(chk, seq, SCTP_STREAM_RESET_RESULT_ERR_BAD_SEQNO);
3817	}
3818	return (0);
3819}
3820
3821static void
3822sctp_handle_str_reset_request_out(struct sctp_tcb *stcb,
3823    struct sctp_tmit_chunk *chk,
3824    struct sctp_stream_reset_out_request *req, int trunc)
3825{
3826	uint32_t seq, tsn;
3827	int number_entries, len;
3828	struct sctp_association *asoc = &stcb->asoc;
3829
3830	seq = ntohl(req->request_seq);
3831
3832	/* now if its not a duplicate we process it */
3833	if (asoc->str_reset_seq_in == seq) {
3834		len = ntohs(req->ph.param_length);
3835		number_entries = ((len - sizeof(struct sctp_stream_reset_out_request)) / sizeof(uint16_t));
3836		/*
3837		 * the sender is resetting, handle the list issue.. we must
3838		 * a) verify if we can do the reset, if so no problem b) If
3839		 * we can't do the reset we must copy the request. c) queue
3840		 * it, and setup the data in processor to trigger it off
3841		 * when needed and dequeue all the queued data.
3842		 */
3843		tsn = ntohl(req->send_reset_at_tsn);
3844
3845		/* move the reset action back one */
3846		asoc->last_reset_action[1] = asoc->last_reset_action[0];
3847		if (!(asoc->local_strreset_support & SCTP_ENABLE_RESET_STREAM_REQ)) {
3848			asoc->last_reset_action[0] = SCTP_STREAM_RESET_RESULT_DENIED;
3849		} else if (trunc) {
3850			asoc->last_reset_action[0] = SCTP_STREAM_RESET_RESULT_DENIED;
3851		} else if (SCTP_TSN_GE(asoc->cumulative_tsn, tsn)) {
3852			/* we can do it now */
3853			sctp_reset_in_stream(stcb, number_entries, req->list_of_streams);
3854			asoc->last_reset_action[0] = SCTP_STREAM_RESET_RESULT_PERFORMED;
3855		} else {
3856			/*
3857			 * we must queue it up and thus wait for the TSN's
3858			 * to arrive that are at or before tsn
3859			 */
3860			struct sctp_stream_reset_list *liste;
3861			int siz;
3862
3863			siz = sizeof(struct sctp_stream_reset_list) + (number_entries * sizeof(uint16_t));
3864			SCTP_MALLOC(liste, struct sctp_stream_reset_list *,
3865			    siz, SCTP_M_STRESET);
3866			if (liste == NULL) {
3867				/* gak out of memory */
3868				asoc->last_reset_action[0] = SCTP_STREAM_RESET_RESULT_DENIED;
3869				sctp_add_stream_reset_result(chk, seq, asoc->last_reset_action[0]);
3870				return;
3871			}
3872			liste->tsn = tsn;
3873			liste->number_entries = number_entries;
3874			memcpy(&liste->req, req,
3875			    (sizeof(struct sctp_stream_reset_out_request) + (number_entries * sizeof(uint16_t))));
3876			TAILQ_INSERT_TAIL(&asoc->resetHead, liste, next_resp);
3877			asoc->last_reset_action[0] = SCTP_STREAM_RESET_RESULT_PERFORMED;
3878		}
3879		sctp_add_stream_reset_result(chk, seq, asoc->last_reset_action[0]);
3880		asoc->str_reset_seq_in++;
3881	} else if ((asoc->str_reset_seq_in - 1) == seq) {
3882		/*
3883		 * one seq back, just echo back last action since my
3884		 * response was lost.
3885		 */
3886		sctp_add_stream_reset_result(chk, seq, asoc->last_reset_action[0]);
3887	} else if ((asoc->str_reset_seq_in - 2) == seq) {
3888		/*
3889		 * two seq back, just echo back last action since my
3890		 * response was lost.
3891		 */
3892		sctp_add_stream_reset_result(chk, seq, asoc->last_reset_action[1]);
3893	} else {
3894		sctp_add_stream_reset_result(chk, seq, SCTP_STREAM_RESET_RESULT_ERR_BAD_SEQNO);
3895	}
3896}
3897
3898static void
3899sctp_handle_str_reset_add_strm(struct sctp_tcb *stcb, struct sctp_tmit_chunk *chk,
3900    struct sctp_stream_reset_add_strm *str_add)
3901{
3902	/*
3903	 * Peer is requesting to add more streams. If its within our
3904	 * max-streams we will allow it.
3905	 */
3906	uint32_t num_stream, i;
3907	uint32_t seq;
3908	struct sctp_association *asoc = &stcb->asoc;
3909	struct sctp_queued_to_read *ctl, *nctl;
3910
3911	/* Get the number. */
3912	seq = ntohl(str_add->request_seq);
3913	num_stream = ntohs(str_add->number_of_streams);
3914	/* Now what would be the new total? */
3915	if (asoc->str_reset_seq_in == seq) {
3916		num_stream += stcb->asoc.streamincnt;
3917		stcb->asoc.last_reset_action[1] = stcb->asoc.last_reset_action[0];
3918		if (!(asoc->local_strreset_support & SCTP_ENABLE_CHANGE_ASSOC_REQ)) {
3919			asoc->last_reset_action[0] = SCTP_STREAM_RESET_RESULT_DENIED;
3920		} else if ((num_stream > stcb->asoc.max_inbound_streams) ||
3921		    (num_stream > 0xffff)) {
3922			/* We must reject it they ask for to many */
3923	denied:
3924			stcb->asoc.last_reset_action[0] = SCTP_STREAM_RESET_RESULT_DENIED;
3925		} else {
3926			/* Ok, we can do that :-) */
3927			struct sctp_stream_in *oldstrm;
3928
3929			/* save off the old */
3930			oldstrm = stcb->asoc.strmin;
3931			SCTP_MALLOC(stcb->asoc.strmin, struct sctp_stream_in *,
3932			    (num_stream * sizeof(struct sctp_stream_in)),
3933			    SCTP_M_STRMI);
3934			if (stcb->asoc.strmin == NULL) {
3935				stcb->asoc.strmin = oldstrm;
3936				goto denied;
3937			}
3938			/* copy off the old data */
3939			for (i = 0; i < stcb->asoc.streamincnt; i++) {
3940				TAILQ_INIT(&stcb->asoc.strmin[i].inqueue);
3941				stcb->asoc.strmin[i].stream_no = i;
3942				stcb->asoc.strmin[i].last_sequence_delivered = oldstrm[i].last_sequence_delivered;
3943				stcb->asoc.strmin[i].delivery_started = oldstrm[i].delivery_started;
3944				/* now anything on those queues? */
3945				TAILQ_FOREACH_SAFE(ctl, &oldstrm[i].inqueue, next, nctl) {
3946					TAILQ_REMOVE(&oldstrm[i].inqueue, ctl, next);
3947					TAILQ_INSERT_TAIL(&stcb->asoc.strmin[i].inqueue, ctl, next);
3948				}
3949			}
3950			/* Init the new streams */
3951			for (i = stcb->asoc.streamincnt; i < num_stream; i++) {
3952				TAILQ_INIT(&stcb->asoc.strmin[i].inqueue);
3953				stcb->asoc.strmin[i].stream_no = i;
3954				stcb->asoc.strmin[i].last_sequence_delivered = 0xffff;
3955				stcb->asoc.strmin[i].delivery_started = 0;
3956			}
3957			SCTP_FREE(oldstrm, SCTP_M_STRMI);
3958			/* update the size */
3959			stcb->asoc.streamincnt = num_stream;
3960			stcb->asoc.last_reset_action[0] = SCTP_STREAM_RESET_RESULT_PERFORMED;
3961			sctp_notify_stream_reset_add(stcb, stcb->asoc.streamincnt, stcb->asoc.streamoutcnt, 0);
3962		}
3963		sctp_add_stream_reset_result(chk, seq, asoc->last_reset_action[0]);
3964		asoc->str_reset_seq_in++;
3965	} else if ((asoc->str_reset_seq_in - 1) == seq) {
3966		/*
3967		 * one seq back, just echo back last action since my
3968		 * response was lost.
3969		 */
3970		sctp_add_stream_reset_result(chk, seq, asoc->last_reset_action[0]);
3971	} else if ((asoc->str_reset_seq_in - 2) == seq) {
3972		/*
3973		 * two seq back, just echo back last action since my
3974		 * response was lost.
3975		 */
3976		sctp_add_stream_reset_result(chk, seq, asoc->last_reset_action[1]);
3977	} else {
3978		sctp_add_stream_reset_result(chk, seq, SCTP_STREAM_RESET_RESULT_ERR_BAD_SEQNO);
3979
3980	}
3981}
3982
3983static void
3984sctp_handle_str_reset_add_out_strm(struct sctp_tcb *stcb, struct sctp_tmit_chunk *chk,
3985    struct sctp_stream_reset_add_strm *str_add)
3986{
3987	/*
3988	 * Peer is requesting to add more streams. If its within our
3989	 * max-streams we will allow it.
3990	 */
3991	uint16_t num_stream;
3992	uint32_t seq;
3993	struct sctp_association *asoc = &stcb->asoc;
3994
3995	/* Get the number. */
3996	seq = ntohl(str_add->request_seq);
3997	num_stream = ntohs(str_add->number_of_streams);
3998	/* Now what would be the new total? */
3999	if (asoc->str_reset_seq_in == seq) {
4000		stcb->asoc.last_reset_action[1] = stcb->asoc.last_reset_action[0];
4001		if (!(asoc->local_strreset_support & SCTP_ENABLE_CHANGE_ASSOC_REQ)) {
4002			asoc->last_reset_action[0] = SCTP_STREAM_RESET_RESULT_DENIED;
4003		} else if (stcb->asoc.stream_reset_outstanding) {
4004			/* We must reject it we have something pending */
4005			stcb->asoc.last_reset_action[0] = SCTP_STREAM_RESET_RESULT_ERR_IN_PROGRESS;
4006		} else {
4007			/* Ok, we can do that :-) */
4008			int mychk;
4009
4010			mychk = stcb->asoc.streamoutcnt;
4011			mychk += num_stream;
4012			if (mychk < 0x10000) {
4013				stcb->asoc.last_reset_action[0] = SCTP_STREAM_RESET_RESULT_PERFORMED;
4014				if (sctp_send_str_reset_req(stcb, 0, NULL, 0, 0, 0, 1, num_stream, 0, 1)) {
4015					stcb->asoc.last_reset_action[0] = SCTP_STREAM_RESET_RESULT_DENIED;
4016				}
4017			} else {
4018				stcb->asoc.last_reset_action[0] = SCTP_STREAM_RESET_RESULT_DENIED;
4019			}
4020		}
4021		sctp_add_stream_reset_result(chk, seq, stcb->asoc.last_reset_action[0]);
4022		asoc->str_reset_seq_in++;
4023	} else if ((asoc->str_reset_seq_in - 1) == seq) {
4024		/*
4025		 * one seq back, just echo back last action since my
4026		 * response was lost.
4027		 */
4028		sctp_add_stream_reset_result(chk, seq, asoc->last_reset_action[0]);
4029	} else if ((asoc->str_reset_seq_in - 2) == seq) {
4030		/*
4031		 * two seq back, just echo back last action since my
4032		 * response was lost.
4033		 */
4034		sctp_add_stream_reset_result(chk, seq, asoc->last_reset_action[1]);
4035	} else {
4036		sctp_add_stream_reset_result(chk, seq, SCTP_STREAM_RESET_RESULT_ERR_BAD_SEQNO);
4037	}
4038}
4039
4040#ifdef __GNUC__
4041__attribute__((noinline))
4042#endif
4043	static int
4044	    sctp_handle_stream_reset(struct sctp_tcb *stcb, struct mbuf *m, int offset,
4045        struct sctp_stream_reset_out_req *sr_req)
4046{
4047	int chk_length, param_len, ptype;
4048	struct sctp_paramhdr pstore;
4049	uint8_t cstore[SCTP_CHUNK_BUFFER_SIZE];
4050	uint32_t seq = 0;
4051	int num_req = 0;
4052	int trunc = 0;
4053	struct sctp_tmit_chunk *chk;
4054	struct sctp_chunkhdr *ch;
4055	struct sctp_paramhdr *ph;
4056	int ret_code = 0;
4057	int num_param = 0;
4058
4059	/* now it may be a reset or a reset-response */
4060	chk_length = ntohs(sr_req->ch.chunk_length);
4061
4062	/* setup for adding the response */
4063	sctp_alloc_a_chunk(stcb, chk);
4064	if (chk == NULL) {
4065		return (ret_code);
4066	}
4067	chk->rec.chunk_id.id = SCTP_STREAM_RESET;
4068	chk->rec.chunk_id.can_take_data = 0;
4069	chk->asoc = &stcb->asoc;
4070	chk->no_fr_allowed = 0;
4071	chk->book_size = chk->send_size = sizeof(struct sctp_chunkhdr);
4072	chk->book_size_scale = 0;
4073	chk->data = sctp_get_mbuf_for_msg(MCLBYTES, 0, M_DONTWAIT, 1, MT_DATA);
4074	if (chk->data == NULL) {
4075strres_nochunk:
4076		if (chk->data) {
4077			sctp_m_freem(chk->data);
4078			chk->data = NULL;
4079		}
4080		sctp_free_a_chunk(stcb, chk, SCTP_SO_NOT_LOCKED);
4081		return (ret_code);
4082	}
4083	SCTP_BUF_RESV_UF(chk->data, SCTP_MIN_OVERHEAD);
4084
4085	/* setup chunk parameters */
4086	chk->sent = SCTP_DATAGRAM_UNSENT;
4087	chk->snd_count = 0;
4088	chk->whoTo = NULL;
4089
4090	ch = mtod(chk->data, struct sctp_chunkhdr *);
4091	ch->chunk_type = SCTP_STREAM_RESET;
4092	ch->chunk_flags = 0;
4093	ch->chunk_length = htons(chk->send_size);
4094	SCTP_BUF_LEN(chk->data) = SCTP_SIZE32(chk->send_size);
4095	offset += sizeof(struct sctp_chunkhdr);
4096	while ((size_t)chk_length >= sizeof(struct sctp_stream_reset_tsn_request)) {
4097		ph = (struct sctp_paramhdr *)sctp_m_getptr(m, offset, sizeof(pstore), (uint8_t *) & pstore);
4098		if (ph == NULL)
4099			break;
4100		param_len = ntohs(ph->param_length);
4101		if (param_len < (int)sizeof(struct sctp_stream_reset_tsn_request)) {
4102			/* bad param */
4103			break;
4104		}
4105		ph = (struct sctp_paramhdr *)sctp_m_getptr(m, offset, min(param_len, (int)sizeof(cstore)),
4106		    (uint8_t *) & cstore);
4107		ptype = ntohs(ph->param_type);
4108		num_param++;
4109		if (param_len > (int)sizeof(cstore)) {
4110			trunc = 1;
4111		} else {
4112			trunc = 0;
4113		}
4114		if (num_param > SCTP_MAX_RESET_PARAMS) {
4115			/* hit the max of parameters already sorry.. */
4116			break;
4117		}
4118		if (ptype == SCTP_STR_RESET_OUT_REQUEST) {
4119			struct sctp_stream_reset_out_request *req_out;
4120
4121			req_out = (struct sctp_stream_reset_out_request *)ph;
4122			num_req++;
4123			if (stcb->asoc.stream_reset_outstanding) {
4124				seq = ntohl(req_out->response_seq);
4125				if (seq == stcb->asoc.str_reset_seq_out) {
4126					/* implicit ack */
4127					(void)sctp_handle_stream_reset_response(stcb, seq, SCTP_STREAM_RESET_RESULT_PERFORMED, NULL);
4128				}
4129			}
4130			sctp_handle_str_reset_request_out(stcb, chk, req_out, trunc);
4131		} else if (ptype == SCTP_STR_RESET_ADD_OUT_STREAMS) {
4132			struct sctp_stream_reset_add_strm *str_add;
4133
4134			str_add = (struct sctp_stream_reset_add_strm *)ph;
4135			num_req++;
4136			sctp_handle_str_reset_add_strm(stcb, chk, str_add);
4137		} else if (ptype == SCTP_STR_RESET_ADD_IN_STREAMS) {
4138			struct sctp_stream_reset_add_strm *str_add;
4139
4140			str_add = (struct sctp_stream_reset_add_strm *)ph;
4141			num_req++;
4142			sctp_handle_str_reset_add_out_strm(stcb, chk, str_add);
4143		} else if (ptype == SCTP_STR_RESET_IN_REQUEST) {
4144			struct sctp_stream_reset_in_request *req_in;
4145
4146			num_req++;
4147			req_in = (struct sctp_stream_reset_in_request *)ph;
4148			sctp_handle_str_reset_request_in(stcb, chk, req_in, trunc);
4149		} else if (ptype == SCTP_STR_RESET_TSN_REQUEST) {
4150			struct sctp_stream_reset_tsn_request *req_tsn;
4151
4152			num_req++;
4153			req_tsn = (struct sctp_stream_reset_tsn_request *)ph;
4154			if (sctp_handle_str_reset_request_tsn(stcb, chk, req_tsn)) {
4155				ret_code = 1;
4156				goto strres_nochunk;
4157			}
4158			/* no more */
4159			break;
4160		} else if (ptype == SCTP_STR_RESET_RESPONSE) {
4161			struct sctp_stream_reset_response *resp;
4162			uint32_t result;
4163
4164			resp = (struct sctp_stream_reset_response *)ph;
4165			seq = ntohl(resp->response_seq);
4166			result = ntohl(resp->result);
4167			if (sctp_handle_stream_reset_response(stcb, seq, result, resp)) {
4168				ret_code = 1;
4169				goto strres_nochunk;
4170			}
4171		} else {
4172			break;
4173		}
4174		offset += SCTP_SIZE32(param_len);
4175		chk_length -= SCTP_SIZE32(param_len);
4176	}
4177	if (num_req == 0) {
4178		/* we have no response free the stuff */
4179		goto strres_nochunk;
4180	}
4181	/* ok we have a chunk to link in */
4182	TAILQ_INSERT_TAIL(&stcb->asoc.control_send_queue,
4183	    chk,
4184	    sctp_next);
4185	stcb->asoc.ctrl_queue_cnt++;
4186	return (ret_code);
4187}
4188
4189/*
4190 * Handle a router or endpoints report of a packet loss, there are two ways
4191 * to handle this, either we get the whole packet and must disect it
4192 * ourselves (possibly with truncation and or corruption) or it is a summary
4193 * from a middle box that did the disectting for us.
4194 */
4195static void
4196sctp_handle_packet_dropped(struct sctp_pktdrop_chunk *cp,
4197    struct sctp_tcb *stcb, struct sctp_nets *net, uint32_t limit)
4198{
4199	uint32_t bottle_bw, on_queue;
4200	uint16_t trunc_len;
4201	unsigned int chlen;
4202	unsigned int at;
4203	struct sctp_chunk_desc desc;
4204	struct sctp_chunkhdr *ch;
4205
4206	chlen = ntohs(cp->ch.chunk_length);
4207	chlen -= sizeof(struct sctp_pktdrop_chunk);
4208	/* XXX possible chlen underflow */
4209	if (chlen == 0) {
4210		ch = NULL;
4211		if (cp->ch.chunk_flags & SCTP_FROM_MIDDLE_BOX)
4212			SCTP_STAT_INCR(sctps_pdrpbwrpt);
4213	} else {
4214		ch = (struct sctp_chunkhdr *)(cp->data + sizeof(struct sctphdr));
4215		chlen -= sizeof(struct sctphdr);
4216		/* XXX possible chlen underflow */
4217		memset(&desc, 0, sizeof(desc));
4218	}
4219	trunc_len = (uint16_t) ntohs(cp->trunc_len);
4220	if (trunc_len > limit) {
4221		trunc_len = limit;
4222	}
4223	/* now the chunks themselves */
4224	while ((ch != NULL) && (chlen >= sizeof(struct sctp_chunkhdr))) {
4225		desc.chunk_type = ch->chunk_type;
4226		/* get amount we need to move */
4227		at = ntohs(ch->chunk_length);
4228		if (at < sizeof(struct sctp_chunkhdr)) {
4229			/* corrupt chunk, maybe at the end? */
4230			SCTP_STAT_INCR(sctps_pdrpcrupt);
4231			break;
4232		}
4233		if (trunc_len == 0) {
4234			/* we are supposed to have all of it */
4235			if (at > chlen) {
4236				/* corrupt skip it */
4237				SCTP_STAT_INCR(sctps_pdrpcrupt);
4238				break;
4239			}
4240		} else {
4241			/* is there enough of it left ? */
4242			if (desc.chunk_type == SCTP_DATA) {
4243				if (chlen < (sizeof(struct sctp_data_chunk) +
4244				    sizeof(desc.data_bytes))) {
4245					break;
4246				}
4247			} else {
4248				if (chlen < sizeof(struct sctp_chunkhdr)) {
4249					break;
4250				}
4251			}
4252		}
4253		if (desc.chunk_type == SCTP_DATA) {
4254			/* can we get out the tsn? */
4255			if ((cp->ch.chunk_flags & SCTP_FROM_MIDDLE_BOX))
4256				SCTP_STAT_INCR(sctps_pdrpmbda);
4257
4258			if (chlen >= (sizeof(struct sctp_data_chunk) + sizeof(uint32_t))) {
4259				/* yep */
4260				struct sctp_data_chunk *dcp;
4261				uint8_t *ddp;
4262				unsigned int iii;
4263
4264				dcp = (struct sctp_data_chunk *)ch;
4265				ddp = (uint8_t *) (dcp + 1);
4266				for (iii = 0; iii < sizeof(desc.data_bytes); iii++) {
4267					desc.data_bytes[iii] = ddp[iii];
4268				}
4269				desc.tsn_ifany = dcp->dp.tsn;
4270			} else {
4271				/* nope we are done. */
4272				SCTP_STAT_INCR(sctps_pdrpnedat);
4273				break;
4274			}
4275		} else {
4276			if ((cp->ch.chunk_flags & SCTP_FROM_MIDDLE_BOX))
4277				SCTP_STAT_INCR(sctps_pdrpmbct);
4278		}
4279
4280		if (process_chunk_drop(stcb, &desc, net, cp->ch.chunk_flags)) {
4281			SCTP_STAT_INCR(sctps_pdrppdbrk);
4282			break;
4283		}
4284		if (SCTP_SIZE32(at) > chlen) {
4285			break;
4286		}
4287		chlen -= SCTP_SIZE32(at);
4288		if (chlen < sizeof(struct sctp_chunkhdr)) {
4289			/* done, none left */
4290			break;
4291		}
4292		ch = (struct sctp_chunkhdr *)((caddr_t)ch + SCTP_SIZE32(at));
4293	}
4294	/* Now update any rwnd --- possibly */
4295	if ((cp->ch.chunk_flags & SCTP_FROM_MIDDLE_BOX) == 0) {
4296		/* From a peer, we get a rwnd report */
4297		uint32_t a_rwnd;
4298
4299		SCTP_STAT_INCR(sctps_pdrpfehos);
4300
4301		bottle_bw = ntohl(cp->bottle_bw);
4302		on_queue = ntohl(cp->current_onq);
4303		if (bottle_bw && on_queue) {
4304			/* a rwnd report is in here */
4305			if (bottle_bw > on_queue)
4306				a_rwnd = bottle_bw - on_queue;
4307			else
4308				a_rwnd = 0;
4309
4310			if (a_rwnd == 0)
4311				stcb->asoc.peers_rwnd = 0;
4312			else {
4313				if (a_rwnd > stcb->asoc.total_flight) {
4314					stcb->asoc.peers_rwnd =
4315					    a_rwnd - stcb->asoc.total_flight;
4316				} else {
4317					stcb->asoc.peers_rwnd = 0;
4318				}
4319				if (stcb->asoc.peers_rwnd <
4320				    stcb->sctp_ep->sctp_ep.sctp_sws_sender) {
4321					/* SWS sender side engages */
4322					stcb->asoc.peers_rwnd = 0;
4323				}
4324			}
4325		}
4326	} else {
4327		SCTP_STAT_INCR(sctps_pdrpfmbox);
4328	}
4329
4330	/* now middle boxes in sat networks get a cwnd bump */
4331	if ((cp->ch.chunk_flags & SCTP_FROM_MIDDLE_BOX) &&
4332	    (stcb->asoc.sat_t3_loss_recovery == 0) &&
4333	    (stcb->asoc.sat_network)) {
4334		/*
4335		 * This is debateable but for sat networks it makes sense
4336		 * Note if a T3 timer has went off, we will prohibit any
4337		 * changes to cwnd until we exit the t3 loss recovery.
4338		 */
4339		stcb->asoc.cc_functions.sctp_cwnd_update_after_packet_dropped(stcb,
4340		    net, cp, &bottle_bw, &on_queue);
4341	}
4342}
4343
4344/*
4345 * handles all control chunks in a packet inputs: - m: mbuf chain, assumed to
4346 * still contain IP/SCTP header - stcb: is the tcb found for this packet -
4347 * offset: offset into the mbuf chain to first chunkhdr - length: is the
4348 * length of the complete packet outputs: - length: modified to remaining
4349 * length after control processing - netp: modified to new sctp_nets after
4350 * cookie-echo processing - return NULL to discard the packet (ie. no asoc,
4351 * bad packet,...) otherwise return the tcb for this packet
4352 */
4353#ifdef __GNUC__
4354__attribute__((noinline))
4355#endif
4356	static struct sctp_tcb *
4357	         sctp_process_control(struct mbuf *m, int iphlen, int *offset, int length,
4358             struct sctphdr *sh, struct sctp_chunkhdr *ch, struct sctp_inpcb *inp,
4359             struct sctp_tcb *stcb, struct sctp_nets **netp, int *fwd_tsn_seen,
4360             uint32_t vrf_id, uint16_t port)
4361{
4362	struct sctp_association *asoc;
4363	uint32_t vtag_in;
4364	int num_chunks = 0;	/* number of control chunks processed */
4365	uint32_t chk_length;
4366	int ret;
4367	int abort_no_unlock = 0;
4368	int ecne_seen = 0;
4369
4370	/*
4371	 * How big should this be, and should it be alloc'd? Lets try the
4372	 * d-mtu-ceiling for now (2k) and that should hopefully work ...
4373	 * until we get into jumbo grams and such..
4374	 */
4375	uint8_t chunk_buf[SCTP_CHUNK_BUFFER_SIZE];
4376	struct sctp_tcb *locked_tcb = stcb;
4377	int got_auth = 0;
4378	uint32_t auth_offset = 0, auth_len = 0;
4379	int auth_skipped = 0;
4380	int asconf_cnt = 0;
4381
4382#if defined (__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
4383	struct socket *so;
4384
4385#endif
4386
4387	SCTPDBG(SCTP_DEBUG_INPUT1, "sctp_process_control: iphlen=%u, offset=%u, length=%u stcb:%p\n",
4388	    iphlen, *offset, length, stcb);
4389
4390	/* validate chunk header length... */
4391	if (ntohs(ch->chunk_length) < sizeof(*ch)) {
4392		SCTPDBG(SCTP_DEBUG_INPUT1, "Invalid header length %d\n",
4393		    ntohs(ch->chunk_length));
4394		if (locked_tcb) {
4395			SCTP_TCB_UNLOCK(locked_tcb);
4396		}
4397		return (NULL);
4398	}
4399	/*
4400	 * validate the verification tag
4401	 */
4402	vtag_in = ntohl(sh->v_tag);
4403
4404	if (locked_tcb) {
4405		SCTP_TCB_LOCK_ASSERT(locked_tcb);
4406	}
4407	if (ch->chunk_type == SCTP_INITIATION) {
4408		SCTPDBG(SCTP_DEBUG_INPUT1, "Its an INIT of len:%d vtag:%x\n",
4409		    ntohs(ch->chunk_length), vtag_in);
4410		if (vtag_in != 0) {
4411			/* protocol error- silently discard... */
4412			SCTP_STAT_INCR(sctps_badvtag);
4413			if (locked_tcb) {
4414				SCTP_TCB_UNLOCK(locked_tcb);
4415			}
4416			return (NULL);
4417		}
4418	} else if (ch->chunk_type != SCTP_COOKIE_ECHO) {
4419		/*
4420		 * If there is no stcb, skip the AUTH chunk and process
4421		 * later after a stcb is found (to validate the lookup was
4422		 * valid.
4423		 */
4424		if ((ch->chunk_type == SCTP_AUTHENTICATION) &&
4425		    (stcb == NULL) &&
4426		    !SCTP_BASE_SYSCTL(sctp_auth_disable)) {
4427			/* save this chunk for later processing */
4428			auth_skipped = 1;
4429			auth_offset = *offset;
4430			auth_len = ntohs(ch->chunk_length);
4431
4432			/* (temporarily) move past this chunk */
4433			*offset += SCTP_SIZE32(auth_len);
4434			if (*offset >= length) {
4435				/* no more data left in the mbuf chain */
4436				*offset = length;
4437				if (locked_tcb) {
4438					SCTP_TCB_UNLOCK(locked_tcb);
4439				}
4440				return (NULL);
4441			}
4442			ch = (struct sctp_chunkhdr *)sctp_m_getptr(m, *offset,
4443			    sizeof(struct sctp_chunkhdr), chunk_buf);
4444		}
4445		if (ch == NULL) {
4446			/* Help */
4447			*offset = length;
4448			if (locked_tcb) {
4449				SCTP_TCB_UNLOCK(locked_tcb);
4450			}
4451			return (NULL);
4452		}
4453		if (ch->chunk_type == SCTP_COOKIE_ECHO) {
4454			goto process_control_chunks;
4455		}
4456		/*
4457		 * first check if it's an ASCONF with an unknown src addr we
4458		 * need to look inside to find the association
4459		 */
4460		if (ch->chunk_type == SCTP_ASCONF && stcb == NULL) {
4461			struct sctp_chunkhdr *asconf_ch = ch;
4462			uint32_t asconf_offset = 0, asconf_len = 0;
4463
4464			/* inp's refcount may be reduced */
4465			SCTP_INP_INCR_REF(inp);
4466
4467			asconf_offset = *offset;
4468			do {
4469				asconf_len = ntohs(asconf_ch->chunk_length);
4470				if (asconf_len < sizeof(struct sctp_asconf_paramhdr))
4471					break;
4472				stcb = sctp_findassociation_ep_asconf(m,
4473				    *offset, sh, &inp, netp, vrf_id);
4474				if (stcb != NULL)
4475					break;
4476				asconf_offset += SCTP_SIZE32(asconf_len);
4477				asconf_ch = (struct sctp_chunkhdr *)sctp_m_getptr(m, asconf_offset,
4478				    sizeof(struct sctp_chunkhdr), chunk_buf);
4479			} while (asconf_ch != NULL && asconf_ch->chunk_type == SCTP_ASCONF);
4480			if (stcb == NULL) {
4481				/*
4482				 * reduce inp's refcount if not reduced in
4483				 * sctp_findassociation_ep_asconf().
4484				 */
4485				SCTP_INP_DECR_REF(inp);
4486			} else {
4487				locked_tcb = stcb;
4488			}
4489
4490			/* now go back and verify any auth chunk to be sure */
4491			if (auth_skipped && (stcb != NULL)) {
4492				struct sctp_auth_chunk *auth;
4493
4494				auth = (struct sctp_auth_chunk *)
4495				    sctp_m_getptr(m, auth_offset,
4496				    auth_len, chunk_buf);
4497				got_auth = 1;
4498				auth_skipped = 0;
4499				if ((auth == NULL) || sctp_handle_auth(stcb, auth, m,
4500				    auth_offset)) {
4501					/* auth HMAC failed so dump it */
4502					*offset = length;
4503					if (locked_tcb) {
4504						SCTP_TCB_UNLOCK(locked_tcb);
4505					}
4506					return (NULL);
4507				} else {
4508					/* remaining chunks are HMAC checked */
4509					stcb->asoc.authenticated = 1;
4510				}
4511			}
4512		}
4513		if (stcb == NULL) {
4514			/* no association, so it's out of the blue... */
4515			sctp_handle_ootb(m, iphlen, *offset, sh, inp, NULL,
4516			    vrf_id, port);
4517			*offset = length;
4518			if (locked_tcb) {
4519				SCTP_TCB_UNLOCK(locked_tcb);
4520			}
4521			return (NULL);
4522		}
4523		asoc = &stcb->asoc;
4524		/* ABORT and SHUTDOWN can use either v_tag... */
4525		if ((ch->chunk_type == SCTP_ABORT_ASSOCIATION) ||
4526		    (ch->chunk_type == SCTP_SHUTDOWN_COMPLETE) ||
4527		    (ch->chunk_type == SCTP_PACKET_DROPPED)) {
4528			if ((vtag_in == asoc->my_vtag) ||
4529			    ((ch->chunk_flags & SCTP_HAD_NO_TCB) &&
4530			    (vtag_in == asoc->peer_vtag))) {
4531				/* this is valid */
4532			} else {
4533				/* drop this packet... */
4534				SCTP_STAT_INCR(sctps_badvtag);
4535				if (locked_tcb) {
4536					SCTP_TCB_UNLOCK(locked_tcb);
4537				}
4538				return (NULL);
4539			}
4540		} else if (ch->chunk_type == SCTP_SHUTDOWN_ACK) {
4541			if (vtag_in != asoc->my_vtag) {
4542				/*
4543				 * this could be a stale SHUTDOWN-ACK or the
4544				 * peer never got the SHUTDOWN-COMPLETE and
4545				 * is still hung; we have started a new asoc
4546				 * but it won't complete until the shutdown
4547				 * is completed
4548				 */
4549				if (locked_tcb) {
4550					SCTP_TCB_UNLOCK(locked_tcb);
4551				}
4552				sctp_handle_ootb(m, iphlen, *offset, sh, inp,
4553				    NULL, vrf_id, port);
4554				return (NULL);
4555			}
4556		} else {
4557			/* for all other chunks, vtag must match */
4558			if (vtag_in != asoc->my_vtag) {
4559				/* invalid vtag... */
4560				SCTPDBG(SCTP_DEBUG_INPUT3,
4561				    "invalid vtag: %xh, expect %xh\n",
4562				    vtag_in, asoc->my_vtag);
4563				SCTP_STAT_INCR(sctps_badvtag);
4564				if (locked_tcb) {
4565					SCTP_TCB_UNLOCK(locked_tcb);
4566				}
4567				*offset = length;
4568				return (NULL);
4569			}
4570		}
4571	}			/* end if !SCTP_COOKIE_ECHO */
4572	/*
4573	 * process all control chunks...
4574	 */
4575	if (((ch->chunk_type == SCTP_SELECTIVE_ACK) ||
4576	    (ch->chunk_type == SCTP_NR_SELECTIVE_ACK) ||
4577	    (ch->chunk_type == SCTP_HEARTBEAT_REQUEST)) &&
4578	    (SCTP_GET_STATE(&stcb->asoc) == SCTP_STATE_COOKIE_ECHOED)) {
4579		/* implied cookie-ack.. we must have lost the ack */
4580		if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_THRESHOLD_LOGGING) {
4581			sctp_misc_ints(SCTP_THRESHOLD_CLEAR,
4582			    stcb->asoc.overall_error_count,
4583			    0,
4584			    SCTP_FROM_SCTP_INPUT,
4585			    __LINE__);
4586		}
4587		stcb->asoc.overall_error_count = 0;
4588		sctp_handle_cookie_ack((struct sctp_cookie_ack_chunk *)ch, stcb,
4589		    *netp);
4590	}
4591process_control_chunks:
4592	while (IS_SCTP_CONTROL(ch)) {
4593		/* validate chunk length */
4594		chk_length = ntohs(ch->chunk_length);
4595		SCTPDBG(SCTP_DEBUG_INPUT2, "sctp_process_control: processing a chunk type=%u, len=%u\n",
4596		    ch->chunk_type, chk_length);
4597		SCTP_LTRACE_CHK(inp, stcb, ch->chunk_type, chk_length);
4598		if (chk_length < sizeof(*ch) ||
4599		    (*offset + (int)chk_length) > length) {
4600			*offset = length;
4601			if (locked_tcb) {
4602				SCTP_TCB_UNLOCK(locked_tcb);
4603			}
4604			return (NULL);
4605		}
4606		SCTP_STAT_INCR_COUNTER64(sctps_incontrolchunks);
4607		/*
4608		 * INIT-ACK only gets the init ack "header" portion only
4609		 * because we don't have to process the peer's COOKIE. All
4610		 * others get a complete chunk.
4611		 */
4612		if ((ch->chunk_type == SCTP_INITIATION_ACK) ||
4613		    (ch->chunk_type == SCTP_INITIATION)) {
4614			/* get an init-ack chunk */
4615			ch = (struct sctp_chunkhdr *)sctp_m_getptr(m, *offset,
4616			    sizeof(struct sctp_init_ack_chunk), chunk_buf);
4617			if (ch == NULL) {
4618				*offset = length;
4619				if (locked_tcb) {
4620					SCTP_TCB_UNLOCK(locked_tcb);
4621				}
4622				return (NULL);
4623			}
4624		} else {
4625			/* For cookies and all other chunks. */
4626			if (chk_length > sizeof(chunk_buf)) {
4627				/*
4628				 * use just the size of the chunk buffer so
4629				 * the front part of our chunks fit in
4630				 * contiguous space up to the chunk buffer
4631				 * size (508 bytes). For chunks that need to
4632				 * get more than that they must use the
4633				 * sctp_m_getptr() function or other means
4634				 * (e.g. know how to parse mbuf chains).
4635				 * Cookies do this already.
4636				 */
4637				ch = (struct sctp_chunkhdr *)sctp_m_getptr(m, *offset,
4638				    (sizeof(chunk_buf) - 4),
4639				    chunk_buf);
4640				if (ch == NULL) {
4641					*offset = length;
4642					if (locked_tcb) {
4643						SCTP_TCB_UNLOCK(locked_tcb);
4644					}
4645					return (NULL);
4646				}
4647			} else {
4648				/* We can fit it all */
4649				ch = (struct sctp_chunkhdr *)sctp_m_getptr(m, *offset,
4650				    chk_length, chunk_buf);
4651				if (ch == NULL) {
4652					SCTP_PRINTF("sctp_process_control: Can't get the all data....\n");
4653					*offset = length;
4654					if (locked_tcb) {
4655						SCTP_TCB_UNLOCK(locked_tcb);
4656					}
4657					return (NULL);
4658				}
4659			}
4660		}
4661		num_chunks++;
4662		/* Save off the last place we got a control from */
4663		if (stcb != NULL) {
4664			if (((netp != NULL) && (*netp != NULL)) || (ch->chunk_type == SCTP_ASCONF)) {
4665				/*
4666				 * allow last_control to be NULL if
4667				 * ASCONF... ASCONF processing will find the
4668				 * right net later
4669				 */
4670				if ((netp != NULL) && (*netp != NULL))
4671					stcb->asoc.last_control_chunk_from = *netp;
4672			}
4673		}
4674#ifdef SCTP_AUDITING_ENABLED
4675		sctp_audit_log(0xB0, ch->chunk_type);
4676#endif
4677
4678		/* check to see if this chunk required auth, but isn't */
4679		if ((stcb != NULL) &&
4680		    !SCTP_BASE_SYSCTL(sctp_auth_disable) &&
4681		    sctp_auth_is_required_chunk(ch->chunk_type, stcb->asoc.local_auth_chunks) &&
4682		    !stcb->asoc.authenticated) {
4683			/* "silently" ignore */
4684			SCTP_STAT_INCR(sctps_recvauthmissing);
4685			goto next_chunk;
4686		}
4687		switch (ch->chunk_type) {
4688		case SCTP_INITIATION:
4689			SCTPDBG(SCTP_DEBUG_INPUT3, "SCTP_INIT\n");
4690			/* The INIT chunk must be the only chunk. */
4691			if ((num_chunks > 1) ||
4692			    (length - *offset > (int)SCTP_SIZE32(chk_length))) {
4693				sctp_abort_association(inp, stcb, m,
4694				    iphlen, sh, NULL, vrf_id, port);
4695				*offset = length;
4696				return (NULL);
4697			}
4698			/* Honor our resource limit. */
4699			if (chk_length > SCTP_LARGEST_INIT_ACCEPTED) {
4700				struct mbuf *op_err;
4701
4702				op_err = sctp_generate_invmanparam(SCTP_CAUSE_OUT_OF_RESC);
4703				sctp_abort_association(inp, stcb, m,
4704				    iphlen, sh, op_err, vrf_id, port);
4705				*offset = length;
4706				return (NULL);
4707			}
4708			sctp_handle_init(m, iphlen, *offset, sh,
4709			    (struct sctp_init_chunk *)ch, inp,
4710			    stcb, &abort_no_unlock, vrf_id, port);
4711			*offset = length;
4712			if ((!abort_no_unlock) && (locked_tcb)) {
4713				SCTP_TCB_UNLOCK(locked_tcb);
4714			}
4715			return (NULL);
4716			break;
4717		case SCTP_PAD_CHUNK:
4718			break;
4719		case SCTP_INITIATION_ACK:
4720			SCTPDBG(SCTP_DEBUG_INPUT3, "SCTP_INIT-ACK\n");
4721			if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE) {
4722				/* We are not interested anymore */
4723				if ((stcb) && (stcb->asoc.total_output_queue_size)) {
4724					;
4725				} else {
4726					if (locked_tcb != stcb) {
4727						/* Very unlikely */
4728						SCTP_TCB_UNLOCK(locked_tcb);
4729					}
4730					*offset = length;
4731					if (stcb) {
4732#if defined (__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
4733						so = SCTP_INP_SO(inp);
4734						atomic_add_int(&stcb->asoc.refcnt, 1);
4735						SCTP_TCB_UNLOCK(stcb);
4736						SCTP_SOCKET_LOCK(so, 1);
4737						SCTP_TCB_LOCK(stcb);
4738						atomic_subtract_int(&stcb->asoc.refcnt, 1);
4739#endif
4740						(void)sctp_free_assoc(inp, stcb, SCTP_NORMAL_PROC, SCTP_FROM_SCTP_INPUT + SCTP_LOC_27);
4741#if defined (__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
4742						SCTP_SOCKET_UNLOCK(so, 1);
4743#endif
4744					}
4745					return (NULL);
4746				}
4747			}
4748			/* The INIT-ACK chunk must be the only chunk. */
4749			if ((num_chunks > 1) ||
4750			    (length - *offset > (int)SCTP_SIZE32(chk_length))) {
4751				*offset = length;
4752				if (locked_tcb) {
4753					SCTP_TCB_UNLOCK(locked_tcb);
4754				}
4755				return (NULL);
4756			}
4757			if ((netp) && (*netp)) {
4758				ret = sctp_handle_init_ack(m, iphlen, *offset, sh,
4759				    (struct sctp_init_ack_chunk *)ch, stcb, *netp, &abort_no_unlock, vrf_id);
4760			} else {
4761				ret = -1;
4762			}
4763			*offset = length;
4764			if (abort_no_unlock) {
4765				return (NULL);
4766			}
4767			/*
4768			 * Special case, I must call the output routine to
4769			 * get the cookie echoed
4770			 */
4771			if ((stcb != NULL) && (ret == 0)) {
4772				sctp_chunk_output(stcb->sctp_ep, stcb, SCTP_OUTPUT_FROM_CONTROL_PROC, SCTP_SO_NOT_LOCKED);
4773			}
4774			if (locked_tcb) {
4775				SCTP_TCB_UNLOCK(locked_tcb);
4776			}
4777			return (NULL);
4778			break;
4779		case SCTP_SELECTIVE_ACK:
4780			{
4781				struct sctp_sack_chunk *sack;
4782				int abort_now = 0;
4783				uint32_t a_rwnd, cum_ack;
4784				uint16_t num_seg, num_dup;
4785				uint8_t flags;
4786				int offset_seg, offset_dup;
4787
4788				SCTPDBG(SCTP_DEBUG_INPUT3, "SCTP_SACK\n");
4789				SCTP_STAT_INCR(sctps_recvsacks);
4790				if (stcb == NULL) {
4791					SCTPDBG(SCTP_DEBUG_INDATA1, "No stcb when processing SACK chunk\n");
4792					break;
4793				}
4794				if (chk_length < sizeof(struct sctp_sack_chunk)) {
4795					SCTPDBG(SCTP_DEBUG_INDATA1, "Bad size on SACK chunk, too small\n");
4796					break;
4797				}
4798				if (SCTP_GET_STATE(&stcb->asoc) == SCTP_STATE_SHUTDOWN_ACK_SENT) {
4799					/*-
4800					 * If we have sent a shutdown-ack, we will pay no
4801					 * attention to a sack sent in to us since
4802					 * we don't care anymore.
4803					 */
4804					break;
4805				}
4806				sack = (struct sctp_sack_chunk *)ch;
4807				flags = ch->chunk_flags;
4808				cum_ack = ntohl(sack->sack.cum_tsn_ack);
4809				num_seg = ntohs(sack->sack.num_gap_ack_blks);
4810				num_dup = ntohs(sack->sack.num_dup_tsns);
4811				a_rwnd = (uint32_t) ntohl(sack->sack.a_rwnd);
4812				if (sizeof(struct sctp_sack_chunk) +
4813				    num_seg * sizeof(struct sctp_gap_ack_block) +
4814				    num_dup * sizeof(uint32_t) != chk_length) {
4815					SCTPDBG(SCTP_DEBUG_INDATA1, "Bad size of SACK chunk\n");
4816					break;
4817				}
4818				offset_seg = *offset + sizeof(struct sctp_sack_chunk);
4819				offset_dup = offset_seg + num_seg * sizeof(struct sctp_gap_ack_block);
4820				SCTPDBG(SCTP_DEBUG_INPUT3, "SCTP_SACK process cum_ack:%x num_seg:%d a_rwnd:%d\n",
4821				    cum_ack, num_seg, a_rwnd);
4822				stcb->asoc.seen_a_sack_this_pkt = 1;
4823				if ((stcb->asoc.pr_sctp_cnt == 0) &&
4824				    (num_seg == 0) &&
4825				    SCTP_TSN_GE(cum_ack, stcb->asoc.last_acked_seq) &&
4826				    (stcb->asoc.saw_sack_with_frags == 0) &&
4827				    (stcb->asoc.saw_sack_with_nr_frags == 0) &&
4828				    (!TAILQ_EMPTY(&stcb->asoc.sent_queue))
4829				    ) {
4830					/*
4831					 * We have a SIMPLE sack having no
4832					 * prior segments and data on sent
4833					 * queue to be acked.. Use the
4834					 * faster path sack processing. We
4835					 * also allow window update sacks
4836					 * with no missing segments to go
4837					 * this way too.
4838					 */
4839					sctp_express_handle_sack(stcb, cum_ack, a_rwnd, &abort_now, ecne_seen);
4840				} else {
4841					if (netp && *netp)
4842						sctp_handle_sack(m, offset_seg, offset_dup, stcb,
4843						    num_seg, 0, num_dup, &abort_now, flags,
4844						    cum_ack, a_rwnd, ecne_seen);
4845				}
4846				if (abort_now) {
4847					/* ABORT signal from sack processing */
4848					*offset = length;
4849					return (NULL);
4850				}
4851				if (TAILQ_EMPTY(&stcb->asoc.send_queue) &&
4852				    TAILQ_EMPTY(&stcb->asoc.sent_queue) &&
4853				    (stcb->asoc.stream_queue_cnt == 0)) {
4854					sctp_ulp_notify(SCTP_NOTIFY_SENDER_DRY, stcb, 0, NULL, SCTP_SO_NOT_LOCKED);
4855				}
4856			}
4857			break;
4858			/*
4859			 * EY - nr_sack:  If the received chunk is an
4860			 * nr_sack chunk
4861			 */
4862		case SCTP_NR_SELECTIVE_ACK:
4863			{
4864				struct sctp_nr_sack_chunk *nr_sack;
4865				int abort_now = 0;
4866				uint32_t a_rwnd, cum_ack;
4867				uint16_t num_seg, num_nr_seg, num_dup;
4868				uint8_t flags;
4869				int offset_seg, offset_dup;
4870
4871				SCTPDBG(SCTP_DEBUG_INPUT3, "SCTP_NR_SACK\n");
4872				SCTP_STAT_INCR(sctps_recvsacks);
4873				if (stcb == NULL) {
4874					SCTPDBG(SCTP_DEBUG_INDATA1, "No stcb when processing NR-SACK chunk\n");
4875					break;
4876				}
4877				if ((stcb->asoc.sctp_nr_sack_on_off == 0) ||
4878				    (stcb->asoc.peer_supports_nr_sack == 0)) {
4879					goto unknown_chunk;
4880				}
4881				if (chk_length < sizeof(struct sctp_nr_sack_chunk)) {
4882					SCTPDBG(SCTP_DEBUG_INDATA1, "Bad size on NR-SACK chunk, too small\n");
4883					break;
4884				}
4885				if (SCTP_GET_STATE(&stcb->asoc) == SCTP_STATE_SHUTDOWN_ACK_SENT) {
4886					/*-
4887					 * If we have sent a shutdown-ack, we will pay no
4888					 * attention to a sack sent in to us since
4889					 * we don't care anymore.
4890					 */
4891					break;
4892				}
4893				nr_sack = (struct sctp_nr_sack_chunk *)ch;
4894				flags = ch->chunk_flags;
4895				cum_ack = ntohl(nr_sack->nr_sack.cum_tsn_ack);
4896				num_seg = ntohs(nr_sack->nr_sack.num_gap_ack_blks);
4897				num_nr_seg = ntohs(nr_sack->nr_sack.num_nr_gap_ack_blks);
4898				num_dup = ntohs(nr_sack->nr_sack.num_dup_tsns);
4899				a_rwnd = (uint32_t) ntohl(nr_sack->nr_sack.a_rwnd);
4900				if (sizeof(struct sctp_nr_sack_chunk) +
4901				    (num_seg + num_nr_seg) * sizeof(struct sctp_gap_ack_block) +
4902				    num_dup * sizeof(uint32_t) != chk_length) {
4903					SCTPDBG(SCTP_DEBUG_INDATA1, "Bad size of NR_SACK chunk\n");
4904					break;
4905				}
4906				offset_seg = *offset + sizeof(struct sctp_nr_sack_chunk);
4907				offset_dup = offset_seg + num_seg * sizeof(struct sctp_gap_ack_block);
4908				SCTPDBG(SCTP_DEBUG_INPUT3, "SCTP_NR_SACK process cum_ack:%x num_seg:%d a_rwnd:%d\n",
4909				    cum_ack, num_seg, a_rwnd);
4910				stcb->asoc.seen_a_sack_this_pkt = 1;
4911				if ((stcb->asoc.pr_sctp_cnt == 0) &&
4912				    (num_seg == 0) && (num_nr_seg == 0) &&
4913				    SCTP_TSN_GE(cum_ack, stcb->asoc.last_acked_seq) &&
4914				    (stcb->asoc.saw_sack_with_frags == 0) &&
4915				    (stcb->asoc.saw_sack_with_nr_frags == 0) &&
4916				    (!TAILQ_EMPTY(&stcb->asoc.sent_queue))) {
4917					/*
4918					 * We have a SIMPLE sack having no
4919					 * prior segments and data on sent
4920					 * queue to be acked. Use the faster
4921					 * path sack processing. We also
4922					 * allow window update sacks with no
4923					 * missing segments to go this way
4924					 * too.
4925					 */
4926					sctp_express_handle_sack(stcb, cum_ack, a_rwnd,
4927					    &abort_now, ecne_seen);
4928				} else {
4929					if (netp && *netp)
4930						sctp_handle_sack(m, offset_seg, offset_dup, stcb,
4931						    num_seg, num_nr_seg, num_dup, &abort_now, flags,
4932						    cum_ack, a_rwnd, ecne_seen);
4933				}
4934				if (abort_now) {
4935					/* ABORT signal from sack processing */
4936					*offset = length;
4937					return (NULL);
4938				}
4939				if (TAILQ_EMPTY(&stcb->asoc.send_queue) &&
4940				    TAILQ_EMPTY(&stcb->asoc.sent_queue) &&
4941				    (stcb->asoc.stream_queue_cnt == 0)) {
4942					sctp_ulp_notify(SCTP_NOTIFY_SENDER_DRY, stcb, 0, NULL, SCTP_SO_NOT_LOCKED);
4943				}
4944			}
4945			break;
4946
4947		case SCTP_HEARTBEAT_REQUEST:
4948			SCTPDBG(SCTP_DEBUG_INPUT3, "SCTP_HEARTBEAT\n");
4949			if ((stcb) && netp && *netp) {
4950				SCTP_STAT_INCR(sctps_recvheartbeat);
4951				sctp_send_heartbeat_ack(stcb, m, *offset,
4952				    chk_length, *netp);
4953
4954				/* He's alive so give him credit */
4955				if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_THRESHOLD_LOGGING) {
4956					sctp_misc_ints(SCTP_THRESHOLD_CLEAR,
4957					    stcb->asoc.overall_error_count,
4958					    0,
4959					    SCTP_FROM_SCTP_INPUT,
4960					    __LINE__);
4961				}
4962				stcb->asoc.overall_error_count = 0;
4963			}
4964			break;
4965		case SCTP_HEARTBEAT_ACK:
4966			SCTPDBG(SCTP_DEBUG_INPUT3, "SCTP_HEARTBEAT-ACK\n");
4967			if ((stcb == NULL) || (chk_length != sizeof(struct sctp_heartbeat_chunk))) {
4968				/* Its not ours */
4969				*offset = length;
4970				if (locked_tcb) {
4971					SCTP_TCB_UNLOCK(locked_tcb);
4972				}
4973				return (NULL);
4974			}
4975			/* He's alive so give him credit */
4976			if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_THRESHOLD_LOGGING) {
4977				sctp_misc_ints(SCTP_THRESHOLD_CLEAR,
4978				    stcb->asoc.overall_error_count,
4979				    0,
4980				    SCTP_FROM_SCTP_INPUT,
4981				    __LINE__);
4982			}
4983			stcb->asoc.overall_error_count = 0;
4984			SCTP_STAT_INCR(sctps_recvheartbeatack);
4985			if (netp && *netp)
4986				sctp_handle_heartbeat_ack((struct sctp_heartbeat_chunk *)ch,
4987				    stcb, *netp);
4988			break;
4989		case SCTP_ABORT_ASSOCIATION:
4990			SCTPDBG(SCTP_DEBUG_INPUT3, "SCTP_ABORT, stcb %p\n",
4991			    stcb);
4992			if ((stcb) && netp && *netp)
4993				sctp_handle_abort((struct sctp_abort_chunk *)ch,
4994				    stcb, *netp);
4995			*offset = length;
4996			return (NULL);
4997			break;
4998		case SCTP_SHUTDOWN:
4999			SCTPDBG(SCTP_DEBUG_INPUT3, "SCTP_SHUTDOWN, stcb %p\n",
5000			    stcb);
5001			if ((stcb == NULL) || (chk_length != sizeof(struct sctp_shutdown_chunk))) {
5002				*offset = length;
5003				if (locked_tcb) {
5004					SCTP_TCB_UNLOCK(locked_tcb);
5005				}
5006				return (NULL);
5007			}
5008			if (netp && *netp) {
5009				int abort_flag = 0;
5010
5011				sctp_handle_shutdown((struct sctp_shutdown_chunk *)ch,
5012				    stcb, *netp, &abort_flag);
5013				if (abort_flag) {
5014					*offset = length;
5015					return (NULL);
5016				}
5017			}
5018			break;
5019		case SCTP_SHUTDOWN_ACK:
5020			SCTPDBG(SCTP_DEBUG_INPUT3, "SCTP_SHUTDOWN-ACK, stcb %p\n", stcb);
5021			if ((stcb) && (netp) && (*netp))
5022				sctp_handle_shutdown_ack((struct sctp_shutdown_ack_chunk *)ch, stcb, *netp);
5023			*offset = length;
5024			return (NULL);
5025			break;
5026
5027		case SCTP_OPERATION_ERROR:
5028			SCTPDBG(SCTP_DEBUG_INPUT3, "SCTP_OP-ERR\n");
5029			if ((stcb) && netp && *netp && sctp_handle_error(ch, stcb, *netp) < 0) {
5030				*offset = length;
5031				return (NULL);
5032			}
5033			break;
5034		case SCTP_COOKIE_ECHO:
5035			SCTPDBG(SCTP_DEBUG_INPUT3,
5036			    "SCTP_COOKIE-ECHO, stcb %p\n", stcb);
5037			if ((stcb) && (stcb->asoc.total_output_queue_size)) {
5038				;
5039			} else {
5040				if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE) {
5041					/* We are not interested anymore */
5042			abend:
5043					if (stcb) {
5044						SCTP_TCB_UNLOCK(stcb);
5045					}
5046					*offset = length;
5047					return (NULL);
5048				}
5049			}
5050			/*
5051			 * First are we accepting? We do this again here
5052			 * since it is possible that a previous endpoint WAS
5053			 * listening responded to a INIT-ACK and then
5054			 * closed. We opened and bound.. and are now no
5055			 * longer listening.
5056			 */
5057
5058			if ((stcb == NULL) && (inp->sctp_socket->so_qlen >= inp->sctp_socket->so_qlimit)) {
5059				if ((inp->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE) &&
5060				    (SCTP_BASE_SYSCTL(sctp_abort_if_one_2_one_hits_limit))) {
5061					struct mbuf *op_err;
5062
5063					op_err = sctp_generate_invmanparam(SCTP_CAUSE_OUT_OF_RESC);
5064					sctp_abort_association(inp, stcb, m,
5065					    iphlen, sh, op_err, vrf_id, port);
5066				}
5067				*offset = length;
5068				return (NULL);
5069			} else {
5070				struct mbuf *ret_buf;
5071				struct sctp_inpcb *linp;
5072
5073				if (stcb) {
5074					linp = NULL;
5075				} else {
5076					linp = inp;
5077				}
5078
5079				if (linp) {
5080					SCTP_ASOC_CREATE_LOCK(linp);
5081					if ((inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE) ||
5082					    (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE)) {
5083						SCTP_ASOC_CREATE_UNLOCK(linp);
5084						goto abend;
5085					}
5086				}
5087				if (netp) {
5088					ret_buf =
5089					    sctp_handle_cookie_echo(m, iphlen,
5090					    *offset, sh,
5091					    (struct sctp_cookie_echo_chunk *)ch,
5092					    &inp, &stcb, netp,
5093					    auth_skipped,
5094					    auth_offset,
5095					    auth_len,
5096					    &locked_tcb,
5097					    vrf_id,
5098					    port);
5099				} else {
5100					ret_buf = NULL;
5101				}
5102				if (linp) {
5103					SCTP_ASOC_CREATE_UNLOCK(linp);
5104				}
5105				if (ret_buf == NULL) {
5106					if (locked_tcb) {
5107						SCTP_TCB_UNLOCK(locked_tcb);
5108					}
5109					SCTPDBG(SCTP_DEBUG_INPUT3,
5110					    "GAK, null buffer\n");
5111					*offset = length;
5112					return (NULL);
5113				}
5114				/* if AUTH skipped, see if it verified... */
5115				if (auth_skipped) {
5116					got_auth = 1;
5117					auth_skipped = 0;
5118				}
5119				if (!TAILQ_EMPTY(&stcb->asoc.sent_queue)) {
5120					/*
5121					 * Restart the timer if we have
5122					 * pending data
5123					 */
5124					struct sctp_tmit_chunk *chk;
5125
5126					chk = TAILQ_FIRST(&stcb->asoc.sent_queue);
5127					sctp_timer_start(SCTP_TIMER_TYPE_SEND, stcb->sctp_ep, stcb, chk->whoTo);
5128				}
5129			}
5130			break;
5131		case SCTP_COOKIE_ACK:
5132			SCTPDBG(SCTP_DEBUG_INPUT3, "SCTP_COOKIE-ACK, stcb %p\n", stcb);
5133			if ((stcb == NULL) || chk_length != sizeof(struct sctp_cookie_ack_chunk)) {
5134				if (locked_tcb) {
5135					SCTP_TCB_UNLOCK(locked_tcb);
5136				}
5137				return (NULL);
5138			}
5139			if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE) {
5140				/* We are not interested anymore */
5141				if ((stcb) && (stcb->asoc.total_output_queue_size)) {
5142					;
5143				} else if (stcb) {
5144#if defined (__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
5145					so = SCTP_INP_SO(inp);
5146					atomic_add_int(&stcb->asoc.refcnt, 1);
5147					SCTP_TCB_UNLOCK(stcb);
5148					SCTP_SOCKET_LOCK(so, 1);
5149					SCTP_TCB_LOCK(stcb);
5150					atomic_subtract_int(&stcb->asoc.refcnt, 1);
5151#endif
5152					(void)sctp_free_assoc(inp, stcb, SCTP_NORMAL_PROC, SCTP_FROM_SCTP_INPUT + SCTP_LOC_27);
5153#if defined (__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
5154					SCTP_SOCKET_UNLOCK(so, 1);
5155#endif
5156					*offset = length;
5157					return (NULL);
5158				}
5159			}
5160			/* He's alive so give him credit */
5161			if ((stcb) && netp && *netp) {
5162				if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_THRESHOLD_LOGGING) {
5163					sctp_misc_ints(SCTP_THRESHOLD_CLEAR,
5164					    stcb->asoc.overall_error_count,
5165					    0,
5166					    SCTP_FROM_SCTP_INPUT,
5167					    __LINE__);
5168				}
5169				stcb->asoc.overall_error_count = 0;
5170				sctp_handle_cookie_ack((struct sctp_cookie_ack_chunk *)ch, stcb, *netp);
5171			}
5172			break;
5173		case SCTP_ECN_ECHO:
5174			SCTPDBG(SCTP_DEBUG_INPUT3, "SCTP_ECN-ECHO\n");
5175			/* He's alive so give him credit */
5176			if ((stcb == NULL) || (chk_length != sizeof(struct sctp_ecne_chunk))) {
5177				/* Its not ours */
5178				if (locked_tcb) {
5179					SCTP_TCB_UNLOCK(locked_tcb);
5180				}
5181				*offset = length;
5182				return (NULL);
5183			}
5184			if (stcb) {
5185				if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_THRESHOLD_LOGGING) {
5186					sctp_misc_ints(SCTP_THRESHOLD_CLEAR,
5187					    stcb->asoc.overall_error_count,
5188					    0,
5189					    SCTP_FROM_SCTP_INPUT,
5190					    __LINE__);
5191				}
5192				stcb->asoc.overall_error_count = 0;
5193				sctp_handle_ecn_echo((struct sctp_ecne_chunk *)ch,
5194				    stcb);
5195				ecne_seen = 1;
5196			}
5197			break;
5198		case SCTP_ECN_CWR:
5199			SCTPDBG(SCTP_DEBUG_INPUT3, "SCTP_ECN-CWR\n");
5200			/* He's alive so give him credit */
5201			if ((stcb == NULL) || (chk_length != sizeof(struct sctp_cwr_chunk))) {
5202				/* Its not ours */
5203				if (locked_tcb) {
5204					SCTP_TCB_UNLOCK(locked_tcb);
5205				}
5206				*offset = length;
5207				return (NULL);
5208			}
5209			if (stcb) {
5210				if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_THRESHOLD_LOGGING) {
5211					sctp_misc_ints(SCTP_THRESHOLD_CLEAR,
5212					    stcb->asoc.overall_error_count,
5213					    0,
5214					    SCTP_FROM_SCTP_INPUT,
5215					    __LINE__);
5216				}
5217				stcb->asoc.overall_error_count = 0;
5218				sctp_handle_ecn_cwr((struct sctp_cwr_chunk *)ch, stcb, *netp);
5219			}
5220			break;
5221		case SCTP_SHUTDOWN_COMPLETE:
5222			SCTPDBG(SCTP_DEBUG_INPUT3, "SCTP_SHUTDOWN-COMPLETE, stcb %p\n", stcb);
5223			/* must be first and only chunk */
5224			if ((num_chunks > 1) ||
5225			    (length - *offset > (int)SCTP_SIZE32(chk_length))) {
5226				*offset = length;
5227				if (locked_tcb) {
5228					SCTP_TCB_UNLOCK(locked_tcb);
5229				}
5230				return (NULL);
5231			}
5232			if ((stcb) && netp && *netp) {
5233				sctp_handle_shutdown_complete((struct sctp_shutdown_complete_chunk *)ch,
5234				    stcb, *netp);
5235			}
5236			*offset = length;
5237			return (NULL);
5238			break;
5239		case SCTP_ASCONF:
5240			SCTPDBG(SCTP_DEBUG_INPUT3, "SCTP_ASCONF\n");
5241			/* He's alive so give him credit */
5242			if (stcb) {
5243				if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_THRESHOLD_LOGGING) {
5244					sctp_misc_ints(SCTP_THRESHOLD_CLEAR,
5245					    stcb->asoc.overall_error_count,
5246					    0,
5247					    SCTP_FROM_SCTP_INPUT,
5248					    __LINE__);
5249				}
5250				stcb->asoc.overall_error_count = 0;
5251				sctp_handle_asconf(m, *offset,
5252				    (struct sctp_asconf_chunk *)ch, stcb, asconf_cnt == 0);
5253				asconf_cnt++;
5254			}
5255			break;
5256		case SCTP_ASCONF_ACK:
5257			SCTPDBG(SCTP_DEBUG_INPUT3, "SCTP_ASCONF-ACK\n");
5258			if (chk_length < sizeof(struct sctp_asconf_ack_chunk)) {
5259				/* Its not ours */
5260				if (locked_tcb) {
5261					SCTP_TCB_UNLOCK(locked_tcb);
5262				}
5263				*offset = length;
5264				return (NULL);
5265			}
5266			if ((stcb) && netp && *netp) {
5267				/* He's alive so give him credit */
5268				if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_THRESHOLD_LOGGING) {
5269					sctp_misc_ints(SCTP_THRESHOLD_CLEAR,
5270					    stcb->asoc.overall_error_count,
5271					    0,
5272					    SCTP_FROM_SCTP_INPUT,
5273					    __LINE__);
5274				}
5275				stcb->asoc.overall_error_count = 0;
5276				sctp_handle_asconf_ack(m, *offset,
5277				    (struct sctp_asconf_ack_chunk *)ch, stcb, *netp, &abort_no_unlock);
5278				if (abort_no_unlock)
5279					return (NULL);
5280			}
5281			break;
5282		case SCTP_FORWARD_CUM_TSN:
5283			SCTPDBG(SCTP_DEBUG_INPUT3, "SCTP_FWD-TSN\n");
5284			if (chk_length < sizeof(struct sctp_forward_tsn_chunk)) {
5285				/* Its not ours */
5286				if (locked_tcb) {
5287					SCTP_TCB_UNLOCK(locked_tcb);
5288				}
5289				*offset = length;
5290				return (NULL);
5291			}
5292			/* He's alive so give him credit */
5293			if (stcb) {
5294				int abort_flag = 0;
5295
5296				stcb->asoc.overall_error_count = 0;
5297				if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_THRESHOLD_LOGGING) {
5298					sctp_misc_ints(SCTP_THRESHOLD_CLEAR,
5299					    stcb->asoc.overall_error_count,
5300					    0,
5301					    SCTP_FROM_SCTP_INPUT,
5302					    __LINE__);
5303				}
5304				*fwd_tsn_seen = 1;
5305				if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE) {
5306					/* We are not interested anymore */
5307#if defined (__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
5308					so = SCTP_INP_SO(inp);
5309					atomic_add_int(&stcb->asoc.refcnt, 1);
5310					SCTP_TCB_UNLOCK(stcb);
5311					SCTP_SOCKET_LOCK(so, 1);
5312					SCTP_TCB_LOCK(stcb);
5313					atomic_subtract_int(&stcb->asoc.refcnt, 1);
5314#endif
5315					(void)sctp_free_assoc(inp, stcb, SCTP_NORMAL_PROC, SCTP_FROM_SCTP_INPUT + SCTP_LOC_29);
5316#if defined (__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
5317					SCTP_SOCKET_UNLOCK(so, 1);
5318#endif
5319					*offset = length;
5320					return (NULL);
5321				}
5322				sctp_handle_forward_tsn(stcb,
5323				    (struct sctp_forward_tsn_chunk *)ch, &abort_flag, m, *offset);
5324				if (abort_flag) {
5325					*offset = length;
5326					return (NULL);
5327				} else {
5328					if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_THRESHOLD_LOGGING) {
5329						sctp_misc_ints(SCTP_THRESHOLD_CLEAR,
5330						    stcb->asoc.overall_error_count,
5331						    0,
5332						    SCTP_FROM_SCTP_INPUT,
5333						    __LINE__);
5334					}
5335					stcb->asoc.overall_error_count = 0;
5336				}
5337
5338			}
5339			break;
5340		case SCTP_STREAM_RESET:
5341			SCTPDBG(SCTP_DEBUG_INPUT3, "SCTP_STREAM_RESET\n");
5342			if (((stcb == NULL) || (ch == NULL) || (chk_length < sizeof(struct sctp_stream_reset_tsn_req)))) {
5343				/* Its not ours */
5344				if (locked_tcb) {
5345					SCTP_TCB_UNLOCK(locked_tcb);
5346				}
5347				*offset = length;
5348				return (NULL);
5349			}
5350			if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE) {
5351				/* We are not interested anymore */
5352#if defined (__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
5353				so = SCTP_INP_SO(inp);
5354				atomic_add_int(&stcb->asoc.refcnt, 1);
5355				SCTP_TCB_UNLOCK(stcb);
5356				SCTP_SOCKET_LOCK(so, 1);
5357				SCTP_TCB_LOCK(stcb);
5358				atomic_subtract_int(&stcb->asoc.refcnt, 1);
5359#endif
5360				(void)sctp_free_assoc(inp, stcb, SCTP_NORMAL_PROC, SCTP_FROM_SCTP_INPUT + SCTP_LOC_30);
5361#if defined (__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
5362				SCTP_SOCKET_UNLOCK(so, 1);
5363#endif
5364				*offset = length;
5365				return (NULL);
5366			}
5367			if (stcb->asoc.peer_supports_strreset == 0) {
5368				/*
5369				 * hmm, peer should have announced this, but
5370				 * we will turn it on since he is sending us
5371				 * a stream reset.
5372				 */
5373				stcb->asoc.peer_supports_strreset = 1;
5374			}
5375			if (sctp_handle_stream_reset(stcb, m, *offset, (struct sctp_stream_reset_out_req *)ch)) {
5376				/* stop processing */
5377				*offset = length;
5378				return (NULL);
5379			}
5380			break;
5381		case SCTP_PACKET_DROPPED:
5382			SCTPDBG(SCTP_DEBUG_INPUT3, "SCTP_PACKET_DROPPED\n");
5383			/* re-get it all please */
5384			if (chk_length < sizeof(struct sctp_pktdrop_chunk)) {
5385				/* Its not ours */
5386				if (locked_tcb) {
5387					SCTP_TCB_UNLOCK(locked_tcb);
5388				}
5389				*offset = length;
5390				return (NULL);
5391			}
5392			if (ch && (stcb) && netp && (*netp)) {
5393				sctp_handle_packet_dropped((struct sctp_pktdrop_chunk *)ch,
5394				    stcb, *netp,
5395				    min(chk_length, (sizeof(chunk_buf) - 4)));
5396
5397			}
5398			break;
5399
5400		case SCTP_AUTHENTICATION:
5401			SCTPDBG(SCTP_DEBUG_INPUT3, "SCTP_AUTHENTICATION\n");
5402			if (SCTP_BASE_SYSCTL(sctp_auth_disable))
5403				goto unknown_chunk;
5404
5405			if (stcb == NULL) {
5406				/* save the first AUTH for later processing */
5407				if (auth_skipped == 0) {
5408					auth_offset = *offset;
5409					auth_len = chk_length;
5410					auth_skipped = 1;
5411				}
5412				/* skip this chunk (temporarily) */
5413				goto next_chunk;
5414			}
5415			if ((chk_length < (sizeof(struct sctp_auth_chunk))) ||
5416			    (chk_length > (sizeof(struct sctp_auth_chunk) +
5417			    SCTP_AUTH_DIGEST_LEN_MAX))) {
5418				/* Its not ours */
5419				if (locked_tcb) {
5420					SCTP_TCB_UNLOCK(locked_tcb);
5421				}
5422				*offset = length;
5423				return (NULL);
5424			}
5425			if (got_auth == 1) {
5426				/* skip this chunk... it's already auth'd */
5427				goto next_chunk;
5428			}
5429			got_auth = 1;
5430			if ((ch == NULL) || sctp_handle_auth(stcb, (struct sctp_auth_chunk *)ch,
5431			    m, *offset)) {
5432				/* auth HMAC failed so dump the packet */
5433				*offset = length;
5434				return (stcb);
5435			} else {
5436				/* remaining chunks are HMAC checked */
5437				stcb->asoc.authenticated = 1;
5438			}
5439			break;
5440
5441		default:
5442	unknown_chunk:
5443			/* it's an unknown chunk! */
5444			if ((ch->chunk_type & 0x40) && (stcb != NULL)) {
5445				struct mbuf *mm;
5446				struct sctp_paramhdr *phd;
5447
5448				mm = sctp_get_mbuf_for_msg(sizeof(struct sctp_paramhdr),
5449				    0, M_DONTWAIT, 1, MT_DATA);
5450				if (mm) {
5451					phd = mtod(mm, struct sctp_paramhdr *);
5452					/*
5453					 * We cheat and use param type since
5454					 * we did not bother to define a
5455					 * error cause struct. They are the
5456					 * same basic format with different
5457					 * names.
5458					 */
5459					phd->param_type = htons(SCTP_CAUSE_UNRECOG_CHUNK);
5460					phd->param_length = htons(chk_length + sizeof(*phd));
5461					SCTP_BUF_LEN(mm) = sizeof(*phd);
5462					SCTP_BUF_NEXT(mm) = SCTP_M_COPYM(m, *offset, chk_length, M_DONTWAIT);
5463					if (SCTP_BUF_NEXT(mm)) {
5464						if (sctp_pad_lastmbuf(SCTP_BUF_NEXT(mm), SCTP_SIZE32(chk_length) - chk_length, NULL)) {
5465							sctp_m_freem(mm);
5466						} else {
5467#ifdef SCTP_MBUF_LOGGING
5468							if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_MBUF_LOGGING_ENABLE) {
5469								struct mbuf *mat;
5470
5471								for (mat = SCTP_BUF_NEXT(mm); mat; mat = SCTP_BUF_NEXT(mat)) {
5472									if (SCTP_BUF_IS_EXTENDED(mat)) {
5473										sctp_log_mb(mat, SCTP_MBUF_ICOPY);
5474									}
5475								}
5476							}
5477#endif
5478							sctp_queue_op_err(stcb, mm);
5479						}
5480					} else {
5481						sctp_m_freem(mm);
5482					}
5483				}
5484			}
5485			if ((ch->chunk_type & 0x80) == 0) {
5486				/* discard this packet */
5487				*offset = length;
5488				return (stcb);
5489			}	/* else skip this bad chunk and continue... */
5490			break;
5491		}		/* switch (ch->chunk_type) */
5492
5493
5494next_chunk:
5495		/* get the next chunk */
5496		*offset += SCTP_SIZE32(chk_length);
5497		if (*offset >= length) {
5498			/* no more data left in the mbuf chain */
5499			break;
5500		}
5501		ch = (struct sctp_chunkhdr *)sctp_m_getptr(m, *offset,
5502		    sizeof(struct sctp_chunkhdr), chunk_buf);
5503		if (ch == NULL) {
5504			if (locked_tcb) {
5505				SCTP_TCB_UNLOCK(locked_tcb);
5506			}
5507			*offset = length;
5508			return (NULL);
5509		}
5510	}			/* while */
5511
5512	if (asconf_cnt > 0 && stcb != NULL) {
5513		sctp_send_asconf_ack(stcb);
5514	}
5515	return (stcb);
5516}
5517
5518
5519#ifdef INVARIANTS
5520#ifdef __GNUC__
5521__attribute__((noinline))
5522#endif
5523	void
5524	     sctp_validate_no_locks(struct sctp_inpcb *inp)
5525{
5526	struct sctp_tcb *lstcb;
5527
5528	LIST_FOREACH(lstcb, &inp->sctp_asoc_list, sctp_tcblist) {
5529		if (mtx_owned(&lstcb->tcb_mtx)) {
5530			panic("Own lock on stcb at return from input");
5531		}
5532	}
5533	if (mtx_owned(&inp->inp_create_mtx)) {
5534		panic("Own create lock on inp");
5535	}
5536	if (mtx_owned(&inp->inp_mtx)) {
5537		panic("Own inp lock on inp");
5538	}
5539}
5540
5541#endif
5542
5543/*
5544 * common input chunk processing (v4 and v6)
5545 */
5546void
5547sctp_common_input_processing(struct mbuf **mm, int iphlen, int offset,
5548    int length, struct sctphdr *sh, struct sctp_chunkhdr *ch,
5549    struct sctp_inpcb *inp, struct sctp_tcb *stcb, struct sctp_nets *net,
5550    uint8_t ecn_bits, uint32_t vrf_id, uint16_t port)
5551{
5552	/*
5553	 * Control chunk processing
5554	 */
5555	uint32_t high_tsn;
5556	int fwd_tsn_seen = 0, data_processed = 0;
5557	struct mbuf *m = *mm;
5558	int un_sent;
5559	int cnt_ctrl_ready = 0;
5560
5561	SCTP_STAT_INCR(sctps_recvdatagrams);
5562#ifdef SCTP_AUDITING_ENABLED
5563	sctp_audit_log(0xE0, 1);
5564	sctp_auditing(0, inp, stcb, net);
5565#endif
5566
5567	SCTPDBG(SCTP_DEBUG_INPUT1, "Ok, Common input processing called, m:%p iphlen:%d offset:%d length:%d stcb:%p\n",
5568	    m, iphlen, offset, length, stcb);
5569	if (stcb) {
5570		/* always clear this before beginning a packet */
5571		stcb->asoc.authenticated = 0;
5572		stcb->asoc.seen_a_sack_this_pkt = 0;
5573		SCTPDBG(SCTP_DEBUG_INPUT1, "stcb:%p state:%x\n",
5574		    stcb, stcb->asoc.state);
5575
5576		if ((stcb->asoc.state & SCTP_STATE_WAS_ABORTED) ||
5577		    (stcb->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED)) {
5578			/*-
5579			 * If we hit here, we had a ref count
5580			 * up when the assoc was aborted and the
5581			 * timer is clearing out the assoc, we should
5582			 * NOT respond to any packet.. its OOTB.
5583			 */
5584			SCTP_TCB_UNLOCK(stcb);
5585			sctp_handle_ootb(m, iphlen, offset, sh, inp, NULL,
5586			    vrf_id, port);
5587			goto out_now;
5588		}
5589	}
5590	if (IS_SCTP_CONTROL(ch)) {
5591		/* process the control portion of the SCTP packet */
5592		/* sa_ignore NO_NULL_CHK */
5593		stcb = sctp_process_control(m, iphlen, &offset, length, sh, ch,
5594		    inp, stcb, &net, &fwd_tsn_seen, vrf_id, port);
5595		if (stcb) {
5596			/*
5597			 * This covers us if the cookie-echo was there and
5598			 * it changes our INP.
5599			 */
5600			inp = stcb->sctp_ep;
5601			if ((net) && (port)) {
5602				if (net->port == 0) {
5603					sctp_pathmtu_adjustment(stcb, net->mtu - sizeof(struct udphdr));
5604				}
5605				net->port = port;
5606			}
5607		}
5608	} else {
5609		/*
5610		 * no control chunks, so pre-process DATA chunks (these
5611		 * checks are taken care of by control processing)
5612		 */
5613
5614		/*
5615		 * if DATA only packet, and auth is required, then punt...
5616		 * can't have authenticated without any AUTH (control)
5617		 * chunks
5618		 */
5619		if ((stcb != NULL) &&
5620		    !SCTP_BASE_SYSCTL(sctp_auth_disable) &&
5621		    sctp_auth_is_required_chunk(SCTP_DATA, stcb->asoc.local_auth_chunks)) {
5622			/* "silently" ignore */
5623			SCTP_STAT_INCR(sctps_recvauthmissing);
5624			SCTP_TCB_UNLOCK(stcb);
5625			goto out_now;
5626		}
5627		if (stcb == NULL) {
5628			/* out of the blue DATA chunk */
5629			sctp_handle_ootb(m, iphlen, offset, sh, inp, NULL,
5630			    vrf_id, port);
5631			goto out_now;
5632		}
5633		if (stcb->asoc.my_vtag != ntohl(sh->v_tag)) {
5634			/* v_tag mismatch! */
5635			SCTP_STAT_INCR(sctps_badvtag);
5636			SCTP_TCB_UNLOCK(stcb);
5637			goto out_now;
5638		}
5639	}
5640
5641	if (stcb == NULL) {
5642		/*
5643		 * no valid TCB for this packet, or we found it's a bad
5644		 * packet while processing control, or we're done with this
5645		 * packet (done or skip rest of data), so we drop it...
5646		 */
5647		goto out_now;
5648	}
5649	/*
5650	 * DATA chunk processing
5651	 */
5652	/* plow through the data chunks while length > offset */
5653
5654	/*
5655	 * Rest should be DATA only.  Check authentication state if AUTH for
5656	 * DATA is required.
5657	 */
5658	if ((length > offset) &&
5659	    (stcb != NULL) &&
5660	    !SCTP_BASE_SYSCTL(sctp_auth_disable) &&
5661	    sctp_auth_is_required_chunk(SCTP_DATA, stcb->asoc.local_auth_chunks) &&
5662	    !stcb->asoc.authenticated) {
5663		/* "silently" ignore */
5664		SCTP_STAT_INCR(sctps_recvauthmissing);
5665		SCTPDBG(SCTP_DEBUG_AUTH1,
5666		    "Data chunk requires AUTH, skipped\n");
5667		goto trigger_send;
5668	}
5669	if (length > offset) {
5670		int retval;
5671
5672		/*
5673		 * First check to make sure our state is correct. We would
5674		 * not get here unless we really did have a tag, so we don't
5675		 * abort if this happens, just dump the chunk silently.
5676		 */
5677		switch (SCTP_GET_STATE(&stcb->asoc)) {
5678		case SCTP_STATE_COOKIE_ECHOED:
5679			/*
5680			 * we consider data with valid tags in this state
5681			 * shows us the cookie-ack was lost. Imply it was
5682			 * there.
5683			 */
5684			if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_THRESHOLD_LOGGING) {
5685				sctp_misc_ints(SCTP_THRESHOLD_CLEAR,
5686				    stcb->asoc.overall_error_count,
5687				    0,
5688				    SCTP_FROM_SCTP_INPUT,
5689				    __LINE__);
5690			}
5691			stcb->asoc.overall_error_count = 0;
5692			sctp_handle_cookie_ack((struct sctp_cookie_ack_chunk *)ch, stcb, net);
5693			break;
5694		case SCTP_STATE_COOKIE_WAIT:
5695			/*
5696			 * We consider OOTB any data sent during asoc setup.
5697			 */
5698			sctp_handle_ootb(m, iphlen, offset, sh, inp, NULL,
5699			    vrf_id, port);
5700			SCTP_TCB_UNLOCK(stcb);
5701			goto out_now;
5702			/* sa_ignore NOTREACHED */
5703			break;
5704		case SCTP_STATE_EMPTY:	/* should not happen */
5705		case SCTP_STATE_INUSE:	/* should not happen */
5706		case SCTP_STATE_SHUTDOWN_RECEIVED:	/* This is a peer error */
5707		case SCTP_STATE_SHUTDOWN_ACK_SENT:
5708		default:
5709			SCTP_TCB_UNLOCK(stcb);
5710			goto out_now;
5711			/* sa_ignore NOTREACHED */
5712			break;
5713		case SCTP_STATE_OPEN:
5714		case SCTP_STATE_SHUTDOWN_SENT:
5715			break;
5716		}
5717		/* plow through the data chunks while length > offset */
5718		retval = sctp_process_data(mm, iphlen, &offset, length, sh,
5719		    inp, stcb, net, &high_tsn);
5720		if (retval == 2) {
5721			/*
5722			 * The association aborted, NO UNLOCK needed since
5723			 * the association is destroyed.
5724			 */
5725			goto out_now;
5726		}
5727		data_processed = 1;
5728		/*
5729		 * Anything important needs to have been m_copy'ed in
5730		 * process_data
5731		 */
5732	}
5733	/* take care of ecn */
5734	if ((data_processed == 1) &&
5735	    (stcb->asoc.ecn_allowed == 1) &&
5736	    ((ecn_bits & SCTP_CE_BITS) == SCTP_CE_BITS)) {
5737		/* Yep, we need to add a ECNE */
5738		sctp_send_ecn_echo(stcb, net, high_tsn);
5739	}
5740	if ((data_processed == 0) && (fwd_tsn_seen)) {
5741		int was_a_gap;
5742		uint32_t highest_tsn;
5743
5744		if (SCTP_TSN_GT(stcb->asoc.highest_tsn_inside_nr_map, stcb->asoc.highest_tsn_inside_map)) {
5745			highest_tsn = stcb->asoc.highest_tsn_inside_nr_map;
5746		} else {
5747			highest_tsn = stcb->asoc.highest_tsn_inside_map;
5748		}
5749		was_a_gap = SCTP_TSN_GT(highest_tsn, stcb->asoc.cumulative_tsn);
5750		stcb->asoc.send_sack = 1;
5751		sctp_sack_check(stcb, was_a_gap);
5752	} else if (fwd_tsn_seen) {
5753		stcb->asoc.send_sack = 1;
5754	}
5755	/* trigger send of any chunks in queue... */
5756trigger_send:
5757#ifdef SCTP_AUDITING_ENABLED
5758	sctp_audit_log(0xE0, 2);
5759	sctp_auditing(1, inp, stcb, net);
5760#endif
5761	SCTPDBG(SCTP_DEBUG_INPUT1,
5762	    "Check for chunk output prw:%d tqe:%d tf=%d\n",
5763	    stcb->asoc.peers_rwnd,
5764	    TAILQ_EMPTY(&stcb->asoc.control_send_queue),
5765	    stcb->asoc.total_flight);
5766	un_sent = (stcb->asoc.total_output_queue_size - stcb->asoc.total_flight);
5767	if (!TAILQ_EMPTY(&stcb->asoc.control_send_queue)) {
5768		cnt_ctrl_ready = stcb->asoc.ctrl_queue_cnt - stcb->asoc.ecn_echo_cnt_onq;
5769	}
5770	if (cnt_ctrl_ready ||
5771	    ((un_sent) &&
5772	    (stcb->asoc.peers_rwnd > 0 ||
5773	    (stcb->asoc.peers_rwnd <= 0 && stcb->asoc.total_flight == 0)))) {
5774		SCTPDBG(SCTP_DEBUG_INPUT3, "Calling chunk OUTPUT\n");
5775		sctp_chunk_output(inp, stcb, SCTP_OUTPUT_FROM_CONTROL_PROC, SCTP_SO_NOT_LOCKED);
5776		SCTPDBG(SCTP_DEBUG_INPUT3, "chunk OUTPUT returns\n");
5777	}
5778#ifdef SCTP_AUDITING_ENABLED
5779	sctp_audit_log(0xE0, 3);
5780	sctp_auditing(2, inp, stcb, net);
5781#endif
5782	SCTP_TCB_UNLOCK(stcb);
5783out_now:
5784#ifdef INVARIANTS
5785	sctp_validate_no_locks(inp);
5786#endif
5787	return;
5788}
5789
5790#if 0
5791static void
5792sctp_print_mbuf_chain(struct mbuf *m)
5793{
5794	for (; m; m = SCTP_BUF_NEXT(m)) {
5795		SCTP_PRINTF("%p: m_len = %ld\n", m, SCTP_BUF_LEN(m));
5796		if (SCTP_BUF_IS_EXTENDED(m))
5797			SCTP_PRINTF("%p: extend_size = %d\n", m, SCTP_BUF_EXTEND_SIZE(m));
5798	}
5799}
5800
5801#endif
5802
5803#ifdef INET
5804void
5805sctp_input_with_port(struct mbuf *i_pak, int off, uint16_t port)
5806{
5807	struct mbuf *m;
5808	int iphlen;
5809	uint32_t vrf_id = 0;
5810	uint8_t ecn_bits;
5811	struct ip *ip;
5812	struct sctphdr *sh;
5813	struct sctp_inpcb *inp = NULL;
5814	struct sctp_nets *net;
5815	struct sctp_tcb *stcb = NULL;
5816	struct sctp_chunkhdr *ch;
5817	int refcount_up = 0;
5818	int length, mlen, offset;
5819
5820#if !defined(SCTP_WITH_NO_CSUM)
5821	uint32_t check, calc_check;
5822
5823#endif
5824
5825	if (SCTP_GET_PKT_VRFID(i_pak, vrf_id)) {
5826		SCTP_RELEASE_PKT(i_pak);
5827		return;
5828	}
5829	mlen = SCTP_HEADER_LEN(i_pak);
5830	iphlen = off;
5831	m = SCTP_HEADER_TO_CHAIN(i_pak);
5832
5833	net = NULL;
5834	SCTP_STAT_INCR(sctps_recvpackets);
5835	SCTP_STAT_INCR_COUNTER64(sctps_inpackets);
5836
5837
5838#ifdef SCTP_MBUF_LOGGING
5839	/* Log in any input mbufs */
5840	if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_MBUF_LOGGING_ENABLE) {
5841		struct mbuf *mat;
5842
5843		for (mat = m; mat; mat = SCTP_BUF_NEXT(mat)) {
5844			if (SCTP_BUF_IS_EXTENDED(mat)) {
5845				sctp_log_mb(mat, SCTP_MBUF_INPUT);
5846			}
5847		}
5848	}
5849#endif
5850#ifdef  SCTP_PACKET_LOGGING
5851	if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_LAST_PACKET_TRACING)
5852		sctp_packet_log(m, mlen);
5853#endif
5854	/*
5855	 * Must take out the iphlen, since mlen expects this (only effect lb
5856	 * case)
5857	 */
5858	mlen -= iphlen;
5859
5860	/*
5861	 * Get IP, SCTP, and first chunk header together in first mbuf.
5862	 */
5863	ip = mtod(m, struct ip *);
5864	offset = iphlen + sizeof(*sh) + sizeof(*ch);
5865	if (SCTP_BUF_LEN(m) < offset) {
5866		if ((m = m_pullup(m, offset)) == 0) {
5867			SCTP_STAT_INCR(sctps_hdrops);
5868			return;
5869		}
5870		ip = mtod(m, struct ip *);
5871	}
5872	/* validate mbuf chain length with IP payload length */
5873	if (mlen < (SCTP_GET_IPV4_LENGTH(ip) - iphlen)) {
5874		SCTP_STAT_INCR(sctps_hdrops);
5875		goto bad;
5876	}
5877	sh = (struct sctphdr *)((caddr_t)ip + iphlen);
5878	ch = (struct sctp_chunkhdr *)((caddr_t)sh + sizeof(*sh));
5879	SCTPDBG(SCTP_DEBUG_INPUT1,
5880	    "sctp_input() length:%d iphlen:%d\n", mlen, iphlen);
5881
5882	/* SCTP does not allow broadcasts or multicasts */
5883	if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr))) {
5884		goto bad;
5885	}
5886	if (SCTP_IS_IT_BROADCAST(ip->ip_dst, m)) {
5887		/*
5888		 * We only look at broadcast if its a front state, All
5889		 * others we will not have a tcb for anyway.
5890		 */
5891		goto bad;
5892	}
5893	/* validate SCTP checksum */
5894	SCTPDBG(SCTP_DEBUG_CRCOFFLOAD,
5895	    "sctp_input(): Packet of length %d received on %s with csum_flags 0x%x.\n",
5896	    m->m_pkthdr.len,
5897	    if_name(m->m_pkthdr.rcvif),
5898	    m->m_pkthdr.csum_flags);
5899#if defined(SCTP_WITH_NO_CSUM)
5900	SCTP_STAT_INCR(sctps_recvnocrc);
5901#else
5902	if (m->m_pkthdr.csum_flags & CSUM_SCTP_VALID) {
5903		SCTP_STAT_INCR(sctps_recvhwcrc);
5904		goto sctp_skip_csum_4;
5905	}
5906	check = sh->checksum;	/* save incoming checksum */
5907	sh->checksum = 0;	/* prepare for calc */
5908	calc_check = sctp_calculate_cksum(m, iphlen);
5909	sh->checksum = check;
5910	SCTP_STAT_INCR(sctps_recvswcrc);
5911	if (calc_check != check) {
5912		SCTPDBG(SCTP_DEBUG_INPUT1, "Bad CSUM on SCTP packet calc_check:%x check:%x  m:%p mlen:%d iphlen:%d\n",
5913		    calc_check, check, m, mlen, iphlen);
5914
5915		stcb = sctp_findassociation_addr(m,
5916		    offset - sizeof(*ch),
5917		    sh, ch, &inp, &net,
5918		    vrf_id);
5919		if ((net) && (port)) {
5920			if (net->port == 0) {
5921				sctp_pathmtu_adjustment(stcb, net->mtu - sizeof(struct udphdr));
5922			}
5923			net->port = port;
5924		}
5925		if ((net != NULL) && (m->m_flags & M_FLOWID)) {
5926			net->flowid = m->m_pkthdr.flowid;
5927#ifdef INVARIANTS
5928			net->flowidset = 1;
5929#endif
5930		}
5931		if ((inp) && (stcb)) {
5932			sctp_send_packet_dropped(stcb, net, m, iphlen, 1);
5933			sctp_chunk_output(inp, stcb, SCTP_OUTPUT_FROM_INPUT_ERROR, SCTP_SO_NOT_LOCKED);
5934		} else if ((inp != NULL) && (stcb == NULL)) {
5935			refcount_up = 1;
5936		}
5937		SCTP_STAT_INCR(sctps_badsum);
5938		SCTP_STAT_INCR_COUNTER32(sctps_checksumerrors);
5939		goto bad;
5940	}
5941sctp_skip_csum_4:
5942#endif
5943	/* destination port of 0 is illegal, based on RFC2960. */
5944	if (sh->dest_port == 0) {
5945		SCTP_STAT_INCR(sctps_hdrops);
5946		goto bad;
5947	}
5948	/*
5949	 * Locate pcb and tcb for datagram sctp_findassociation_addr() wants
5950	 * IP/SCTP/first chunk header...
5951	 */
5952	stcb = sctp_findassociation_addr(m, offset - sizeof(*ch),
5953	    sh, ch, &inp, &net, vrf_id);
5954	if ((net) && (port)) {
5955		if (net->port == 0) {
5956			sctp_pathmtu_adjustment(stcb, net->mtu - sizeof(struct udphdr));
5957		}
5958		net->port = port;
5959	}
5960	if ((net != NULL) && (m->m_flags & M_FLOWID)) {
5961		net->flowid = m->m_pkthdr.flowid;
5962#ifdef INVARIANTS
5963		net->flowidset = 1;
5964#endif
5965	}
5966	/* inp's ref-count increased && stcb locked */
5967	if (inp == NULL) {
5968		struct sctp_init_chunk *init_chk, chunk_buf;
5969
5970		SCTP_STAT_INCR(sctps_noport);
5971#ifdef ICMP_BANDLIM
5972		/*
5973		 * we use the bandwidth limiting to protect against sending
5974		 * too many ABORTS all at once. In this case these count the
5975		 * same as an ICMP message.
5976		 */
5977		if (badport_bandlim(0) < 0)
5978			goto bad;
5979#endif				/* ICMP_BANDLIM */
5980		SCTPDBG(SCTP_DEBUG_INPUT1,
5981		    "Sending a ABORT from packet entry!\n");
5982		if (ch->chunk_type == SCTP_INITIATION) {
5983			/*
5984			 * we do a trick here to get the INIT tag, dig in
5985			 * and get the tag from the INIT and put it in the
5986			 * common header.
5987			 */
5988			init_chk = (struct sctp_init_chunk *)sctp_m_getptr(m,
5989			    iphlen + sizeof(*sh), sizeof(*init_chk),
5990			    (uint8_t *) & chunk_buf);
5991			if (init_chk != NULL)
5992				sh->v_tag = init_chk->init.initiate_tag;
5993		}
5994		if (ch->chunk_type == SCTP_SHUTDOWN_ACK) {
5995			sctp_send_shutdown_complete2(m, sh, vrf_id, port);
5996			goto bad;
5997		}
5998		if (ch->chunk_type == SCTP_SHUTDOWN_COMPLETE) {
5999			goto bad;
6000		}
6001		if (ch->chunk_type != SCTP_ABORT_ASSOCIATION) {
6002			if ((SCTP_BASE_SYSCTL(sctp_blackhole) == 0) ||
6003			    ((SCTP_BASE_SYSCTL(sctp_blackhole) == 1) &&
6004			    (ch->chunk_type != SCTP_INIT))) {
6005				sctp_send_abort(m, iphlen, sh, 0, NULL, vrf_id, port);
6006			}
6007		}
6008		goto bad;
6009	} else if (stcb == NULL) {
6010		refcount_up = 1;
6011	}
6012#ifdef IPSEC
6013	/*
6014	 * I very much doubt any of the IPSEC stuff will work but I have no
6015	 * idea, so I will leave it in place.
6016	 */
6017	if (inp && ipsec4_in_reject(m, &inp->ip_inp.inp)) {
6018		MODULE_GLOBAL(ipsec4stat).in_polvio++;
6019		SCTP_STAT_INCR(sctps_hdrops);
6020		goto bad;
6021	}
6022#endif				/* IPSEC */
6023
6024	/*
6025	 * common chunk processing
6026	 */
6027	length = ip->ip_len + iphlen;
6028	offset -= sizeof(struct sctp_chunkhdr);
6029
6030	ecn_bits = ip->ip_tos;
6031
6032	/* sa_ignore NO_NULL_CHK */
6033	sctp_common_input_processing(&m, iphlen, offset, length, sh, ch,
6034	    inp, stcb, net, ecn_bits, vrf_id, port);
6035	/* inp's ref-count reduced && stcb unlocked */
6036	if (m) {
6037		sctp_m_freem(m);
6038	}
6039	if ((inp) && (refcount_up)) {
6040		/* reduce ref-count */
6041		SCTP_INP_DECR_REF(inp);
6042	}
6043	return;
6044bad:
6045	if (stcb) {
6046		SCTP_TCB_UNLOCK(stcb);
6047	}
6048	if ((inp) && (refcount_up)) {
6049		/* reduce ref-count */
6050		SCTP_INP_DECR_REF(inp);
6051	}
6052	if (m) {
6053		sctp_m_freem(m);
6054	}
6055	return;
6056}
6057
6058#if defined(__FreeBSD__) && defined(SCTP_MCORE_INPUT) && defined(SMP)
6059extern int *sctp_cpuarry;
6060
6061#endif
6062
6063void
6064sctp_input(struct mbuf *m, int off)
6065{
6066#if defined(__FreeBSD__) && defined(SCTP_MCORE_INPUT) && defined(SMP)
6067	struct ip *ip;
6068	struct sctphdr *sh;
6069	int offset;
6070	int cpu_to_use;
6071	uint32_t flowid, tag;
6072
6073	if (mp_ncpus > 1) {
6074		if (m->m_flags & M_FLOWID) {
6075			flowid = m->m_pkthdr.flowid;
6076		} else {
6077			/*
6078			 * No flow id built by lower layers fix it so we
6079			 * create one.
6080			 */
6081			ip = mtod(m, struct ip *);
6082			offset = off + sizeof(*sh);
6083			if (SCTP_BUF_LEN(m) < offset) {
6084				if ((m = m_pullup(m, offset)) == 0) {
6085					SCTP_STAT_INCR(sctps_hdrops);
6086					return;
6087				}
6088				ip = mtod(m, struct ip *);
6089			}
6090			sh = (struct sctphdr *)((caddr_t)ip + off);
6091			tag = htonl(sh->v_tag);
6092			flowid = tag ^ ntohs(sh->dest_port) ^ ntohs(sh->src_port);
6093			m->m_pkthdr.flowid = flowid;
6094			m->m_flags |= M_FLOWID;
6095		}
6096		cpu_to_use = sctp_cpuarry[flowid % mp_ncpus];
6097		sctp_queue_to_mcore(m, off, cpu_to_use);
6098		return;
6099	}
6100#endif
6101	sctp_input_with_port(m, off, 0);
6102}
6103
6104#endif
6105