3 * Transmission Control Protocol for IP
5 * This file contains common functions for the TCP implementation, such as functinos
6 * for manipulating the data structures and the TCP timer functions. TCP functions
7 * related to input and output is found in tcp_in.c and tcp_out.c respectively.
12 * Copyright (c) 2001-2004 Swedish Institute of Computer Science.
13 * All rights reserved.
15 * Redistribution and use in source and binary forms, with or without modification,
16 * are permitted provided that the following conditions are met:
18 * 1. Redistributions of source code must retain the above copyright notice,
19 * this list of conditions and the following disclaimer.
20 * 2. Redistributions in binary form must reproduce the above copyright notice,
21 * this list of conditions and the following disclaimer in the documentation
22 * and/or other materials provided with the distribution.
23 * 3. The name of the author may not be used to endorse or promote products
24 * derived from this software without specific prior written permission.
26 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
27 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
28 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
29 * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
30 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
31 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
33 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
34 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
37 * This file is part of the lwIP TCP/IP stack.
39 * Author: Adam Dunkels <adam@sics.se>
45 #if LWIP_TCP /* don't build if not configured for use in lwipopts.h */
49 #include "lwip/memp.h"
50 #include "lwip/snmp.h"
52 #include "lwip/tcp_impl.h"
53 #include "lwip/debug.h"
54 #include "lwip/stats.h"
56 #include "lwip/ip6_addr.h"
61 #ifndef TCP_LOCAL_PORT_RANGE_START
62 /* From http://www.iana.org/assignments/port-numbers:
63 "The Dynamic and/or Private Ports are those from 49152 through 65535" */
64 #define TCP_LOCAL_PORT_RANGE_START 0xc000
65 #define TCP_LOCAL_PORT_RANGE_END 0xffff
66 #define TCP_ENSURE_LOCAL_PORT_RANGE(port) (((port) & ~TCP_LOCAL_PORT_RANGE_START) + TCP_LOCAL_PORT_RANGE_START)
69 const char * const tcp_state_str[] = {
83 /* last local TCP port */
84 static u16_t tcp_port = TCP_LOCAL_PORT_RANGE_START;
86 /* Incremented every coarse grained timer shot (typically every 500 ms). */
88 const u8_t tcp_backoff[13] =
89 { 1, 2, 3, 4, 5, 6, 7, 7, 7, 7, 7, 7, 7};
90 /* Times per slowtmr hits */
91 const u8_t tcp_persist_backoff[7] = { 3, 6, 12, 24, 48, 96, 120 };
93 /* The TCP PCB lists. */
95 /** List of all TCP PCBs bound but not yet (connected || listening) */
96 struct tcp_pcb *tcp_bound_pcbs;
97 /** List of all TCP PCBs in LISTEN state */
98 union tcp_listen_pcbs_t tcp_listen_pcbs;
99 /** List of all TCP PCBs that are in a state in which
100 * they accept or send data. */
101 struct tcp_pcb *tcp_active_pcbs;
102 /** List of all TCP PCBs in TIME-WAIT state */
103 struct tcp_pcb *tcp_tw_pcbs;
105 #define NUM_TCP_PCB_LISTS 4
106 #define NUM_TCP_PCB_LISTS_NO_TIME_WAIT 3
107 /** An array with all (non-temporary) PCB lists, mainly used for smaller code size */
108 struct tcp_pcb ** const tcp_pcb_lists[] = {&tcp_listen_pcbs.pcbs, &tcp_bound_pcbs,
109 &tcp_active_pcbs, &tcp_tw_pcbs};
111 /** Only used for temporary storage. */
112 struct tcp_pcb *tcp_tmp_pcb;
114 /** Timer counter to handle calling slow-timer from tcp_tmr() */
115 static u8_t tcp_timer;
116 static u16_t tcp_new_port(void);
119 * Initialize this module.
124 #if LWIP_RANDOMIZE_INITIAL_LOCAL_PORTS && defined(LWIP_RAND)
125 tcp_port = TCP_ENSURE_LOCAL_PORT_RANGE(LWIP_RAND());
126 #endif /* LWIP_RANDOMIZE_INITIAL_LOCAL_PORTS && defined(LWIP_RAND) */
130 * Called periodically to dispatch TCP timers.
135 /* Call tcp_fasttmr() every 250 ms */
138 if (++tcp_timer & 1) {
139 /* Call tcp_tmr() every 500 ms, i.e., every other timer
140 tcp_tmr() is called. */
146 * Closes the TX side of a connection held by the PCB.
147 * For tcp_close(), a RST is sent if the application didn't receive all data
148 * (tcp_recved() not called for all data passed to recv callback).
150 * Listening pcbs are freed and may not be referenced any more.
151 * Connection pcbs are freed if not yet connected and may not be referenced
152 * any more. If a connection is established (at least SYN received or in
153 * a closing state), the connection is closed, and put in a closing state.
154 * The pcb is then automatically freed in tcp_slowtmr(). It is therefore
155 * unsafe to reference it.
157 * @param pcb the tcp_pcb to close
158 * @return ERR_OK if connection has been closed
159 * another err_t if closing failed and pcb is not freed
162 tcp_close_shutdown(struct tcp_pcb *pcb, u8_t rst_on_unacked_data)
166 if (rst_on_unacked_data && (pcb->state != LISTEN)) {
167 if ((pcb->refused_data != NULL) || (pcb->rcv_wnd != TCP_WND)) {
168 /* Not all data received by application, send RST to tell the remote
170 LWIP_ASSERT("pcb->flags & TF_RXCLOSED", pcb->flags & TF_RXCLOSED);
172 /* don't call tcp_abort here: we must not deallocate the pcb since
173 that might not be expected when calling tcp_close */
174 tcp_rst(pcb->snd_nxt, pcb->rcv_nxt, &pcb->local_ip, &pcb->remote_ip,
175 pcb->local_port, pcb->remote_port, PCB_ISIPV6(pcb));
179 /* TODO: to which state do we move now? */
181 /* move to TIME_WAIT since we close actively */
182 TCP_RMV(&tcp_active_pcbs, pcb);
183 pcb->state = TIME_WAIT;
184 TCP_REG(&tcp_tw_pcbs, pcb);
190 switch (pcb->state) {
192 /* Closing a pcb in the CLOSED state might seem erroneous,
193 * however, it is in this state once allocated and as yet unused
194 * and the user needs some way to free it should the need arise.
195 * Calling tcp_close() with a pcb that has already been closed, (i.e. twice)
196 * or for a pcb that has been used and then entered the CLOSED state
197 * is erroneous, but this should never happen as the pcb has in those cases
198 * been freed, and so any remaining handles are bogus. */
200 if (pcb->local_port != 0) {
201 TCP_RMV(&tcp_bound_pcbs, pcb);
203 memp_free(MEMP_TCP_PCB, pcb);
208 tcp_pcb_remove(&tcp_listen_pcbs.pcbs, pcb);
209 memp_free(MEMP_TCP_PCB_LISTEN, pcb);
214 tcp_pcb_remove(&tcp_active_pcbs, pcb);
215 memp_free(MEMP_TCP_PCB, pcb);
217 snmp_inc_tcpattemptfails();
220 err = tcp_send_fin(pcb);
222 snmp_inc_tcpattemptfails();
223 pcb->state = FIN_WAIT_1;
227 err = tcp_send_fin(pcb);
229 snmp_inc_tcpestabresets();
230 pcb->state = FIN_WAIT_1;
234 err = tcp_send_fin(pcb);
236 snmp_inc_tcpestabresets();
237 pcb->state = LAST_ACK;
241 /* Has already been closed, do nothing. */
247 if (pcb != NULL && err == ERR_OK) {
248 /* To ensure all data has been sent when tcp_close returns, we have
249 to make sure tcp_output doesn't fail.
250 Since we don't really have to ensure all data has been sent when tcp_close
251 returns (unsent data is sent from tcp timer functions, also), we don't care
252 for the return value of tcp_output for now. */
253 /* @todo: When implementing SO_LINGER, this must be changed somehow:
254 If SOF_LINGER is set, the data should be sent and acked before close returns.
255 This can only be valid for sequential APIs, not for the raw API. */
262 * Closes the connection held by the PCB.
264 * Listening pcbs are freed and may not be referenced any more.
265 * Connection pcbs are freed if not yet connected and may not be referenced
266 * any more. If a connection is established (at least SYN received or in
267 * a closing state), the connection is closed, and put in a closing state.
268 * The pcb is then automatically freed in tcp_slowtmr(). It is therefore
269 * unsafe to reference it (unless an error is returned).
271 * @param pcb the tcp_pcb to close
272 * @return ERR_OK if connection has been closed
273 * another err_t if closing failed and pcb is not freed
276 tcp_close(struct tcp_pcb *pcb)
279 LWIP_DEBUGF(TCP_DEBUG, ("tcp_close: closing in "));
280 tcp_debug_print_state(pcb->state);
281 #endif /* TCP_DEBUG */
283 if (pcb->state != LISTEN) {
284 /* Set a flag not to receive any more data... */
285 pcb->flags |= TF_RXCLOSED;
288 return tcp_close_shutdown(pcb, 1);
292 * Causes all or part of a full-duplex connection of this PCB to be shut down.
293 * This doesn't deallocate the PCB!
295 * @param pcb PCB to shutdown
296 * @param shut_rx shut down receive side if this is != 0
297 * @param shut_tx shut down send side if this is != 0
298 * @return ERR_OK if shutdown succeeded (or the PCB has already been shut down)
299 * another err_t on error.
302 tcp_shutdown(struct tcp_pcb *pcb, int shut_rx, int shut_tx)
304 if (pcb->state == LISTEN) {
308 /* shut down the receive side: free buffered data... */
309 if (pcb->refused_data != NULL) {
310 pbuf_free(pcb->refused_data);
311 pcb->refused_data = NULL;
313 /* ... and set a flag not to receive any more data */
314 pcb->flags |= TF_RXCLOSED;
317 /* This can't happen twice since if it succeeds, the pcb's state is changed.
318 Only close in these states as the others directly deallocate the PCB */
319 switch (pcb->state) {
323 return tcp_close_shutdown(pcb, 0);
325 /* don't shut down other states */
329 /* @todo: return another err_t if not in correct state or already shut? */
334 * Abandons a connection and optionally sends a RST to the remote
335 * host. Deletes the local protocol control block. This is done when
336 * a connection is killed because of shortage of memory.
338 * @param pcb the tcp_pcb to abort
339 * @param reset boolean to indicate whether a reset should be sent
342 tcp_abandon(struct tcp_pcb *pcb, int reset)
345 #if LWIP_CALLBACK_API
347 #endif /* LWIP_CALLBACK_API */
350 /* pcb->state LISTEN not allowed here */
351 LWIP_ASSERT("don't call tcp_abort/tcp_abandon for listen-pcbs",
352 pcb->state != LISTEN);
353 /* Figure out on which TCP PCB list we are, and remove us. If we
354 are in an active state, call the receive function associated with
355 the PCB with a NULL argument, and send an RST to the remote end. */
356 if (pcb->state == TIME_WAIT) {
357 tcp_pcb_remove(&tcp_tw_pcbs, pcb);
358 memp_free(MEMP_TCP_PCB, pcb);
360 seqno = pcb->snd_nxt;
361 ackno = pcb->rcv_nxt;
362 #if LWIP_CALLBACK_API
364 #endif /* LWIP_CALLBACK_API */
365 errf_arg = pcb->callback_arg;
366 tcp_pcb_remove(&tcp_active_pcbs, pcb);
367 if (pcb->unacked != NULL) {
368 tcp_segs_free(pcb->unacked);
370 if (pcb->unsent != NULL) {
371 tcp_segs_free(pcb->unsent);
374 if (pcb->ooseq != NULL) {
375 tcp_segs_free(pcb->ooseq);
377 #endif /* TCP_QUEUE_OOSEQ */
379 LWIP_DEBUGF(TCP_RST_DEBUG, ("tcp_abandon: sending RST\n"));
380 tcp_rst(seqno, ackno, &pcb->local_ip, &pcb->remote_ip, pcb->local_port, pcb->remote_port, PCB_ISIPV6(pcb));
382 memp_free(MEMP_TCP_PCB, pcb);
383 TCP_EVENT_ERR(errf, errf_arg, ERR_ABRT);
388 * Aborts the connection by sending a RST (reset) segment to the remote
389 * host. The pcb is deallocated. This function never fails.
391 * ATTENTION: When calling this from one of the TCP callbacks, make
392 * sure you always return ERR_ABRT (and never return ERR_ABRT otherwise
393 * or you will risk accessing deallocated memory or memory leaks!
395 * @param pcb the tcp pcb to abort
398 tcp_abort(struct tcp_pcb *pcb)
404 * Binds the connection to a local portnumber and IP address. If the
405 * IP address is not given (i.e., ipaddr == NULL), the IP address of
406 * the outgoing network interface is used instead.
408 * @param pcb the tcp_pcb to bind (no check is done whether this pcb is
410 * @param ipaddr the local ip address to bind to (use IP_ADDR_ANY to bind
411 * to any local address
412 * @param port the local port to bind to
413 * @return ERR_USE if the port is already in use
414 * ERR_VAL if bind failed because the PCB is not in a valid state
418 tcp_bind(struct tcp_pcb *pcb, ip_addr_t *ipaddr, u16_t port)
421 int max_pcb_list = NUM_TCP_PCB_LISTS;
422 struct tcp_pcb *cpcb;
424 LWIP_ERROR("tcp_bind: can only bind in state CLOSED", pcb->state == CLOSED, return ERR_VAL);
427 /* Unless the REUSEADDR flag is set,
428 we have to check the pcbs in TIME-WAIT state, also.
429 We do not dump TIME_WAIT pcb's; they can still be matched by incoming
430 packets using both local and remote IP addresses and ports to distinguish.
432 if ((pcb->so_options & SOF_REUSEADDR) != 0) {
433 max_pcb_list = NUM_TCP_PCB_LISTS_NO_TIME_WAIT;
435 #endif /* SO_REUSE */
438 port = tcp_new_port();
444 /* Check if the address already is in use (on all lists) */
445 for (i = 0; i < max_pcb_list; i++) {
446 for(cpcb = *tcp_pcb_lists[i]; cpcb != NULL; cpcb = cpcb->next) {
447 if (cpcb->local_port == port) {
449 /* Omit checking for the same port if both pcbs have REUSEADDR set.
450 For SO_REUSEADDR, the duplicate-check for a 5-tuple is done in
452 if (((pcb->so_options & SOF_REUSEADDR) == 0) ||
453 ((cpcb->so_options & SOF_REUSEADDR) == 0))
454 #endif /* SO_REUSE */
456 /* @todo: check accept_any_ip_version */
457 if (IP_PCB_IPVER_EQ(pcb, cpcb) &&
458 (ipX_addr_isany(PCB_ISIPV6(pcb), &cpcb->local_ip) ||
459 ipX_addr_isany(PCB_ISIPV6(pcb), ip_2_ipX(ipaddr)) ||
460 ipX_addr_cmp(PCB_ISIPV6(pcb), &cpcb->local_ip, ip_2_ipX(ipaddr)))) {
468 if (!ipX_addr_isany(PCB_ISIPV6(pcb), ip_2_ipX(ipaddr))) {
469 ipX_addr_set(PCB_ISIPV6(pcb), &pcb->local_ip, ip_2_ipX(ipaddr));
471 pcb->local_port = port;
472 TCP_REG(&tcp_bound_pcbs, pcb);
473 LWIP_DEBUGF(TCP_DEBUG, ("tcp_bind: bind to port %"U16_F"\n", port));
476 #if LWIP_CALLBACK_API
478 * Default accept callback if no accept callback is specified by the user.
481 tcp_accept_null(void *arg, struct tcp_pcb *pcb, err_t err)
483 LWIP_UNUSED_ARG(arg);
484 LWIP_UNUSED_ARG(pcb);
485 LWIP_UNUSED_ARG(err);
489 #endif /* LWIP_CALLBACK_API */
492 * Set the state of the connection to be LISTEN, which means that it
493 * is able to accept incoming connections. The protocol control block
494 * is reallocated in order to consume less memory. Setting the
495 * connection to LISTEN is an irreversible process.
497 * @param pcb the original tcp_pcb
498 * @param backlog the incoming connections queue limit
499 * @return tcp_pcb used for listening, consumes less memory.
501 * @note The original tcp_pcb is freed. This function therefore has to be
503 * tpcb = tcp_listen(tpcb);
506 tcp_listen_with_backlog(struct tcp_pcb *pcb, u8_t backlog)
508 struct tcp_pcb_listen *lpcb;
510 LWIP_UNUSED_ARG(backlog);
511 LWIP_ERROR("tcp_listen: pcb already connected", pcb->state == CLOSED, return NULL);
513 /* already listening? */
514 if (pcb->state == LISTEN) {
518 if ((pcb->so_options & SOF_REUSEADDR) != 0) {
519 /* Since SOF_REUSEADDR allows reusing a local address before the pcb's usage
520 is declared (listen-/connection-pcb), we have to make sure now that
521 this port is only used once for every local IP. */
522 for(lpcb = tcp_listen_pcbs.listen_pcbs; lpcb != NULL; lpcb = lpcb->next) {
523 if ((lpcb->local_port == pcb->local_port) &&
524 IP_PCB_IPVER_EQ(pcb, lpcb)) {
525 if (ipX_addr_cmp(PCB_ISIPV6(pcb), &lpcb->local_ip, &pcb->local_ip)) {
526 /* this address/port is already used */
532 #endif /* SO_REUSE */
533 lpcb = (struct tcp_pcb_listen *)memp_malloc(MEMP_TCP_PCB_LISTEN);
537 lpcb->callback_arg = pcb->callback_arg;
538 lpcb->local_port = pcb->local_port;
539 lpcb->state = LISTEN;
540 lpcb->prio = pcb->prio;
541 lpcb->so_options = pcb->so_options;
542 lpcb->so_options |= SOF_ACCEPTCONN;
543 lpcb->ttl = pcb->ttl;
544 lpcb->tos = pcb->tos;
546 PCB_ISIPV6(lpcb) = PCB_ISIPV6(pcb);
547 lpcb->accept_any_ip_version = 0;
548 #endif /* LWIP_IPV6 */
549 ipX_addr_copy(PCB_ISIPV6(pcb), lpcb->local_ip, pcb->local_ip);
550 if (pcb->local_port != 0) {
551 TCP_RMV(&tcp_bound_pcbs, pcb);
553 memp_free(MEMP_TCP_PCB, pcb);
554 #if LWIP_CALLBACK_API
555 lpcb->accept = tcp_accept_null;
556 #endif /* LWIP_CALLBACK_API */
557 #if TCP_LISTEN_BACKLOG
558 lpcb->accepts_pending = 0;
559 lpcb->backlog = (backlog ? backlog : 1);
560 #endif /* TCP_LISTEN_BACKLOG */
561 TCP_REG(&tcp_listen_pcbs.pcbs, (struct tcp_pcb *)lpcb);
562 return (struct tcp_pcb *)lpcb;
567 * Same as tcp_listen_with_backlog, but allows to accept IPv4 and IPv6
568 * connections, if the pcb's local address is set to ANY.
571 tcp_listen_dual_with_backlog(struct tcp_pcb *pcb, u8_t backlog)
573 struct tcp_pcb *lpcb;
575 if (!ipX_addr_isany(PCB_ISIPV6(pcb), &pcb->local_ip)) {
578 lpcb = tcp_listen_with_backlog(pcb, backlog);
580 ((struct tcp_pcb_listen*)lpcb)->accept_any_ip_version = 1;
584 #endif /* LWIP_IPV6 */
587 * Update the state that tracks the available window space to advertise.
589 * Returns how much extra window would be advertised if we sent an
592 u32_t tcp_update_rcv_ann_wnd(struct tcp_pcb *pcb)
594 u32_t new_right_edge = pcb->rcv_nxt + pcb->rcv_wnd;
596 if (TCP_SEQ_GEQ(new_right_edge, pcb->rcv_ann_right_edge + LWIP_MIN((TCP_WND / 2), pcb->mss))) {
597 /* we can advertise more window */
598 pcb->rcv_ann_wnd = pcb->rcv_wnd;
599 return new_right_edge - pcb->rcv_ann_right_edge;
601 if (TCP_SEQ_GT(pcb->rcv_nxt, pcb->rcv_ann_right_edge)) {
602 /* Can happen due to other end sending out of advertised window,
603 * but within actual available (but not yet advertised) window */
604 pcb->rcv_ann_wnd = 0;
606 /* keep the right edge of window constant */
607 u32_t new_rcv_ann_wnd = pcb->rcv_ann_right_edge - pcb->rcv_nxt;
608 LWIP_ASSERT("new_rcv_ann_wnd <= 0xffff", new_rcv_ann_wnd <= 0xffff);
609 pcb->rcv_ann_wnd = (u16_t)new_rcv_ann_wnd;
616 * This function should be called by the application when it has
617 * processed the data. The purpose is to advertise a larger window
618 * when the data has been processed.
620 * @param pcb the tcp_pcb for which data is read
621 * @param len the amount of bytes that have been read by the application
624 tcp_recved(struct tcp_pcb *pcb, u16_t len)
628 /* pcb->state LISTEN not allowed here */
629 LWIP_ASSERT("don't call tcp_recved for listen-pcbs",
630 pcb->state != LISTEN);
631 LWIP_ASSERT("tcp_recved: len would wrap rcv_wnd\n",
632 len <= 0xffff - pcb->rcv_wnd );
635 if (pcb->rcv_wnd > TCP_WND) {
636 pcb->rcv_wnd = TCP_WND;
639 wnd_inflation = tcp_update_rcv_ann_wnd(pcb);
641 /* If the change in the right edge of window is significant (default
642 * watermark is TCP_WND/4), then send an explicit update now.
643 * Otherwise wait for a packet to be sent in the normal course of
644 * events (or more window to be available later) */
645 if (wnd_inflation >= TCP_WND_UPDATE_THRESHOLD) {
650 LWIP_DEBUGF(TCP_DEBUG, ("tcp_recved: recveived %"U16_F" bytes, wnd %"U16_F" (%"U16_F").\n",
651 len, pcb->rcv_wnd, TCP_WND - pcb->rcv_wnd));
655 * Allocate a new local TCP port.
657 * @return a new (free) local TCP port number
667 if (tcp_port++ == TCP_LOCAL_PORT_RANGE_END) {
668 tcp_port = TCP_LOCAL_PORT_RANGE_START;
670 /* Check all PCB lists. */
671 for (i = 0; i < NUM_TCP_PCB_LISTS; i++) {
672 for(pcb = *tcp_pcb_lists[i]; pcb != NULL; pcb = pcb->next) {
673 if (pcb->local_port == tcp_port) {
674 if (++n > (TCP_LOCAL_PORT_RANGE_END - TCP_LOCAL_PORT_RANGE_START)) {
685 * Connects to another host. The function given as the "connected"
686 * argument will be called when the connection has been established.
688 * @param pcb the tcp_pcb used to establish the connection
689 * @param ipaddr the remote ip address to connect to
690 * @param port the remote tcp port to connect to
691 * @param connected callback function to call when connected (or on error)
692 * @return ERR_VAL if invalid arguments are given
693 * ERR_OK if connect request has been sent
694 * other err_t values if connect request couldn't be sent
697 tcp_connect(struct tcp_pcb *pcb, ip_addr_t *ipaddr, u16_t port,
698 tcp_connected_fn connected)
702 u16_t old_local_port;
704 LWIP_ERROR("tcp_connect: can only connect from state CLOSED", pcb->state == CLOSED, return ERR_ISCONN);
706 LWIP_DEBUGF(TCP_DEBUG, ("tcp_connect to port %"U16_F"\n", port));
707 if (ipaddr != NULL) {
708 ipX_addr_set(PCB_ISIPV6(pcb), &pcb->remote_ip, ip_2_ipX(ipaddr));
712 pcb->remote_port = port;
714 /* check if we have a route to the remote host */
715 if (ipX_addr_isany(PCB_ISIPV6(pcb), &pcb->local_ip)) {
716 /* no local IP address set, yet. */
718 ipX_addr_t *local_ip;
719 ipX_route_get_local_ipX(PCB_ISIPV6(pcb), &pcb->local_ip, &pcb->remote_ip, netif, local_ip);
720 if ((netif == NULL) || (local_ip == NULL)) {
721 /* Don't even try to send a SYN packet if we have no route
722 since that will fail. */
725 /* Use the address as local address of the pcb. */
726 ipX_addr_copy(PCB_ISIPV6(pcb), pcb->local_ip, *local_ip);
729 old_local_port = pcb->local_port;
730 if (pcb->local_port == 0) {
731 pcb->local_port = tcp_new_port();
732 if (pcb->local_port == 0) {
737 if ((pcb->so_options & SOF_REUSEADDR) != 0) {
738 /* Since SOF_REUSEADDR allows reusing a local address, we have to make sure
739 now that the 5-tuple is unique. */
740 struct tcp_pcb *cpcb;
742 /* Don't check listen- and bound-PCBs, check active- and TIME-WAIT PCBs. */
743 for (i = 2; i < NUM_TCP_PCB_LISTS; i++) {
744 for(cpcb = *tcp_pcb_lists[i]; cpcb != NULL; cpcb = cpcb->next) {
745 if ((cpcb->local_port == pcb->local_port) &&
746 (cpcb->remote_port == port) &&
747 IP_PCB_IPVER_EQ(cpcb, pcb) &&
748 ipX_addr_cmp(PCB_ISIPV6(pcb), &cpcb->local_ip, &pcb->local_ip) &&
749 ipX_addr_cmp(PCB_ISIPV6(pcb), &cpcb->remote_ip, ip_2_ipX(ipaddr))) {
750 /* linux returns EISCONN here, but ERR_USE should be OK for us */
756 #endif /* SO_REUSE */
757 iss = tcp_next_iss();
760 pcb->lastack = iss - 1;
761 pcb->snd_lbb = iss - 1;
762 pcb->rcv_wnd = TCP_WND;
763 pcb->rcv_ann_wnd = TCP_WND;
764 pcb->rcv_ann_right_edge = pcb->rcv_nxt;
765 pcb->snd_wnd = TCP_WND;
766 /* As initial send MSS, we use TCP_MSS but limit it to 536.
767 The send MSS is updated when an MSS option is received. */
768 pcb->mss = (TCP_MSS > 536) ? 536 : TCP_MSS;
769 #if TCP_CALCULATE_EFF_SEND_MSS
770 pcb->mss = tcp_eff_send_mss(pcb->mss, &pcb->local_ip, &pcb->remote_ip, PCB_ISIPV6(pcb));
771 #endif /* TCP_CALCULATE_EFF_SEND_MSS */
773 pcb->ssthresh = pcb->mss * 10;
774 #if LWIP_CALLBACK_API
775 pcb->connected = connected;
776 #else /* LWIP_CALLBACK_API */
777 LWIP_UNUSED_ARG(connected);
778 #endif /* LWIP_CALLBACK_API */
780 /* Send a SYN together with the MSS option. */
781 ret = tcp_enqueue_flags(pcb, TCP_SYN);
783 /* SYN segment was enqueued, changed the pcbs state now */
784 pcb->state = SYN_SENT;
785 if (old_local_port != 0) {
786 TCP_RMV(&tcp_bound_pcbs, pcb);
788 TCP_REG(&tcp_active_pcbs, pcb);
789 snmp_inc_tcpactiveopens();
797 * Called every 500 ms and implements the retransmission timer and the timer that
798 * removes PCBs that have been in TIME-WAIT for enough time. It also increments
799 * various timers such as the inactivity timer in each PCB.
801 * Automatically called from tcp_tmr().
806 struct tcp_pcb *pcb, *prev;
808 u8_t pcb_remove; /* flag if a PCB should be removed */
809 u8_t pcb_reset; /* flag if a RST should be sent when removing */
816 /* Steps through all of the active PCBs. */
818 pcb = tcp_active_pcbs;
820 LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: no active pcbs\n"));
822 while (pcb != NULL) {
823 LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: processing active pcb\n"));
824 LWIP_ASSERT("tcp_slowtmr: active pcb->state != CLOSED\n", pcb->state != CLOSED);
825 LWIP_ASSERT("tcp_slowtmr: active pcb->state != LISTEN\n", pcb->state != LISTEN);
826 LWIP_ASSERT("tcp_slowtmr: active pcb->state != TIME-WAIT\n", pcb->state != TIME_WAIT);
831 if (pcb->state == SYN_SENT && pcb->nrtx == TCP_SYNMAXRTX) {
833 LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: max SYN retries reached\n"));
835 else if (pcb->nrtx == TCP_MAXRTX) {
837 LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: max DATA retries reached\n"));
839 if (pcb->persist_backoff > 0) {
840 /* If snd_wnd is zero, use persist timer to send 1 byte probes
841 * instead of using the standard retransmission mechanism. */
843 if (pcb->persist_cnt >= tcp_persist_backoff[pcb->persist_backoff-1]) {
844 pcb->persist_cnt = 0;
845 if (pcb->persist_backoff < sizeof(tcp_persist_backoff)) {
846 pcb->persist_backoff++;
848 tcp_zero_window_probe(pcb);
851 /* Increase the retransmission timer if it is running */
855 if (pcb->unacked != NULL && pcb->rtime >= pcb->rto) {
856 /* Time for a retransmission. */
857 LWIP_DEBUGF(TCP_RTO_DEBUG, ("tcp_slowtmr: rtime %"S16_F
858 " pcb->rto %"S16_F"\n",
859 pcb->rtime, pcb->rto));
861 /* Double retransmission time-out unless we are trying to
862 * connect to somebody (i.e., we are in SYN_SENT). */
863 if (pcb->state != SYN_SENT) {
864 pcb->rto = ((pcb->sa >> 3) + pcb->sv) << tcp_backoff[pcb->nrtx];
867 /* Reset the retransmission timer. */
870 /* Reduce congestion window and ssthresh. */
871 eff_wnd = LWIP_MIN(pcb->cwnd, pcb->snd_wnd);
872 pcb->ssthresh = eff_wnd >> 1;
873 if (pcb->ssthresh < (pcb->mss << 1)) {
874 pcb->ssthresh = (pcb->mss << 1);
876 pcb->cwnd = pcb->mss;
877 LWIP_DEBUGF(TCP_CWND_DEBUG, ("tcp_slowtmr: cwnd %"U16_F
878 " ssthresh %"U16_F"\n",
879 pcb->cwnd, pcb->ssthresh));
881 /* The following needs to be called AFTER cwnd is set to one
887 /* Check if this PCB has stayed too long in FIN-WAIT-2 */
888 if (pcb->state == FIN_WAIT_2) {
889 if ((u32_t)(tcp_ticks - pcb->tmr) >
890 TCP_FIN_WAIT_TIMEOUT / TCP_SLOW_INTERVAL) {
892 LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: removing pcb stuck in FIN-WAIT-2\n"));
896 /* Check if KEEPALIVE should be sent */
897 if((pcb->so_options & SOF_KEEPALIVE) &&
898 ((pcb->state == ESTABLISHED) ||
899 (pcb->state == CLOSE_WAIT))) {
900 #if LWIP_TCP_KEEPALIVE
901 if((u32_t)(tcp_ticks - pcb->tmr) >
902 (pcb->keep_idle + (pcb->keep_cnt*pcb->keep_intvl))
905 if((u32_t)(tcp_ticks - pcb->tmr) >
906 (pcb->keep_idle + TCP_MAXIDLE) / TCP_SLOW_INTERVAL)
907 #endif /* LWIP_TCP_KEEPALIVE */
909 LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: KEEPALIVE timeout. Aborting connection to "));
910 ipX_addr_debug_print(PCB_ISIPV6(pcb), TCP_DEBUG, &pcb->remote_ip);
911 LWIP_DEBUGF(TCP_DEBUG, ("\n"));
916 #if LWIP_TCP_KEEPALIVE
917 else if((u32_t)(tcp_ticks - pcb->tmr) >
918 (pcb->keep_idle + pcb->keep_cnt_sent * pcb->keep_intvl)
921 else if((u32_t)(tcp_ticks - pcb->tmr) >
922 (pcb->keep_idle + pcb->keep_cnt_sent * TCP_KEEPINTVL_DEFAULT)
924 #endif /* LWIP_TCP_KEEPALIVE */
927 pcb->keep_cnt_sent++;
931 /* If this PCB has queued out of sequence data, but has been
932 inactive for too long, will drop the data (it will eventually
933 be retransmitted). */
935 if (pcb->ooseq != NULL &&
936 (u32_t)tcp_ticks - pcb->tmr >= pcb->rto * TCP_OOSEQ_TIMEOUT) {
937 tcp_segs_free(pcb->ooseq);
939 LWIP_DEBUGF(TCP_CWND_DEBUG, ("tcp_slowtmr: dropping OOSEQ queued data\n"));
941 #endif /* TCP_QUEUE_OOSEQ */
943 /* Check if this PCB has stayed too long in SYN-RCVD */
944 if (pcb->state == SYN_RCVD) {
945 if ((u32_t)(tcp_ticks - pcb->tmr) >
946 TCP_SYN_RCVD_TIMEOUT / TCP_SLOW_INTERVAL) {
948 LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: removing pcb stuck in SYN-RCVD\n"));
952 /* Check if this PCB has stayed too long in LAST-ACK */
953 if (pcb->state == LAST_ACK) {
954 if ((u32_t)(tcp_ticks - pcb->tmr) > 2 * TCP_MSL / TCP_SLOW_INTERVAL) {
956 LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: removing pcb stuck in LAST-ACK\n"));
960 /* If the PCB should be removed, do it. */
962 struct tcp_pcb *pcb2;
964 /* Remove PCB from tcp_active_pcbs list. */
966 LWIP_ASSERT("tcp_slowtmr: middle tcp != tcp_active_pcbs", pcb != tcp_active_pcbs);
967 prev->next = pcb->next;
969 /* This PCB was the first. */
970 LWIP_ASSERT("tcp_slowtmr: first pcb == tcp_active_pcbs", tcp_active_pcbs == pcb);
971 tcp_active_pcbs = pcb->next;
974 TCP_EVENT_ERR(pcb->errf, pcb->callback_arg, ERR_ABRT);
976 tcp_rst(pcb->snd_nxt, pcb->rcv_nxt, &pcb->local_ip, &pcb->remote_ip,
977 pcb->local_port, pcb->remote_port, PCB_ISIPV6(pcb));
982 memp_free(MEMP_TCP_PCB, pcb2);
984 /* get the 'next' element now and work with 'prev' below (in case of abort) */
988 /* We check if we should poll the connection. */
990 if (prev->polltmr >= prev->pollinterval) {
992 LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: polling application\n"));
993 TCP_EVENT_POLL(prev, err);
994 /* if err == ERR_ABRT, 'prev' is already deallocated */
1003 /* Steps through all of the TIME-WAIT PCBs. */
1006 while (pcb != NULL) {
1007 LWIP_ASSERT("tcp_slowtmr: TIME-WAIT pcb->state == TIME-WAIT", pcb->state == TIME_WAIT);
1010 /* Check if this PCB has stayed long enough in TIME-WAIT */
1011 if ((u32_t)(tcp_ticks - pcb->tmr) > 2 * TCP_MSL / TCP_SLOW_INTERVAL) {
1017 /* If the PCB should be removed, do it. */
1019 struct tcp_pcb *pcb2;
1021 /* Remove PCB from tcp_tw_pcbs list. */
1023 LWIP_ASSERT("tcp_slowtmr: middle tcp != tcp_tw_pcbs", pcb != tcp_tw_pcbs);
1024 prev->next = pcb->next;
1026 /* This PCB was the first. */
1027 LWIP_ASSERT("tcp_slowtmr: first pcb == tcp_tw_pcbs", tcp_tw_pcbs == pcb);
1028 tcp_tw_pcbs = pcb->next;
1032 memp_free(MEMP_TCP_PCB, pcb2);
1041 * Is called every TCP_FAST_INTERVAL (250 ms) and process data previously
1042 * "refused" by upper layer (application) and sends delayed ACKs.
1044 * Automatically called from tcp_tmr().
1049 struct tcp_pcb *pcb = tcp_active_pcbs;
1051 while(pcb != NULL) {
1052 struct tcp_pcb *next = pcb->next;
1053 /* If there is data which was previously "refused" by upper layer */
1054 if (pcb->refused_data != NULL) {
1055 /* Notify again application with data previously received. */
1057 u8_t refused_flags = pcb->refused_data->flags;
1058 /* set pcb->refused_data to NULL in case the callback frees it and then
1060 struct pbuf *refused_data = pcb->refused_data;
1061 pcb->refused_data = NULL;
1062 LWIP_DEBUGF(TCP_INPUT_DEBUG, ("tcp_fasttmr: notify kept packet\n"));
1063 TCP_EVENT_RECV(pcb, refused_data, ERR_OK, err);
1064 if (err == ERR_OK) {
1065 /* did refused_data include a FIN? If so, handle it now. */
1066 if (refused_flags & PBUF_FLAG_TCP_FIN) {
1067 /* correct rcv_wnd as the application won't call tcp_recved()
1068 for the FIN's seqno */
1069 if (pcb->rcv_wnd != TCP_WND) {
1072 TCP_EVENT_CLOSED(pcb, err);
1073 if (err == ERR_ABRT) {
1077 } else if (err == ERR_ABRT) {
1078 /* if err == ERR_ABRT, 'pcb' is already deallocated */
1081 /* data is still refused */
1082 pcb->refused_data = refused_data;
1086 /* send delayed ACKs */
1087 if (pcb && (pcb->flags & TF_ACK_DELAY)) {
1088 LWIP_DEBUGF(TCP_DEBUG, ("tcp_fasttmr: delayed ACK\n"));
1091 pcb->flags &= ~(TF_ACK_DELAY | TF_ACK_NOW);
1099 * Deallocates a list of TCP segments (tcp_seg structures).
1101 * @param seg tcp_seg list of TCP segments to free
1104 tcp_segs_free(struct tcp_seg *seg)
1106 while (seg != NULL) {
1107 struct tcp_seg *next = seg->next;
1114 * Frees a TCP segment (tcp_seg structure).
1116 * @param seg single tcp_seg to free
1119 tcp_seg_free(struct tcp_seg *seg)
1122 if (seg->p != NULL) {
1126 #endif /* TCP_DEBUG */
1128 memp_free(MEMP_TCP_SEG, seg);
1133 * Sets the priority of a connection.
1135 * @param pcb the tcp_pcb to manipulate
1136 * @param prio new priority
1139 tcp_setprio(struct tcp_pcb *pcb, u8_t prio)
1146 * Returns a copy of the given TCP segment.
1147 * The pbuf and data are not copied, only the pointers
1149 * @param seg the old tcp_seg
1150 * @return a copy of seg
1153 tcp_seg_copy(struct tcp_seg *seg)
1155 struct tcp_seg *cseg;
1157 cseg = (struct tcp_seg *)memp_malloc(MEMP_TCP_SEG);
1161 SMEMCPY((u8_t *)cseg, (const u8_t *)seg, sizeof(struct tcp_seg));
1165 #endif /* TCP_QUEUE_OOSEQ */
1167 #if LWIP_CALLBACK_API
1169 * Default receive callback that is called if the user didn't register
1170 * a recv callback for the pcb.
1173 tcp_recv_null(void *arg, struct tcp_pcb *pcb, struct pbuf *p, err_t err)
1175 LWIP_UNUSED_ARG(arg);
1177 tcp_recved(pcb, p->tot_len);
1179 } else if (err == ERR_OK) {
1180 return tcp_close(pcb);
1184 #endif /* LWIP_CALLBACK_API */
1187 * Kills the oldest active connection that has the same or lower priority than
1190 * @param prio minimum priority
1193 tcp_kill_prio(u8_t prio)
1195 struct tcp_pcb *pcb, *inactive;
1200 mprio = TCP_PRIO_MAX;
1202 /* We kill the oldest active connection that has lower priority than prio. */
1205 for(pcb = tcp_active_pcbs; pcb != NULL; pcb = pcb->next) {
1206 if (pcb->prio <= prio &&
1207 pcb->prio <= mprio &&
1208 (u32_t)(tcp_ticks - pcb->tmr) >= inactivity) {
1209 inactivity = tcp_ticks - pcb->tmr;
1214 if (inactive != NULL) {
1215 LWIP_DEBUGF(TCP_DEBUG, ("tcp_kill_prio: killing oldest PCB %p (%"S32_F")\n",
1216 (void *)inactive, inactivity));
1217 tcp_abort(inactive);
1222 * Kills the oldest connection that is in TIME_WAIT state.
1223 * Called from tcp_alloc() if no more connections are available.
1226 tcp_kill_timewait(void)
1228 struct tcp_pcb *pcb, *inactive;
1233 /* Go through the list of TIME_WAIT pcbs and get the oldest pcb. */
1234 for(pcb = tcp_tw_pcbs; pcb != NULL; pcb = pcb->next) {
1235 if ((u32_t)(tcp_ticks - pcb->tmr) >= inactivity) {
1236 inactivity = tcp_ticks - pcb->tmr;
1240 if (inactive != NULL) {
1241 LWIP_DEBUGF(TCP_DEBUG, ("tcp_kill_timewait: killing oldest TIME-WAIT PCB %p (%"S32_F")\n",
1242 (void *)inactive, inactivity));
1243 tcp_abort(inactive);
1248 * Allocate a new tcp_pcb structure.
1250 * @param prio priority for the new pcb
1251 * @return a new tcp_pcb that initially is in state CLOSED
1254 tcp_alloc(u8_t prio)
1256 struct tcp_pcb *pcb;
1259 pcb = (struct tcp_pcb *)memp_malloc(MEMP_TCP_PCB);
1261 /* Try killing oldest connection in TIME-WAIT. */
1262 LWIP_DEBUGF(TCP_DEBUG, ("tcp_alloc: killing off oldest TIME-WAIT connection\n"));
1263 tcp_kill_timewait();
1264 /* Try to allocate a tcp_pcb again. */
1265 pcb = (struct tcp_pcb *)memp_malloc(MEMP_TCP_PCB);
1267 /* Try killing active connections with lower priority than the new one. */
1268 LWIP_DEBUGF(TCP_DEBUG, ("tcp_alloc: killing connection with prio lower than %d\n", prio));
1269 tcp_kill_prio(prio);
1270 /* Try to allocate a tcp_pcb again. */
1271 pcb = (struct tcp_pcb *)memp_malloc(MEMP_TCP_PCB);
1273 /* adjust err stats: memp_malloc failed twice before */
1274 MEMP_STATS_DEC(err, MEMP_TCP_PCB);
1278 /* adjust err stats: timewait PCB was freed above */
1279 MEMP_STATS_DEC(err, MEMP_TCP_PCB);
1283 memset(pcb, 0, sizeof(struct tcp_pcb));
1285 pcb->snd_buf = TCP_SND_BUF;
1286 pcb->snd_queuelen = 0;
1287 pcb->rcv_wnd = TCP_WND;
1288 pcb->rcv_ann_wnd = TCP_WND;
1291 /* As initial send MSS, we use TCP_MSS but limit it to 536.
1292 The send MSS is updated when an MSS option is received. */
1293 pcb->mss = (TCP_MSS > 536) ? 536 : TCP_MSS;
1294 pcb->rto = 3000 / TCP_SLOW_INTERVAL;
1296 pcb->sv = 3000 / TCP_SLOW_INTERVAL;
1299 iss = tcp_next_iss();
1304 pcb->tmr = tcp_ticks;
1308 #if LWIP_CALLBACK_API
1309 pcb->recv = tcp_recv_null;
1310 #endif /* LWIP_CALLBACK_API */
1312 /* Init KEEPALIVE timer */
1313 pcb->keep_idle = TCP_KEEPIDLE_DEFAULT;
1315 #if LWIP_TCP_KEEPALIVE
1316 pcb->keep_intvl = TCP_KEEPINTVL_DEFAULT;
1317 pcb->keep_cnt = TCP_KEEPCNT_DEFAULT;
1318 #endif /* LWIP_TCP_KEEPALIVE */
1320 pcb->keep_cnt_sent = 0;
1326 * Creates a new TCP protocol control block but doesn't place it on
1327 * any of the TCP PCB lists.
1328 * The pcb is not put on any list until binding using tcp_bind().
1330 * @internal: Maybe there should be a idle TCP PCB list where these
1331 * PCBs are put on. Port reservation using tcp_bind() is implemented but
1332 * allocated pcbs that are not bound can't be killed automatically if wanting
1333 * to allocate a pcb with higher prio (@see tcp_kill_prio())
1335 * @return a new tcp_pcb that initially is in state CLOSED
1340 return tcp_alloc(TCP_PRIO_NORMAL);
1345 * Creates a new TCP-over-IPv6 protocol control block but doesn't
1346 * place it on any of the TCP PCB lists.
1347 * The pcb is not put on any list until binding using tcp_bind().
1349 * @return a new tcp_pcb that initially is in state CLOSED
1354 struct tcp_pcb * pcb;
1355 pcb = tcp_alloc(TCP_PRIO_NORMAL);
1359 #endif /* LWIP_IPV6 */
1362 * Used to specify the argument that should be passed callback
1365 * @param pcb tcp_pcb to set the callback argument
1366 * @param arg void pointer argument to pass to callback functions
1369 tcp_arg(struct tcp_pcb *pcb, void *arg)
1371 /* This function is allowed to be called for both listen pcbs and
1373 pcb->callback_arg = arg;
1375 #if LWIP_CALLBACK_API
1378 * Used to specify the function that should be called when a TCP
1379 * connection receives data.
1381 * @param pcb tcp_pcb to set the recv callback
1382 * @param recv callback function to call for this pcb when data is received
1385 tcp_recv(struct tcp_pcb *pcb, tcp_recv_fn recv)
1387 LWIP_ASSERT("invalid socket state for recv callback", pcb->state != LISTEN);
1392 * Used to specify the function that should be called when TCP data
1393 * has been successfully delivered to the remote host.
1395 * @param pcb tcp_pcb to set the sent callback
1396 * @param sent callback function to call for this pcb when data is successfully sent
1399 tcp_sent(struct tcp_pcb *pcb, tcp_sent_fn sent)
1401 LWIP_ASSERT("invalid socket state for sent callback", pcb->state != LISTEN);
1406 * Used to specify the function that should be called when a fatal error
1407 * has occured on the connection.
1409 * @param pcb tcp_pcb to set the err callback
1410 * @param err callback function to call for this pcb when a fatal error
1411 * has occured on the connection
1414 tcp_err(struct tcp_pcb *pcb, tcp_err_fn err)
1416 LWIP_ASSERT("invalid socket state for err callback", pcb->state != LISTEN);
1421 * Used for specifying the function that should be called when a
1422 * LISTENing connection has been connected to another host.
1424 * @param pcb tcp_pcb to set the accept callback
1425 * @param accept callback function to call for this pcb when LISTENing
1426 * connection has been connected to another host
1429 tcp_accept(struct tcp_pcb *pcb, tcp_accept_fn accept)
1431 /* This function is allowed to be called for both listen pcbs and
1433 pcb->accept = accept;
1435 #endif /* LWIP_CALLBACK_API */
1439 * Used to specify the function that should be called periodically
1440 * from TCP. The interval is specified in terms of the TCP coarse
1441 * timer interval, which is called twice a second.
1445 tcp_poll(struct tcp_pcb *pcb, tcp_poll_fn poll, u8_t interval)
1447 LWIP_ASSERT("invalid socket state for poll", pcb->state != LISTEN);
1448 #if LWIP_CALLBACK_API
1450 #else /* LWIP_CALLBACK_API */
1451 LWIP_UNUSED_ARG(poll);
1452 #endif /* LWIP_CALLBACK_API */
1453 pcb->pollinterval = interval;
1457 * Purges a TCP PCB. Removes any buffered data and frees the buffer memory
1458 * (pcb->ooseq, pcb->unsent and pcb->unacked are freed).
1460 * @param pcb tcp_pcb to purge. The pcb itself is not deallocated!
1463 tcp_pcb_purge(struct tcp_pcb *pcb)
1465 if (pcb->state != CLOSED &&
1466 pcb->state != TIME_WAIT &&
1467 pcb->state != LISTEN) {
1469 LWIP_DEBUGF(TCP_DEBUG, ("tcp_pcb_purge\n"));
1471 #if TCP_LISTEN_BACKLOG
1472 if (pcb->state == SYN_RCVD) {
1473 /* Need to find the corresponding listen_pcb and decrease its accepts_pending */
1474 struct tcp_pcb_listen *lpcb;
1475 LWIP_ASSERT("tcp_pcb_purge: pcb->state == SYN_RCVD but tcp_listen_pcbs is NULL",
1476 tcp_listen_pcbs.listen_pcbs != NULL);
1477 for (lpcb = tcp_listen_pcbs.listen_pcbs; lpcb != NULL; lpcb = lpcb->next) {
1478 if ((lpcb->local_port == pcb->local_port) &&
1479 IP_PCB_IPVER_EQ(pcb, lpcb) &&
1480 (ipX_addr_isany(PCB_ISIPV6(lpcb), &lpcb->local_ip) ||
1481 ipX_addr_cmp(PCB_ISIPV6(lpcb), &pcb->local_ip, &lpcb->local_ip))) {
1482 /* port and address of the listen pcb match the timed-out pcb */
1483 LWIP_ASSERT("tcp_pcb_purge: listen pcb does not have accepts pending",
1484 lpcb->accepts_pending > 0);
1485 lpcb->accepts_pending--;
1490 #endif /* TCP_LISTEN_BACKLOG */
1493 if (pcb->refused_data != NULL) {
1494 LWIP_DEBUGF(TCP_DEBUG, ("tcp_pcb_purge: data left on ->refused_data\n"));
1495 pbuf_free(pcb->refused_data);
1496 pcb->refused_data = NULL;
1498 if (pcb->unsent != NULL) {
1499 LWIP_DEBUGF(TCP_DEBUG, ("tcp_pcb_purge: not all data sent\n"));
1501 if (pcb->unacked != NULL) {
1502 LWIP_DEBUGF(TCP_DEBUG, ("tcp_pcb_purge: data left on ->unacked\n"));
1505 if (pcb->ooseq != NULL) {
1506 LWIP_DEBUGF(TCP_DEBUG, ("tcp_pcb_purge: data left on ->ooseq\n"));
1508 tcp_segs_free(pcb->ooseq);
1510 #endif /* TCP_QUEUE_OOSEQ */
1512 /* Stop the retransmission timer as it will expect data on unacked
1513 queue if it fires */
1516 tcp_segs_free(pcb->unsent);
1517 tcp_segs_free(pcb->unacked);
1518 pcb->unacked = pcb->unsent = NULL;
1520 pcb->unsent_oversize = 0;
1521 #endif /* TCP_OVERSIZE */
1526 * Purges the PCB and removes it from a PCB list. Any delayed ACKs are sent first.
1528 * @param pcblist PCB list to purge.
1529 * @param pcb tcp_pcb to purge. The pcb itself is NOT deallocated!
1532 tcp_pcb_remove(struct tcp_pcb **pcblist, struct tcp_pcb *pcb)
1534 TCP_RMV(pcblist, pcb);
1538 /* if there is an outstanding delayed ACKs, send it */
1539 if (pcb->state != TIME_WAIT &&
1540 pcb->state != LISTEN &&
1541 pcb->flags & TF_ACK_DELAY) {
1542 pcb->flags |= TF_ACK_NOW;
1546 if (pcb->state != LISTEN) {
1547 LWIP_ASSERT("unsent segments leaking", pcb->unsent == NULL);
1548 LWIP_ASSERT("unacked segments leaking", pcb->unacked == NULL);
1550 LWIP_ASSERT("ooseq segments leaking", pcb->ooseq == NULL);
1551 #endif /* TCP_QUEUE_OOSEQ */
1554 pcb->state = CLOSED;
1556 LWIP_ASSERT("tcp_pcb_remove: tcp_pcbs_sane()", tcp_pcbs_sane());
1560 * Calculates a new initial sequence number for new connections.
1562 * @return u32_t pseudo random sequence number
1567 static u32_t iss = 6510;
1569 iss += tcp_ticks; /* XXX */
1573 #if TCP_CALCULATE_EFF_SEND_MSS
1575 * Calcluates the effective send mss that can be used for a specific IP address
1576 * by using ip_route to determin the netif used to send to the address and
1577 * calculating the minimum of TCP_MSS and that netif's mtu (if set).
1580 tcp_eff_send_mss_impl(u16_t sendmss, ipX_addr_t *dest
1582 , ipX_addr_t *src, u8_t isipv6
1583 #endif /* LWIP_IPV6 */
1587 struct netif *outif;
1590 outif = ipX_route(isipv6, src, dest);
1593 /* First look in destination cache, to see if there is a Path MTU. */
1594 mtu = nd6_get_destination_mtu(ipX_2_ip6(dest), outif);
1596 #endif /* LWIP_IPV6 */
1598 if (outif == NULL) {
1605 mss_s = mtu - IP_HLEN - TCP_HLEN;
1607 /* for IPv6, substract the difference in header size */
1608 mss_s -= (IP6_HLEN - IP_HLEN);
1609 #endif /* LWIP_IPV6 */
1610 /* RFC 1122, chap 4.2.2.6:
1611 * Eff.snd.MSS = min(SendMSS+20, MMS_S) - TCPhdrsize - IPoptionsize
1612 * We correct for TCP options in tcp_write(), and don't support IP options.
1614 sendmss = LWIP_MIN(sendmss, mss_s);
1618 #endif /* TCP_CALCULATE_EFF_SEND_MSS */
1621 tcp_debug_state_str(enum tcp_state s)
1623 return tcp_state_str[s];
1626 #if TCP_DEBUG || TCP_INPUT_DEBUG || TCP_OUTPUT_DEBUG
1628 * Print a tcp header for debugging purposes.
1630 * @param tcphdr pointer to a struct tcp_hdr
1633 tcp_debug_print(struct tcp_hdr *tcphdr)
1635 LWIP_DEBUGF(TCP_DEBUG, ("TCP header:\n"));
1636 LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
1637 LWIP_DEBUGF(TCP_DEBUG, ("| %5"U16_F" | %5"U16_F" | (src port, dest port)\n",
1638 ntohs(tcphdr->src), ntohs(tcphdr->dest)));
1639 LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
1640 LWIP_DEBUGF(TCP_DEBUG, ("| %010"U32_F" | (seq no)\n",
1641 ntohl(tcphdr->seqno)));
1642 LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
1643 LWIP_DEBUGF(TCP_DEBUG, ("| %010"U32_F" | (ack no)\n",
1644 ntohl(tcphdr->ackno)));
1645 LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
1646 LWIP_DEBUGF(TCP_DEBUG, ("| %2"U16_F" | |%"U16_F"%"U16_F"%"U16_F"%"U16_F"%"U16_F"%"U16_F"| %5"U16_F" | (hdrlen, flags (",
1647 TCPH_HDRLEN(tcphdr),
1648 TCPH_FLAGS(tcphdr) >> 5 & 1,
1649 TCPH_FLAGS(tcphdr) >> 4 & 1,
1650 TCPH_FLAGS(tcphdr) >> 3 & 1,
1651 TCPH_FLAGS(tcphdr) >> 2 & 1,
1652 TCPH_FLAGS(tcphdr) >> 1 & 1,
1653 TCPH_FLAGS(tcphdr) & 1,
1654 ntohs(tcphdr->wnd)));
1655 tcp_debug_print_flags(TCPH_FLAGS(tcphdr));
1656 LWIP_DEBUGF(TCP_DEBUG, ("), win)\n"));
1657 LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
1658 LWIP_DEBUGF(TCP_DEBUG, ("| 0x%04"X16_F" | %5"U16_F" | (chksum, urgp)\n",
1659 ntohs(tcphdr->chksum), ntohs(tcphdr->urgp)));
1660 LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
1664 * Print a tcp state for debugging purposes.
1666 * @param s enum tcp_state to print
1669 tcp_debug_print_state(enum tcp_state s)
1671 LWIP_DEBUGF(TCP_DEBUG, ("State: %s\n", tcp_state_str[s]));
1675 * Print tcp flags for debugging purposes.
1677 * @param flags tcp flags, all active flags are printed
1680 tcp_debug_print_flags(u8_t flags)
1682 if (flags & TCP_FIN) {
1683 LWIP_DEBUGF(TCP_DEBUG, ("FIN "));
1685 if (flags & TCP_SYN) {
1686 LWIP_DEBUGF(TCP_DEBUG, ("SYN "));
1688 if (flags & TCP_RST) {
1689 LWIP_DEBUGF(TCP_DEBUG, ("RST "));
1691 if (flags & TCP_PSH) {
1692 LWIP_DEBUGF(TCP_DEBUG, ("PSH "));
1694 if (flags & TCP_ACK) {
1695 LWIP_DEBUGF(TCP_DEBUG, ("ACK "));
1697 if (flags & TCP_URG) {
1698 LWIP_DEBUGF(TCP_DEBUG, ("URG "));
1700 if (flags & TCP_ECE) {
1701 LWIP_DEBUGF(TCP_DEBUG, ("ECE "));
1703 if (flags & TCP_CWR) {
1704 LWIP_DEBUGF(TCP_DEBUG, ("CWR "));
1706 LWIP_DEBUGF(TCP_DEBUG, ("\n"));
1710 * Print all tcp_pcbs in every list for debugging purposes.
1713 tcp_debug_print_pcbs(void)
1715 struct tcp_pcb *pcb;
1716 LWIP_DEBUGF(TCP_DEBUG, ("Active PCB states:\n"));
1717 for(pcb = tcp_active_pcbs; pcb != NULL; pcb = pcb->next) {
1718 LWIP_DEBUGF(TCP_DEBUG, ("Local port %"U16_F", foreign port %"U16_F" snd_nxt %"U32_F" rcv_nxt %"U32_F" ",
1719 pcb->local_port, pcb->remote_port,
1720 pcb->snd_nxt, pcb->rcv_nxt));
1721 tcp_debug_print_state(pcb->state);
1723 LWIP_DEBUGF(TCP_DEBUG, ("Listen PCB states:\n"));
1724 for(pcb = (struct tcp_pcb *)tcp_listen_pcbs.pcbs; pcb != NULL; pcb = pcb->next) {
1725 LWIP_DEBUGF(TCP_DEBUG, ("Local port %"U16_F", foreign port %"U16_F" snd_nxt %"U32_F" rcv_nxt %"U32_F" ",
1726 pcb->local_port, pcb->remote_port,
1727 pcb->snd_nxt, pcb->rcv_nxt));
1728 tcp_debug_print_state(pcb->state);
1730 LWIP_DEBUGF(TCP_DEBUG, ("TIME-WAIT PCB states:\n"));
1731 for(pcb = tcp_tw_pcbs; pcb != NULL; pcb = pcb->next) {
1732 LWIP_DEBUGF(TCP_DEBUG, ("Local port %"U16_F", foreign port %"U16_F" snd_nxt %"U32_F" rcv_nxt %"U32_F" ",
1733 pcb->local_port, pcb->remote_port,
1734 pcb->snd_nxt, pcb->rcv_nxt));
1735 tcp_debug_print_state(pcb->state);
1740 * Check state consistency of the tcp_pcb lists.
1745 struct tcp_pcb *pcb;
1746 for(pcb = tcp_active_pcbs; pcb != NULL; pcb = pcb->next) {
1747 LWIP_ASSERT("tcp_pcbs_sane: active pcb->state != CLOSED", pcb->state != CLOSED);
1748 LWIP_ASSERT("tcp_pcbs_sane: active pcb->state != LISTEN", pcb->state != LISTEN);
1749 LWIP_ASSERT("tcp_pcbs_sane: active pcb->state != TIME-WAIT", pcb->state != TIME_WAIT);
1751 for(pcb = tcp_tw_pcbs; pcb != NULL; pcb = pcb->next) {
1752 LWIP_ASSERT("tcp_pcbs_sane: tw pcb->state == TIME-WAIT", pcb->state == TIME_WAIT);
1756 #endif /* TCP_DEBUG */
1758 #endif /* LWIP_TCP */