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