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