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