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