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