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