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"
51 #include "lwip/priv/tcp_priv.h"
52 #include "lwip/debug.h"
53 #include "lwip/stats.h"
55 #include "lwip/ip6_addr.h"
60 #ifndef TCP_LOCAL_PORT_RANGE_START
61 /* From http://www.iana.org/assignments/port-numbers:
62 "The Dynamic and/or Private Ports are those from 49152 through 65535" */
63 #define TCP_LOCAL_PORT_RANGE_START 0xc000
64 #define TCP_LOCAL_PORT_RANGE_END 0xffff
65 #define TCP_ENSURE_LOCAL_PORT_RANGE(port) ((u16_t)(((port) & ~TCP_LOCAL_PORT_RANGE_START) + TCP_LOCAL_PORT_RANGE_START))
68 #if LWIP_TCP_KEEPALIVE
69 #define TCP_KEEP_DUR(pcb) ((pcb)->keep_cnt * (pcb)->keep_intvl)
70 #define TCP_KEEP_INTVL(pcb) ((pcb)->keep_intvl)
71 #else /* LWIP_TCP_KEEPALIVE */
72 #define TCP_KEEP_DUR(pcb) TCP_MAXIDLE
73 #define TCP_KEEP_INTVL(pcb) TCP_KEEPINTVL_DEFAULT
74 #endif /* LWIP_TCP_KEEPALIVE */
76 const char * const tcp_state_str[] = {
90 /* last local TCP port */
91 static u16_t tcp_port = TCP_LOCAL_PORT_RANGE_START;
93 /* Incremented every coarse grained timer shot (typically every 500 ms). */
95 const u8_t tcp_backoff[13] =
96 { 1, 2, 3, 4, 5, 6, 7, 7, 7, 7, 7, 7, 7};
97 /* Times per slowtmr hits */
98 const u8_t tcp_persist_backoff[7] = { 3, 6, 12, 24, 48, 96, 120 };
100 /* The TCP PCB lists. */
102 /** List of all TCP PCBs bound but not yet (connected || listening) */
103 struct tcp_pcb *tcp_bound_pcbs;
104 /** List of all TCP PCBs in LISTEN state */
105 union tcp_listen_pcbs_t tcp_listen_pcbs;
106 /** List of all TCP PCBs that are in a state in which
107 * they accept or send data. */
108 struct tcp_pcb *tcp_active_pcbs;
109 /** List of all TCP PCBs in TIME-WAIT state */
110 struct tcp_pcb *tcp_tw_pcbs;
112 #define NUM_TCP_PCB_LISTS 4
113 #define NUM_TCP_PCB_LISTS_NO_TIME_WAIT 3
114 /** An array with all (non-temporary) PCB lists, mainly used for smaller code size */
115 struct tcp_pcb ** const tcp_pcb_lists[] = {&tcp_listen_pcbs.pcbs, &tcp_bound_pcbs,
116 &tcp_active_pcbs, &tcp_tw_pcbs};
118 /** Only used for temporary storage. */
119 struct tcp_pcb *tcp_tmp_pcb;
121 u8_t tcp_active_pcbs_changed;
123 /** Timer counter to handle calling slow-timer from tcp_tmr() */
124 static u8_t tcp_timer;
125 static u8_t tcp_timer_ctr;
126 static u16_t tcp_new_port(void);
129 * Initialize this module.
134 #if LWIP_RANDOMIZE_INITIAL_LOCAL_PORTS && defined(LWIP_RAND)
135 tcp_port = TCP_ENSURE_LOCAL_PORT_RANGE(LWIP_RAND());
136 #endif /* LWIP_RANDOMIZE_INITIAL_LOCAL_PORTS && defined(LWIP_RAND) */
140 * Called periodically to dispatch TCP timers.
145 /* Call tcp_fasttmr() every 250 ms */
148 if (++tcp_timer & 1) {
149 /* Call tcp_tmr() every 500 ms, i.e., every other timer
150 tcp_tmr() is called. */
156 * Closes the TX side of a connection held by the PCB.
157 * For tcp_close(), a RST is sent if the application didn't receive all data
158 * (tcp_recved() not called for all data passed to recv callback).
160 * Listening pcbs are freed and may not be referenced any more.
161 * Connection pcbs are freed if not yet connected and may not be referenced
162 * any more. If a connection is established (at least SYN received or in
163 * a closing state), the connection is closed, and put in a closing state.
164 * The pcb is then automatically freed in tcp_slowtmr(). It is therefore
165 * unsafe to reference it.
167 * @param pcb the tcp_pcb to close
168 * @return ERR_OK if connection has been closed
169 * another err_t if closing failed and pcb is not freed
172 tcp_close_shutdown(struct tcp_pcb *pcb, u8_t rst_on_unacked_data)
176 if (rst_on_unacked_data && ((pcb->state == ESTABLISHED) || (pcb->state == CLOSE_WAIT))) {
177 if ((pcb->refused_data != NULL) || (pcb->rcv_wnd != TCP_WND_MAX(pcb))) {
178 /* Not all data received by application, send RST to tell the remote
180 LWIP_ASSERT("pcb->flags & TF_RXCLOSED", pcb->flags & TF_RXCLOSED);
182 /* don't call tcp_abort here: we must not deallocate the pcb since
183 that might not be expected when calling tcp_close */
184 tcp_rst(pcb->snd_nxt, pcb->rcv_nxt, &pcb->local_ip, &pcb->remote_ip,
185 pcb->local_port, pcb->remote_port);
189 if (pcb->state == ESTABLISHED) {
190 /* move to TIME_WAIT since we close actively */
191 pcb->state = TIME_WAIT;
192 TCP_REG(&tcp_tw_pcbs, pcb);
194 /* CLOSE_WAIT: deallocate the pcb since we already sent a RST for it */
195 if (tcp_input_pcb == pcb) {
196 /* prevent using a deallocated pcb: free it from tcp_input later */
197 tcp_trigger_input_pcb_close();
199 memp_free(MEMP_TCP_PCB, pcb);
206 switch (pcb->state) {
208 /* Closing a pcb in the CLOSED state might seem erroneous,
209 * however, it is in this state once allocated and as yet unused
210 * and the user needs some way to free it should the need arise.
211 * Calling tcp_close() with a pcb that has already been closed, (i.e. twice)
212 * or for a pcb that has been used and then entered the CLOSED state
213 * is erroneous, but this should never happen as the pcb has in those cases
214 * been freed, and so any remaining handles are bogus. */
216 if (pcb->local_port != 0) {
217 TCP_RMV(&tcp_bound_pcbs, pcb);
219 memp_free(MEMP_TCP_PCB, pcb);
224 tcp_pcb_remove(&tcp_listen_pcbs.pcbs, pcb);
225 memp_free(MEMP_TCP_PCB_LISTEN, pcb);
230 TCP_PCB_REMOVE_ACTIVE(pcb);
231 memp_free(MEMP_TCP_PCB, pcb);
233 MIB2_STATS_INC(mib2.tcpattemptfails);
236 err = tcp_send_fin(pcb);
238 MIB2_STATS_INC(mib2.tcpattemptfails);
239 pcb->state = FIN_WAIT_1;
243 err = tcp_send_fin(pcb);
245 MIB2_STATS_INC(mib2.tcpestabresets);
246 pcb->state = FIN_WAIT_1;
250 err = tcp_send_fin(pcb);
252 MIB2_STATS_INC(mib2.tcpestabresets);
253 pcb->state = LAST_ACK;
257 /* Has already been closed, do nothing. */
263 if (pcb != NULL && err == ERR_OK) {
264 /* To ensure all data has been sent when tcp_close returns, we have
265 to make sure tcp_output doesn't fail.
266 Since we don't really have to ensure all data has been sent when tcp_close
267 returns (unsent data is sent from tcp timer functions, also), we don't care
268 for the return value of tcp_output for now. */
275 * Closes the connection held by the PCB.
277 * Listening pcbs are freed and may not be referenced any more.
278 * Connection pcbs are freed if not yet connected and may not be referenced
279 * any more. If a connection is established (at least SYN received or in
280 * a closing state), the connection is closed, and put in a closing state.
281 * The pcb is then automatically freed in tcp_slowtmr(). It is therefore
282 * unsafe to reference it (unless an error is returned).
284 * @param pcb the tcp_pcb to close
285 * @return ERR_OK if connection has been closed
286 * another err_t if closing failed and pcb is not freed
289 tcp_close(struct tcp_pcb *pcb)
292 LWIP_DEBUGF(TCP_DEBUG, ("tcp_close: closing in "));
293 tcp_debug_print_state(pcb->state);
294 #endif /* TCP_DEBUG */
296 if (pcb->state != LISTEN) {
297 /* Set a flag not to receive any more data... */
298 pcb->flags |= TF_RXCLOSED;
301 return tcp_close_shutdown(pcb, 1);
305 * Causes all or part of a full-duplex connection of this PCB to be shut down.
306 * This doesn't deallocate the PCB unless shutting down both sides!
307 * Shutting down both sides is the same as calling tcp_close, so if it succeds,
308 * the PCB should not be referenced any more.
310 * @param pcb PCB to shutdown
311 * @param shut_rx shut down receive side if this is != 0
312 * @param shut_tx shut down send side if this is != 0
313 * @return ERR_OK if shutdown succeeded (or the PCB has already been shut down)
314 * another err_t on error.
317 tcp_shutdown(struct tcp_pcb *pcb, int shut_rx, int shut_tx)
319 if (pcb->state == LISTEN) {
323 /* shut down the receive side: set a flag not to receive any more data... */
324 pcb->flags |= TF_RXCLOSED;
326 /* shutting down the tx AND rx side is the same as closing for the raw API */
327 return tcp_close_shutdown(pcb, 1);
329 /* ... and free buffered data */
330 if (pcb->refused_data != NULL) {
331 pbuf_free(pcb->refused_data);
332 pcb->refused_data = NULL;
336 /* This can't happen twice since if it succeeds, the pcb's state is changed.
337 Only close in these states as the others directly deallocate the PCB */
338 switch (pcb->state) {
342 return tcp_close_shutdown(pcb, (u8_t)shut_rx);
344 /* Not (yet?) connected, cannot shutdown the TX side as that would bring us
345 into CLOSED state, where the PCB is deallocated. */
353 * Abandons a connection and optionally sends a RST to the remote
354 * host. Deletes the local protocol control block. This is done when
355 * a connection is killed because of shortage of memory.
357 * @param pcb the tcp_pcb to abort
358 * @param reset boolean to indicate whether a reset should be sent
361 tcp_abandon(struct tcp_pcb *pcb, int reset)
364 #if LWIP_CALLBACK_API
366 #endif /* LWIP_CALLBACK_API */
369 /* pcb->state LISTEN not allowed here */
370 LWIP_ASSERT("don't call tcp_abort/tcp_abandon for listen-pcbs",
371 pcb->state != LISTEN);
372 /* Figure out on which TCP PCB list we are, and remove us. If we
373 are in an active state, call the receive function associated with
374 the PCB with a NULL argument, and send an RST to the remote end. */
375 if (pcb->state == TIME_WAIT) {
376 tcp_pcb_remove(&tcp_tw_pcbs, pcb);
377 memp_free(MEMP_TCP_PCB, pcb);
380 u16_t local_port = 0;
381 seqno = pcb->snd_nxt;
382 ackno = pcb->rcv_nxt;
383 #if LWIP_CALLBACK_API
385 #endif /* LWIP_CALLBACK_API */
386 errf_arg = pcb->callback_arg;
387 if ((pcb->state == CLOSED) && (pcb->local_port != 0)) {
388 /* bound, not yet opened */
389 TCP_RMV(&tcp_bound_pcbs, pcb);
392 local_port = pcb->local_port;
393 TCP_PCB_REMOVE_ACTIVE(pcb);
395 if (pcb->unacked != NULL) {
396 tcp_segs_free(pcb->unacked);
398 if (pcb->unsent != NULL) {
399 tcp_segs_free(pcb->unsent);
402 if (pcb->ooseq != NULL) {
403 tcp_segs_free(pcb->ooseq);
405 #endif /* TCP_QUEUE_OOSEQ */
407 LWIP_DEBUGF(TCP_RST_DEBUG, ("tcp_abandon: sending RST\n"));
408 tcp_rst(seqno, ackno, &pcb->local_ip, &pcb->remote_ip, local_port, pcb->remote_port);
410 memp_free(MEMP_TCP_PCB, pcb);
411 TCP_EVENT_ERR(errf, errf_arg, ERR_ABRT);
416 * Aborts the connection by sending a RST (reset) segment to the remote
417 * host. The pcb is deallocated. This function never fails.
419 * ATTENTION: When calling this from one of the TCP callbacks, make
420 * sure you always return ERR_ABRT (and never return ERR_ABRT otherwise
421 * or you will risk accessing deallocated memory or memory leaks!
423 * @param pcb the tcp pcb to abort
426 tcp_abort(struct tcp_pcb *pcb)
432 * Binds the connection to a local port number and IP address. If the
433 * IP address is not given (i.e., ipaddr == NULL), the IP address of
434 * the outgoing network interface is used instead.
436 * @param pcb the tcp_pcb to bind (no check is done whether this pcb is
438 * @param ipaddr the local ip address to bind to (use IP_ADDR_ANY to bind
439 * to any local address
440 * @param port the local port to bind to
441 * @return ERR_USE if the port is already in use
442 * ERR_VAL if bind failed because the PCB is not in a valid state
446 tcp_bind(struct tcp_pcb *pcb, const ip_addr_t *ipaddr, u16_t port)
449 int max_pcb_list = NUM_TCP_PCB_LISTS;
450 struct tcp_pcb *cpcb;
452 if ((pcb == NULL) || !IP_ADDR_PCB_VERSION_MATCH(pcb, ipaddr)) {
456 LWIP_ERROR("tcp_bind: can only bind in state CLOSED", pcb->state == CLOSED, return ERR_VAL);
459 /* Unless the REUSEADDR flag is set,
460 we have to check the pcbs in TIME-WAIT state, also.
461 We do not dump TIME_WAIT pcb's; they can still be matched by incoming
462 packets using both local and remote IP addresses and ports to distinguish.
464 if (ip_get_option(pcb, SOF_REUSEADDR)) {
465 max_pcb_list = NUM_TCP_PCB_LISTS_NO_TIME_WAIT;
467 #endif /* SO_REUSE */
470 port = tcp_new_port();
476 /* Check if the address already is in use (on all lists) */
477 for (i = 0; i < max_pcb_list; i++) {
478 for (cpcb = *tcp_pcb_lists[i]; cpcb != NULL; cpcb = cpcb->next) {
479 if (cpcb->local_port == port) {
481 /* Omit checking for the same port if both pcbs have REUSEADDR set.
482 For SO_REUSEADDR, the duplicate-check for a 5-tuple is done in
484 if (!ip_get_option(pcb, SOF_REUSEADDR) ||
485 !ip_get_option(cpcb, SOF_REUSEADDR))
486 #endif /* SO_REUSE */
488 /* @todo: check accept_any_ip_version */
489 if (IP_PCB_IPVER_EQ(pcb, cpcb) &&
490 (ip_addr_isany(&cpcb->local_ip) ||
491 ip_addr_isany(ipaddr) ||
492 ip_addr_cmp(&cpcb->local_ip, ipaddr))) {
500 if (!ip_addr_isany(ipaddr)) {
501 ip_addr_set(&pcb->local_ip, ipaddr);
503 pcb->local_port = port;
504 TCP_REG(&tcp_bound_pcbs, pcb);
505 LWIP_DEBUGF(TCP_DEBUG, ("tcp_bind: bind to port %"U16_F"\n", port));
508 #if LWIP_CALLBACK_API
510 * Default accept callback if no accept callback is specified by the user.
513 tcp_accept_null(void *arg, struct tcp_pcb *pcb, err_t err)
515 LWIP_UNUSED_ARG(arg);
516 LWIP_UNUSED_ARG(pcb);
517 LWIP_UNUSED_ARG(err);
521 #endif /* LWIP_CALLBACK_API */
524 * Set the state of the connection to be LISTEN, which means that it
525 * is able to accept incoming connections. The protocol control block
526 * is reallocated in order to consume less memory. Setting the
527 * connection to LISTEN is an irreversible process.
529 * @param pcb the original tcp_pcb
530 * @param backlog the incoming connections queue limit
531 * @return tcp_pcb used for listening, consumes less memory.
533 * @note The original tcp_pcb is freed. This function therefore has to be
535 * tpcb = tcp_listen(tpcb);
538 tcp_listen_with_backlog(struct tcp_pcb *pcb, u8_t backlog)
540 struct tcp_pcb_listen *lpcb;
542 LWIP_UNUSED_ARG(backlog);
543 LWIP_ERROR("tcp_listen: pcb already connected", pcb->state == CLOSED, return NULL);
545 /* already listening? */
546 if (pcb->state == LISTEN) {
550 if (ip_get_option(pcb, SOF_REUSEADDR)) {
551 /* Since SOF_REUSEADDR allows reusing a local address before the pcb's usage
552 is declared (listen-/connection-pcb), we have to make sure now that
553 this port is only used once for every local IP. */
554 for (lpcb = tcp_listen_pcbs.listen_pcbs; lpcb != NULL; lpcb = lpcb->next) {
555 if ((lpcb->local_port == pcb->local_port) &&
556 IP_PCB_IPVER_EQ(pcb, lpcb)) {
557 if (ip_addr_cmp(&lpcb->local_ip, &pcb->local_ip)) {
558 /* this address/port is already used */
564 #endif /* SO_REUSE */
565 lpcb = (struct tcp_pcb_listen *)memp_malloc(MEMP_TCP_PCB_LISTEN);
569 lpcb->callback_arg = pcb->callback_arg;
570 lpcb->local_port = pcb->local_port;
571 lpcb->state = LISTEN;
572 lpcb->prio = pcb->prio;
573 lpcb->so_options = pcb->so_options;
574 lpcb->ttl = pcb->ttl;
575 lpcb->tos = pcb->tos;
576 #if LWIP_IPV4 && LWIP_IPV6
577 PCB_ISIPV6(lpcb) = PCB_ISIPV6(pcb);
578 lpcb->accept_any_ip_version = 0;
579 #endif /* LWIP_IPV4 && LWIP_IPV6 */
580 ip_addr_copy(lpcb->local_ip, pcb->local_ip);
581 if (pcb->local_port != 0) {
582 TCP_RMV(&tcp_bound_pcbs, pcb);
584 memp_free(MEMP_TCP_PCB, pcb);
585 #if LWIP_CALLBACK_API
586 lpcb->accept = tcp_accept_null;
587 #endif /* LWIP_CALLBACK_API */
588 #if TCP_LISTEN_BACKLOG
589 lpcb->accepts_pending = 0;
590 lpcb->backlog = (backlog ? backlog : 1);
591 #endif /* TCP_LISTEN_BACKLOG */
592 TCP_REG(&tcp_listen_pcbs.pcbs, (struct tcp_pcb *)lpcb);
593 return (struct tcp_pcb *)lpcb;
596 #if LWIP_IPV4 && LWIP_IPV6
598 * Same as tcp_listen_with_backlog, but allows to accept IPv4 and IPv6
599 * connections, if the pcb's local address is set to ANY.
602 tcp_listen_dual_with_backlog(struct tcp_pcb *pcb, u8_t backlog)
604 struct tcp_pcb *lpcb;
605 struct tcp_pcb_listen *l;
607 if (pcb->local_port != 0) {
608 /* Check that there's noone listening on this port already
609 (don't check the IP address since we'll set it to ANY */
610 for (l = tcp_listen_pcbs.listen_pcbs; l != NULL; l = l->next) {
611 if (l->local_port == pcb->local_port) {
612 /* this port is already used */
618 lpcb = tcp_listen_with_backlog(pcb, backlog);
619 if ((lpcb != NULL) &&
620 ip_addr_isany(&pcb->local_ip)) {
621 /* The default behavior is to accept connections on either
622 * IPv4 or IPv6, if not bound. */
623 /* @see NETCONN_FLAG_IPV6_V6ONLY for changing this behavior */
624 ((struct tcp_pcb_listen*)lpcb)->accept_any_ip_version = 1;
628 #endif /* LWIP_IPV4 && LWIP_IPV6 */
631 * Update the state that tracks the available window space to advertise.
633 * Returns how much extra window would be advertised if we sent an
636 u32_t tcp_update_rcv_ann_wnd(struct tcp_pcb *pcb)
638 u32_t new_right_edge = pcb->rcv_nxt + pcb->rcv_wnd;
640 if (TCP_SEQ_GEQ(new_right_edge, pcb->rcv_ann_right_edge + LWIP_MIN((TCP_WND / 2), pcb->mss))) {
641 /* we can advertise more window */
642 pcb->rcv_ann_wnd = pcb->rcv_wnd;
643 return new_right_edge - pcb->rcv_ann_right_edge;
645 if (TCP_SEQ_GT(pcb->rcv_nxt, pcb->rcv_ann_right_edge)) {
646 /* Can happen due to other end sending out of advertised window,
647 * but within actual available (but not yet advertised) window */
648 pcb->rcv_ann_wnd = 0;
650 /* keep the right edge of window constant */
651 u32_t new_rcv_ann_wnd = pcb->rcv_ann_right_edge - pcb->rcv_nxt;
653 LWIP_ASSERT("new_rcv_ann_wnd <= 0xffff", new_rcv_ann_wnd <= 0xffff);
655 pcb->rcv_ann_wnd = (tcpwnd_size_t)new_rcv_ann_wnd;
662 * This function should be called by the application when it has
663 * processed the data. The purpose is to advertise a larger window
664 * when the data has been processed.
666 * @param pcb the tcp_pcb for which data is read
667 * @param len the amount of bytes that have been read by the application
670 tcp_recved(struct tcp_pcb *pcb, u16_t len)
674 /* pcb->state LISTEN not allowed here */
675 LWIP_ASSERT("don't call tcp_recved for listen-pcbs",
676 pcb->state != LISTEN);
679 if (pcb->rcv_wnd > TCP_WND_MAX(pcb)) {
680 pcb->rcv_wnd = TCP_WND_MAX(pcb);
681 } else if (pcb->rcv_wnd == 0) {
682 /* rcv_wnd overflowed */
683 if ((pcb->state == CLOSE_WAIT) || (pcb->state == LAST_ACK)) {
684 /* In passive close, we allow this, since the FIN bit is added to rcv_wnd
685 by the stack itself, since it is not mandatory for an application
686 to call tcp_recved() for the FIN bit, but e.g. the netconn API does so. */
687 pcb->rcv_wnd = TCP_WND_MAX(pcb);
689 LWIP_ASSERT("tcp_recved: len wrapped rcv_wnd\n", 0);
693 wnd_inflation = tcp_update_rcv_ann_wnd(pcb);
695 /* If the change in the right edge of window is significant (default
696 * watermark is TCP_WND/4), then send an explicit update now.
697 * Otherwise wait for a packet to be sent in the normal course of
698 * events (or more window to be available later) */
699 if (wnd_inflation >= TCP_WND_UPDATE_THRESHOLD) {
704 LWIP_DEBUGF(TCP_DEBUG, ("tcp_recved: received %"U16_F" bytes, wnd %"TCPWNDSIZE_F" (%"TCPWNDSIZE_F").\n",
705 len, pcb->rcv_wnd, TCP_WND_MAX(pcb) - pcb->rcv_wnd));
709 * Allocate a new local TCP port.
711 * @return a new (free) local TCP port number
721 if (tcp_port++ == TCP_LOCAL_PORT_RANGE_END) {
722 tcp_port = TCP_LOCAL_PORT_RANGE_START;
724 /* Check all PCB lists. */
725 for (i = 0; i < NUM_TCP_PCB_LISTS; i++) {
726 for (pcb = *tcp_pcb_lists[i]; pcb != NULL; pcb = pcb->next) {
727 if (pcb->local_port == tcp_port) {
728 if (++n > (TCP_LOCAL_PORT_RANGE_END - TCP_LOCAL_PORT_RANGE_START)) {
739 * Connects to another host. The function given as the "connected"
740 * argument will be called when the connection has been established.
742 * @param pcb the tcp_pcb used to establish the connection
743 * @param ipaddr the remote ip address to connect to
744 * @param port the remote tcp port to connect to
745 * @param connected callback function to call when connected (on error,
746 the err calback will be called)
747 * @return ERR_VAL if invalid arguments are given
748 * ERR_OK if connect request has been sent
749 * other err_t values if connect request couldn't be sent
752 tcp_connect(struct tcp_pcb *pcb, const ip_addr_t *ipaddr, u16_t port,
753 tcp_connected_fn connected)
757 u16_t old_local_port;
759 if ((pcb == NULL) || !IP_ADDR_PCB_VERSION_MATCH(pcb, ipaddr)) {
763 LWIP_ERROR("tcp_connect: can only connect from state CLOSED", pcb->state == CLOSED, return ERR_ISCONN);
765 LWIP_DEBUGF(TCP_DEBUG, ("tcp_connect to port %"U16_F"\n", port));
766 if (ipaddr != NULL) {
767 ip_addr_set(&pcb->remote_ip, ipaddr);
771 pcb->remote_port = port;
773 /* check if we have a route to the remote host */
774 if (ip_addr_isany(&pcb->local_ip)) {
775 /* no local IP address set, yet. */
777 const ip_addr_t *local_ip;
778 ip_route_get_local_ip(PCB_ISIPV6(pcb), &pcb->local_ip, &pcb->remote_ip, netif, local_ip);
779 if ((netif == NULL) || (local_ip == NULL)) {
780 /* Don't even try to send a SYN packet if we have no route
781 since that will fail. */
784 /* Use the address as local address of the pcb. */
785 ip_addr_copy(pcb->local_ip, *local_ip);
788 old_local_port = pcb->local_port;
789 if (pcb->local_port == 0) {
790 pcb->local_port = tcp_new_port();
791 if (pcb->local_port == 0) {
796 if (ip_get_option(pcb, SOF_REUSEADDR)) {
797 /* Since SOF_REUSEADDR allows reusing a local address, we have to make sure
798 now that the 5-tuple is unique. */
799 struct tcp_pcb *cpcb;
801 /* Don't check listen- and bound-PCBs, check active- and TIME-WAIT PCBs. */
802 for (i = 2; i < NUM_TCP_PCB_LISTS; i++) {
803 for (cpcb = *tcp_pcb_lists[i]; cpcb != NULL; cpcb = cpcb->next) {
804 if ((cpcb->local_port == pcb->local_port) &&
805 (cpcb->remote_port == port) &&
806 IP_PCB_IPVER_EQ(cpcb, pcb) &&
807 ip_addr_cmp(&cpcb->local_ip, &pcb->local_ip) &&
808 ip_addr_cmp(&cpcb->remote_ip, ipaddr)) {
809 /* linux returns EISCONN here, but ERR_USE should be OK for us */
815 #endif /* SO_REUSE */
816 iss = tcp_next_iss();
819 pcb->lastack = iss - 1;
820 pcb->snd_lbb = iss - 1;
821 /* Start with a window that does not need scaling. When window scaling is
822 enabled and used, the window is enlarged when both sides agree on scaling. */
823 pcb->rcv_wnd = pcb->rcv_ann_wnd = TCPWND_MIN16(TCP_WND);
824 pcb->rcv_ann_right_edge = pcb->rcv_nxt;
825 pcb->snd_wnd = TCP_WND;
826 /* As initial send MSS, we use TCP_MSS but limit it to 536.
827 The send MSS is updated when an MSS option is received. */
828 pcb->mss = (TCP_MSS > 536) ? 536 : TCP_MSS;
829 #if TCP_CALCULATE_EFF_SEND_MSS
830 pcb->mss = tcp_eff_send_mss(pcb->mss, &pcb->local_ip, &pcb->remote_ip, PCB_ISIPV6(pcb));
831 #endif /* TCP_CALCULATE_EFF_SEND_MSS */
833 pcb->ssthresh = TCP_WND;
834 #if LWIP_CALLBACK_API
835 pcb->connected = connected;
836 #else /* LWIP_CALLBACK_API */
837 LWIP_UNUSED_ARG(connected);
838 #endif /* LWIP_CALLBACK_API */
840 /* Send a SYN together with the MSS option. */
841 ret = tcp_enqueue_flags(pcb, TCP_SYN);
843 /* SYN segment was enqueued, changed the pcbs state now */
844 pcb->state = SYN_SENT;
845 if (old_local_port != 0) {
846 TCP_RMV(&tcp_bound_pcbs, pcb);
849 MIB2_STATS_INC(mib2.tcpactiveopens);
857 * Called every 500 ms and implements the retransmission timer and the timer that
858 * removes PCBs that have been in TIME-WAIT for enough time. It also increments
859 * various timers such as the inactivity timer in each PCB.
861 * Automatically called from tcp_tmr().
866 struct tcp_pcb *pcb, *prev;
867 tcpwnd_size_t eff_wnd;
868 u8_t pcb_remove; /* flag if a PCB should be removed */
869 u8_t pcb_reset; /* flag if a RST should be sent when removing */
878 /* Steps through all of the active PCBs. */
880 pcb = tcp_active_pcbs;
882 LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: no active pcbs\n"));
884 while (pcb != NULL) {
885 LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: processing active pcb\n"));
886 LWIP_ASSERT("tcp_slowtmr: active pcb->state != CLOSED\n", pcb->state != CLOSED);
887 LWIP_ASSERT("tcp_slowtmr: active pcb->state != LISTEN\n", pcb->state != LISTEN);
888 LWIP_ASSERT("tcp_slowtmr: active pcb->state != TIME-WAIT\n", pcb->state != TIME_WAIT);
889 if (pcb->last_timer == tcp_timer_ctr) {
890 /* skip this pcb, we have already processed it */
894 pcb->last_timer = tcp_timer_ctr;
899 if (pcb->state == SYN_SENT && pcb->nrtx == TCP_SYNMAXRTX) {
901 LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: max SYN retries reached\n"));
903 else if (pcb->nrtx == TCP_MAXRTX) {
905 LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: max DATA retries reached\n"));
907 if (pcb->persist_backoff > 0) {
908 /* If snd_wnd is zero, use persist timer to send 1 byte probes
909 * instead of using the standard retransmission mechanism. */
910 u8_t backoff_cnt = tcp_persist_backoff[pcb->persist_backoff-1];
911 if (pcb->persist_cnt < backoff_cnt) {
914 if (pcb->persist_cnt >= backoff_cnt) {
915 if (tcp_zero_window_probe(pcb) == ERR_OK) {
916 pcb->persist_cnt = 0;
917 if (pcb->persist_backoff < sizeof(tcp_persist_backoff)) {
918 pcb->persist_backoff++;
923 /* Increase the retransmission timer if it is running */
924 if (pcb->rtime >= 0) {
928 if (pcb->unacked != NULL && pcb->rtime >= pcb->rto) {
929 /* Time for a retransmission. */
930 LWIP_DEBUGF(TCP_RTO_DEBUG, ("tcp_slowtmr: rtime %"S16_F
931 " pcb->rto %"S16_F"\n",
932 pcb->rtime, pcb->rto));
934 /* Double retransmission time-out unless we are trying to
935 * connect to somebody (i.e., we are in SYN_SENT). */
936 if (pcb->state != SYN_SENT) {
937 pcb->rto = ((pcb->sa >> 3) + pcb->sv) << tcp_backoff[pcb->nrtx];
940 /* Reset the retransmission timer. */
943 /* Reduce congestion window and ssthresh. */
944 eff_wnd = LWIP_MIN(pcb->cwnd, pcb->snd_wnd);
945 pcb->ssthresh = eff_wnd >> 1;
946 if (pcb->ssthresh < (tcpwnd_size_t)(pcb->mss << 1)) {
947 pcb->ssthresh = (pcb->mss << 1);
949 pcb->cwnd = pcb->mss;
950 LWIP_DEBUGF(TCP_CWND_DEBUG, ("tcp_slowtmr: cwnd %"TCPWNDSIZE_F
951 " ssthresh %"TCPWNDSIZE_F"\n",
952 pcb->cwnd, pcb->ssthresh));
954 /* The following needs to be called AFTER cwnd is set to one
960 /* Check if this PCB has stayed too long in FIN-WAIT-2 */
961 if (pcb->state == FIN_WAIT_2) {
962 /* If this PCB is in FIN_WAIT_2 because of SHUT_WR don't let it time out. */
963 if (pcb->flags & TF_RXCLOSED) {
964 /* PCB was fully closed (either through close() or SHUT_RDWR):
965 normal FIN-WAIT timeout handling. */
966 if ((u32_t)(tcp_ticks - pcb->tmr) >
967 TCP_FIN_WAIT_TIMEOUT / TCP_SLOW_INTERVAL) {
969 LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: removing pcb stuck in FIN-WAIT-2\n"));
974 /* Check if KEEPALIVE should be sent */
975 if (ip_get_option(pcb, SOF_KEEPALIVE) &&
976 ((pcb->state == ESTABLISHED) ||
977 (pcb->state == CLOSE_WAIT))) {
978 if ((u32_t)(tcp_ticks - pcb->tmr) >
979 (pcb->keep_idle + TCP_KEEP_DUR(pcb)) / TCP_SLOW_INTERVAL)
981 LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: KEEPALIVE timeout. Aborting connection to "));
982 ip_addr_debug_print(TCP_DEBUG, &pcb->remote_ip);
983 LWIP_DEBUGF(TCP_DEBUG, ("\n"));
987 } else if ((u32_t)(tcp_ticks - pcb->tmr) >
988 (pcb->keep_idle + pcb->keep_cnt_sent * TCP_KEEP_INTVL(pcb))
991 err = tcp_keepalive(pcb);
993 pcb->keep_cnt_sent++;
998 /* If this PCB has queued out of sequence data, but has been
999 inactive for too long, will drop the data (it will eventually
1000 be retransmitted). */
1002 if (pcb->ooseq != NULL &&
1003 (u32_t)tcp_ticks - pcb->tmr >= pcb->rto * TCP_OOSEQ_TIMEOUT) {
1004 tcp_segs_free(pcb->ooseq);
1006 LWIP_DEBUGF(TCP_CWND_DEBUG, ("tcp_slowtmr: dropping OOSEQ queued data\n"));
1008 #endif /* TCP_QUEUE_OOSEQ */
1010 /* Check if this PCB has stayed too long in SYN-RCVD */
1011 if (pcb->state == SYN_RCVD) {
1012 if ((u32_t)(tcp_ticks - pcb->tmr) >
1013 TCP_SYN_RCVD_TIMEOUT / TCP_SLOW_INTERVAL) {
1015 LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: removing pcb stuck in SYN-RCVD\n"));
1019 /* Check if this PCB has stayed too long in LAST-ACK */
1020 if (pcb->state == LAST_ACK) {
1021 if ((u32_t)(tcp_ticks - pcb->tmr) > 2 * TCP_MSL / TCP_SLOW_INTERVAL) {
1023 LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: removing pcb stuck in LAST-ACK\n"));
1027 /* If the PCB should be removed, do it. */
1029 struct tcp_pcb *pcb2;
1033 /* Remove PCB from tcp_active_pcbs list. */
1035 LWIP_ASSERT("tcp_slowtmr: middle tcp != tcp_active_pcbs", pcb != tcp_active_pcbs);
1036 prev->next = pcb->next;
1038 /* This PCB was the first. */
1039 LWIP_ASSERT("tcp_slowtmr: first pcb == tcp_active_pcbs", tcp_active_pcbs == pcb);
1040 tcp_active_pcbs = pcb->next;
1044 tcp_rst(pcb->snd_nxt, pcb->rcv_nxt, &pcb->local_ip, &pcb->remote_ip,
1045 pcb->local_port, pcb->remote_port);
1049 err_arg = pcb->callback_arg;
1052 memp_free(MEMP_TCP_PCB, pcb2);
1054 tcp_active_pcbs_changed = 0;
1055 TCP_EVENT_ERR(err_fn, err_arg, ERR_ABRT);
1056 if (tcp_active_pcbs_changed) {
1057 goto tcp_slowtmr_start;
1060 /* get the 'next' element now and work with 'prev' below (in case of abort) */
1064 /* We check if we should poll the connection. */
1066 if (prev->polltmr >= prev->pollinterval) {
1068 LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: polling application\n"));
1069 tcp_active_pcbs_changed = 0;
1070 TCP_EVENT_POLL(prev, err);
1071 if (tcp_active_pcbs_changed) {
1072 goto tcp_slowtmr_start;
1074 /* if err == ERR_ABRT, 'prev' is already deallocated */
1075 if (err == ERR_OK) {
1083 /* Steps through all of the TIME-WAIT PCBs. */
1086 while (pcb != NULL) {
1087 LWIP_ASSERT("tcp_slowtmr: TIME-WAIT pcb->state == TIME-WAIT", pcb->state == TIME_WAIT);
1090 /* Check if this PCB has stayed long enough in TIME-WAIT */
1091 if ((u32_t)(tcp_ticks - pcb->tmr) > 2 * TCP_MSL / TCP_SLOW_INTERVAL) {
1095 /* If the PCB should be removed, do it. */
1097 struct tcp_pcb *pcb2;
1099 /* Remove PCB from tcp_tw_pcbs list. */
1101 LWIP_ASSERT("tcp_slowtmr: middle tcp != tcp_tw_pcbs", pcb != tcp_tw_pcbs);
1102 prev->next = pcb->next;
1104 /* This PCB was the first. */
1105 LWIP_ASSERT("tcp_slowtmr: first pcb == tcp_tw_pcbs", tcp_tw_pcbs == pcb);
1106 tcp_tw_pcbs = pcb->next;
1110 memp_free(MEMP_TCP_PCB, pcb2);
1119 * Is called every TCP_FAST_INTERVAL (250 ms) and process data previously
1120 * "refused" by upper layer (application) and sends delayed ACKs.
1122 * Automatically called from tcp_tmr().
1127 struct tcp_pcb *pcb;
1132 pcb = tcp_active_pcbs;
1134 while (pcb != NULL) {
1135 if (pcb->last_timer != tcp_timer_ctr) {
1136 struct tcp_pcb *next;
1137 pcb->last_timer = tcp_timer_ctr;
1138 /* send delayed ACKs */
1139 if (pcb->flags & TF_ACK_DELAY) {
1140 LWIP_DEBUGF(TCP_DEBUG, ("tcp_fasttmr: delayed ACK\n"));
1143 pcb->flags &= ~(TF_ACK_DELAY | TF_ACK_NOW);
1148 /* If there is data which was previously "refused" by upper layer */
1149 if (pcb->refused_data != NULL) {
1150 tcp_active_pcbs_changed = 0;
1151 tcp_process_refused_data(pcb);
1152 if (tcp_active_pcbs_changed) {
1153 /* application callback has changed the pcb list: restart the loop */
1154 goto tcp_fasttmr_start;
1164 /** Call tcp_output for all active pcbs that have TF_NAGLEMEMERR set */
1168 struct tcp_pcb *pcb;
1170 for (pcb = tcp_active_pcbs; pcb != NULL; pcb = pcb->next) {
1171 if (pcb->flags & TF_NAGLEMEMERR) {
1177 /** Pass pcb->refused_data to the recv callback */
1179 tcp_process_refused_data(struct tcp_pcb *pcb)
1181 #if TCP_QUEUE_OOSEQ && LWIP_WND_SCALE
1183 while (pcb->refused_data != NULL)
1184 #endif /* TCP_QUEUE_OOSEQ && LWIP_WND_SCALE */
1187 u8_t refused_flags = pcb->refused_data->flags;
1188 /* set pcb->refused_data to NULL in case the callback frees it and then
1190 struct pbuf *refused_data = pcb->refused_data;
1191 #if TCP_QUEUE_OOSEQ && LWIP_WND_SCALE
1192 pbuf_split_64k(refused_data, &rest);
1193 pcb->refused_data = rest;
1194 #else /* TCP_QUEUE_OOSEQ && LWIP_WND_SCALE */
1195 pcb->refused_data = NULL;
1196 #endif /* TCP_QUEUE_OOSEQ && LWIP_WND_SCALE */
1197 /* Notify again application with data previously received. */
1198 LWIP_DEBUGF(TCP_INPUT_DEBUG, ("tcp_input: notify kept packet\n"));
1199 TCP_EVENT_RECV(pcb, refused_data, ERR_OK, err);
1200 if (err == ERR_OK) {
1201 /* did refused_data include a FIN? */
1202 if (refused_flags & PBUF_FLAG_TCP_FIN
1203 #if TCP_QUEUE_OOSEQ && LWIP_WND_SCALE
1205 #endif /* TCP_QUEUE_OOSEQ && LWIP_WND_SCALE */
1207 /* correct rcv_wnd as the application won't call tcp_recved()
1208 for the FIN's seqno */
1209 if (pcb->rcv_wnd != TCP_WND_MAX(pcb)) {
1212 TCP_EVENT_CLOSED(pcb, err);
1213 if (err == ERR_ABRT) {
1217 } else if (err == ERR_ABRT) {
1218 /* if err == ERR_ABRT, 'pcb' is already deallocated */
1219 /* Drop incoming packets because pcb is "full" (only if the incoming
1220 segment contains data). */
1221 LWIP_DEBUGF(TCP_INPUT_DEBUG, ("tcp_input: drop incoming packets, because pcb is \"full\"\n"));
1224 /* data is still refused, pbuf is still valid (go on for ACK-only packets) */
1225 #if TCP_QUEUE_OOSEQ && LWIP_WND_SCALE
1227 pbuf_cat(refused_data, rest);
1229 #endif /* TCP_QUEUE_OOSEQ && LWIP_WND_SCALE */
1230 pcb->refused_data = refused_data;
1231 return ERR_INPROGRESS;
1238 * Deallocates a list of TCP segments (tcp_seg structures).
1240 * @param seg tcp_seg list of TCP segments to free
1243 tcp_segs_free(struct tcp_seg *seg)
1245 while (seg != NULL) {
1246 struct tcp_seg *next = seg->next;
1253 * Frees a TCP segment (tcp_seg structure).
1255 * @param seg single tcp_seg to free
1258 tcp_seg_free(struct tcp_seg *seg)
1261 if (seg->p != NULL) {
1265 #endif /* TCP_DEBUG */
1267 memp_free(MEMP_TCP_SEG, seg);
1272 * Sets the priority of a connection.
1274 * @param pcb the tcp_pcb to manipulate
1275 * @param prio new priority
1278 tcp_setprio(struct tcp_pcb *pcb, u8_t prio)
1285 * Returns a copy of the given TCP segment.
1286 * The pbuf and data are not copied, only the pointers
1288 * @param seg the old tcp_seg
1289 * @return a copy of seg
1292 tcp_seg_copy(struct tcp_seg *seg)
1294 struct tcp_seg *cseg;
1296 cseg = (struct tcp_seg *)memp_malloc(MEMP_TCP_SEG);
1300 SMEMCPY((u8_t *)cseg, (const u8_t *)seg, sizeof(struct tcp_seg));
1304 #endif /* TCP_QUEUE_OOSEQ */
1306 #if LWIP_CALLBACK_API
1308 * Default receive callback that is called if the user didn't register
1309 * a recv callback for the pcb.
1312 tcp_recv_null(void *arg, struct tcp_pcb *pcb, struct pbuf *p, err_t err)
1314 LWIP_UNUSED_ARG(arg);
1316 tcp_recved(pcb, p->tot_len);
1318 } else if (err == ERR_OK) {
1319 return tcp_close(pcb);
1323 #endif /* LWIP_CALLBACK_API */
1326 * Kills the oldest active connection that has the same or lower priority than
1329 * @param prio minimum priority
1332 tcp_kill_prio(u8_t prio)
1334 struct tcp_pcb *pcb, *inactive;
1338 mprio = TCP_PRIO_MAX;
1340 /* We kill the oldest active connection that has lower priority than prio. */
1343 for (pcb = tcp_active_pcbs; pcb != NULL; pcb = pcb->next) {
1344 if (pcb->prio <= prio &&
1345 pcb->prio <= mprio &&
1346 (u32_t)(tcp_ticks - pcb->tmr) >= inactivity) {
1347 inactivity = tcp_ticks - pcb->tmr;
1352 if (inactive != NULL) {
1353 LWIP_DEBUGF(TCP_DEBUG, ("tcp_kill_prio: killing oldest PCB %p (%"S32_F")\n",
1354 (void *)inactive, inactivity));
1355 tcp_abort(inactive);
1360 * Kills the oldest connection that is in specific state.
1361 * Called from tcp_alloc() for LAST_ACK and CLOSING if no more connections are available.
1364 tcp_kill_state(enum tcp_state state)
1366 struct tcp_pcb *pcb, *inactive;
1369 LWIP_ASSERT("invalid state", (state == CLOSING) || (state == LAST_ACK));
1373 /* Go through the list of active pcbs and get the oldest pcb that is in state
1374 CLOSING/LAST_ACK. */
1375 for (pcb = tcp_active_pcbs; pcb != NULL; pcb = pcb->next) {
1376 if (pcb->state == state) {
1377 if ((u32_t)(tcp_ticks - pcb->tmr) >= inactivity) {
1378 inactivity = tcp_ticks - pcb->tmr;
1383 if (inactive != NULL) {
1384 LWIP_DEBUGF(TCP_DEBUG, ("tcp_kill_closing: killing oldest %s PCB %p (%"S32_F")\n",
1385 tcp_state_str[state], (void *)inactive, inactivity));
1386 /* Don't send a RST, since no data is lost. */
1387 tcp_abandon(inactive, 0);
1392 * Kills the oldest connection that is in TIME_WAIT state.
1393 * Called from tcp_alloc() if no more connections are available.
1396 tcp_kill_timewait(void)
1398 struct tcp_pcb *pcb, *inactive;
1403 /* Go through the list of TIME_WAIT pcbs and get the oldest pcb. */
1404 for (pcb = tcp_tw_pcbs; pcb != NULL; pcb = pcb->next) {
1405 if ((u32_t)(tcp_ticks - pcb->tmr) >= inactivity) {
1406 inactivity = tcp_ticks - pcb->tmr;
1410 if (inactive != NULL) {
1411 LWIP_DEBUGF(TCP_DEBUG, ("tcp_kill_timewait: killing oldest TIME-WAIT PCB %p (%"S32_F")\n",
1412 (void *)inactive, inactivity));
1413 tcp_abort(inactive);
1418 * Allocate a new tcp_pcb structure.
1420 * @param prio priority for the new pcb
1421 * @return a new tcp_pcb that initially is in state CLOSED
1424 tcp_alloc(u8_t prio)
1426 struct tcp_pcb *pcb;
1429 pcb = (struct tcp_pcb *)memp_malloc(MEMP_TCP_PCB);
1431 /* Try killing oldest connection in TIME-WAIT. */
1432 LWIP_DEBUGF(TCP_DEBUG, ("tcp_alloc: killing off oldest TIME-WAIT connection\n"));
1433 tcp_kill_timewait();
1434 /* Try to allocate a tcp_pcb again. */
1435 pcb = (struct tcp_pcb *)memp_malloc(MEMP_TCP_PCB);
1437 /* Try killing oldest connection in LAST-ACK (these wouldn't go to TIME-WAIT). */
1438 LWIP_DEBUGF(TCP_DEBUG, ("tcp_alloc: killing off oldest LAST-ACK connection\n"));
1439 tcp_kill_state(LAST_ACK);
1440 /* Try to allocate a tcp_pcb again. */
1441 pcb = (struct tcp_pcb *)memp_malloc(MEMP_TCP_PCB);
1443 /* Try killing oldest connection in CLOSING. */
1444 LWIP_DEBUGF(TCP_DEBUG, ("tcp_alloc: killing off oldest CLOSING connection\n"));
1445 tcp_kill_state(CLOSING);
1446 /* Try to allocate a tcp_pcb again. */
1447 pcb = (struct tcp_pcb *)memp_malloc(MEMP_TCP_PCB);
1449 /* Try killing active connections with lower priority than the new one. */
1450 LWIP_DEBUGF(TCP_DEBUG, ("tcp_alloc: killing connection with prio lower than %d\n", prio));
1451 tcp_kill_prio(prio);
1452 /* Try to allocate a tcp_pcb again. */
1453 pcb = (struct tcp_pcb *)memp_malloc(MEMP_TCP_PCB);
1455 /* adjust err stats: memp_malloc failed multiple times before */
1456 MEMP_STATS_DEC(err, MEMP_TCP_PCB);
1460 /* adjust err stats: memp_malloc failed multiple times before */
1461 MEMP_STATS_DEC(err, MEMP_TCP_PCB);
1465 /* adjust err stats: memp_malloc failed multiple times before */
1466 MEMP_STATS_DEC(err, MEMP_TCP_PCB);
1470 /* adjust err stats: memp_malloc failed above */
1471 MEMP_STATS_DEC(err, MEMP_TCP_PCB);
1475 memset(pcb, 0, sizeof(struct tcp_pcb));
1477 pcb->snd_buf = TCP_SND_BUF;
1478 pcb->snd_queuelen = 0;
1479 /* Start with a window that does not need scaling. When window scaling is
1480 enabled and used, the window is enlarged when both sides agree on scaling. */
1481 pcb->rcv_wnd = pcb->rcv_ann_wnd = TCPWND_MIN16(TCP_WND);
1483 /* snd_scale and rcv_scale are zero unless both sides agree to use scaling */
1489 /* As initial send MSS, we use TCP_MSS but limit it to 536.
1490 The send MSS is updated when an MSS option is received. */
1491 pcb->mss = (TCP_MSS > 536) ? 536 : TCP_MSS;
1492 pcb->rto = 3000 / TCP_SLOW_INTERVAL;
1494 pcb->sv = 3000 / TCP_SLOW_INTERVAL;
1497 iss = tcp_next_iss();
1502 pcb->tmr = tcp_ticks;
1503 pcb->last_timer = tcp_timer_ctr;
1507 #if LWIP_CALLBACK_API
1508 pcb->recv = tcp_recv_null;
1509 #endif /* LWIP_CALLBACK_API */
1511 /* Init KEEPALIVE timer */
1512 pcb->keep_idle = TCP_KEEPIDLE_DEFAULT;
1514 #if LWIP_TCP_KEEPALIVE
1515 pcb->keep_intvl = TCP_KEEPINTVL_DEFAULT;
1516 pcb->keep_cnt = TCP_KEEPCNT_DEFAULT;
1517 #endif /* LWIP_TCP_KEEPALIVE */
1519 pcb->keep_cnt_sent = 0;
1525 * Creates a new TCP protocol control block but doesn't place it on
1526 * any of the TCP PCB lists.
1527 * The pcb is not put on any list until binding using tcp_bind().
1529 * @internal: Maybe there should be a idle TCP PCB list where these
1530 * PCBs are put on. Port reservation using tcp_bind() is implemented but
1531 * allocated pcbs that are not bound can't be killed automatically if wanting
1532 * to allocate a pcb with higher prio (@see tcp_kill_prio())
1534 * @return a new tcp_pcb that initially is in state CLOSED
1539 return tcp_alloc(TCP_PRIO_NORMAL);
1544 * Creates a new TCP-over-IPv6 protocol control block but doesn't
1545 * place it on any of the TCP PCB lists.
1546 * The pcb is not put on any list until binding using tcp_bind().
1548 * @return a new tcp_pcb that initially is in state CLOSED
1553 struct tcp_pcb * pcb;
1554 pcb = tcp_alloc(TCP_PRIO_NORMAL);
1557 #endif /* LWIP_IPV4 */
1560 #endif /* LWIP_IPV6 */
1563 * Used to specify the argument that should be passed callback
1566 * @param pcb tcp_pcb to set the callback argument
1567 * @param arg void pointer argument to pass to callback functions
1570 tcp_arg(struct tcp_pcb *pcb, void *arg)
1572 /* This function is allowed to be called for both listen pcbs and
1574 pcb->callback_arg = arg;
1576 #if LWIP_CALLBACK_API
1579 * Used to specify the function that should be called when a TCP
1580 * connection receives data.
1582 * @param pcb tcp_pcb to set the recv callback
1583 * @param recv callback function to call for this pcb when data is received
1586 tcp_recv(struct tcp_pcb *pcb, tcp_recv_fn recv)
1588 LWIP_ASSERT("invalid socket state for recv callback", pcb->state != LISTEN);
1593 * Used to specify the function that should be called when TCP data
1594 * has been successfully delivered to the remote host.
1596 * @param pcb tcp_pcb to set the sent callback
1597 * @param sent callback function to call for this pcb when data is successfully sent
1600 tcp_sent(struct tcp_pcb *pcb, tcp_sent_fn sent)
1602 LWIP_ASSERT("invalid socket state for sent callback", pcb->state != LISTEN);
1607 * Used to specify the function that should be called when a fatal error
1608 * has occurred on the connection.
1610 * @param pcb tcp_pcb to set the err callback
1611 * @param err callback function to call for this pcb when a fatal error
1612 * has occurred on the connection
1615 tcp_err(struct tcp_pcb *pcb, tcp_err_fn err)
1617 LWIP_ASSERT("invalid socket state for err callback", pcb->state != LISTEN);
1622 * Used for specifying the function that should be called when a
1623 * LISTENing connection has been connected to another host.
1625 * @param pcb tcp_pcb to set the accept callback
1626 * @param accept callback function to call for this pcb when LISTENing
1627 * connection has been connected to another host
1630 tcp_accept(struct tcp_pcb *pcb, tcp_accept_fn accept)
1632 /* This function is allowed to be called for both listen pcbs and
1634 pcb->accept = accept;
1636 #endif /* LWIP_CALLBACK_API */
1640 * Used to specify the function that should be called periodically
1641 * from TCP. The interval is specified in terms of the TCP coarse
1642 * timer interval, which is called twice a second.
1646 tcp_poll(struct tcp_pcb *pcb, tcp_poll_fn poll, u8_t interval)
1648 LWIP_ASSERT("invalid socket state for poll", pcb->state != LISTEN);
1649 #if LWIP_CALLBACK_API
1651 #else /* LWIP_CALLBACK_API */
1652 LWIP_UNUSED_ARG(poll);
1653 #endif /* LWIP_CALLBACK_API */
1654 pcb->pollinterval = interval;
1658 * Purges a TCP PCB. Removes any buffered data and frees the buffer memory
1659 * (pcb->ooseq, pcb->unsent and pcb->unacked are freed).
1661 * @param pcb tcp_pcb to purge. The pcb itself is not deallocated!
1664 tcp_pcb_purge(struct tcp_pcb *pcb)
1666 if (pcb->state != CLOSED &&
1667 pcb->state != TIME_WAIT &&
1668 pcb->state != LISTEN) {
1670 LWIP_DEBUGF(TCP_DEBUG, ("tcp_pcb_purge\n"));
1672 #if TCP_LISTEN_BACKLOG
1673 if (pcb->state == SYN_RCVD) {
1674 /* Need to find the corresponding listen_pcb and decrease its accepts_pending */
1675 struct tcp_pcb_listen *lpcb;
1676 LWIP_ASSERT("tcp_pcb_purge: pcb->state == SYN_RCVD but tcp_listen_pcbs is NULL",
1677 tcp_listen_pcbs.listen_pcbs != NULL);
1678 for (lpcb = tcp_listen_pcbs.listen_pcbs; lpcb != NULL; lpcb = lpcb->next) {
1679 if ((lpcb->local_port == pcb->local_port) &&
1680 IP_PCB_IPVER_EQ(pcb, lpcb) &&
1681 (ip_addr_isany(&lpcb->local_ip) ||
1682 ip_addr_cmp(&pcb->local_ip, &lpcb->local_ip))) {
1683 /* port and address of the listen pcb match the timed-out pcb */
1684 LWIP_ASSERT("tcp_pcb_purge: listen pcb does not have accepts pending",
1685 lpcb->accepts_pending > 0);
1686 lpcb->accepts_pending--;
1691 #endif /* TCP_LISTEN_BACKLOG */
1694 if (pcb->refused_data != NULL) {
1695 LWIP_DEBUGF(TCP_DEBUG, ("tcp_pcb_purge: data left on ->refused_data\n"));
1696 pbuf_free(pcb->refused_data);
1697 pcb->refused_data = NULL;
1699 if (pcb->unsent != NULL) {
1700 LWIP_DEBUGF(TCP_DEBUG, ("tcp_pcb_purge: not all data sent\n"));
1702 if (pcb->unacked != NULL) {
1703 LWIP_DEBUGF(TCP_DEBUG, ("tcp_pcb_purge: data left on ->unacked\n"));
1706 if (pcb->ooseq != NULL) {
1707 LWIP_DEBUGF(TCP_DEBUG, ("tcp_pcb_purge: data left on ->ooseq\n"));
1709 tcp_segs_free(pcb->ooseq);
1711 #endif /* TCP_QUEUE_OOSEQ */
1713 /* Stop the retransmission timer as it will expect data on unacked
1714 queue if it fires */
1717 tcp_segs_free(pcb->unsent);
1718 tcp_segs_free(pcb->unacked);
1719 pcb->unacked = pcb->unsent = NULL;
1721 pcb->unsent_oversize = 0;
1722 #endif /* TCP_OVERSIZE */
1727 * Purges the PCB and removes it from a PCB list. Any delayed ACKs are sent first.
1729 * @param pcblist PCB list to purge.
1730 * @param pcb tcp_pcb to purge. The pcb itself is NOT deallocated!
1733 tcp_pcb_remove(struct tcp_pcb **pcblist, struct tcp_pcb *pcb)
1735 TCP_RMV(pcblist, pcb);
1739 /* if there is an outstanding delayed ACKs, send it */
1740 if (pcb->state != TIME_WAIT &&
1741 pcb->state != LISTEN &&
1742 pcb->flags & TF_ACK_DELAY) {
1743 pcb->flags |= TF_ACK_NOW;
1747 if (pcb->state != LISTEN) {
1748 LWIP_ASSERT("unsent segments leaking", pcb->unsent == NULL);
1749 LWIP_ASSERT("unacked segments leaking", pcb->unacked == NULL);
1751 LWIP_ASSERT("ooseq segments leaking", pcb->ooseq == NULL);
1752 #endif /* TCP_QUEUE_OOSEQ */
1755 pcb->state = CLOSED;
1756 /* reset the local port to prevent the pcb from being 'bound' */
1757 pcb->local_port = 0;
1759 LWIP_ASSERT("tcp_pcb_remove: tcp_pcbs_sane()", tcp_pcbs_sane());
1763 * Calculates a new initial sequence number for new connections.
1765 * @return u32_t pseudo random sequence number
1770 static u32_t iss = 6510;
1772 iss += tcp_ticks; /* XXX */
1776 #if TCP_CALCULATE_EFF_SEND_MSS
1778 * Calculates the effective send mss that can be used for a specific IP address
1779 * by using ip_route to determine the netif used to send to the address and
1780 * calculating the minimum of TCP_MSS and that netif's mtu (if set).
1783 tcp_eff_send_mss_impl(u16_t sendmss, const ip_addr_t *dest
1784 #if LWIP_IPV6 || LWIP_IPV4_SRC_ROUTING
1785 , const ip_addr_t *src
1786 #endif /* LWIP_IPV6 || LWIP_IPV4_SRC_ROUTING */
1787 #if LWIP_IPV6 && LWIP_IPV4
1789 #endif /* LWIP_IPV6 && LWIP_IPV4 */
1793 struct netif *outif;
1796 outif = ip_route(isipv6, src, dest);
1800 #endif /* LWIP_IPV4 */
1802 /* First look in destination cache, to see if there is a Path MTU. */
1803 mtu = nd6_get_destination_mtu(ip_2_ip6(dest), outif);
1807 #endif /* LWIP_IPV4 */
1808 #endif /* LWIP_IPV6 */
1811 if (outif == NULL) {
1816 #endif /* LWIP_IPV4 */
1822 #endif /* LWIP_IPV4 */
1824 mss_s = mtu - IP6_HLEN - TCP_HLEN;
1828 #endif /* LWIP_IPV4 */
1829 #endif /* LWIP_IPV6 */
1832 mss_s = mtu - IP_HLEN - TCP_HLEN;
1834 #endif /* LWIP_IPV4 */
1835 /* RFC 1122, chap 4.2.2.6:
1836 * Eff.snd.MSS = min(SendMSS+20, MMS_S) - TCPhdrsize - IPoptionsize
1837 * We correct for TCP options in tcp_write(), and don't support IP options.
1839 sendmss = LWIP_MIN(sendmss, mss_s);
1843 #endif /* TCP_CALCULATE_EFF_SEND_MSS */
1846 /** Helper function for tcp_netif_ipv4_addr_changed() that iterates a pcb list */
1848 tcp_netif_ipv4_addr_changed_pcblist(const ip4_addr_t* old_addr, struct tcp_pcb* pcb_list)
1850 struct tcp_pcb *pcb;
1852 while (pcb != NULL) {
1853 /* PCB bound to current local interface address? */
1854 if (!IP_IS_V6_VAL(pcb->local_ip) && ip4_addr_cmp(ip_2_ip4(&pcb->local_ip), old_addr)
1856 /* connections to link-local addresses must persist (RFC3927 ch. 1.9) */
1857 && !ip4_addr_islinklocal(ip_2_ip4(&pcb->local_ip))
1858 #endif /* LWIP_AUTOIP */
1860 /* this connection must be aborted */
1861 struct tcp_pcb *next = pcb->next;
1862 LWIP_DEBUGF(NETIF_DEBUG | LWIP_DBG_STATE, ("netif_set_ipaddr: aborting TCP pcb %p\n", (void *)pcb));
1871 /** This function is called from netif.c when address is changed or netif is removed
1873 * @param old_addr IPv4 address of the netif before change
1874 * @param new_addr IPv4 address of the netif after change or NULL if netif has been removed
1876 void tcp_netif_ipv4_addr_changed(const ip4_addr_t* old_addr, const ip4_addr_t* new_addr)
1878 struct tcp_pcb_listen *lpcb, *next;
1880 tcp_netif_ipv4_addr_changed_pcblist(old_addr, tcp_active_pcbs);
1881 tcp_netif_ipv4_addr_changed_pcblist(old_addr, tcp_bound_pcbs);
1883 if (!ip4_addr_isany(new_addr)) {
1884 /* PCB bound to current local interface address? */
1885 for (lpcb = tcp_listen_pcbs.listen_pcbs; lpcb != NULL; lpcb = next) {
1887 /* Is this an IPv4 pcb? */
1888 if (!IP_IS_V6_VAL(lpcb->local_ip)) {
1889 /* PCB bound to current local interface address? */
1890 if ((!(ip4_addr_isany(ip_2_ip4(&lpcb->local_ip)))) &&
1891 (ip4_addr_cmp(ip_2_ip4(&lpcb->local_ip), old_addr))) {
1892 /* The PCB is listening to the old ipaddr and
1893 * is set to listen to the new one instead */
1894 ip_addr_copy_from_ip4(lpcb->local_ip, *new_addr);
1900 #endif /* LWIP_IPV4 */
1903 tcp_debug_state_str(enum tcp_state s)
1905 return tcp_state_str[s];
1908 #if TCP_DEBUG || TCP_INPUT_DEBUG || TCP_OUTPUT_DEBUG
1910 * Print a tcp header for debugging purposes.
1912 * @param tcphdr pointer to a struct tcp_hdr
1915 tcp_debug_print(struct tcp_hdr *tcphdr)
1917 LWIP_DEBUGF(TCP_DEBUG, ("TCP header:\n"));
1918 LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
1919 LWIP_DEBUGF(TCP_DEBUG, ("| %5"U16_F" | %5"U16_F" | (src port, dest port)\n",
1920 ntohs(tcphdr->src), ntohs(tcphdr->dest)));
1921 LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
1922 LWIP_DEBUGF(TCP_DEBUG, ("| %010"U32_F" | (seq no)\n",
1923 ntohl(tcphdr->seqno)));
1924 LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
1925 LWIP_DEBUGF(TCP_DEBUG, ("| %010"U32_F" | (ack no)\n",
1926 ntohl(tcphdr->ackno)));
1927 LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
1928 LWIP_DEBUGF(TCP_DEBUG, ("| %2"U16_F" | |%"U16_F"%"U16_F"%"U16_F"%"U16_F"%"U16_F"%"U16_F"| %5"U16_F" | (hdrlen, flags (",
1929 TCPH_HDRLEN(tcphdr),
1930 TCPH_FLAGS(tcphdr) >> 5 & 1,
1931 TCPH_FLAGS(tcphdr) >> 4 & 1,
1932 TCPH_FLAGS(tcphdr) >> 3 & 1,
1933 TCPH_FLAGS(tcphdr) >> 2 & 1,
1934 TCPH_FLAGS(tcphdr) >> 1 & 1,
1935 TCPH_FLAGS(tcphdr) & 1,
1936 ntohs(tcphdr->wnd)));
1937 tcp_debug_print_flags(TCPH_FLAGS(tcphdr));
1938 LWIP_DEBUGF(TCP_DEBUG, ("), win)\n"));
1939 LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
1940 LWIP_DEBUGF(TCP_DEBUG, ("| 0x%04"X16_F" | %5"U16_F" | (chksum, urgp)\n",
1941 ntohs(tcphdr->chksum), ntohs(tcphdr->urgp)));
1942 LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
1946 * Print a tcp state for debugging purposes.
1948 * @param s enum tcp_state to print
1951 tcp_debug_print_state(enum tcp_state s)
1953 LWIP_DEBUGF(TCP_DEBUG, ("State: %s\n", tcp_state_str[s]));
1957 * Print tcp flags for debugging purposes.
1959 * @param flags tcp flags, all active flags are printed
1962 tcp_debug_print_flags(u8_t flags)
1964 if (flags & TCP_FIN) {
1965 LWIP_DEBUGF(TCP_DEBUG, ("FIN "));
1967 if (flags & TCP_SYN) {
1968 LWIP_DEBUGF(TCP_DEBUG, ("SYN "));
1970 if (flags & TCP_RST) {
1971 LWIP_DEBUGF(TCP_DEBUG, ("RST "));
1973 if (flags & TCP_PSH) {
1974 LWIP_DEBUGF(TCP_DEBUG, ("PSH "));
1976 if (flags & TCP_ACK) {
1977 LWIP_DEBUGF(TCP_DEBUG, ("ACK "));
1979 if (flags & TCP_URG) {
1980 LWIP_DEBUGF(TCP_DEBUG, ("URG "));
1982 if (flags & TCP_ECE) {
1983 LWIP_DEBUGF(TCP_DEBUG, ("ECE "));
1985 if (flags & TCP_CWR) {
1986 LWIP_DEBUGF(TCP_DEBUG, ("CWR "));
1988 LWIP_DEBUGF(TCP_DEBUG, ("\n"));
1992 * Print all tcp_pcbs in every list for debugging purposes.
1995 tcp_debug_print_pcbs(void)
1997 struct tcp_pcb *pcb;
1998 LWIP_DEBUGF(TCP_DEBUG, ("Active PCB states:\n"));
1999 for (pcb = tcp_active_pcbs; pcb != NULL; pcb = pcb->next) {
2000 LWIP_DEBUGF(TCP_DEBUG, ("Local port %"U16_F", foreign port %"U16_F" snd_nxt %"U32_F" rcv_nxt %"U32_F" ",
2001 pcb->local_port, pcb->remote_port,
2002 pcb->snd_nxt, pcb->rcv_nxt));
2003 tcp_debug_print_state(pcb->state);
2005 LWIP_DEBUGF(TCP_DEBUG, ("Listen PCB states:\n"));
2006 for (pcb = (struct tcp_pcb *)tcp_listen_pcbs.pcbs; pcb != NULL; pcb = pcb->next) {
2007 LWIP_DEBUGF(TCP_DEBUG, ("Local port %"U16_F", foreign port %"U16_F" snd_nxt %"U32_F" rcv_nxt %"U32_F" ",
2008 pcb->local_port, pcb->remote_port,
2009 pcb->snd_nxt, pcb->rcv_nxt));
2010 tcp_debug_print_state(pcb->state);
2012 LWIP_DEBUGF(TCP_DEBUG, ("TIME-WAIT PCB states:\n"));
2013 for (pcb = tcp_tw_pcbs; pcb != NULL; pcb = pcb->next) {
2014 LWIP_DEBUGF(TCP_DEBUG, ("Local port %"U16_F", foreign port %"U16_F" snd_nxt %"U32_F" rcv_nxt %"U32_F" ",
2015 pcb->local_port, pcb->remote_port,
2016 pcb->snd_nxt, pcb->rcv_nxt));
2017 tcp_debug_print_state(pcb->state);
2022 * Check state consistency of the tcp_pcb lists.
2027 struct tcp_pcb *pcb;
2028 for (pcb = tcp_active_pcbs; pcb != NULL; pcb = pcb->next) {
2029 LWIP_ASSERT("tcp_pcbs_sane: active pcb->state != CLOSED", pcb->state != CLOSED);
2030 LWIP_ASSERT("tcp_pcbs_sane: active pcb->state != LISTEN", pcb->state != LISTEN);
2031 LWIP_ASSERT("tcp_pcbs_sane: active pcb->state != TIME-WAIT", pcb->state != TIME_WAIT);
2033 for (pcb = tcp_tw_pcbs; pcb != NULL; pcb = pcb->next) {
2034 LWIP_ASSERT("tcp_pcbs_sane: tw pcb->state == TIME-WAIT", pcb->state == TIME_WAIT);
2038 #endif /* TCP_DEBUG */
2040 #endif /* LWIP_TCP */