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: set a flag not to receive any more data */
309 pcb->flags |= TF_RXCLOSED;
312 /* This can't happen twice since if it succeeds, the pcb's state is changed.
313 Only close in these states as the others directly deallocate the PCB */
314 switch (pcb->state) {
318 /* if shut_tx AND shut_rx, send RST if we have unacked data */
319 return tcp_close_shutdown(pcb, (u8_t)shut_rx);
321 /* don't shut down other states */
325 if (shut_rx && (pcb->refused_data != NULL)) {
326 /* shut down the receive side: free buffered data if we come here */
327 pbuf_free(pcb->refused_data);
328 pcb->refused_data = NULL;
330 /* @todo: return another err_t if not in correct state or already shut? */
335 * Abandons a connection and optionally sends a RST to the remote
336 * host. Deletes the local protocol control block. This is done when
337 * a connection is killed because of shortage of memory.
339 * @param pcb the tcp_pcb to abort
340 * @param reset boolean to indicate whether a reset should be sent
343 tcp_abandon(struct tcp_pcb *pcb, int reset)
346 #if LWIP_CALLBACK_API
348 #endif /* LWIP_CALLBACK_API */
351 /* pcb->state LISTEN not allowed here */
352 LWIP_ASSERT("don't call tcp_abort/tcp_abandon for listen-pcbs",
353 pcb->state != LISTEN);
354 /* Figure out on which TCP PCB list we are, and remove us. If we
355 are in an active state, call the receive function associated with
356 the PCB with a NULL argument, and send an RST to the remote end. */
357 if (pcb->state == TIME_WAIT) {
358 tcp_pcb_remove(&tcp_tw_pcbs, pcb);
359 memp_free(MEMP_TCP_PCB, pcb);
361 seqno = pcb->snd_nxt;
362 ackno = pcb->rcv_nxt;
363 #if LWIP_CALLBACK_API
365 #endif /* LWIP_CALLBACK_API */
366 errf_arg = pcb->callback_arg;
367 tcp_pcb_remove(&tcp_active_pcbs, pcb);
368 if (pcb->unacked != NULL) {
369 tcp_segs_free(pcb->unacked);
371 if (pcb->unsent != NULL) {
372 tcp_segs_free(pcb->unsent);
375 if (pcb->ooseq != NULL) {
376 tcp_segs_free(pcb->ooseq);
378 #endif /* TCP_QUEUE_OOSEQ */
380 LWIP_DEBUGF(TCP_RST_DEBUG, ("tcp_abandon: sending RST\n"));
381 tcp_rst(seqno, ackno, &pcb->local_ip, &pcb->remote_ip, pcb->local_port, pcb->remote_port, PCB_ISIPV6(pcb));
383 memp_free(MEMP_TCP_PCB, pcb);
384 TCP_EVENT_ERR(errf, errf_arg, ERR_ABRT);
389 * Aborts the connection by sending a RST (reset) segment to the remote
390 * host. The pcb is deallocated. This function never fails.
392 * ATTENTION: When calling this from one of the TCP callbacks, make
393 * sure you always return ERR_ABRT (and never return ERR_ABRT otherwise
394 * or you will risk accessing deallocated memory or memory leaks!
396 * @param pcb the tcp pcb to abort
399 tcp_abort(struct tcp_pcb *pcb)
405 * Binds the connection to a local portnumber and IP address. If the
406 * IP address is not given (i.e., ipaddr == NULL), the IP address of
407 * the outgoing network interface is used instead.
409 * @param pcb the tcp_pcb to bind (no check is done whether this pcb is
411 * @param ipaddr the local ip address to bind to (use IP_ADDR_ANY to bind
412 * to any local address
413 * @param port the local port to bind to
414 * @return ERR_USE if the port is already in use
415 * ERR_VAL if bind failed because the PCB is not in a valid state
419 tcp_bind(struct tcp_pcb *pcb, ip_addr_t *ipaddr, u16_t port)
422 int max_pcb_list = NUM_TCP_PCB_LISTS;
423 struct tcp_pcb *cpcb;
425 LWIP_ERROR("tcp_bind: can only bind in state CLOSED", pcb->state == CLOSED, return ERR_VAL);
428 /* Unless the REUSEADDR flag is set,
429 we have to check the pcbs in TIME-WAIT state, also.
430 We do not dump TIME_WAIT pcb's; they can still be matched by incoming
431 packets using both local and remote IP addresses and ports to distinguish.
433 if ((pcb->so_options & SOF_REUSEADDR) != 0) {
434 max_pcb_list = NUM_TCP_PCB_LISTS_NO_TIME_WAIT;
436 #endif /* SO_REUSE */
439 port = tcp_new_port();
445 /* Check if the address already is in use (on all lists) */
446 for (i = 0; i < max_pcb_list; i++) {
447 for(cpcb = *tcp_pcb_lists[i]; cpcb != NULL; cpcb = cpcb->next) {
448 if (cpcb->local_port == port) {
450 /* Omit checking for the same port if both pcbs have REUSEADDR set.
451 For SO_REUSEADDR, the duplicate-check for a 5-tuple is done in
453 if (((pcb->so_options & SOF_REUSEADDR) == 0) ||
454 ((cpcb->so_options & SOF_REUSEADDR) == 0))
455 #endif /* SO_REUSE */
457 /* @todo: check accept_any_ip_version */
458 if (IP_PCB_IPVER_EQ(pcb, cpcb) &&
459 (ipX_addr_isany(PCB_ISIPV6(pcb), &cpcb->local_ip) ||
460 ipX_addr_isany(PCB_ISIPV6(pcb), ip_2_ipX(ipaddr)) ||
461 ipX_addr_cmp(PCB_ISIPV6(pcb), &cpcb->local_ip, ip_2_ipX(ipaddr)))) {
469 if (!ipX_addr_isany(PCB_ISIPV6(pcb), ip_2_ipX(ipaddr))) {
470 ipX_addr_set(PCB_ISIPV6(pcb), &pcb->local_ip, ip_2_ipX(ipaddr));
472 pcb->local_port = port;
473 TCP_REG(&tcp_bound_pcbs, pcb);
474 LWIP_DEBUGF(TCP_DEBUG, ("tcp_bind: bind to port %"U16_F"\n", port));
477 #if LWIP_CALLBACK_API
479 * Default accept callback if no accept callback is specified by the user.
482 tcp_accept_null(void *arg, struct tcp_pcb *pcb, err_t err)
484 LWIP_UNUSED_ARG(arg);
485 LWIP_UNUSED_ARG(pcb);
486 LWIP_UNUSED_ARG(err);
490 #endif /* LWIP_CALLBACK_API */
493 * Set the state of the connection to be LISTEN, which means that it
494 * is able to accept incoming connections. The protocol control block
495 * is reallocated in order to consume less memory. Setting the
496 * connection to LISTEN is an irreversible process.
498 * @param pcb the original tcp_pcb
499 * @param backlog the incoming connections queue limit
500 * @return tcp_pcb used for listening, consumes less memory.
502 * @note The original tcp_pcb is freed. This function therefore has to be
504 * tpcb = tcp_listen(tpcb);
507 tcp_listen_with_backlog(struct tcp_pcb *pcb, u8_t backlog)
509 struct tcp_pcb_listen *lpcb;
511 LWIP_UNUSED_ARG(backlog);
512 LWIP_ERROR("tcp_listen: pcb already connected", pcb->state == CLOSED, return NULL);
514 /* already listening? */
515 if (pcb->state == LISTEN) {
519 if ((pcb->so_options & SOF_REUSEADDR) != 0) {
520 /* Since SOF_REUSEADDR allows reusing a local address before the pcb's usage
521 is declared (listen-/connection-pcb), we have to make sure now that
522 this port is only used once for every local IP. */
523 for(lpcb = tcp_listen_pcbs.listen_pcbs; lpcb != NULL; lpcb = lpcb->next) {
524 if ((lpcb->local_port == pcb->local_port) &&
525 IP_PCB_IPVER_EQ(pcb, lpcb)) {
526 if (ipX_addr_cmp(PCB_ISIPV6(pcb), &lpcb->local_ip, &pcb->local_ip)) {
527 /* this address/port is already used */
533 #endif /* SO_REUSE */
534 lpcb = (struct tcp_pcb_listen *)memp_malloc(MEMP_TCP_PCB_LISTEN);
538 lpcb->callback_arg = pcb->callback_arg;
539 lpcb->local_port = pcb->local_port;
540 lpcb->state = LISTEN;
541 lpcb->prio = pcb->prio;
542 lpcb->so_options = pcb->so_options;
543 lpcb->so_options |= SOF_ACCEPTCONN;
544 lpcb->ttl = pcb->ttl;
545 lpcb->tos = pcb->tos;
547 PCB_ISIPV6(lpcb) = PCB_ISIPV6(pcb);
548 lpcb->accept_any_ip_version = 0;
549 #endif /* LWIP_IPV6 */
550 ipX_addr_copy(PCB_ISIPV6(pcb), lpcb->local_ip, pcb->local_ip);
551 if (pcb->local_port != 0) {
552 TCP_RMV(&tcp_bound_pcbs, pcb);
554 memp_free(MEMP_TCP_PCB, pcb);
555 #if LWIP_CALLBACK_API
556 lpcb->accept = tcp_accept_null;
557 #endif /* LWIP_CALLBACK_API */
558 #if TCP_LISTEN_BACKLOG
559 lpcb->accepts_pending = 0;
560 lpcb->backlog = (backlog ? backlog : 1);
561 #endif /* TCP_LISTEN_BACKLOG */
562 TCP_REG(&tcp_listen_pcbs.pcbs, (struct tcp_pcb *)lpcb);
563 return (struct tcp_pcb *)lpcb;
568 * Same as tcp_listen_with_backlog, but allows to accept IPv4 and IPv6
569 * connections, if the pcb's local address is set to ANY.
572 tcp_listen_dual_with_backlog(struct tcp_pcb *pcb, u8_t backlog)
574 struct tcp_pcb *lpcb;
576 if (!ipX_addr_isany(PCB_ISIPV6(pcb), &pcb->local_ip)) {
579 lpcb = tcp_listen_with_backlog(pcb, backlog);
581 ((struct tcp_pcb_listen*)lpcb)->accept_any_ip_version = 1;
585 #endif /* LWIP_IPV6 */
588 * Update the state that tracks the available window space to advertise.
590 * Returns how much extra window would be advertised if we sent an
593 u32_t tcp_update_rcv_ann_wnd(struct tcp_pcb *pcb)
595 u32_t new_right_edge = pcb->rcv_nxt + pcb->rcv_wnd;
597 if (TCP_SEQ_GEQ(new_right_edge, pcb->rcv_ann_right_edge + LWIP_MIN((TCP_WND / 2), pcb->mss))) {
598 /* we can advertise more window */
599 pcb->rcv_ann_wnd = pcb->rcv_wnd;
600 return new_right_edge - pcb->rcv_ann_right_edge;
602 if (TCP_SEQ_GT(pcb->rcv_nxt, pcb->rcv_ann_right_edge)) {
603 /* Can happen due to other end sending out of advertised window,
604 * but within actual available (but not yet advertised) window */
605 pcb->rcv_ann_wnd = 0;
607 /* keep the right edge of window constant */
608 u32_t new_rcv_ann_wnd = pcb->rcv_ann_right_edge - pcb->rcv_nxt;
609 LWIP_ASSERT("new_rcv_ann_wnd <= 0xffff", new_rcv_ann_wnd <= 0xffff);
610 pcb->rcv_ann_wnd = (u16_t)new_rcv_ann_wnd;
617 * This function should be called by the application when it has
618 * processed the data. The purpose is to advertise a larger window
619 * when the data has been processed.
621 * @param pcb the tcp_pcb for which data is read
622 * @param len the amount of bytes that have been read by the application
625 tcp_recved(struct tcp_pcb *pcb, u16_t len)
629 /* pcb->state LISTEN not allowed here */
630 LWIP_ASSERT("don't call tcp_recved for listen-pcbs",
631 pcb->state != LISTEN);
632 LWIP_ASSERT("tcp_recved: len would wrap rcv_wnd\n",
633 len <= 0xffff - pcb->rcv_wnd );
636 if (pcb->rcv_wnd > TCP_WND) {
637 pcb->rcv_wnd = TCP_WND;
640 wnd_inflation = tcp_update_rcv_ann_wnd(pcb);
642 /* If the change in the right edge of window is significant (default
643 * watermark is TCP_WND/4), then send an explicit update now.
644 * Otherwise wait for a packet to be sent in the normal course of
645 * events (or more window to be available later) */
646 if (wnd_inflation >= TCP_WND_UPDATE_THRESHOLD) {
651 LWIP_DEBUGF(TCP_DEBUG, ("tcp_recved: recveived %"U16_F" bytes, wnd %"U16_F" (%"U16_F").\n",
652 len, pcb->rcv_wnd, TCP_WND - pcb->rcv_wnd));
656 * Allocate a new local TCP port.
658 * @return a new (free) local TCP port number
668 if (tcp_port++ == TCP_LOCAL_PORT_RANGE_END) {
669 tcp_port = TCP_LOCAL_PORT_RANGE_START;
671 /* Check all PCB lists. */
672 for (i = 0; i < NUM_TCP_PCB_LISTS; i++) {
673 for(pcb = *tcp_pcb_lists[i]; pcb != NULL; pcb = pcb->next) {
674 if (pcb->local_port == tcp_port) {
675 if (++n > (TCP_LOCAL_PORT_RANGE_END - TCP_LOCAL_PORT_RANGE_START)) {
686 * Connects to another host. The function given as the "connected"
687 * argument will be called when the connection has been established.
689 * @param pcb the tcp_pcb used to establish the connection
690 * @param ipaddr the remote ip address to connect to
691 * @param port the remote tcp port to connect to
692 * @param connected callback function to call when connected (or on error)
693 * @return ERR_VAL if invalid arguments are given
694 * ERR_OK if connect request has been sent
695 * other err_t values if connect request couldn't be sent
698 tcp_connect(struct tcp_pcb *pcb, ip_addr_t *ipaddr, u16_t port,
699 tcp_connected_fn connected)
703 u16_t old_local_port;
705 LWIP_ERROR("tcp_connect: can only connect from state CLOSED", pcb->state == CLOSED, return ERR_ISCONN);
707 LWIP_DEBUGF(TCP_DEBUG, ("tcp_connect to port %"U16_F"\n", port));
708 if (ipaddr != NULL) {
709 ipX_addr_set(PCB_ISIPV6(pcb), &pcb->remote_ip, ip_2_ipX(ipaddr));
713 pcb->remote_port = port;
715 /* check if we have a route to the remote host */
716 if (ipX_addr_isany(PCB_ISIPV6(pcb), &pcb->local_ip)) {
717 /* no local IP address set, yet. */
719 ipX_addr_t *local_ip;
720 ipX_route_get_local_ipX(PCB_ISIPV6(pcb), &pcb->local_ip, &pcb->remote_ip, netif, local_ip);
721 if ((netif == NULL) || (local_ip == NULL)) {
722 /* Don't even try to send a SYN packet if we have no route
723 since that will fail. */
726 /* Use the address as local address of the pcb. */
727 ipX_addr_copy(PCB_ISIPV6(pcb), pcb->local_ip, *local_ip);
730 old_local_port = pcb->local_port;
731 if (pcb->local_port == 0) {
732 pcb->local_port = tcp_new_port();
733 if (pcb->local_port == 0) {
738 if ((pcb->so_options & SOF_REUSEADDR) != 0) {
739 /* Since SOF_REUSEADDR allows reusing a local address, we have to make sure
740 now that the 5-tuple is unique. */
741 struct tcp_pcb *cpcb;
743 /* Don't check listen- and bound-PCBs, check active- and TIME-WAIT PCBs. */
744 for (i = 2; i < NUM_TCP_PCB_LISTS; i++) {
745 for(cpcb = *tcp_pcb_lists[i]; cpcb != NULL; cpcb = cpcb->next) {
746 if ((cpcb->local_port == pcb->local_port) &&
747 (cpcb->remote_port == port) &&
748 IP_PCB_IPVER_EQ(cpcb, pcb) &&
749 ipX_addr_cmp(PCB_ISIPV6(pcb), &cpcb->local_ip, &pcb->local_ip) &&
750 ipX_addr_cmp(PCB_ISIPV6(pcb), &cpcb->remote_ip, ip_2_ipX(ipaddr))) {
751 /* linux returns EISCONN here, but ERR_USE should be OK for us */
757 #endif /* SO_REUSE */
758 iss = tcp_next_iss();
761 pcb->lastack = iss - 1;
762 pcb->snd_lbb = iss - 1;
763 pcb->rcv_wnd = TCP_WND;
764 pcb->rcv_ann_wnd = TCP_WND;
765 pcb->rcv_ann_right_edge = pcb->rcv_nxt;
766 pcb->snd_wnd = TCP_WND;
767 /* As initial send MSS, we use TCP_MSS but limit it to 536.
768 The send MSS is updated when an MSS option is received. */
769 pcb->mss = (TCP_MSS > 536) ? 536 : TCP_MSS;
770 #if TCP_CALCULATE_EFF_SEND_MSS
771 pcb->mss = tcp_eff_send_mss(pcb->mss, &pcb->local_ip, &pcb->remote_ip, PCB_ISIPV6(pcb));
772 #endif /* TCP_CALCULATE_EFF_SEND_MSS */
774 pcb->ssthresh = pcb->mss * 10;
775 #if LWIP_CALLBACK_API
776 pcb->connected = connected;
777 #else /* LWIP_CALLBACK_API */
778 LWIP_UNUSED_ARG(connected);
779 #endif /* LWIP_CALLBACK_API */
781 /* Send a SYN together with the MSS option. */
782 ret = tcp_enqueue_flags(pcb, TCP_SYN);
784 /* SYN segment was enqueued, changed the pcbs state now */
785 pcb->state = SYN_SENT;
786 if (old_local_port != 0) {
787 TCP_RMV(&tcp_bound_pcbs, pcb);
789 TCP_REG(&tcp_active_pcbs, pcb);
790 snmp_inc_tcpactiveopens();
798 * Called every 500 ms and implements the retransmission timer and the timer that
799 * removes PCBs that have been in TIME-WAIT for enough time. It also increments
800 * various timers such as the inactivity timer in each PCB.
802 * Automatically called from tcp_tmr().
807 struct tcp_pcb *pcb, *prev;
809 u8_t pcb_remove; /* flag if a PCB should be removed */
810 u8_t pcb_reset; /* flag if a RST should be sent when removing */
817 /* Steps through all of the active PCBs. */
819 pcb = tcp_active_pcbs;
821 LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: no active pcbs\n"));
823 while (pcb != NULL) {
824 LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: processing active pcb\n"));
825 LWIP_ASSERT("tcp_slowtmr: active pcb->state != CLOSED\n", pcb->state != CLOSED);
826 LWIP_ASSERT("tcp_slowtmr: active pcb->state != LISTEN\n", pcb->state != LISTEN);
827 LWIP_ASSERT("tcp_slowtmr: active pcb->state != TIME-WAIT\n", pcb->state != TIME_WAIT);
832 if (pcb->state == SYN_SENT && pcb->nrtx == TCP_SYNMAXRTX) {
834 LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: max SYN retries reached\n"));
836 else if (pcb->nrtx == TCP_MAXRTX) {
838 LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: max DATA retries reached\n"));
840 if (pcb->persist_backoff > 0) {
841 /* If snd_wnd is zero, use persist timer to send 1 byte probes
842 * instead of using the standard retransmission mechanism. */
844 if (pcb->persist_cnt >= tcp_persist_backoff[pcb->persist_backoff-1]) {
845 pcb->persist_cnt = 0;
846 if (pcb->persist_backoff < sizeof(tcp_persist_backoff)) {
847 pcb->persist_backoff++;
849 tcp_zero_window_probe(pcb);
852 /* Increase the retransmission timer if it is running */
856 if (pcb->unacked != NULL && pcb->rtime >= pcb->rto) {
857 /* Time for a retransmission. */
858 LWIP_DEBUGF(TCP_RTO_DEBUG, ("tcp_slowtmr: rtime %"S16_F
859 " pcb->rto %"S16_F"\n",
860 pcb->rtime, pcb->rto));
862 /* Double retransmission time-out unless we are trying to
863 * connect to somebody (i.e., we are in SYN_SENT). */
864 if (pcb->state != SYN_SENT) {
865 pcb->rto = ((pcb->sa >> 3) + pcb->sv) << tcp_backoff[pcb->nrtx];
868 /* Reset the retransmission timer. */
871 /* Reduce congestion window and ssthresh. */
872 eff_wnd = LWIP_MIN(pcb->cwnd, pcb->snd_wnd);
873 pcb->ssthresh = eff_wnd >> 1;
874 if (pcb->ssthresh < (pcb->mss << 1)) {
875 pcb->ssthresh = (pcb->mss << 1);
877 pcb->cwnd = pcb->mss;
878 LWIP_DEBUGF(TCP_CWND_DEBUG, ("tcp_slowtmr: cwnd %"U16_F
879 " ssthresh %"U16_F"\n",
880 pcb->cwnd, pcb->ssthresh));
882 /* The following needs to be called AFTER cwnd is set to one
888 /* Check if this PCB has stayed too long in FIN-WAIT-2 */
889 if (pcb->state == FIN_WAIT_2) {
890 if ((u32_t)(tcp_ticks - pcb->tmr) >
891 TCP_FIN_WAIT_TIMEOUT / TCP_SLOW_INTERVAL) {
893 LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: removing pcb stuck in FIN-WAIT-2\n"));
897 /* Check if KEEPALIVE should be sent */
898 if((pcb->so_options & SOF_KEEPALIVE) &&
899 ((pcb->state == ESTABLISHED) ||
900 (pcb->state == CLOSE_WAIT))) {
901 #if LWIP_TCP_KEEPALIVE
902 if((u32_t)(tcp_ticks - pcb->tmr) >
903 (pcb->keep_idle + (pcb->keep_cnt*pcb->keep_intvl))
906 if((u32_t)(tcp_ticks - pcb->tmr) >
907 (pcb->keep_idle + TCP_MAXIDLE) / TCP_SLOW_INTERVAL)
908 #endif /* LWIP_TCP_KEEPALIVE */
910 LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: KEEPALIVE timeout. Aborting connection to "));
911 ipX_addr_debug_print(PCB_ISIPV6(pcb), TCP_DEBUG, &pcb->remote_ip);
912 LWIP_DEBUGF(TCP_DEBUG, ("\n"));
917 #if LWIP_TCP_KEEPALIVE
918 else if((u32_t)(tcp_ticks - pcb->tmr) >
919 (pcb->keep_idle + pcb->keep_cnt_sent * pcb->keep_intvl)
922 else if((u32_t)(tcp_ticks - pcb->tmr) >
923 (pcb->keep_idle + pcb->keep_cnt_sent * TCP_KEEPINTVL_DEFAULT)
925 #endif /* LWIP_TCP_KEEPALIVE */
928 pcb->keep_cnt_sent++;
932 /* If this PCB has queued out of sequence data, but has been
933 inactive for too long, will drop the data (it will eventually
934 be retransmitted). */
936 if (pcb->ooseq != NULL &&
937 (u32_t)tcp_ticks - pcb->tmr >= pcb->rto * TCP_OOSEQ_TIMEOUT) {
938 tcp_segs_free(pcb->ooseq);
940 LWIP_DEBUGF(TCP_CWND_DEBUG, ("tcp_slowtmr: dropping OOSEQ queued data\n"));
942 #endif /* TCP_QUEUE_OOSEQ */
944 /* Check if this PCB has stayed too long in SYN-RCVD */
945 if (pcb->state == SYN_RCVD) {
946 if ((u32_t)(tcp_ticks - pcb->tmr) >
947 TCP_SYN_RCVD_TIMEOUT / TCP_SLOW_INTERVAL) {
949 LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: removing pcb stuck in SYN-RCVD\n"));
953 /* Check if this PCB has stayed too long in LAST-ACK */
954 if (pcb->state == LAST_ACK) {
955 if ((u32_t)(tcp_ticks - pcb->tmr) > 2 * TCP_MSL / TCP_SLOW_INTERVAL) {
957 LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: removing pcb stuck in LAST-ACK\n"));
961 /* If the PCB should be removed, do it. */
963 struct tcp_pcb *pcb2;
965 /* Remove PCB from tcp_active_pcbs list. */
967 LWIP_ASSERT("tcp_slowtmr: middle tcp != tcp_active_pcbs", pcb != tcp_active_pcbs);
968 prev->next = pcb->next;
970 /* This PCB was the first. */
971 LWIP_ASSERT("tcp_slowtmr: first pcb == tcp_active_pcbs", tcp_active_pcbs == pcb);
972 tcp_active_pcbs = pcb->next;
975 TCP_EVENT_ERR(pcb->errf, pcb->callback_arg, ERR_ABRT);
977 tcp_rst(pcb->snd_nxt, pcb->rcv_nxt, &pcb->local_ip, &pcb->remote_ip,
978 pcb->local_port, pcb->remote_port, PCB_ISIPV6(pcb));
983 memp_free(MEMP_TCP_PCB, pcb2);
985 /* get the 'next' element now and work with 'prev' below (in case of abort) */
989 /* We check if we should poll the connection. */
991 if (prev->polltmr >= prev->pollinterval) {
993 LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: polling application\n"));
994 TCP_EVENT_POLL(prev, err);
995 /* if err == ERR_ABRT, 'prev' is already deallocated */
1004 /* Steps through all of the TIME-WAIT PCBs. */
1007 while (pcb != NULL) {
1008 LWIP_ASSERT("tcp_slowtmr: TIME-WAIT pcb->state == TIME-WAIT", pcb->state == TIME_WAIT);
1011 /* Check if this PCB has stayed long enough in TIME-WAIT */
1012 if ((u32_t)(tcp_ticks - pcb->tmr) > 2 * TCP_MSL / TCP_SLOW_INTERVAL) {
1018 /* If the PCB should be removed, do it. */
1020 struct tcp_pcb *pcb2;
1022 /* Remove PCB from tcp_tw_pcbs list. */
1024 LWIP_ASSERT("tcp_slowtmr: middle tcp != tcp_tw_pcbs", pcb != tcp_tw_pcbs);
1025 prev->next = pcb->next;
1027 /* This PCB was the first. */
1028 LWIP_ASSERT("tcp_slowtmr: first pcb == tcp_tw_pcbs", tcp_tw_pcbs == pcb);
1029 tcp_tw_pcbs = pcb->next;
1033 memp_free(MEMP_TCP_PCB, pcb2);
1042 * Is called every TCP_FAST_INTERVAL (250 ms) and process data previously
1043 * "refused" by upper layer (application) and sends delayed ACKs.
1045 * Automatically called from tcp_tmr().
1050 struct tcp_pcb *pcb = tcp_active_pcbs;
1052 while(pcb != NULL) {
1053 struct tcp_pcb *next = pcb->next;
1054 /* If there is data which was previously "refused" by upper layer */
1055 if (pcb->refused_data != NULL) {
1056 /* Notify again application with data previously received. */
1058 LWIP_DEBUGF(TCP_INPUT_DEBUG, ("tcp_fasttmr: notify kept packet\n"));
1059 TCP_EVENT_RECV(pcb, pcb->refused_data, ERR_OK, err);
1060 if (err == ERR_OK) {
1061 pcb->refused_data = NULL;
1062 } else if (err == ERR_ABRT) {
1063 /* if err == ERR_ABRT, 'pcb' is already deallocated */
1068 /* send delayed ACKs */
1069 if (pcb && (pcb->flags & TF_ACK_DELAY)) {
1070 LWIP_DEBUGF(TCP_DEBUG, ("tcp_fasttmr: delayed ACK\n"));
1073 pcb->flags &= ~(TF_ACK_DELAY | TF_ACK_NOW);
1081 * Deallocates a list of TCP segments (tcp_seg structures).
1083 * @param seg tcp_seg list of TCP segments to free
1086 tcp_segs_free(struct tcp_seg *seg)
1088 while (seg != NULL) {
1089 struct tcp_seg *next = seg->next;
1096 * Frees a TCP segment (tcp_seg structure).
1098 * @param seg single tcp_seg to free
1101 tcp_seg_free(struct tcp_seg *seg)
1104 if (seg->p != NULL) {
1108 #endif /* TCP_DEBUG */
1110 memp_free(MEMP_TCP_SEG, seg);
1115 * Sets the priority of a connection.
1117 * @param pcb the tcp_pcb to manipulate
1118 * @param prio new priority
1121 tcp_setprio(struct tcp_pcb *pcb, u8_t prio)
1128 * Returns a copy of the given TCP segment.
1129 * The pbuf and data are not copied, only the pointers
1131 * @param seg the old tcp_seg
1132 * @return a copy of seg
1135 tcp_seg_copy(struct tcp_seg *seg)
1137 struct tcp_seg *cseg;
1139 cseg = (struct tcp_seg *)memp_malloc(MEMP_TCP_SEG);
1143 SMEMCPY((u8_t *)cseg, (const u8_t *)seg, sizeof(struct tcp_seg));
1147 #endif /* TCP_QUEUE_OOSEQ */
1149 #if LWIP_CALLBACK_API
1151 * Default receive callback that is called if the user didn't register
1152 * a recv callback for the pcb.
1155 tcp_recv_null(void *arg, struct tcp_pcb *pcb, struct pbuf *p, err_t err)
1157 LWIP_UNUSED_ARG(arg);
1159 tcp_recved(pcb, p->tot_len);
1161 } else if (err == ERR_OK) {
1162 return tcp_close(pcb);
1166 #endif /* LWIP_CALLBACK_API */
1169 * Kills the oldest active connection that has the same or lower priority than
1172 * @param prio minimum priority
1175 tcp_kill_prio(u8_t prio)
1177 struct tcp_pcb *pcb, *inactive;
1182 mprio = TCP_PRIO_MAX;
1184 /* We kill the oldest active connection that has lower priority than prio. */
1187 for(pcb = tcp_active_pcbs; pcb != NULL; pcb = pcb->next) {
1188 if (pcb->prio <= prio &&
1189 pcb->prio <= mprio &&
1190 (u32_t)(tcp_ticks - pcb->tmr) >= inactivity) {
1191 inactivity = tcp_ticks - pcb->tmr;
1196 if (inactive != NULL) {
1197 LWIP_DEBUGF(TCP_DEBUG, ("tcp_kill_prio: killing oldest PCB %p (%"S32_F")\n",
1198 (void *)inactive, inactivity));
1199 tcp_abort(inactive);
1204 * Kills the oldest connection that is in TIME_WAIT state.
1205 * Called from tcp_alloc() if no more connections are available.
1208 tcp_kill_timewait(void)
1210 struct tcp_pcb *pcb, *inactive;
1215 /* Go through the list of TIME_WAIT pcbs and get the oldest pcb. */
1216 for(pcb = tcp_tw_pcbs; pcb != NULL; pcb = pcb->next) {
1217 if ((u32_t)(tcp_ticks - pcb->tmr) >= inactivity) {
1218 inactivity = tcp_ticks - pcb->tmr;
1222 if (inactive != NULL) {
1223 LWIP_DEBUGF(TCP_DEBUG, ("tcp_kill_timewait: killing oldest TIME-WAIT PCB %p (%"S32_F")\n",
1224 (void *)inactive, inactivity));
1225 tcp_abort(inactive);
1230 * Allocate a new tcp_pcb structure.
1232 * @param prio priority for the new pcb
1233 * @return a new tcp_pcb that initially is in state CLOSED
1236 tcp_alloc(u8_t prio)
1238 struct tcp_pcb *pcb;
1241 pcb = (struct tcp_pcb *)memp_malloc(MEMP_TCP_PCB);
1243 /* Try killing oldest connection in TIME-WAIT. */
1244 LWIP_DEBUGF(TCP_DEBUG, ("tcp_alloc: killing off oldest TIME-WAIT connection\n"));
1245 tcp_kill_timewait();
1246 /* Try to allocate a tcp_pcb again. */
1247 pcb = (struct tcp_pcb *)memp_malloc(MEMP_TCP_PCB);
1249 /* Try killing active connections with lower priority than the new one. */
1250 LWIP_DEBUGF(TCP_DEBUG, ("tcp_alloc: killing connection with prio lower than %d\n", prio));
1251 tcp_kill_prio(prio);
1252 /* Try to allocate a tcp_pcb again. */
1253 pcb = (struct tcp_pcb *)memp_malloc(MEMP_TCP_PCB);
1255 /* adjust err stats: memp_malloc failed twice before */
1256 MEMP_STATS_DEC(err, MEMP_TCP_PCB);
1260 /* adjust err stats: timewait PCB was freed above */
1261 MEMP_STATS_DEC(err, MEMP_TCP_PCB);
1265 memset(pcb, 0, sizeof(struct tcp_pcb));
1267 pcb->snd_buf = TCP_SND_BUF;
1268 pcb->snd_queuelen = 0;
1269 pcb->rcv_wnd = TCP_WND;
1270 pcb->rcv_ann_wnd = TCP_WND;
1273 /* As initial send MSS, we use TCP_MSS but limit it to 536.
1274 The send MSS is updated when an MSS option is received. */
1275 pcb->mss = (TCP_MSS > 536) ? 536 : TCP_MSS;
1276 pcb->rto = 3000 / TCP_SLOW_INTERVAL;
1278 pcb->sv = 3000 / TCP_SLOW_INTERVAL;
1281 iss = tcp_next_iss();
1286 pcb->tmr = tcp_ticks;
1290 #if LWIP_CALLBACK_API
1291 pcb->recv = tcp_recv_null;
1292 #endif /* LWIP_CALLBACK_API */
1294 /* Init KEEPALIVE timer */
1295 pcb->keep_idle = TCP_KEEPIDLE_DEFAULT;
1297 #if LWIP_TCP_KEEPALIVE
1298 pcb->keep_intvl = TCP_KEEPINTVL_DEFAULT;
1299 pcb->keep_cnt = TCP_KEEPCNT_DEFAULT;
1300 #endif /* LWIP_TCP_KEEPALIVE */
1302 pcb->keep_cnt_sent = 0;
1308 * Creates a new TCP protocol control block but doesn't place it on
1309 * any of the TCP PCB lists.
1310 * The pcb is not put on any list until binding using tcp_bind().
1312 * @internal: Maybe there should be a idle TCP PCB list where these
1313 * PCBs are put on. Port reservation using tcp_bind() is implemented but
1314 * allocated pcbs that are not bound can't be killed automatically if wanting
1315 * to allocate a pcb with higher prio (@see tcp_kill_prio())
1317 * @return a new tcp_pcb that initially is in state CLOSED
1322 return tcp_alloc(TCP_PRIO_NORMAL);
1327 * Creates a new TCP-over-IPv6 protocol control block but doesn't
1328 * place it on any of the TCP PCB lists.
1329 * The pcb is not put on any list until binding using tcp_bind().
1331 * @return a new tcp_pcb that initially is in state CLOSED
1336 struct tcp_pcb * pcb;
1337 pcb = tcp_alloc(TCP_PRIO_NORMAL);
1341 #endif /* LWIP_IPV6 */
1344 * Used to specify the argument that should be passed callback
1347 * @param pcb tcp_pcb to set the callback argument
1348 * @param arg void pointer argument to pass to callback functions
1351 tcp_arg(struct tcp_pcb *pcb, void *arg)
1353 /* This function is allowed to be called for both listen pcbs and
1355 pcb->callback_arg = arg;
1357 #if LWIP_CALLBACK_API
1360 * Used to specify the function that should be called when a TCP
1361 * connection receives data.
1363 * @param pcb tcp_pcb to set the recv callback
1364 * @param recv callback function to call for this pcb when data is received
1367 tcp_recv(struct tcp_pcb *pcb, tcp_recv_fn recv)
1369 LWIP_ASSERT("invalid socket state for recv callback", pcb->state != LISTEN);
1374 * Used to specify the function that should be called when TCP data
1375 * has been successfully delivered to the remote host.
1377 * @param pcb tcp_pcb to set the sent callback
1378 * @param sent callback function to call for this pcb when data is successfully sent
1381 tcp_sent(struct tcp_pcb *pcb, tcp_sent_fn sent)
1383 LWIP_ASSERT("invalid socket state for sent callback", pcb->state != LISTEN);
1388 * Used to specify the function that should be called when a fatal error
1389 * has occured on the connection.
1391 * @param pcb tcp_pcb to set the err callback
1392 * @param err callback function to call for this pcb when a fatal error
1393 * has occured on the connection
1396 tcp_err(struct tcp_pcb *pcb, tcp_err_fn err)
1398 LWIP_ASSERT("invalid socket state for err callback", pcb->state != LISTEN);
1403 * Used for specifying the function that should be called when a
1404 * LISTENing connection has been connected to another host.
1406 * @param pcb tcp_pcb to set the accept callback
1407 * @param accept callback function to call for this pcb when LISTENing
1408 * connection has been connected to another host
1411 tcp_accept(struct tcp_pcb *pcb, tcp_accept_fn accept)
1413 /* This function is allowed to be called for both listen pcbs and
1415 pcb->accept = accept;
1417 #endif /* LWIP_CALLBACK_API */
1421 * Used to specify the function that should be called periodically
1422 * from TCP. The interval is specified in terms of the TCP coarse
1423 * timer interval, which is called twice a second.
1427 tcp_poll(struct tcp_pcb *pcb, tcp_poll_fn poll, u8_t interval)
1429 LWIP_ASSERT("invalid socket state for poll", pcb->state != LISTEN);
1430 #if LWIP_CALLBACK_API
1432 #else /* LWIP_CALLBACK_API */
1433 LWIP_UNUSED_ARG(poll);
1434 #endif /* LWIP_CALLBACK_API */
1435 pcb->pollinterval = interval;
1439 * Purges a TCP PCB. Removes any buffered data and frees the buffer memory
1440 * (pcb->ooseq, pcb->unsent and pcb->unacked are freed).
1442 * @param pcb tcp_pcb to purge. The pcb itself is not deallocated!
1445 tcp_pcb_purge(struct tcp_pcb *pcb)
1447 if (pcb->state != CLOSED &&
1448 pcb->state != TIME_WAIT &&
1449 pcb->state != LISTEN) {
1451 LWIP_DEBUGF(TCP_DEBUG, ("tcp_pcb_purge\n"));
1453 #if TCP_LISTEN_BACKLOG
1454 if (pcb->state == SYN_RCVD) {
1455 /* Need to find the corresponding listen_pcb and decrease its accepts_pending */
1456 struct tcp_pcb_listen *lpcb;
1457 LWIP_ASSERT("tcp_pcb_purge: pcb->state == SYN_RCVD but tcp_listen_pcbs is NULL",
1458 tcp_listen_pcbs.listen_pcbs != NULL);
1459 for (lpcb = tcp_listen_pcbs.listen_pcbs; lpcb != NULL; lpcb = lpcb->next) {
1460 if ((lpcb->local_port == pcb->local_port) &&
1461 IP_PCB_IPVER_EQ(pcb, lpcb) &&
1462 (ipX_addr_isany(PCB_ISIPV6(lpcb), &lpcb->local_ip) ||
1463 ipX_addr_cmp(PCB_ISIPV6(lpcb), &pcb->local_ip, &lpcb->local_ip))) {
1464 /* port and address of the listen pcb match the timed-out pcb */
1465 LWIP_ASSERT("tcp_pcb_purge: listen pcb does not have accepts pending",
1466 lpcb->accepts_pending > 0);
1467 lpcb->accepts_pending--;
1472 #endif /* TCP_LISTEN_BACKLOG */
1475 if (pcb->refused_data != NULL) {
1476 LWIP_DEBUGF(TCP_DEBUG, ("tcp_pcb_purge: data left on ->refused_data\n"));
1477 pbuf_free(pcb->refused_data);
1478 pcb->refused_data = NULL;
1480 if (pcb->unsent != NULL) {
1481 LWIP_DEBUGF(TCP_DEBUG, ("tcp_pcb_purge: not all data sent\n"));
1483 if (pcb->unacked != NULL) {
1484 LWIP_DEBUGF(TCP_DEBUG, ("tcp_pcb_purge: data left on ->unacked\n"));
1487 if (pcb->ooseq != NULL) {
1488 LWIP_DEBUGF(TCP_DEBUG, ("tcp_pcb_purge: data left on ->ooseq\n"));
1490 tcp_segs_free(pcb->ooseq);
1492 #endif /* TCP_QUEUE_OOSEQ */
1494 /* Stop the retransmission timer as it will expect data on unacked
1495 queue if it fires */
1498 tcp_segs_free(pcb->unsent);
1499 tcp_segs_free(pcb->unacked);
1500 pcb->unacked = pcb->unsent = NULL;
1502 pcb->unsent_oversize = 0;
1503 #endif /* TCP_OVERSIZE */
1508 * Purges the PCB and removes it from a PCB list. Any delayed ACKs are sent first.
1510 * @param pcblist PCB list to purge.
1511 * @param pcb tcp_pcb to purge. The pcb itself is NOT deallocated!
1514 tcp_pcb_remove(struct tcp_pcb **pcblist, struct tcp_pcb *pcb)
1516 TCP_RMV(pcblist, pcb);
1520 /* if there is an outstanding delayed ACKs, send it */
1521 if (pcb->state != TIME_WAIT &&
1522 pcb->state != LISTEN &&
1523 pcb->flags & TF_ACK_DELAY) {
1524 pcb->flags |= TF_ACK_NOW;
1528 if (pcb->state != LISTEN) {
1529 LWIP_ASSERT("unsent segments leaking", pcb->unsent == NULL);
1530 LWIP_ASSERT("unacked segments leaking", pcb->unacked == NULL);
1532 LWIP_ASSERT("ooseq segments leaking", pcb->ooseq == NULL);
1533 #endif /* TCP_QUEUE_OOSEQ */
1536 pcb->state = CLOSED;
1538 LWIP_ASSERT("tcp_pcb_remove: tcp_pcbs_sane()", tcp_pcbs_sane());
1542 * Calculates a new initial sequence number for new connections.
1544 * @return u32_t pseudo random sequence number
1549 static u32_t iss = 6510;
1551 iss += tcp_ticks; /* XXX */
1555 #if TCP_CALCULATE_EFF_SEND_MSS
1557 * Calcluates the effective send mss that can be used for a specific IP address
1558 * by using ip_route to determin the netif used to send to the address and
1559 * calculating the minimum of TCP_MSS and that netif's mtu (if set).
1562 tcp_eff_send_mss_impl(u16_t sendmss, ipX_addr_t *dest
1564 , ipX_addr_t *src, u8_t isipv6
1565 #endif /* LWIP_IPV6 */
1569 struct netif *outif;
1572 outif = ipX_route(isipv6, src, dest);
1575 /* First look in destination cache, to see if there is a Path MTU. */
1576 mtu = nd6_get_destination_mtu(ipX_2_ip6(dest), outif);
1578 #endif /* LWIP_IPV6 */
1580 if (outif == NULL) {
1587 mss_s = mtu - IP_HLEN - TCP_HLEN;
1589 /* for IPv6, substract the difference in header size */
1590 mss_s -= (IP6_HLEN - IP_HLEN);
1591 #endif /* LWIP_IPV6 */
1592 /* RFC 1122, chap 4.2.2.6:
1593 * Eff.snd.MSS = min(SendMSS+20, MMS_S) - TCPhdrsize - IPoptionsize
1594 * We correct for TCP options in tcp_write(), and don't support IP options.
1596 sendmss = LWIP_MIN(sendmss, mss_s);
1600 #endif /* TCP_CALCULATE_EFF_SEND_MSS */
1603 tcp_debug_state_str(enum tcp_state s)
1605 return tcp_state_str[s];
1608 #if TCP_DEBUG || TCP_INPUT_DEBUG || TCP_OUTPUT_DEBUG
1610 * Print a tcp header for debugging purposes.
1612 * @param tcphdr pointer to a struct tcp_hdr
1615 tcp_debug_print(struct tcp_hdr *tcphdr)
1617 LWIP_DEBUGF(TCP_DEBUG, ("TCP header:\n"));
1618 LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
1619 LWIP_DEBUGF(TCP_DEBUG, ("| %5"U16_F" | %5"U16_F" | (src port, dest port)\n",
1620 ntohs(tcphdr->src), ntohs(tcphdr->dest)));
1621 LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
1622 LWIP_DEBUGF(TCP_DEBUG, ("| %010"U32_F" | (seq no)\n",
1623 ntohl(tcphdr->seqno)));
1624 LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
1625 LWIP_DEBUGF(TCP_DEBUG, ("| %010"U32_F" | (ack no)\n",
1626 ntohl(tcphdr->ackno)));
1627 LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
1628 LWIP_DEBUGF(TCP_DEBUG, ("| %2"U16_F" | |%"U16_F"%"U16_F"%"U16_F"%"U16_F"%"U16_F"%"U16_F"| %5"U16_F" | (hdrlen, flags (",
1629 TCPH_HDRLEN(tcphdr),
1630 TCPH_FLAGS(tcphdr) >> 5 & 1,
1631 TCPH_FLAGS(tcphdr) >> 4 & 1,
1632 TCPH_FLAGS(tcphdr) >> 3 & 1,
1633 TCPH_FLAGS(tcphdr) >> 2 & 1,
1634 TCPH_FLAGS(tcphdr) >> 1 & 1,
1635 TCPH_FLAGS(tcphdr) & 1,
1636 ntohs(tcphdr->wnd)));
1637 tcp_debug_print_flags(TCPH_FLAGS(tcphdr));
1638 LWIP_DEBUGF(TCP_DEBUG, ("), win)\n"));
1639 LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
1640 LWIP_DEBUGF(TCP_DEBUG, ("| 0x%04"X16_F" | %5"U16_F" | (chksum, urgp)\n",
1641 ntohs(tcphdr->chksum), ntohs(tcphdr->urgp)));
1642 LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
1646 * Print a tcp state for debugging purposes.
1648 * @param s enum tcp_state to print
1651 tcp_debug_print_state(enum tcp_state s)
1653 LWIP_DEBUGF(TCP_DEBUG, ("State: %s\n", tcp_state_str[s]));
1657 * Print tcp flags for debugging purposes.
1659 * @param flags tcp flags, all active flags are printed
1662 tcp_debug_print_flags(u8_t flags)
1664 if (flags & TCP_FIN) {
1665 LWIP_DEBUGF(TCP_DEBUG, ("FIN "));
1667 if (flags & TCP_SYN) {
1668 LWIP_DEBUGF(TCP_DEBUG, ("SYN "));
1670 if (flags & TCP_RST) {
1671 LWIP_DEBUGF(TCP_DEBUG, ("RST "));
1673 if (flags & TCP_PSH) {
1674 LWIP_DEBUGF(TCP_DEBUG, ("PSH "));
1676 if (flags & TCP_ACK) {
1677 LWIP_DEBUGF(TCP_DEBUG, ("ACK "));
1679 if (flags & TCP_URG) {
1680 LWIP_DEBUGF(TCP_DEBUG, ("URG "));
1682 if (flags & TCP_ECE) {
1683 LWIP_DEBUGF(TCP_DEBUG, ("ECE "));
1685 if (flags & TCP_CWR) {
1686 LWIP_DEBUGF(TCP_DEBUG, ("CWR "));
1688 LWIP_DEBUGF(TCP_DEBUG, ("\n"));
1692 * Print all tcp_pcbs in every list for debugging purposes.
1695 tcp_debug_print_pcbs(void)
1697 struct tcp_pcb *pcb;
1698 LWIP_DEBUGF(TCP_DEBUG, ("Active PCB states:\n"));
1699 for(pcb = tcp_active_pcbs; pcb != NULL; pcb = pcb->next) {
1700 LWIP_DEBUGF(TCP_DEBUG, ("Local port %"U16_F", foreign port %"U16_F" snd_nxt %"U32_F" rcv_nxt %"U32_F" ",
1701 pcb->local_port, pcb->remote_port,
1702 pcb->snd_nxt, pcb->rcv_nxt));
1703 tcp_debug_print_state(pcb->state);
1705 LWIP_DEBUGF(TCP_DEBUG, ("Listen PCB states:\n"));
1706 for(pcb = (struct tcp_pcb *)tcp_listen_pcbs.pcbs; pcb != NULL; pcb = pcb->next) {
1707 LWIP_DEBUGF(TCP_DEBUG, ("Local port %"U16_F", foreign port %"U16_F" snd_nxt %"U32_F" rcv_nxt %"U32_F" ",
1708 pcb->local_port, pcb->remote_port,
1709 pcb->snd_nxt, pcb->rcv_nxt));
1710 tcp_debug_print_state(pcb->state);
1712 LWIP_DEBUGF(TCP_DEBUG, ("TIME-WAIT PCB states:\n"));
1713 for(pcb = tcp_tw_pcbs; pcb != NULL; pcb = pcb->next) {
1714 LWIP_DEBUGF(TCP_DEBUG, ("Local port %"U16_F", foreign port %"U16_F" snd_nxt %"U32_F" rcv_nxt %"U32_F" ",
1715 pcb->local_port, pcb->remote_port,
1716 pcb->snd_nxt, pcb->rcv_nxt));
1717 tcp_debug_print_state(pcb->state);
1722 * Check state consistency of the tcp_pcb lists.
1727 struct tcp_pcb *pcb;
1728 for(pcb = tcp_active_pcbs; pcb != NULL; pcb = pcb->next) {
1729 LWIP_ASSERT("tcp_pcbs_sane: active pcb->state != CLOSED", pcb->state != CLOSED);
1730 LWIP_ASSERT("tcp_pcbs_sane: active pcb->state != LISTEN", pcb->state != LISTEN);
1731 LWIP_ASSERT("tcp_pcbs_sane: active pcb->state != TIME-WAIT", pcb->state != TIME_WAIT);
1733 for(pcb = tcp_tw_pcbs; pcb != NULL; pcb = pcb->next) {
1734 LWIP_ASSERT("tcp_pcbs_sane: tw pcb->state == TIME-WAIT", pcb->state == TIME_WAIT);
1738 #endif /* TCP_DEBUG */
1740 #endif /* LWIP_TCP */