xref: /minix/minix/lib/liblwip/dist/src/core/tcp.c (revision ef8d499e)
1 /**
2  * @file
3  * Transmission Control Protocol for IP
4  * See also @ref tcp_raw
5  *
6  * @defgroup tcp_raw TCP
7  * @ingroup callbackstyle_api
8  * Transmission Control Protocol for IP\n
9  * @see @ref raw_api and @ref netconn
10  *
11  * Common functions for the TCP implementation, such as functinos
12  * for manipulating the data structures and the TCP timer functions. TCP functions
13  * related to input and output is found in tcp_in.c and tcp_out.c respectively.\n
14  */
15 
16 /*
17  * Copyright (c) 2001-2004 Swedish Institute of Computer Science.
18  * All rights reserved.
19  *
20  * Redistribution and use in source and binary forms, with or without modification,
21  * are permitted provided that the following conditions are met:
22  *
23  * 1. Redistributions of source code must retain the above copyright notice,
24  *    this list of conditions and the following disclaimer.
25  * 2. Redistributions in binary form must reproduce the above copyright notice,
26  *    this list of conditions and the following disclaimer in the documentation
27  *    and/or other materials provided with the distribution.
28  * 3. The name of the author may not be used to endorse or promote products
29  *    derived from this software without specific prior written permission.
30  *
31  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
32  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
33  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
34  * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
35  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
36  * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
37  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
38  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
39  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
40  * OF SUCH DAMAGE.
41  *
42  * This file is part of the lwIP TCP/IP stack.
43  *
44  * Author: Adam Dunkels <adam@sics.se>
45  *
46  */
47 
48 #include "lwip/opt.h"
49 
50 #if LWIP_TCP /* don't build if not configured for use in lwipopts.h */
51 
52 #include "lwip/def.h"
53 #include "lwip/mem.h"
54 #include "lwip/memp.h"
55 #include "lwip/tcp.h"
56 #include "lwip/priv/tcp_priv.h"
57 #include "lwip/debug.h"
58 #include "lwip/stats.h"
59 #include "lwip/ip6.h"
60 #include "lwip/ip6_addr.h"
61 #include "lwip/nd6.h"
62 
63 #include <string.h>
64 
65 #ifdef LWIP_HOOK_FILENAME
66 #include LWIP_HOOK_FILENAME
67 #endif
68 
69 #ifndef TCP_LOCAL_PORT_RANGE_START
70 /* From http://www.iana.org/assignments/port-numbers:
71    "The Dynamic and/or Private Ports are those from 49152 through 65535" */
72 #define TCP_LOCAL_PORT_RANGE_START        0xc000
73 #define TCP_LOCAL_PORT_RANGE_END          0xffff
74 #define TCP_ENSURE_LOCAL_PORT_RANGE(port) ((u16_t)(((port) & ~TCP_LOCAL_PORT_RANGE_START) + TCP_LOCAL_PORT_RANGE_START))
75 #endif
76 
77 #if LWIP_TCP_KEEPALIVE
78 #define TCP_KEEP_DUR(pcb)   ((pcb)->keep_cnt * (pcb)->keep_intvl)
79 #define TCP_KEEP_INTVL(pcb) ((pcb)->keep_intvl)
80 #else /* LWIP_TCP_KEEPALIVE */
81 #define TCP_KEEP_DUR(pcb)   TCP_MAXIDLE
82 #define TCP_KEEP_INTVL(pcb) TCP_KEEPINTVL_DEFAULT
83 #endif /* LWIP_TCP_KEEPALIVE */
84 
85 /* As initial send MSS, we use TCP_MSS but limit it to 536. */
86 #if TCP_MSS > 536
87 #define INITIAL_MSS 536
88 #else
89 #define INITIAL_MSS TCP_MSS
90 #endif
91 
92 static const char * const tcp_state_str[] = {
93   "CLOSED",
94   "LISTEN",
95   "SYN_SENT",
96   "SYN_RCVD",
97   "ESTABLISHED",
98   "FIN_WAIT_1",
99   "FIN_WAIT_2",
100   "CLOSE_WAIT",
101   "CLOSING",
102   "LAST_ACK",
103   "TIME_WAIT"
104 };
105 
106 /* last local TCP port */
107 static u16_t tcp_port = TCP_LOCAL_PORT_RANGE_START;
108 
109 /* Incremented every coarse grained timer shot (typically every 500 ms). */
110 u32_t tcp_ticks;
111 static const u8_t tcp_backoff[13] =
112     { 1, 2, 3, 4, 5, 6, 7, 7, 7, 7, 7, 7, 7};
113  /* Times per slowtmr hits */
114 static const u8_t tcp_persist_backoff[7] = { 3, 6, 12, 24, 48, 96, 120 };
115 
116 /* The TCP PCB lists. */
117 
118 /** List of all TCP PCBs bound but not yet (connected || listening) */
119 struct tcp_pcb *tcp_bound_pcbs;
120 /** List of all TCP PCBs in LISTEN state */
121 union tcp_listen_pcbs_t tcp_listen_pcbs;
122 /** List of all TCP PCBs that are in a state in which
123  * they accept or send data. */
124 struct tcp_pcb *tcp_active_pcbs;
125 /** List of all TCP PCBs in TIME-WAIT state */
126 struct tcp_pcb *tcp_tw_pcbs;
127 
128 /** An array with all (non-temporary) PCB lists, mainly used for smaller code size */
129 struct tcp_pcb ** const tcp_pcb_lists[] = {&tcp_listen_pcbs.pcbs, &tcp_bound_pcbs,
130   &tcp_active_pcbs, &tcp_tw_pcbs};
131 
132 u8_t tcp_active_pcbs_changed;
133 
134 /** Timer counter to handle calling slow-timer from tcp_tmr() */
135 static u8_t tcp_timer;
136 static u8_t tcp_timer_ctr;
137 static u16_t tcp_new_port(void);
138 
139 static err_t tcp_close_shutdown_fin(struct tcp_pcb *pcb);
140 
141 /**
142  * Initialize this module.
143  */
144 void
145 tcp_init(void)
146 {
147 #if LWIP_RANDOMIZE_INITIAL_LOCAL_PORTS && defined(LWIP_RAND)
148   tcp_port = TCP_ENSURE_LOCAL_PORT_RANGE(LWIP_RAND());
149 #endif /* LWIP_RANDOMIZE_INITIAL_LOCAL_PORTS && defined(LWIP_RAND) */
150 }
151 
152 /**
153  * Called periodically to dispatch TCP timers.
154  */
155 void
156 tcp_tmr(void)
157 {
158   /* Call tcp_fasttmr() every 250 ms */
159   tcp_fasttmr();
160 
161   if (++tcp_timer & 1) {
162     /* Call tcp_slowtmr() every 500 ms, i.e., every other timer
163        tcp_tmr() is called. */
164     tcp_slowtmr();
165   }
166 }
167 
168 #if LWIP_CALLBACK_API || TCP_LISTEN_BACKLOG
169 /** Called when a listen pcb is closed. Iterates one pcb list and removes the
170  * closed listener pcb from pcb->listener if matching.
171  */
172 static void
173 tcp_remove_listener(struct tcp_pcb *list, struct tcp_pcb_listen *lpcb)
174 {
175    struct tcp_pcb *pcb;
176    for (pcb = list; pcb != NULL; pcb = pcb->next) {
177       if (pcb->listener == lpcb) {
178          pcb->listener = NULL;
179       }
180    }
181 }
182 #endif
183 
184 /** Called when a listen pcb is closed. Iterates all pcb lists and removes the
185  * closed listener pcb from pcb->listener if matching.
186  */
187 static void
188 tcp_listen_closed(struct tcp_pcb *pcb)
189 {
190 #if LWIP_CALLBACK_API || TCP_LISTEN_BACKLOG
191   size_t i;
192   LWIP_ASSERT("pcb != NULL", pcb != NULL);
193   LWIP_ASSERT("pcb->state == LISTEN", pcb->state == LISTEN);
194   for (i = 1; i < LWIP_ARRAYSIZE(tcp_pcb_lists); i++) {
195     tcp_remove_listener(*tcp_pcb_lists[i], (struct tcp_pcb_listen*)pcb);
196   }
197 #endif
198   LWIP_UNUSED_ARG(pcb);
199 }
200 
201 #if TCP_LISTEN_BACKLOG
202 /** @ingroup tcp_raw
203  * Delay accepting a connection in respect to the listen backlog:
204  * the number of outstanding connections is increased until
205  * tcp_backlog_accepted() is called.
206  *
207  * ATTENTION: the caller is responsible for calling tcp_backlog_accepted()
208  * or else the backlog feature will get out of sync!
209  *
210  * @param pcb the connection pcb which is not fully accepted yet
211  */
212 void
213 tcp_backlog_delayed(struct tcp_pcb* pcb)
214 {
215   LWIP_ASSERT("pcb != NULL", pcb != NULL);
216   if ((pcb->flags & TF_BACKLOGPEND) == 0) {
217     if (pcb->listener != NULL) {
218       pcb->listener->accepts_pending++;
219       LWIP_ASSERT("accepts_pending != 0", pcb->listener->accepts_pending != 0);
220       pcb->flags |= TF_BACKLOGPEND;
221     }
222   }
223 }
224 
225 /** @ingroup tcp_raw
226  * A delayed-accept a connection is accepted (or closed/aborted): decreases
227  * the number of outstanding connections after calling tcp_backlog_delayed().
228  *
229  * ATTENTION: the caller is responsible for calling tcp_backlog_accepted()
230  * or else the backlog feature will get out of sync!
231  *
232  * @param pcb the connection pcb which is now fully accepted (or closed/aborted)
233  */
234 void
235 tcp_backlog_accepted(struct tcp_pcb* pcb)
236 {
237   LWIP_ASSERT("pcb != NULL", pcb != NULL);
238   if ((pcb->flags & TF_BACKLOGPEND) != 0) {
239     if (pcb->listener != NULL) {
240       LWIP_ASSERT("accepts_pending != 0", pcb->listener->accepts_pending != 0);
241       pcb->listener->accepts_pending--;
242       pcb->flags &= ~TF_BACKLOGPEND;
243     }
244   }
245 }
246 #endif /* TCP_LISTEN_BACKLOG */
247 
248 /**
249  * Closes the TX side of a connection held by the PCB.
250  * For tcp_close(), a RST is sent if the application didn't receive all data
251  * (tcp_recved() not called for all data passed to recv callback).
252  *
253  * Listening pcbs are freed and may not be referenced any more.
254  * Connection pcbs are freed if not yet connected and may not be referenced
255  * any more. If a connection is established (at least SYN received or in
256  * a closing state), the connection is closed, and put in a closing state.
257  * The pcb is then automatically freed in tcp_slowtmr(). It is therefore
258  * unsafe to reference it.
259  *
260  * @param pcb the tcp_pcb to close
261  * @return ERR_OK if connection has been closed
262  *         another err_t if closing failed and pcb is not freed
263  */
264 static err_t
265 tcp_close_shutdown(struct tcp_pcb *pcb, u8_t rst_on_unacked_data)
266 {
267   if (rst_on_unacked_data && ((pcb->state == ESTABLISHED) || (pcb->state == CLOSE_WAIT))) {
268     if ((pcb->refused_data != NULL) || (pcb->rcv_wnd != TCP_WND_MAX(pcb))) {
269       /* Not all data received by application, send RST to tell the remote
270          side about this. */
271       LWIP_ASSERT("pcb->flags & TF_RXCLOSED", pcb->flags & TF_RXCLOSED);
272 
273       /* don't call tcp_abort here: we must not deallocate the pcb since
274          that might not be expected when calling tcp_close */
275       tcp_rst(pcb->snd_nxt, pcb->rcv_nxt, &pcb->local_ip, &pcb->remote_ip,
276                pcb->local_port, pcb->remote_port);
277 
278       tcp_pcb_purge(pcb);
279       TCP_RMV_ACTIVE(pcb);
280       if (pcb->state == ESTABLISHED) {
281         /* move to TIME_WAIT since we close actively */
282         pcb->state = TIME_WAIT;
283         TCP_REG(&tcp_tw_pcbs, pcb);
284       } else {
285         /* CLOSE_WAIT: deallocate the pcb since we already sent a RST for it */
286         if (tcp_input_pcb == pcb) {
287           /* prevent using a deallocated pcb: free it from tcp_input later */
288           tcp_trigger_input_pcb_close();
289         } else {
290           memp_free(MEMP_TCP_PCB, pcb);
291         }
292       }
293       return ERR_OK;
294     }
295   }
296 
297   /* - states which free the pcb are handled here,
298      - states which send FIN and change state are handled in tcp_close_shutdown_fin() */
299   switch (pcb->state) {
300   case CLOSED:
301     /* Closing a pcb in the CLOSED state might seem erroneous,
302      * however, it is in this state once allocated and as yet unused
303      * and the user needs some way to free it should the need arise.
304      * Calling tcp_close() with a pcb that has already been closed, (i.e. twice)
305      * or for a pcb that has been used and then entered the CLOSED state
306      * is erroneous, but this should never happen as the pcb has in those cases
307      * been freed, and so any remaining handles are bogus. */
308     if (pcb->local_port != 0) {
309       TCP_RMV(&tcp_bound_pcbs, pcb);
310     }
311     memp_free(MEMP_TCP_PCB, pcb);
312     break;
313   case LISTEN:
314     tcp_listen_closed(pcb);
315     tcp_pcb_remove(&tcp_listen_pcbs.pcbs, pcb);
316     memp_free(MEMP_TCP_PCB_LISTEN, pcb);
317     break;
318   case SYN_SENT:
319     TCP_PCB_REMOVE_ACTIVE(pcb);
320     memp_free(MEMP_TCP_PCB, pcb);
321     MIB2_STATS_INC(mib2.tcpattemptfails);
322     break;
323   default:
324     return tcp_close_shutdown_fin(pcb);
325   }
326   return ERR_OK;
327 }
328 
329 static err_t
330 tcp_close_shutdown_fin(struct tcp_pcb *pcb)
331 {
332   err_t err;
333   LWIP_ASSERT("pcb != NULL", pcb != NULL);
334 
335   switch (pcb->state) {
336   case SYN_RCVD:
337     err = tcp_send_fin(pcb);
338     if (err == ERR_OK) {
339       tcp_backlog_accepted(pcb);
340       MIB2_STATS_INC(mib2.tcpattemptfails);
341       pcb->state = FIN_WAIT_1;
342     }
343     break;
344   case ESTABLISHED:
345     err = tcp_send_fin(pcb);
346     if (err == ERR_OK) {
347       MIB2_STATS_INC(mib2.tcpestabresets);
348       pcb->state = FIN_WAIT_1;
349     }
350     break;
351   case CLOSE_WAIT:
352     err = tcp_send_fin(pcb);
353     if (err == ERR_OK) {
354       MIB2_STATS_INC(mib2.tcpestabresets);
355       pcb->state = LAST_ACK;
356     }
357     break;
358   default:
359     /* Has already been closed, do nothing. */
360     return ERR_OK;
361     break;
362   }
363 
364   if (err == ERR_OK) {
365     /* To ensure all data has been sent when tcp_close returns, we have
366        to make sure tcp_output doesn't fail.
367        Since we don't really have to ensure all data has been sent when tcp_close
368        returns (unsent data is sent from tcp timer functions, also), we don't care
369        for the return value of tcp_output for now. */
370     tcp_output(pcb);
371   } else if (err == ERR_MEM) {
372     /* Mark this pcb for closing. Closing is retried from tcp_tmr. */
373     pcb->flags |= TF_CLOSEPEND;
374   }
375   return err;
376 }
377 
378 /**
379  * @ingroup tcp_raw
380  * Closes the connection held by the PCB.
381  *
382  * Listening pcbs are freed and may not be referenced any more.
383  * Connection pcbs are freed if not yet connected and may not be referenced
384  * any more. If a connection is established (at least SYN received or in
385  * a closing state), the connection is closed, and put in a closing state.
386  * The pcb is then automatically freed in tcp_slowtmr(). It is therefore
387  * unsafe to reference it (unless an error is returned).
388  *
389  * @param pcb the tcp_pcb to close
390  * @return ERR_OK if connection has been closed
391  *         another err_t if closing failed and pcb is not freed
392  */
393 err_t
394 tcp_close(struct tcp_pcb *pcb)
395 {
396   LWIP_DEBUGF(TCP_DEBUG, ("tcp_close: closing in "));
397   tcp_debug_print_state(pcb->state);
398 
399   if (pcb->state != LISTEN) {
400     /* Set a flag not to receive any more data... */
401     pcb->flags |= TF_RXCLOSED;
402   }
403   /* ... and close */
404   return tcp_close_shutdown(pcb, 1);
405 }
406 
407 /**
408  * @ingroup tcp_raw
409  * Causes all or part of a full-duplex connection of this PCB to be shut down.
410  * This doesn't deallocate the PCB unless shutting down both sides!
411  * Shutting down both sides is the same as calling tcp_close, so if it succeds,
412  * the PCB should not be referenced any more.
413  *
414  * @param pcb PCB to shutdown
415  * @param shut_rx shut down receive side if this is != 0
416  * @param shut_tx shut down send side if this is != 0
417  * @return ERR_OK if shutdown succeeded (or the PCB has already been shut down)
418  *         another err_t on error.
419  */
420 err_t
421 tcp_shutdown(struct tcp_pcb *pcb, int shut_rx, int shut_tx)
422 {
423   if (pcb->state == LISTEN) {
424     return ERR_CONN;
425   }
426   if (shut_rx) {
427     /* shut down the receive side: set a flag not to receive any more data... */
428     pcb->flags |= TF_RXCLOSED;
429     if (shut_tx) {
430       /* shutting down the tx AND rx side is the same as closing for the raw API */
431       return tcp_close_shutdown(pcb, 1);
432     }
433     /* ... and free buffered data */
434     if (pcb->refused_data != NULL) {
435       pbuf_free(pcb->refused_data);
436       pcb->refused_data = NULL;
437     }
438   }
439   if (shut_tx) {
440     /* This can't happen twice since if it succeeds, the pcb's state is changed.
441        Only close in these states as the others directly deallocate the PCB */
442     switch (pcb->state) {
443     case SYN_RCVD:
444     case ESTABLISHED:
445     case CLOSE_WAIT:
446       return tcp_close_shutdown(pcb, (u8_t)shut_rx);
447     default:
448       /* Not (yet?) connected, cannot shutdown the TX side as that would bring us
449         into CLOSED state, where the PCB is deallocated. */
450       return ERR_CONN;
451     }
452   }
453   return ERR_OK;
454 }
455 
456 /**
457  * Abandons a connection and optionally sends a RST to the remote
458  * host.  Deletes the local protocol control block. This is done when
459  * a connection is killed because of shortage of memory.
460  *
461  * @param pcb the tcp_pcb to abort
462  * @param reset boolean to indicate whether a reset should be sent
463  */
464 void
465 tcp_abandon(struct tcp_pcb *pcb, int reset)
466 {
467   u32_t seqno, ackno;
468 #if LWIP_CALLBACK_API
469   tcp_err_fn errf;
470 #endif /* LWIP_CALLBACK_API */
471   void *errf_arg;
472 
473   /* pcb->state LISTEN not allowed here */
474   LWIP_ASSERT("don't call tcp_abort/tcp_abandon for listen-pcbs",
475     pcb->state != LISTEN);
476   /* Figure out on which TCP PCB list we are, and remove us. If we
477      are in an active state, call the receive function associated with
478      the PCB with a NULL argument, and send an RST to the remote end. */
479   if (pcb->state == TIME_WAIT) {
480     tcp_pcb_remove(&tcp_tw_pcbs, pcb);
481     memp_free(MEMP_TCP_PCB, pcb);
482   } else {
483     int send_rst = 0;
484     u16_t local_port = 0;
485     enum tcp_state last_state;
486     seqno = pcb->snd_nxt;
487     ackno = pcb->rcv_nxt;
488 #if LWIP_CALLBACK_API
489     errf = pcb->errf;
490 #endif /* LWIP_CALLBACK_API */
491     errf_arg = pcb->callback_arg;
492     if (pcb->state == CLOSED) {
493       if (pcb->local_port != 0) {
494         /* bound, not yet opened */
495         TCP_RMV(&tcp_bound_pcbs, pcb);
496       }
497     } else {
498       send_rst = reset;
499       local_port = pcb->local_port;
500       TCP_PCB_REMOVE_ACTIVE(pcb);
501     }
502     if (pcb->unacked != NULL) {
503       tcp_segs_free(pcb->unacked);
504     }
505     if (pcb->unsent != NULL) {
506       tcp_segs_free(pcb->unsent);
507     }
508 #if TCP_QUEUE_OOSEQ
509     if (pcb->ooseq != NULL) {
510       tcp_segs_free(pcb->ooseq);
511     }
512 #endif /* TCP_QUEUE_OOSEQ */
513     tcp_backlog_accepted(pcb);
514     if (send_rst) {
515       LWIP_DEBUGF(TCP_RST_DEBUG, ("tcp_abandon: sending RST\n"));
516       tcp_rst(seqno, ackno, &pcb->local_ip, &pcb->remote_ip, local_port, pcb->remote_port);
517     }
518     last_state = pcb->state;
519     memp_free(MEMP_TCP_PCB, pcb);
520     TCP_EVENT_ERR(last_state, errf, errf_arg, ERR_ABRT);
521   }
522 }
523 
524 /**
525  * @ingroup tcp_raw
526  * Aborts the connection by sending a RST (reset) segment to the remote
527  * host. The pcb is deallocated. This function never fails.
528  *
529  * ATTENTION: When calling this from one of the TCP callbacks, make
530  * sure you always return ERR_ABRT (and never return ERR_ABRT otherwise
531  * or you will risk accessing deallocated memory or memory leaks!
532  *
533  * @param pcb the tcp pcb to abort
534  */
535 void
536 tcp_abort(struct tcp_pcb *pcb)
537 {
538   tcp_abandon(pcb, 1);
539 }
540 
541 /**
542  * @ingroup tcp_raw
543  * Binds the connection to a local port number and IP address. If the
544  * IP address is not given (i.e., ipaddr == NULL), the IP address of
545  * the outgoing network interface is used instead.
546  *
547  * @param pcb the tcp_pcb to bind (no check is done whether this pcb is
548  *        already bound!)
549  * @param ipaddr the local ip address to bind to (use IP4_ADDR_ANY to bind
550  *        to any local address
551  * @param port the local port to bind to
552  * @return ERR_USE if the port is already in use
553  *         ERR_VAL if bind failed because the PCB is not in a valid state
554  *         ERR_OK if bound
555  */
556 err_t
557 tcp_bind(struct tcp_pcb *pcb, const ip_addr_t *ipaddr, u16_t port)
558 {
559   int i;
560   int max_pcb_list = NUM_TCP_PCB_LISTS;
561   struct tcp_pcb *cpcb;
562 #if LWIP_IPV6 && LWIP_IPV6_SCOPES
563   ip_addr_t zoned_ipaddr;
564 #endif /* LWIP_IPV6 && LWIP_IPV6_SCOPES */
565 
566 #if LWIP_IPV4
567   /* Don't propagate NULL pointer (IPv4 ANY) to subsequent functions */
568   if (ipaddr == NULL) {
569     ipaddr = IP4_ADDR_ANY;
570   }
571 #endif /* LWIP_IPV4 */
572 
573   /* still need to check for ipaddr == NULL in IPv6 only case */
574   if ((pcb == NULL) || (ipaddr == NULL)) {
575     return ERR_VAL;
576   }
577 
578   LWIP_ERROR("tcp_bind: can only bind in state CLOSED", pcb->state == CLOSED, return ERR_VAL);
579 
580 #if SO_REUSE
581   /* Unless the REUSEADDR flag is set,
582      we have to check the pcbs in TIME-WAIT state, also.
583      We do not dump TIME_WAIT pcb's; they can still be matched by incoming
584      packets using both local and remote IP addresses and ports to distinguish.
585    */
586   if (ip_get_option(pcb, SOF_REUSEADDR)) {
587     max_pcb_list = NUM_TCP_PCB_LISTS_NO_TIME_WAIT;
588   }
589 #endif /* SO_REUSE */
590 
591 #if LWIP_IPV6 && LWIP_IPV6_SCOPES
592   /* If the given IP address should have a zone but doesn't, assign one now.
593    * This is legacy support: scope-aware callers should always provide properly
594    * zoned source addresses. Do the zone selection before the address-in-use
595    * check below; as such we have to make a temporary copy of the address. */
596   if (IP_IS_V6(ipaddr) && ip6_addr_lacks_zone(ip_2_ip6(ipaddr), IP6_UNICAST)) {
597     ip_addr_copy(zoned_ipaddr, *ipaddr);
598     ip6_addr_select_zone(ip_2_ip6(&zoned_ipaddr), ip_2_ip6(&zoned_ipaddr));
599     ipaddr = &zoned_ipaddr;
600   }
601 #endif /* LWIP_IPV6 && LWIP_IPV6_SCOPES */
602 
603   if (port == 0) {
604     port = tcp_new_port();
605     if (port == 0) {
606       return ERR_BUF;
607     }
608   } else {
609     /* Check if the address already is in use (on all lists) */
610     for (i = 0; i < max_pcb_list; i++) {
611       for (cpcb = *tcp_pcb_lists[i]; cpcb != NULL; cpcb = cpcb->next) {
612         if (cpcb->local_port == port) {
613 #if SO_REUSE
614           /* Omit checking for the same port if both pcbs have REUSEADDR set.
615              For SO_REUSEADDR, the duplicate-check for a 5-tuple is done in
616              tcp_connect. */
617           if (!ip_get_option(pcb, SOF_REUSEADDR) ||
618               !ip_get_option(cpcb, SOF_REUSEADDR))
619 #endif /* SO_REUSE */
620           {
621             /* @todo: check accept_any_ip_version */
622             if ((IP_IS_V6(ipaddr) == IP_IS_V6_VAL(cpcb->local_ip)) &&
623                 (ip_addr_isany(&cpcb->local_ip) ||
624                 ip_addr_isany(ipaddr) ||
625                 ip_addr_cmp(&cpcb->local_ip, ipaddr))) {
626               return ERR_USE;
627             }
628           }
629         }
630       }
631     }
632   }
633 
634   if (!ip_addr_isany(ipaddr)) {
635     ip_addr_set(&pcb->local_ip, ipaddr);
636   }
637   pcb->local_port = port;
638   TCP_REG(&tcp_bound_pcbs, pcb);
639   LWIP_DEBUGF(TCP_DEBUG, ("tcp_bind: bind to port %"U16_F"\n", port));
640   return ERR_OK;
641 }
642 #if LWIP_CALLBACK_API
643 /**
644  * Default accept callback if no accept callback is specified by the user.
645  */
646 static err_t
647 tcp_accept_null(void *arg, struct tcp_pcb *pcb, err_t err)
648 {
649   LWIP_UNUSED_ARG(arg);
650   LWIP_UNUSED_ARG(err);
651 
652   tcp_abort(pcb);
653 
654   return ERR_ABRT;
655 }
656 #endif /* LWIP_CALLBACK_API */
657 
658 /**
659  * @ingroup tcp_raw
660  * Set the state of the connection to be LISTEN, which means that it
661  * is able to accept incoming connections. The protocol control block
662  * is reallocated in order to consume less memory. Setting the
663  * connection to LISTEN is an irreversible process.
664  *
665  * @param pcb the original tcp_pcb
666  * @param backlog the incoming connections queue limit
667  * @return tcp_pcb used for listening, consumes less memory.
668  *
669  * @note The original tcp_pcb is freed. This function therefore has to be
670  *       called like this:
671  *             tpcb = tcp_listen_with_backlog(tpcb, backlog);
672  */
673 struct tcp_pcb *
674 tcp_listen_with_backlog(struct tcp_pcb *pcb, u8_t backlog)
675 {
676   return tcp_listen_with_backlog_and_err(pcb, backlog, NULL);
677 }
678 
679 /**
680  * @ingroup tcp_raw
681  * Set the state of the connection to be LISTEN, which means that it
682  * is able to accept incoming connections. The protocol control block
683  * is reallocated in order to consume less memory. Setting the
684  * connection to LISTEN is an irreversible process.
685  *
686  * @param pcb the original tcp_pcb
687  * @param backlog the incoming connections queue limit
688  * @param err when NULL is returned, this contains the error reason
689  * @return tcp_pcb used for listening, consumes less memory.
690  *
691  * @note The original tcp_pcb is freed. This function therefore has to be
692  *       called like this:
693  *             tpcb = tcp_listen_with_backlog_and_err(tpcb, backlog, &err);
694  */
695 struct tcp_pcb *
696 tcp_listen_with_backlog_and_err(struct tcp_pcb *pcb, u8_t backlog, err_t *err)
697 {
698   struct tcp_pcb_listen *lpcb = NULL;
699   err_t res;
700 
701   LWIP_UNUSED_ARG(backlog);
702   LWIP_ERROR("tcp_listen: pcb already connected", pcb->state == CLOSED, res = ERR_CLSD; goto done);
703 
704   /* already listening? */
705   if (pcb->state == LISTEN) {
706     lpcb = (struct tcp_pcb_listen*)pcb;
707     res = ERR_ALREADY;
708     goto done;
709   }
710 #if SO_REUSE
711   if (ip_get_option(pcb, SOF_REUSEADDR)) {
712     /* Since SOF_REUSEADDR allows reusing a local address before the pcb's usage
713        is declared (listen-/connection-pcb), we have to make sure now that
714        this port is only used once for every local IP. */
715     for (lpcb = tcp_listen_pcbs.listen_pcbs; lpcb != NULL; lpcb = lpcb->next) {
716       if ((lpcb->local_port == pcb->local_port) &&
717           ip_addr_cmp(&lpcb->local_ip, &pcb->local_ip)) {
718         /* this address/port is already used */
719         lpcb = NULL;
720         res = ERR_USE;
721         goto done;
722       }
723     }
724   }
725 #endif /* SO_REUSE */
726   lpcb = (struct tcp_pcb_listen *)memp_malloc(MEMP_TCP_PCB_LISTEN);
727   if (lpcb == NULL) {
728     res = ERR_MEM;
729     goto done;
730   }
731   lpcb->callback_arg = pcb->callback_arg;
732   lpcb->local_port = pcb->local_port;
733   lpcb->state = LISTEN;
734   lpcb->prio = pcb->prio;
735   lpcb->so_options = pcb->so_options;
736   lpcb->ttl = pcb->ttl;
737   lpcb->tos = pcb->tos;
738 #if LWIP_IPV4 && LWIP_IPV6
739   IP_SET_TYPE_VAL(lpcb->remote_ip, pcb->local_ip.type);
740 #endif /* LWIP_IPV4 && LWIP_IPV6 */
741   ip_addr_copy(lpcb->local_ip, pcb->local_ip);
742   if (pcb->local_port != 0) {
743     TCP_RMV(&tcp_bound_pcbs, pcb);
744   }
745   memp_free(MEMP_TCP_PCB, pcb);
746 #if LWIP_CALLBACK_API
747   lpcb->accept = tcp_accept_null;
748 #endif /* LWIP_CALLBACK_API */
749 #if TCP_LISTEN_BACKLOG
750   lpcb->accepts_pending = 0;
751   tcp_backlog_set(lpcb, backlog);
752 #endif /* TCP_LISTEN_BACKLOG */
753   TCP_REG(&tcp_listen_pcbs.pcbs, (struct tcp_pcb *)lpcb);
754   res = ERR_OK;
755 done:
756   if (err != NULL) {
757     *err = res;
758   }
759   return (struct tcp_pcb *)lpcb;
760 }
761 
762 /**
763  * Update the state that tracks the available window space to advertise.
764  *
765  * Returns how much extra window would be advertised if we sent an
766  * update now.
767  */
768 u32_t
769 tcp_update_rcv_ann_wnd(struct tcp_pcb *pcb)
770 {
771   u32_t new_right_edge = pcb->rcv_nxt + pcb->rcv_wnd;
772 
773   if (TCP_SEQ_GEQ(new_right_edge, pcb->rcv_ann_right_edge + LWIP_MIN((TCP_WND / 2), pcb->mss))) {
774     /* we can advertise more window */
775     pcb->rcv_ann_wnd = pcb->rcv_wnd;
776     return new_right_edge - pcb->rcv_ann_right_edge;
777   } else {
778     if (TCP_SEQ_GT(pcb->rcv_nxt, pcb->rcv_ann_right_edge)) {
779       /* Can happen due to other end sending out of advertised window,
780        * but within actual available (but not yet advertised) window */
781       pcb->rcv_ann_wnd = 0;
782     } else {
783       /* keep the right edge of window constant */
784       u32_t new_rcv_ann_wnd = pcb->rcv_ann_right_edge - pcb->rcv_nxt;
785 #if !LWIP_WND_SCALE
786       LWIP_ASSERT("new_rcv_ann_wnd <= 0xffff", new_rcv_ann_wnd <= 0xffff);
787 #endif
788       pcb->rcv_ann_wnd = (tcpwnd_size_t)new_rcv_ann_wnd;
789     }
790     return 0;
791   }
792 }
793 
794 /**
795  * @ingroup tcp_raw
796  * This function should be called by the application when it has
797  * processed the data. The purpose is to advertise a larger window
798  * when the data has been processed.
799  *
800  * @param pcb the tcp_pcb for which data is read
801  * @param len the amount of bytes that have been read by the application
802  */
803 void
804 tcp_recved(struct tcp_pcb *pcb, u16_t len)
805 {
806   int wnd_inflation;
807 
808   /* pcb->state LISTEN not allowed here */
809   LWIP_ASSERT("don't call tcp_recved for listen-pcbs",
810     pcb->state != LISTEN);
811 
812   pcb->rcv_wnd += len;
813   if (pcb->rcv_wnd > TCP_WND_MAX(pcb)) {
814     pcb->rcv_wnd = TCP_WND_MAX(pcb);
815   } else if (pcb->rcv_wnd == 0) {
816     /* rcv_wnd overflowed */
817     if ((pcb->state == CLOSE_WAIT) || (pcb->state == LAST_ACK)) {
818       /* In passive close, we allow this, since the FIN bit is added to rcv_wnd
819          by the stack itself, since it is not mandatory for an application
820          to call tcp_recved() for the FIN bit, but e.g. the netconn API does so. */
821       pcb->rcv_wnd = TCP_WND_MAX(pcb);
822     } else {
823       LWIP_ASSERT("tcp_recved: len wrapped rcv_wnd\n", 0);
824     }
825   }
826 
827   wnd_inflation = tcp_update_rcv_ann_wnd(pcb);
828 
829   /* If the change in the right edge of window is significant (default
830    * watermark is TCP_WND/4), then send an explicit update now.
831    * Otherwise wait for a packet to be sent in the normal course of
832    * events (or more window to be available later) */
833   if (wnd_inflation >= TCP_WND_UPDATE_THRESHOLD) {
834     tcp_ack_now(pcb);
835     tcp_output(pcb);
836   }
837 
838   LWIP_DEBUGF(TCP_DEBUG, ("tcp_recved: received %"U16_F" bytes, wnd %"TCPWNDSIZE_F" (%"TCPWNDSIZE_F").\n",
839          len, pcb->rcv_wnd, (u16_t)(TCP_WND_MAX(pcb) - pcb->rcv_wnd)));
840 }
841 
842 /**
843  * Allocate a new local TCP port.
844  *
845  * @return a new (free) local TCP port number
846  */
847 static u16_t
848 tcp_new_port(void)
849 {
850   u8_t i;
851   u16_t n = 0;
852   struct tcp_pcb *pcb;
853 
854 again:
855   if (tcp_port++ == TCP_LOCAL_PORT_RANGE_END) {
856     tcp_port = TCP_LOCAL_PORT_RANGE_START;
857   }
858   /* Check all PCB lists. */
859   for (i = 0; i < NUM_TCP_PCB_LISTS; i++) {
860     for (pcb = *tcp_pcb_lists[i]; pcb != NULL; pcb = pcb->next) {
861       if (pcb->local_port == tcp_port) {
862         if (++n > (TCP_LOCAL_PORT_RANGE_END - TCP_LOCAL_PORT_RANGE_START)) {
863           return 0;
864         }
865         goto again;
866       }
867     }
868   }
869   return tcp_port;
870 }
871 
872 /**
873  * @ingroup tcp_raw
874  * Connects to another host. The function given as the "connected"
875  * argument will be called when the connection has been established.
876  *
877  * @param pcb the tcp_pcb used to establish the connection
878  * @param ipaddr the remote ip address to connect to
879  * @param port the remote tcp port to connect to
880  * @param connected callback function to call when connected (on error,
881                     the err calback will be called)
882  * @return ERR_VAL if invalid arguments are given
883  *         ERR_OK if connect request has been sent
884  *         other err_t values if connect request couldn't be sent
885  */
886 err_t
887 tcp_connect(struct tcp_pcb *pcb, const ip_addr_t *ipaddr, u16_t port,
888       tcp_connected_fn connected)
889 {
890   struct netif *netif = NULL;
891   err_t ret;
892   u32_t iss;
893   u16_t old_local_port;
894 
895   if ((pcb == NULL) || (ipaddr == NULL)) {
896     return ERR_VAL;
897   }
898 
899   LWIP_ERROR("tcp_connect: can only connect from state CLOSED", pcb->state == CLOSED, return ERR_ISCONN);
900 
901   LWIP_DEBUGF(TCP_DEBUG, ("tcp_connect to port %"U16_F"\n", port));
902   ip_addr_set(&pcb->remote_ip, ipaddr);
903   pcb->remote_port = port;
904 
905   /* check if we have a route to the remote host */
906   if (ip_addr_isany(&pcb->local_ip)) {
907     /* no local IP address set, yet. */
908     const ip_addr_t *local_ip;
909     ip_route_get_local_ip(&pcb->local_ip, &pcb->remote_ip, netif, local_ip);
910     if ((netif == NULL) || (local_ip == NULL)) {
911       /* Don't even try to send a SYN packet if we have no route
912          since that will fail. */
913       return ERR_RTE;
914     }
915     /* Use the address as local address of the pcb. */
916     ip_addr_copy(pcb->local_ip, *local_ip);
917   } else {
918     netif = ip_route(&pcb->local_ip, &pcb->remote_ip);
919     if (netif == NULL) {
920       /* Don't even try to send a SYN packet if we have no route
921          since that will fail. */
922       return ERR_RTE;
923     }
924   }
925   LWIP_ASSERT("netif != NULL", netif != NULL);
926 
927 #if LWIP_IPV6 && LWIP_IPV6_SCOPES
928   /* If the given IP address should have a zone but doesn't, assign one now.
929    * Given that we already have the target netif, this is easy and cheap. */
930   if (IP_IS_V6(&pcb->remote_ip) &&
931       ip6_addr_lacks_zone(ip_2_ip6(&pcb->remote_ip), IP6_UNICAST)) {
932     ip6_addr_assign_zone(ip_2_ip6(&pcb->remote_ip), IP6_UNICAST, netif);
933   }
934 #endif /* LWIP_IPV6 && LWIP_IPV6_SCOPES */
935 
936   old_local_port = pcb->local_port;
937   if (pcb->local_port == 0) {
938     pcb->local_port = tcp_new_port();
939     if (pcb->local_port == 0) {
940       return ERR_BUF;
941     }
942   } else {
943 #if SO_REUSE
944     if (ip_get_option(pcb, SOF_REUSEADDR)) {
945       /* Since SOF_REUSEADDR allows reusing a local address, we have to make sure
946          now that the 5-tuple is unique. */
947       struct tcp_pcb *cpcb;
948       int i;
949       /* Don't check listen- and bound-PCBs, check active- and TIME-WAIT PCBs. */
950       for (i = 2; i < NUM_TCP_PCB_LISTS; i++) {
951         for (cpcb = *tcp_pcb_lists[i]; cpcb != NULL; cpcb = cpcb->next) {
952           if ((cpcb->local_port == pcb->local_port) &&
953               (cpcb->remote_port == port) &&
954               ip_addr_cmp(&cpcb->local_ip, &pcb->local_ip) &&
955               ip_addr_cmp(&cpcb->remote_ip, ipaddr)) {
956             /* linux returns EISCONN here, but ERR_USE should be OK for us */
957             return ERR_USE;
958           }
959         }
960       }
961     }
962 #endif /* SO_REUSE */
963   }
964 
965   iss = tcp_next_iss(pcb);
966   pcb->rcv_nxt = 0;
967   pcb->snd_nxt = iss;
968   pcb->lastack = iss - 1;
969   pcb->snd_wl2 = iss - 1;
970   pcb->snd_lbb = iss - 1;
971   /* Start with a window that does not need scaling. When window scaling is
972      enabled and used, the window is enlarged when both sides agree on scaling. */
973   pcb->rcv_wnd = pcb->rcv_ann_wnd = TCPWND_MIN16(TCP_WND);
974   pcb->rcv_ann_right_edge = pcb->rcv_nxt;
975   pcb->snd_wnd = TCP_WND;
976   /* As initial send MSS, we use TCP_MSS but limit it to 536.
977      The send MSS is updated when an MSS option is received. */
978   pcb->mss = INITIAL_MSS;
979 #if TCP_CALCULATE_EFF_SEND_MSS
980   pcb->mss = tcp_eff_send_mss_netif(pcb->mss, netif, &pcb->remote_ip);
981 #endif /* TCP_CALCULATE_EFF_SEND_MSS */
982   pcb->cwnd = 1;
983 #if LWIP_CALLBACK_API
984   pcb->connected = connected;
985 #else /* LWIP_CALLBACK_API */
986   LWIP_UNUSED_ARG(connected);
987 #endif /* LWIP_CALLBACK_API */
988 
989   /* Send a SYN together with the MSS option. */
990   ret = tcp_enqueue_flags(pcb, TCP_SYN);
991   if (ret == ERR_OK) {
992     /* SYN segment was enqueued, changed the pcbs state now */
993     pcb->state = SYN_SENT;
994     if (old_local_port != 0) {
995       TCP_RMV(&tcp_bound_pcbs, pcb);
996     }
997     TCP_REG_ACTIVE(pcb);
998     MIB2_STATS_INC(mib2.tcpactiveopens);
999 
1000     tcp_output(pcb);
1001   }
1002   return ret;
1003 }
1004 
1005 /**
1006  * Called every 500 ms and implements the retransmission timer and the timer that
1007  * removes PCBs that have been in TIME-WAIT for enough time. It also increments
1008  * various timers such as the inactivity timer in each PCB.
1009  *
1010  * Automatically called from tcp_tmr().
1011  */
1012 void
1013 tcp_slowtmr(void)
1014 {
1015   struct tcp_pcb *pcb, *prev;
1016   tcpwnd_size_t eff_wnd;
1017   u8_t pcb_remove;      /* flag if a PCB should be removed */
1018   u8_t pcb_reset;       /* flag if a RST should be sent when removing */
1019   err_t err;
1020 
1021   err = ERR_OK;
1022 
1023   ++tcp_ticks;
1024   ++tcp_timer_ctr;
1025 
1026 tcp_slowtmr_start:
1027   /* Steps through all of the active PCBs. */
1028   prev = NULL;
1029   pcb = tcp_active_pcbs;
1030   if (pcb == NULL) {
1031     LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: no active pcbs\n"));
1032   }
1033   while (pcb != NULL) {
1034     LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: processing active pcb\n"));
1035     LWIP_ASSERT("tcp_slowtmr: active pcb->state != CLOSED\n", pcb->state != CLOSED);
1036     LWIP_ASSERT("tcp_slowtmr: active pcb->state != LISTEN\n", pcb->state != LISTEN);
1037     LWIP_ASSERT("tcp_slowtmr: active pcb->state != TIME-WAIT\n", pcb->state != TIME_WAIT);
1038     if (pcb->last_timer == tcp_timer_ctr) {
1039       /* skip this pcb, we have already processed it */
1040       pcb = pcb->next;
1041       continue;
1042     }
1043     pcb->last_timer = tcp_timer_ctr;
1044 
1045     pcb_remove = 0;
1046     pcb_reset = 0;
1047 
1048     if (pcb->state == SYN_SENT && pcb->nrtx >= TCP_SYNMAXRTX) {
1049       ++pcb_remove;
1050       LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: max SYN retries reached\n"));
1051     }
1052     else if (pcb->nrtx >= TCP_MAXRTX) {
1053       ++pcb_remove;
1054       LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: max DATA retries reached\n"));
1055     } else {
1056       if (pcb->persist_backoff > 0) {
1057         /* If snd_wnd is zero, use persist timer to send 1 byte probes
1058          * instead of using the standard retransmission mechanism. */
1059         u8_t backoff_cnt = tcp_persist_backoff[pcb->persist_backoff-1];
1060         if (pcb->persist_cnt < backoff_cnt) {
1061           pcb->persist_cnt++;
1062         }
1063         if (pcb->persist_cnt >= backoff_cnt) {
1064           if (tcp_zero_window_probe(pcb) == ERR_OK) {
1065             pcb->persist_cnt = 0;
1066             if (pcb->persist_backoff < sizeof(tcp_persist_backoff)) {
1067               pcb->persist_backoff++;
1068             }
1069           }
1070         }
1071       } else {
1072         /* Increase the retransmission timer if it is running */
1073         if (pcb->rtime >= 0) {
1074           ++pcb->rtime;
1075         }
1076 
1077         if (pcb->unacked != NULL && pcb->rtime >= pcb->rto) {
1078           /* Time for a retransmission. */
1079           LWIP_DEBUGF(TCP_RTO_DEBUG, ("tcp_slowtmr: rtime %"S16_F
1080                                       " pcb->rto %"S16_F"\n",
1081                                       pcb->rtime, pcb->rto));
1082 
1083           /* Double retransmission time-out unless we are trying to
1084            * connect to somebody (i.e., we are in SYN_SENT). */
1085           if (pcb->state != SYN_SENT) {
1086             u8_t backoff_idx = LWIP_MIN(pcb->nrtx, sizeof(tcp_backoff)-1);
1087             pcb->rto = ((pcb->sa >> 3) + pcb->sv) << tcp_backoff[backoff_idx];
1088           }
1089 
1090           /* Reset the retransmission timer. */
1091           pcb->rtime = 0;
1092 
1093           /* Reduce congestion window and ssthresh. */
1094           eff_wnd = LWIP_MIN(pcb->cwnd, pcb->snd_wnd);
1095           pcb->ssthresh = eff_wnd >> 1;
1096           if (pcb->ssthresh < (tcpwnd_size_t)(pcb->mss << 1)) {
1097             pcb->ssthresh = (pcb->mss << 1);
1098           }
1099           pcb->cwnd = pcb->mss;
1100           LWIP_DEBUGF(TCP_CWND_DEBUG, ("tcp_slowtmr: cwnd %"TCPWNDSIZE_F
1101                                        " ssthresh %"TCPWNDSIZE_F"\n",
1102                                        pcb->cwnd, pcb->ssthresh));
1103 
1104           /* The following needs to be called AFTER cwnd is set to one
1105              mss - STJ */
1106           tcp_rexmit_rto(pcb);
1107         }
1108       }
1109     }
1110     /* Check if this PCB has stayed too long in FIN-WAIT-2 */
1111     if (pcb->state == FIN_WAIT_2) {
1112       /* If this PCB is in FIN_WAIT_2 because of SHUT_WR don't let it time out. */
1113       if (pcb->flags & TF_RXCLOSED) {
1114         /* PCB was fully closed (either through close() or SHUT_RDWR):
1115            normal FIN-WAIT timeout handling. */
1116         if ((u32_t)(tcp_ticks - pcb->tmr) >
1117             TCP_FIN_WAIT_TIMEOUT / TCP_SLOW_INTERVAL) {
1118           ++pcb_remove;
1119           LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: removing pcb stuck in FIN-WAIT-2\n"));
1120         }
1121       }
1122     }
1123 
1124     /* Check if KEEPALIVE should be sent */
1125     if (ip_get_option(pcb, SOF_KEEPALIVE) &&
1126        ((pcb->state == ESTABLISHED) ||
1127         (pcb->state == CLOSE_WAIT))) {
1128       if ((u32_t)(tcp_ticks - pcb->tmr) >
1129          (pcb->keep_idle + TCP_KEEP_DUR(pcb)) / TCP_SLOW_INTERVAL)
1130       {
1131         LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: KEEPALIVE timeout. Aborting connection to "));
1132         ip_addr_debug_print(TCP_DEBUG, &pcb->remote_ip);
1133         LWIP_DEBUGF(TCP_DEBUG, ("\n"));
1134 
1135         ++pcb_remove;
1136         ++pcb_reset;
1137       } else if ((u32_t)(tcp_ticks - pcb->tmr) >
1138                 (pcb->keep_idle + pcb->keep_cnt_sent * TCP_KEEP_INTVL(pcb))
1139                 / TCP_SLOW_INTERVAL)
1140       {
1141         err = tcp_keepalive(pcb);
1142         if (err == ERR_OK) {
1143           pcb->keep_cnt_sent++;
1144         }
1145       }
1146     }
1147 
1148     /* If this PCB has queued out of sequence data, but has been
1149        inactive for too long, will drop the data (it will eventually
1150        be retransmitted). */
1151 #if TCP_QUEUE_OOSEQ
1152     if (pcb->ooseq != NULL &&
1153         (u32_t)tcp_ticks - pcb->tmr >= pcb->rto * TCP_OOSEQ_TIMEOUT) {
1154       tcp_segs_free(pcb->ooseq);
1155       pcb->ooseq = NULL;
1156       LWIP_DEBUGF(TCP_CWND_DEBUG, ("tcp_slowtmr: dropping OOSEQ queued data\n"));
1157     }
1158 #endif /* TCP_QUEUE_OOSEQ */
1159 
1160     /* Check if this PCB has stayed too long in SYN-RCVD */
1161     if (pcb->state == SYN_RCVD) {
1162       if ((u32_t)(tcp_ticks - pcb->tmr) >
1163           TCP_SYN_RCVD_TIMEOUT / TCP_SLOW_INTERVAL) {
1164         ++pcb_remove;
1165         LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: removing pcb stuck in SYN-RCVD\n"));
1166       }
1167     }
1168 
1169     /* Check if this PCB has stayed too long in LAST-ACK */
1170     if (pcb->state == LAST_ACK) {
1171       if ((u32_t)(tcp_ticks - pcb->tmr) > 2 * TCP_MSL / TCP_SLOW_INTERVAL) {
1172         ++pcb_remove;
1173         LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: removing pcb stuck in LAST-ACK\n"));
1174       }
1175     }
1176 
1177     /* If the PCB should be removed, do it. */
1178     if (pcb_remove) {
1179       struct tcp_pcb *pcb2;
1180 #if LWIP_CALLBACK_API
1181       tcp_err_fn err_fn = pcb->errf;
1182 #endif /* LWIP_CALLBACK_API */
1183       void *err_arg;
1184       enum tcp_state last_state;
1185       tcp_pcb_purge(pcb);
1186       /* Remove PCB from tcp_active_pcbs list. */
1187       if (prev != NULL) {
1188         LWIP_ASSERT("tcp_slowtmr: middle tcp != tcp_active_pcbs", pcb != tcp_active_pcbs);
1189         prev->next = pcb->next;
1190       } else {
1191         /* This PCB was the first. */
1192         LWIP_ASSERT("tcp_slowtmr: first pcb == tcp_active_pcbs", tcp_active_pcbs == pcb);
1193         tcp_active_pcbs = pcb->next;
1194       }
1195 
1196       if (pcb_reset) {
1197         tcp_rst(pcb->snd_nxt, pcb->rcv_nxt, &pcb->local_ip, &pcb->remote_ip,
1198                  pcb->local_port, pcb->remote_port);
1199       }
1200 
1201       err_arg = pcb->callback_arg;
1202       last_state = pcb->state;
1203       pcb2 = pcb;
1204       pcb = pcb->next;
1205       memp_free(MEMP_TCP_PCB, pcb2);
1206 
1207       tcp_active_pcbs_changed = 0;
1208       TCP_EVENT_ERR(last_state, err_fn, err_arg, ERR_ABRT);
1209       if (tcp_active_pcbs_changed) {
1210         goto tcp_slowtmr_start;
1211       }
1212     } else {
1213       /* get the 'next' element now and work with 'prev' below (in case of abort) */
1214       prev = pcb;
1215       pcb = pcb->next;
1216 
1217       /* We check if we should poll the connection. */
1218       ++prev->polltmr;
1219       if (prev->polltmr >= prev->pollinterval) {
1220         prev->polltmr = 0;
1221         LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: polling application\n"));
1222         tcp_active_pcbs_changed = 0;
1223         TCP_EVENT_POLL(prev, err);
1224         if (tcp_active_pcbs_changed) {
1225           goto tcp_slowtmr_start;
1226         }
1227         /* if err == ERR_ABRT, 'prev' is already deallocated */
1228         if (err == ERR_OK) {
1229           tcp_output(prev);
1230         }
1231       }
1232     }
1233   }
1234 
1235 
1236   /* Steps through all of the TIME-WAIT PCBs. */
1237   prev = NULL;
1238   pcb = tcp_tw_pcbs;
1239   while (pcb != NULL) {
1240     LWIP_ASSERT("tcp_slowtmr: TIME-WAIT pcb->state == TIME-WAIT", pcb->state == TIME_WAIT);
1241     pcb_remove = 0;
1242 
1243     /* Check if this PCB has stayed long enough in TIME-WAIT */
1244     if ((u32_t)(tcp_ticks - pcb->tmr) > 2 * TCP_MSL / TCP_SLOW_INTERVAL) {
1245       ++pcb_remove;
1246     }
1247 
1248     /* If the PCB should be removed, do it. */
1249     if (pcb_remove) {
1250       struct tcp_pcb *pcb2;
1251       tcp_pcb_purge(pcb);
1252       /* Remove PCB from tcp_tw_pcbs list. */
1253       if (prev != NULL) {
1254         LWIP_ASSERT("tcp_slowtmr: middle tcp != tcp_tw_pcbs", pcb != tcp_tw_pcbs);
1255         prev->next = pcb->next;
1256       } else {
1257         /* This PCB was the first. */
1258         LWIP_ASSERT("tcp_slowtmr: first pcb == tcp_tw_pcbs", tcp_tw_pcbs == pcb);
1259         tcp_tw_pcbs = pcb->next;
1260       }
1261       pcb2 = pcb;
1262       pcb = pcb->next;
1263       memp_free(MEMP_TCP_PCB, pcb2);
1264     } else {
1265       prev = pcb;
1266       pcb = pcb->next;
1267     }
1268   }
1269 }
1270 
1271 /**
1272  * Is called every TCP_FAST_INTERVAL (250 ms) and process data previously
1273  * "refused" by upper layer (application) and sends delayed ACKs.
1274  *
1275  * Automatically called from tcp_tmr().
1276  */
1277 void
1278 tcp_fasttmr(void)
1279 {
1280   struct tcp_pcb *pcb;
1281 
1282   ++tcp_timer_ctr;
1283 
1284 tcp_fasttmr_start:
1285   pcb = tcp_active_pcbs;
1286 
1287   while (pcb != NULL) {
1288     if (pcb->last_timer != tcp_timer_ctr) {
1289       struct tcp_pcb *next;
1290       pcb->last_timer = tcp_timer_ctr;
1291       /* send delayed ACKs */
1292       if (pcb->flags & TF_ACK_DELAY) {
1293         LWIP_DEBUGF(TCP_DEBUG, ("tcp_fasttmr: delayed ACK\n"));
1294         tcp_ack_now(pcb);
1295         tcp_output(pcb);
1296         pcb->flags &= ~(TF_ACK_DELAY | TF_ACK_NOW);
1297       }
1298       /* send pending FIN */
1299       if (pcb->flags & TF_CLOSEPEND) {
1300         LWIP_DEBUGF(TCP_DEBUG, ("tcp_fasttmr: pending FIN\n"));
1301         pcb->flags &= ~(TF_CLOSEPEND);
1302         tcp_close_shutdown_fin(pcb);
1303       }
1304 
1305       next = pcb->next;
1306 
1307       /* If there is data which was previously "refused" by upper layer */
1308       if (pcb->refused_data != NULL) {
1309         tcp_active_pcbs_changed = 0;
1310         tcp_process_refused_data(pcb);
1311         if (tcp_active_pcbs_changed) {
1312           /* application callback has changed the pcb list: restart the loop */
1313           goto tcp_fasttmr_start;
1314         }
1315       }
1316       pcb = next;
1317     } else {
1318       pcb = pcb->next;
1319     }
1320   }
1321 }
1322 
1323 /** Call tcp_output for all active pcbs that have TF_NAGLEMEMERR set */
1324 void
1325 tcp_txnow(void)
1326 {
1327   struct tcp_pcb *pcb;
1328 
1329   for (pcb = tcp_active_pcbs; pcb != NULL; pcb = pcb->next) {
1330     if (pcb->flags & TF_NAGLEMEMERR) {
1331       tcp_output(pcb);
1332     }
1333   }
1334 }
1335 
1336 /** Pass pcb->refused_data to the recv callback */
1337 err_t
1338 tcp_process_refused_data(struct tcp_pcb *pcb)
1339 {
1340 #if TCP_QUEUE_OOSEQ && LWIP_WND_SCALE
1341   struct pbuf *rest;
1342   while (pcb->refused_data != NULL)
1343 #endif /* TCP_QUEUE_OOSEQ && LWIP_WND_SCALE */
1344   {
1345     err_t err;
1346     u8_t refused_flags = pcb->refused_data->flags;
1347     /* set pcb->refused_data to NULL in case the callback frees it and then
1348        closes the pcb */
1349     struct pbuf *refused_data = pcb->refused_data;
1350 #if TCP_QUEUE_OOSEQ && LWIP_WND_SCALE
1351     pbuf_split_64k(refused_data, &rest);
1352     pcb->refused_data = rest;
1353 #else /* TCP_QUEUE_OOSEQ && LWIP_WND_SCALE */
1354     pcb->refused_data = NULL;
1355 #endif /* TCP_QUEUE_OOSEQ && LWIP_WND_SCALE */
1356     /* Notify again application with data previously received. */
1357     LWIP_DEBUGF(TCP_INPUT_DEBUG, ("tcp_input: notify kept packet\n"));
1358     TCP_EVENT_RECV(pcb, refused_data, ERR_OK, err);
1359     if (err == ERR_OK) {
1360       /* did refused_data include a FIN? */
1361       if ((refused_flags & PBUF_FLAG_TCP_FIN)
1362 #if TCP_QUEUE_OOSEQ && LWIP_WND_SCALE
1363           && (rest == NULL)
1364 #endif /* TCP_QUEUE_OOSEQ && LWIP_WND_SCALE */
1365          ) {
1366         /* correct rcv_wnd as the application won't call tcp_recved()
1367            for the FIN's seqno */
1368         if (pcb->rcv_wnd != TCP_WND_MAX(pcb)) {
1369           pcb->rcv_wnd++;
1370         }
1371         TCP_EVENT_CLOSED(pcb, err);
1372         if (err == ERR_ABRT) {
1373           return ERR_ABRT;
1374         }
1375       }
1376     } else if (err == ERR_ABRT) {
1377       /* if err == ERR_ABRT, 'pcb' is already deallocated */
1378       /* Drop incoming packets because pcb is "full" (only if the incoming
1379          segment contains data). */
1380       LWIP_DEBUGF(TCP_INPUT_DEBUG, ("tcp_input: drop incoming packets, because pcb is \"full\"\n"));
1381       return ERR_ABRT;
1382     } else {
1383       /* data is still refused, pbuf is still valid (go on for ACK-only packets) */
1384 #if TCP_QUEUE_OOSEQ && LWIP_WND_SCALE
1385       if (rest != NULL) {
1386         pbuf_cat(refused_data, rest);
1387       }
1388 #endif /* TCP_QUEUE_OOSEQ && LWIP_WND_SCALE */
1389       pcb->refused_data = refused_data;
1390       return ERR_INPROGRESS;
1391     }
1392   }
1393   return ERR_OK;
1394 }
1395 
1396 /**
1397  * Deallocates a list of TCP segments (tcp_seg structures).
1398  *
1399  * @param seg tcp_seg list of TCP segments to free
1400  */
1401 void
1402 tcp_segs_free(struct tcp_seg *seg)
1403 {
1404   while (seg != NULL) {
1405     struct tcp_seg *next = seg->next;
1406     tcp_seg_free(seg);
1407     seg = next;
1408   }
1409 }
1410 
1411 /**
1412  * Frees a TCP segment (tcp_seg structure).
1413  *
1414  * @param seg single tcp_seg to free
1415  */
1416 void
1417 tcp_seg_free(struct tcp_seg *seg)
1418 {
1419   if (seg != NULL) {
1420     if (seg->p != NULL) {
1421       pbuf_free(seg->p);
1422 #if TCP_DEBUG
1423       seg->p = NULL;
1424 #endif /* TCP_DEBUG */
1425     }
1426     memp_free(MEMP_TCP_SEG, seg);
1427   }
1428 }
1429 
1430 /**
1431  * Sets the priority of a connection.
1432  *
1433  * @param pcb the tcp_pcb to manipulate
1434  * @param prio new priority
1435  */
1436 void
1437 tcp_setprio(struct tcp_pcb *pcb, u8_t prio)
1438 {
1439   pcb->prio = prio;
1440 }
1441 
1442 #if TCP_QUEUE_OOSEQ
1443 /**
1444  * Returns a copy of the given TCP segment.
1445  * The pbuf and data are not copied, only the pointers
1446  *
1447  * @param seg the old tcp_seg
1448  * @return a copy of seg
1449  */
1450 struct tcp_seg *
1451 tcp_seg_copy(struct tcp_seg *seg)
1452 {
1453   struct tcp_seg *cseg;
1454 
1455   cseg = (struct tcp_seg *)memp_malloc(MEMP_TCP_SEG);
1456   if (cseg == NULL) {
1457     return NULL;
1458   }
1459   SMEMCPY((u8_t *)cseg, (const u8_t *)seg, sizeof(struct tcp_seg));
1460   pbuf_ref(cseg->p);
1461   return cseg;
1462 }
1463 #endif /* TCP_QUEUE_OOSEQ */
1464 
1465 #if LWIP_CALLBACK_API
1466 /**
1467  * Default receive callback that is called if the user didn't register
1468  * a recv callback for the pcb.
1469  */
1470 err_t
1471 tcp_recv_null(void *arg, struct tcp_pcb *pcb, struct pbuf *p, err_t err)
1472 {
1473   LWIP_UNUSED_ARG(arg);
1474   if (p != NULL) {
1475     tcp_recved(pcb, p->tot_len);
1476     pbuf_free(p);
1477   } else if (err == ERR_OK) {
1478     return tcp_close(pcb);
1479   }
1480   return ERR_OK;
1481 }
1482 #endif /* LWIP_CALLBACK_API */
1483 
1484 /**
1485  * Kills the oldest active connection that has the same or lower priority than
1486  * 'prio'.
1487  *
1488  * @param prio minimum priority
1489  */
1490 static void
1491 tcp_kill_prio(u8_t prio)
1492 {
1493   struct tcp_pcb *pcb, *inactive;
1494   u32_t inactivity;
1495   u8_t mprio;
1496 
1497   mprio = LWIP_MIN(TCP_PRIO_MAX, prio);
1498 
1499   /* We kill the oldest active connection that has lower priority than prio. */
1500   inactivity = 0;
1501   inactive = NULL;
1502   for (pcb = tcp_active_pcbs; pcb != NULL; pcb = pcb->next) {
1503     if (pcb->prio <= mprio &&
1504        (u32_t)(tcp_ticks - pcb->tmr) >= inactivity) {
1505       inactivity = tcp_ticks - pcb->tmr;
1506       inactive = pcb;
1507       mprio = pcb->prio;
1508     }
1509   }
1510   if (inactive != NULL) {
1511     LWIP_DEBUGF(TCP_DEBUG, ("tcp_kill_prio: killing oldest PCB %p (%"S32_F")\n",
1512            (void *)inactive, inactivity));
1513     tcp_abort(inactive);
1514   }
1515 }
1516 
1517 /**
1518  * Kills the oldest connection that is in specific state.
1519  * Called from tcp_alloc() for LAST_ACK and CLOSING if no more connections are available.
1520  */
1521 static void
1522 tcp_kill_state(enum tcp_state state)
1523 {
1524   struct tcp_pcb *pcb, *inactive;
1525   u32_t inactivity;
1526 
1527   LWIP_ASSERT("invalid state", (state == CLOSING) || (state == LAST_ACK));
1528 
1529   inactivity = 0;
1530   inactive = NULL;
1531   /* Go through the list of active pcbs and get the oldest pcb that is in state
1532      CLOSING/LAST_ACK. */
1533   for (pcb = tcp_active_pcbs; pcb != NULL; pcb = pcb->next) {
1534     if (pcb->state == state) {
1535       if ((u32_t)(tcp_ticks - pcb->tmr) >= inactivity) {
1536         inactivity = tcp_ticks - pcb->tmr;
1537         inactive = pcb;
1538       }
1539     }
1540   }
1541   if (inactive != NULL) {
1542     LWIP_DEBUGF(TCP_DEBUG, ("tcp_kill_closing: killing oldest %s PCB %p (%"S32_F")\n",
1543            tcp_state_str[state], (void *)inactive, inactivity));
1544     /* Don't send a RST, since no data is lost. */
1545     tcp_abandon(inactive, 0);
1546   }
1547 }
1548 
1549 /**
1550  * Kills the oldest connection that is in TIME_WAIT state.
1551  * Called from tcp_alloc() if no more connections are available.
1552  */
1553 static void
1554 tcp_kill_timewait(void)
1555 {
1556   struct tcp_pcb *pcb, *inactive;
1557   u32_t inactivity;
1558 
1559   inactivity = 0;
1560   inactive = NULL;
1561   /* Go through the list of TIME_WAIT pcbs and get the oldest pcb. */
1562   for (pcb = tcp_tw_pcbs; pcb != NULL; pcb = pcb->next) {
1563     if ((u32_t)(tcp_ticks - pcb->tmr) >= inactivity) {
1564       inactivity = tcp_ticks - pcb->tmr;
1565       inactive = pcb;
1566     }
1567   }
1568   if (inactive != NULL) {
1569     LWIP_DEBUGF(TCP_DEBUG, ("tcp_kill_timewait: killing oldest TIME-WAIT PCB %p (%"S32_F")\n",
1570            (void *)inactive, inactivity));
1571     tcp_abort(inactive);
1572   }
1573 }
1574 
1575 /**
1576  * Allocate a new tcp_pcb structure.
1577  *
1578  * @param prio priority for the new pcb
1579  * @return a new tcp_pcb that initially is in state CLOSED
1580  */
1581 struct tcp_pcb *
1582 tcp_alloc(u8_t prio)
1583 {
1584   struct tcp_pcb *pcb;
1585 
1586   pcb = (struct tcp_pcb *)memp_malloc(MEMP_TCP_PCB);
1587   if (pcb == NULL) {
1588     /* Try killing oldest connection in TIME-WAIT. */
1589     LWIP_DEBUGF(TCP_DEBUG, ("tcp_alloc: killing off oldest TIME-WAIT connection\n"));
1590     tcp_kill_timewait();
1591     /* Try to allocate a tcp_pcb again. */
1592     pcb = (struct tcp_pcb *)memp_malloc(MEMP_TCP_PCB);
1593     if (pcb == NULL) {
1594       /* Try killing oldest connection in LAST-ACK (these wouldn't go to TIME-WAIT). */
1595       LWIP_DEBUGF(TCP_DEBUG, ("tcp_alloc: killing off oldest LAST-ACK connection\n"));
1596       tcp_kill_state(LAST_ACK);
1597       /* Try to allocate a tcp_pcb again. */
1598       pcb = (struct tcp_pcb *)memp_malloc(MEMP_TCP_PCB);
1599       if (pcb == NULL) {
1600         /* Try killing oldest connection in CLOSING. */
1601         LWIP_DEBUGF(TCP_DEBUG, ("tcp_alloc: killing off oldest CLOSING connection\n"));
1602         tcp_kill_state(CLOSING);
1603         /* Try to allocate a tcp_pcb again. */
1604         pcb = (struct tcp_pcb *)memp_malloc(MEMP_TCP_PCB);
1605         if (pcb == NULL) {
1606           /* Try killing active connections with lower priority than the new one. */
1607           LWIP_DEBUGF(TCP_DEBUG, ("tcp_alloc: killing connection with prio lower than %d\n", prio));
1608           tcp_kill_prio(prio);
1609           /* Try to allocate a tcp_pcb again. */
1610           pcb = (struct tcp_pcb *)memp_malloc(MEMP_TCP_PCB);
1611           if (pcb != NULL) {
1612             /* adjust err stats: memp_malloc failed multiple times before */
1613             MEMP_STATS_DEC(err, MEMP_TCP_PCB);
1614           }
1615         }
1616         if (pcb != NULL) {
1617           /* adjust err stats: memp_malloc failed multiple times before */
1618           MEMP_STATS_DEC(err, MEMP_TCP_PCB);
1619         }
1620       }
1621       if (pcb != NULL) {
1622         /* adjust err stats: memp_malloc failed multiple times before */
1623         MEMP_STATS_DEC(err, MEMP_TCP_PCB);
1624       }
1625     }
1626     if (pcb != NULL) {
1627       /* adjust err stats: memp_malloc failed above */
1628       MEMP_STATS_DEC(err, MEMP_TCP_PCB);
1629     }
1630   }
1631   if (pcb != NULL) {
1632     /* zero out the whole pcb, so there is no need to initialize members to zero */
1633     memset(pcb, 0, sizeof(struct tcp_pcb));
1634     pcb->prio = prio;
1635     pcb->snd_buf = TCP_SND_BUF;
1636     /* Start with a window that does not need scaling. When window scaling is
1637        enabled and used, the window is enlarged when both sides agree on scaling. */
1638     pcb->rcv_wnd = pcb->rcv_ann_wnd = TCPWND_MIN16(TCP_WND);
1639     pcb->ttl = TCP_TTL;
1640     /* As initial send MSS, we use TCP_MSS but limit it to 536.
1641        The send MSS is updated when an MSS option is received. */
1642     pcb->mss = INITIAL_MSS;
1643     pcb->rto = 3000 / TCP_SLOW_INTERVAL;
1644     pcb->sv = 3000 / TCP_SLOW_INTERVAL;
1645     pcb->rtime = -1;
1646     pcb->cwnd = 1;
1647     pcb->tmr = tcp_ticks;
1648     pcb->last_timer = tcp_timer_ctr;
1649 
1650     /* RFC 5681 recommends setting ssthresh abritrarily high and gives an example
1651     of using the largest advertised receive window.  We've seen complications with
1652     receiving TCPs that use window scaling and/or window auto-tuning where the
1653     initial advertised window is very small and then grows rapidly once the
1654     connection is established. To avoid these complications, we set ssthresh to the
1655     largest effective cwnd (amount of in-flight data) that the sender can have. */
1656     pcb->ssthresh = TCP_SND_BUF;
1657 
1658 #if LWIP_CALLBACK_API
1659     pcb->recv = tcp_recv_null;
1660 #endif /* LWIP_CALLBACK_API */
1661 
1662     /* Init KEEPALIVE timer */
1663     pcb->keep_idle  = TCP_KEEPIDLE_DEFAULT;
1664 
1665 #if LWIP_TCP_KEEPALIVE
1666     pcb->keep_intvl = TCP_KEEPINTVL_DEFAULT;
1667     pcb->keep_cnt   = TCP_KEEPCNT_DEFAULT;
1668 #endif /* LWIP_TCP_KEEPALIVE */
1669   }
1670   return pcb;
1671 }
1672 
1673 /**
1674  * @ingroup tcp_raw
1675  * Creates a new TCP protocol control block but doesn't place it on
1676  * any of the TCP PCB lists.
1677  * The pcb is not put on any list until binding using tcp_bind().
1678  *
1679  * @internal: Maybe there should be a idle TCP PCB list where these
1680  * PCBs are put on. Port reservation using tcp_bind() is implemented but
1681  * allocated pcbs that are not bound can't be killed automatically if wanting
1682  * to allocate a pcb with higher prio (@see tcp_kill_prio())
1683  *
1684  * @return a new tcp_pcb that initially is in state CLOSED
1685  */
1686 struct tcp_pcb *
1687 tcp_new(void)
1688 {
1689   return tcp_alloc(TCP_PRIO_NORMAL);
1690 }
1691 
1692 /**
1693  * @ingroup tcp_raw
1694  * Creates a new TCP protocol control block but doesn't
1695  * place it on any of the TCP PCB lists.
1696  * The pcb is not put on any list until binding using tcp_bind().
1697  *
1698  * @param type IP address type, see @ref lwip_ip_addr_type definitions.
1699  * If you want to listen to IPv4 and IPv6 (dual-stack) connections,
1700  * supply @ref IPADDR_TYPE_ANY as argument and bind to @ref IP_ANY_TYPE.
1701  * @return a new tcp_pcb that initially is in state CLOSED
1702  */
1703 struct tcp_pcb *
1704 tcp_new_ip_type(u8_t type)
1705 {
1706   struct tcp_pcb * pcb;
1707   pcb = tcp_alloc(TCP_PRIO_NORMAL);
1708 #if LWIP_IPV4 && LWIP_IPV6
1709   if (pcb != NULL) {
1710     IP_SET_TYPE_VAL(pcb->local_ip, type);
1711     IP_SET_TYPE_VAL(pcb->remote_ip, type);
1712   }
1713 #else
1714   LWIP_UNUSED_ARG(type);
1715 #endif /* LWIP_IPV4 && LWIP_IPV6 */
1716   return pcb;
1717 }
1718 
1719 /**
1720  * @ingroup tcp_raw
1721  * Used to specify the argument that should be passed callback
1722  * functions.
1723  *
1724  * @param pcb tcp_pcb to set the callback argument
1725  * @param arg void pointer argument to pass to callback functions
1726  */
1727 void
1728 tcp_arg(struct tcp_pcb *pcb, void *arg)
1729 {
1730   /* This function is allowed to be called for both listen pcbs and
1731      connection pcbs. */
1732   if (pcb != NULL) {
1733     pcb->callback_arg = arg;
1734   }
1735 }
1736 #if LWIP_CALLBACK_API
1737 
1738 /**
1739  * @ingroup tcp_raw
1740  * Used to specify the function that should be called when a TCP
1741  * connection receives data.
1742  *
1743  * @param pcb tcp_pcb to set the recv callback
1744  * @param recv callback function to call for this pcb when data is received
1745  */
1746 void
1747 tcp_recv(struct tcp_pcb *pcb, tcp_recv_fn recv)
1748 {
1749   if (pcb != NULL) {
1750     LWIP_ASSERT("invalid socket state for recv callback", pcb->state != LISTEN);
1751     pcb->recv = recv;
1752   }
1753 }
1754 
1755 /**
1756  * @ingroup tcp_raw
1757  * Used to specify the function that should be called when TCP data
1758  * has been successfully delivered to the remote host.
1759  *
1760  * @param pcb tcp_pcb to set the sent callback
1761  * @param sent callback function to call for this pcb when data is successfully sent
1762  */
1763 void
1764 tcp_sent(struct tcp_pcb *pcb, tcp_sent_fn sent)
1765 {
1766   if (pcb != NULL) {
1767     LWIP_ASSERT("invalid socket state for sent callback", pcb->state != LISTEN);
1768     pcb->sent = sent;
1769   }
1770 }
1771 
1772 /**
1773  * @ingroup tcp_raw
1774  * Used to specify the function that should be called when a fatal error
1775  * has occurred on the connection.
1776  *
1777  * @note The corresponding pcb is already freed when this callback is called!
1778  *
1779  * @param pcb tcp_pcb to set the err callback
1780  * @param err callback function to call for this pcb when a fatal error
1781  *        has occurred on the connection
1782  */
1783 void
1784 tcp_err(struct tcp_pcb *pcb, tcp_err_fn err)
1785 {
1786   if (pcb != NULL) {
1787     LWIP_ASSERT("invalid socket state for err callback", pcb->state != LISTEN);
1788     pcb->errf = err;
1789   }
1790 }
1791 
1792 /**
1793  * @ingroup tcp_raw
1794  * Used for specifying the function that should be called when a
1795  * LISTENing connection has been connected to another host.
1796  *
1797  * @param pcb tcp_pcb to set the accept callback
1798  * @param accept callback function to call for this pcb when LISTENing
1799  *        connection has been connected to another host
1800  */
1801 void
1802 tcp_accept(struct tcp_pcb *pcb, tcp_accept_fn accept)
1803 {
1804   if ((pcb != NULL) && (pcb->state == LISTEN)) {
1805     struct tcp_pcb_listen *lpcb = (struct tcp_pcb_listen*)pcb;
1806     lpcb->accept = accept;
1807   }
1808 }
1809 #endif /* LWIP_CALLBACK_API */
1810 
1811 
1812 /**
1813  * @ingroup tcp_raw
1814  * Used to specify the function that should be called periodically
1815  * from TCP. The interval is specified in terms of the TCP coarse
1816  * timer interval, which is called twice a second.
1817  *
1818  */
1819 void
1820 tcp_poll(struct tcp_pcb *pcb, tcp_poll_fn poll, u8_t interval)
1821 {
1822   LWIP_ASSERT("invalid socket state for poll", pcb->state != LISTEN);
1823 #if LWIP_CALLBACK_API
1824   pcb->poll = poll;
1825 #else /* LWIP_CALLBACK_API */
1826   LWIP_UNUSED_ARG(poll);
1827 #endif /* LWIP_CALLBACK_API */
1828   pcb->pollinterval = interval;
1829 }
1830 
1831 /**
1832  * Purges a TCP PCB. Removes any buffered data and frees the buffer memory
1833  * (pcb->ooseq, pcb->unsent and pcb->unacked are freed).
1834  *
1835  * @param pcb tcp_pcb to purge. The pcb itself is not deallocated!
1836  */
1837 void
1838 tcp_pcb_purge(struct tcp_pcb *pcb)
1839 {
1840   if (pcb->state != CLOSED &&
1841      pcb->state != TIME_WAIT &&
1842      pcb->state != LISTEN) {
1843 
1844     LWIP_DEBUGF(TCP_DEBUG, ("tcp_pcb_purge\n"));
1845 
1846     tcp_backlog_accepted(pcb);
1847 
1848     if (pcb->refused_data != NULL) {
1849       LWIP_DEBUGF(TCP_DEBUG, ("tcp_pcb_purge: data left on ->refused_data\n"));
1850       pbuf_free(pcb->refused_data);
1851       pcb->refused_data = NULL;
1852     }
1853     if (pcb->unsent != NULL) {
1854       LWIP_DEBUGF(TCP_DEBUG, ("tcp_pcb_purge: not all data sent\n"));
1855     }
1856     if (pcb->unacked != NULL) {
1857       LWIP_DEBUGF(TCP_DEBUG, ("tcp_pcb_purge: data left on ->unacked\n"));
1858     }
1859 #if TCP_QUEUE_OOSEQ
1860     if (pcb->ooseq != NULL) {
1861       LWIP_DEBUGF(TCP_DEBUG, ("tcp_pcb_purge: data left on ->ooseq\n"));
1862     }
1863     tcp_segs_free(pcb->ooseq);
1864     pcb->ooseq = NULL;
1865 #endif /* TCP_QUEUE_OOSEQ */
1866 
1867     /* Stop the retransmission timer as it will expect data on unacked
1868        queue if it fires */
1869     pcb->rtime = -1;
1870 
1871     tcp_segs_free(pcb->unsent);
1872     tcp_segs_free(pcb->unacked);
1873     pcb->unacked = pcb->unsent = NULL;
1874 #if TCP_OVERSIZE
1875     pcb->unsent_oversize = 0;
1876 #endif /* TCP_OVERSIZE */
1877   }
1878 }
1879 
1880 /**
1881  * Purges the PCB and removes it from a PCB list. Any delayed ACKs are sent first.
1882  *
1883  * @param pcblist PCB list to purge.
1884  * @param pcb tcp_pcb to purge. The pcb itself is NOT deallocated!
1885  */
1886 void
1887 tcp_pcb_remove(struct tcp_pcb **pcblist, struct tcp_pcb *pcb)
1888 {
1889   TCP_RMV(pcblist, pcb);
1890 
1891   tcp_pcb_purge(pcb);
1892 
1893   /* if there is an outstanding delayed ACKs, send it */
1894   if ((pcb->state != TIME_WAIT) &&
1895       (pcb->state != LISTEN) &&
1896       (pcb->flags & TF_ACK_DELAY)) {
1897     pcb->flags |= TF_ACK_NOW;
1898     tcp_output(pcb);
1899   }
1900 
1901   if (pcb->state != LISTEN) {
1902     LWIP_ASSERT("unsent segments leaking", pcb->unsent == NULL);
1903     LWIP_ASSERT("unacked segments leaking", pcb->unacked == NULL);
1904 #if TCP_QUEUE_OOSEQ
1905     LWIP_ASSERT("ooseq segments leaking", pcb->ooseq == NULL);
1906 #endif /* TCP_QUEUE_OOSEQ */
1907   }
1908 
1909   pcb->state = CLOSED;
1910   /* reset the local port to prevent the pcb from being 'bound' */
1911   pcb->local_port = 0;
1912 
1913   LWIP_ASSERT("tcp_pcb_remove: tcp_pcbs_sane()", tcp_pcbs_sane());
1914 }
1915 
1916 /**
1917  * Calculates a new initial sequence number for new connections.
1918  *
1919  * @return u32_t pseudo random sequence number
1920  */
1921 u32_t
1922 tcp_next_iss(struct tcp_pcb *pcb)
1923 {
1924 #ifdef LWIP_HOOK_TCP_ISN
1925   return LWIP_HOOK_TCP_ISN(&pcb->local_ip, pcb->local_port, &pcb->remote_ip, pcb->remote_port);
1926 #else /* LWIP_HOOK_TCP_ISN */
1927   static u32_t iss = 6510;
1928 
1929   LWIP_UNUSED_ARG(pcb);
1930 
1931   iss += tcp_ticks;       /* XXX */
1932   return iss;
1933 #endif /* LWIP_HOOK_TCP_ISN */
1934 }
1935 
1936 #if TCP_CALCULATE_EFF_SEND_MSS
1937 /**
1938  * Calculates the effective send mss that can be used for a specific IP address
1939  * by calculating the minimum of TCP_MSS and the mtu (if set) of the target
1940  * netif (if not NULL).
1941  */
1942 u16_t
1943 tcp_eff_send_mss_netif(u16_t sendmss, struct netif *outif, const ip_addr_t *dest)
1944 {
1945   u16_t mss_s;
1946   s16_t mtu;
1947 
1948   LWIP_UNUSED_ARG(dest); /* in case IPv6 is disabled */
1949 
1950 #if LWIP_IPV6
1951 #if LWIP_IPV4
1952   if (IP_IS_V6(dest))
1953 #endif /* LWIP_IPV4 */
1954   {
1955     /* First look in destination cache, to see if there is a Path MTU. */
1956     mtu = nd6_get_destination_mtu(ip_2_ip6(dest), outif);
1957   }
1958 #if LWIP_IPV4
1959   else
1960 #endif /* LWIP_IPV4 */
1961 #endif /* LWIP_IPV6 */
1962 #if LWIP_IPV4
1963   {
1964     if (outif == NULL) {
1965       return sendmss;
1966     }
1967     mtu = outif->mtu;
1968   }
1969 #endif /* LWIP_IPV4 */
1970 
1971   if (mtu != 0) {
1972 #if LWIP_IPV6
1973 #if LWIP_IPV4
1974     if (IP_IS_V6(dest))
1975 #endif /* LWIP_IPV4 */
1976     {
1977       mss_s = mtu - IP6_HLEN - TCP_HLEN;
1978     }
1979 #if LWIP_IPV4
1980     else
1981 #endif /* LWIP_IPV4 */
1982 #endif /* LWIP_IPV6 */
1983 #if LWIP_IPV4
1984     {
1985       mss_s = mtu - IP_HLEN - TCP_HLEN;
1986     }
1987 #endif /* LWIP_IPV4 */
1988     /* RFC 1122, chap 4.2.2.6:
1989      * Eff.snd.MSS = min(SendMSS+20, MMS_S) - TCPhdrsize - IPoptionsize
1990      * We correct for TCP options in tcp_write(), and don't support IP options.
1991      */
1992     sendmss = LWIP_MIN(sendmss, mss_s);
1993   }
1994   return sendmss;
1995 }
1996 #endif /* TCP_CALCULATE_EFF_SEND_MSS */
1997 
1998 /** Helper function for tcp_netif_ip_addr_changed() that iterates a pcb list */
1999 static void
2000 tcp_netif_ip_addr_changed_pcblist(const ip_addr_t* old_addr, struct tcp_pcb* pcb_list)
2001 {
2002   struct tcp_pcb *pcb;
2003   pcb = pcb_list;
2004   while (pcb != NULL) {
2005     /* PCB bound to current local interface address? */
2006     if (ip_addr_cmp(&pcb->local_ip, old_addr)
2007 #if LWIP_AUTOIP
2008       /* connections to link-local addresses must persist (RFC3927 ch. 1.9) */
2009       && (!IP_IS_V4_VAL(pcb->local_ip) || !ip4_addr_islinklocal(ip_2_ip4(&pcb->local_ip)))
2010 #endif /* LWIP_AUTOIP */
2011       ) {
2012       /* this connection must be aborted */
2013       struct tcp_pcb *next = pcb->next;
2014       LWIP_DEBUGF(NETIF_DEBUG | LWIP_DBG_STATE, ("netif_set_ipaddr: aborting TCP pcb %p\n", (void *)pcb));
2015       tcp_abort(pcb);
2016       pcb = next;
2017     } else {
2018       pcb = pcb->next;
2019     }
2020   }
2021 }
2022 
2023 /** This function is called from netif.c when address is changed or netif is removed
2024  *
2025  * @param old_addr IP address of the netif before change
2026  * @param new_addr IP address of the netif after change or NULL if netif has been removed
2027  */
2028 void
2029 tcp_netif_ip_addr_changed(const ip_addr_t* old_addr, const ip_addr_t* new_addr)
2030 {
2031   struct tcp_pcb_listen *lpcb, *next;
2032 
2033   if (!ip_addr_isany(old_addr)) {
2034     tcp_netif_ip_addr_changed_pcblist(old_addr, tcp_active_pcbs);
2035     tcp_netif_ip_addr_changed_pcblist(old_addr, tcp_bound_pcbs);
2036 
2037     if (!ip_addr_isany(new_addr)) {
2038       /* PCB bound to current local interface address? */
2039       for (lpcb = tcp_listen_pcbs.listen_pcbs; lpcb != NULL; lpcb = next) {
2040         next = lpcb->next;
2041         /* PCB bound to current local interface address? */
2042         if (ip_addr_cmp(&lpcb->local_ip, old_addr)) {
2043           /* The PCB is listening to the old ipaddr and
2044             * is set to listen to the new one instead */
2045           ip_addr_copy(lpcb->local_ip, *new_addr);
2046         }
2047       }
2048     }
2049   }
2050 }
2051 
2052 const char*
2053 tcp_debug_state_str(enum tcp_state s)
2054 {
2055   return tcp_state_str[s];
2056 }
2057 
2058 #if TCP_DEBUG || TCP_INPUT_DEBUG || TCP_OUTPUT_DEBUG
2059 /**
2060  * Print a tcp header for debugging purposes.
2061  *
2062  * @param tcphdr pointer to a struct tcp_hdr
2063  */
2064 void
2065 tcp_debug_print(struct tcp_hdr *tcphdr)
2066 {
2067   LWIP_DEBUGF(TCP_DEBUG, ("TCP header:\n"));
2068   LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
2069   LWIP_DEBUGF(TCP_DEBUG, ("|    %5"U16_F"      |    %5"U16_F"      | (src port, dest port)\n",
2070          lwip_ntohs(tcphdr->src), lwip_ntohs(tcphdr->dest)));
2071   LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
2072   LWIP_DEBUGF(TCP_DEBUG, ("|           %010"U32_F"          | (seq no)\n",
2073           lwip_ntohl(tcphdr->seqno)));
2074   LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
2075   LWIP_DEBUGF(TCP_DEBUG, ("|           %010"U32_F"          | (ack no)\n",
2076          lwip_ntohl(tcphdr->ackno)));
2077   LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
2078   LWIP_DEBUGF(TCP_DEBUG, ("| %2"U16_F" |   |%"U16_F"%"U16_F"%"U16_F"%"U16_F"%"U16_F"%"U16_F"|     %5"U16_F"     | (hdrlen, flags (",
2079        TCPH_HDRLEN(tcphdr),
2080          (u16_t)(TCPH_FLAGS(tcphdr) >> 5 & 1),
2081          (u16_t)(TCPH_FLAGS(tcphdr) >> 4 & 1),
2082          (u16_t)(TCPH_FLAGS(tcphdr) >> 3 & 1),
2083          (u16_t)(TCPH_FLAGS(tcphdr) >> 2 & 1),
2084          (u16_t)(TCPH_FLAGS(tcphdr) >> 1 & 1),
2085          (u16_t)(TCPH_FLAGS(tcphdr)      & 1),
2086          lwip_ntohs(tcphdr->wnd)));
2087   tcp_debug_print_flags(TCPH_FLAGS(tcphdr));
2088   LWIP_DEBUGF(TCP_DEBUG, ("), win)\n"));
2089   LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
2090   LWIP_DEBUGF(TCP_DEBUG, ("|    0x%04"X16_F"     |     %5"U16_F"     | (chksum, urgp)\n",
2091          lwip_ntohs(tcphdr->chksum), lwip_ntohs(tcphdr->urgp)));
2092   LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
2093 }
2094 
2095 /**
2096  * Print a tcp state for debugging purposes.
2097  *
2098  * @param s enum tcp_state to print
2099  */
2100 void
2101 tcp_debug_print_state(enum tcp_state s)
2102 {
2103   LWIP_DEBUGF(TCP_DEBUG, ("State: %s\n", tcp_state_str[s]));
2104 }
2105 
2106 /**
2107  * Print tcp flags for debugging purposes.
2108  *
2109  * @param flags tcp flags, all active flags are printed
2110  */
2111 void
2112 tcp_debug_print_flags(u8_t flags)
2113 {
2114   if (flags & TCP_FIN) {
2115     LWIP_DEBUGF(TCP_DEBUG, ("FIN "));
2116   }
2117   if (flags & TCP_SYN) {
2118     LWIP_DEBUGF(TCP_DEBUG, ("SYN "));
2119   }
2120   if (flags & TCP_RST) {
2121     LWIP_DEBUGF(TCP_DEBUG, ("RST "));
2122   }
2123   if (flags & TCP_PSH) {
2124     LWIP_DEBUGF(TCP_DEBUG, ("PSH "));
2125   }
2126   if (flags & TCP_ACK) {
2127     LWIP_DEBUGF(TCP_DEBUG, ("ACK "));
2128   }
2129   if (flags & TCP_URG) {
2130     LWIP_DEBUGF(TCP_DEBUG, ("URG "));
2131   }
2132   if (flags & TCP_ECE) {
2133     LWIP_DEBUGF(TCP_DEBUG, ("ECE "));
2134   }
2135   if (flags & TCP_CWR) {
2136     LWIP_DEBUGF(TCP_DEBUG, ("CWR "));
2137   }
2138   LWIP_DEBUGF(TCP_DEBUG, ("\n"));
2139 }
2140 
2141 /**
2142  * Print all tcp_pcbs in every list for debugging purposes.
2143  */
2144 void
2145 tcp_debug_print_pcbs(void)
2146 {
2147   struct tcp_pcb *pcb;
2148   struct tcp_pcb_listen *pcbl;
2149 
2150   LWIP_DEBUGF(TCP_DEBUG, ("Active PCB states:\n"));
2151   for (pcb = tcp_active_pcbs; pcb != NULL; pcb = pcb->next) {
2152     LWIP_DEBUGF(TCP_DEBUG, ("Local port %"U16_F", foreign port %"U16_F" snd_nxt %"U32_F" rcv_nxt %"U32_F" ",
2153                        pcb->local_port, pcb->remote_port,
2154                        pcb->snd_nxt, pcb->rcv_nxt));
2155     tcp_debug_print_state(pcb->state);
2156   }
2157 
2158   LWIP_DEBUGF(TCP_DEBUG, ("Listen PCB states:\n"));
2159   for (pcbl = tcp_listen_pcbs.listen_pcbs; pcbl != NULL; pcbl = pcbl->next) {
2160     LWIP_DEBUGF(TCP_DEBUG, ("Local port %"U16_F" ", pcbl->local_port));
2161     tcp_debug_print_state(pcbl->state);
2162   }
2163 
2164   LWIP_DEBUGF(TCP_DEBUG, ("TIME-WAIT PCB states:\n"));
2165   for (pcb = tcp_tw_pcbs; pcb != NULL; pcb = pcb->next) {
2166     LWIP_DEBUGF(TCP_DEBUG, ("Local port %"U16_F", foreign port %"U16_F" snd_nxt %"U32_F" rcv_nxt %"U32_F" ",
2167                        pcb->local_port, pcb->remote_port,
2168                        pcb->snd_nxt, pcb->rcv_nxt));
2169     tcp_debug_print_state(pcb->state);
2170   }
2171 }
2172 
2173 /**
2174  * Check state consistency of the tcp_pcb lists.
2175  */
2176 s16_t
2177 tcp_pcbs_sane(void)
2178 {
2179   struct tcp_pcb *pcb;
2180   for (pcb = tcp_active_pcbs; pcb != NULL; pcb = pcb->next) {
2181     LWIP_ASSERT("tcp_pcbs_sane: active pcb->state != CLOSED", pcb->state != CLOSED);
2182     LWIP_ASSERT("tcp_pcbs_sane: active pcb->state != LISTEN", pcb->state != LISTEN);
2183     LWIP_ASSERT("tcp_pcbs_sane: active pcb->state != TIME-WAIT", pcb->state != TIME_WAIT);
2184   }
2185   for (pcb = tcp_tw_pcbs; pcb != NULL; pcb = pcb->next) {
2186     LWIP_ASSERT("tcp_pcbs_sane: tw pcb->state == TIME-WAIT", pcb->state == TIME_WAIT);
2187   }
2188   return 1;
2189 }
2190 #endif /* TCP_DEBUG */
2191 
2192 #endif /* LWIP_TCP */
2193