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