]> rtime.felk.cvut.cz Git - pes-rpp/rpp-lwip.git/blob - src/core/tcp.c
432449390d49a457c338e8c8e59a009ce89eb455
[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       LWIP_DEBUGF(TCP_INPUT_DEBUG, ("tcp_fasttmr: notify kept packet\n"));
1058       TCP_EVENT_RECV(pcb, pcb->refused_data, ERR_OK, err);
1059       if (err == ERR_OK) {
1060         pcb->refused_data = NULL;
1061       } else if (err == ERR_ABRT) {
1062         /* if err == ERR_ABRT, 'pcb' is already deallocated */
1063         pcb = NULL;
1064       }
1065     }
1066
1067     /* send delayed ACKs */
1068     if (pcb && (pcb->flags & TF_ACK_DELAY)) {
1069       LWIP_DEBUGF(TCP_DEBUG, ("tcp_fasttmr: delayed ACK\n"));
1070       tcp_ack_now(pcb);
1071       tcp_output(pcb);
1072       pcb->flags &= ~(TF_ACK_DELAY | TF_ACK_NOW);
1073     }
1074
1075     pcb = next;
1076   }
1077 }
1078
1079 /**
1080  * Deallocates a list of TCP segments (tcp_seg structures).
1081  *
1082  * @param seg tcp_seg list of TCP segments to free
1083  */
1084 void
1085 tcp_segs_free(struct tcp_seg *seg)
1086 {
1087   while (seg != NULL) {
1088     struct tcp_seg *next = seg->next;
1089     tcp_seg_free(seg);
1090     seg = next;
1091   }
1092 }
1093
1094 /**
1095  * Frees a TCP segment (tcp_seg structure).
1096  *
1097  * @param seg single tcp_seg to free
1098  */
1099 void
1100 tcp_seg_free(struct tcp_seg *seg)
1101 {
1102   if (seg != NULL) {
1103     if (seg->p != NULL) {
1104       pbuf_free(seg->p);
1105 #if TCP_DEBUG
1106       seg->p = NULL;
1107 #endif /* TCP_DEBUG */
1108     }
1109     memp_free(MEMP_TCP_SEG, seg);
1110   }
1111 }
1112
1113 /**
1114  * Sets the priority of a connection.
1115  *
1116  * @param pcb the tcp_pcb to manipulate
1117  * @param prio new priority
1118  */
1119 void
1120 tcp_setprio(struct tcp_pcb *pcb, u8_t prio)
1121 {
1122   pcb->prio = prio;
1123 }
1124
1125 #if TCP_QUEUE_OOSEQ
1126 /**
1127  * Returns a copy of the given TCP segment.
1128  * The pbuf and data are not copied, only the pointers
1129  *
1130  * @param seg the old tcp_seg
1131  * @return a copy of seg
1132  */ 
1133 struct tcp_seg *
1134 tcp_seg_copy(struct tcp_seg *seg)
1135 {
1136   struct tcp_seg *cseg;
1137
1138   cseg = (struct tcp_seg *)memp_malloc(MEMP_TCP_SEG);
1139   if (cseg == NULL) {
1140     return NULL;
1141   }
1142   SMEMCPY((u8_t *)cseg, (const u8_t *)seg, sizeof(struct tcp_seg)); 
1143   pbuf_ref(cseg->p);
1144   return cseg;
1145 }
1146 #endif /* TCP_QUEUE_OOSEQ */
1147
1148 #if LWIP_CALLBACK_API
1149 /**
1150  * Default receive callback that is called if the user didn't register
1151  * a recv callback for the pcb.
1152  */
1153 err_t
1154 tcp_recv_null(void *arg, struct tcp_pcb *pcb, struct pbuf *p, err_t err)
1155 {
1156   LWIP_UNUSED_ARG(arg);
1157   if (p != NULL) {
1158     tcp_recved(pcb, p->tot_len);
1159     pbuf_free(p);
1160   } else if (err == ERR_OK) {
1161     return tcp_close(pcb);
1162   }
1163   return ERR_OK;
1164 }
1165 #endif /* LWIP_CALLBACK_API */
1166
1167 /**
1168  * Kills the oldest active connection that has the same or lower priority than
1169  * 'prio'.
1170  *
1171  * @param prio minimum priority
1172  */
1173 static void
1174 tcp_kill_prio(u8_t prio)
1175 {
1176   struct tcp_pcb *pcb, *inactive;
1177   u32_t inactivity;
1178   u8_t mprio;
1179
1180
1181   mprio = TCP_PRIO_MAX;
1182   
1183   /* We kill the oldest active connection that has lower priority than prio. */
1184   inactivity = 0;
1185   inactive = NULL;
1186   for(pcb = tcp_active_pcbs; pcb != NULL; pcb = pcb->next) {
1187     if (pcb->prio <= prio &&
1188        pcb->prio <= mprio &&
1189        (u32_t)(tcp_ticks - pcb->tmr) >= inactivity) {
1190       inactivity = tcp_ticks - pcb->tmr;
1191       inactive = pcb;
1192       mprio = pcb->prio;
1193     }
1194   }
1195   if (inactive != NULL) {
1196     LWIP_DEBUGF(TCP_DEBUG, ("tcp_kill_prio: killing oldest PCB %p (%"S32_F")\n",
1197            (void *)inactive, inactivity));
1198     tcp_abort(inactive);
1199   }
1200 }
1201
1202 /**
1203  * Kills the oldest connection that is in TIME_WAIT state.
1204  * Called from tcp_alloc() if no more connections are available.
1205  */
1206 static void
1207 tcp_kill_timewait(void)
1208 {
1209   struct tcp_pcb *pcb, *inactive;
1210   u32_t inactivity;
1211
1212   inactivity = 0;
1213   inactive = NULL;
1214   /* Go through the list of TIME_WAIT pcbs and get the oldest pcb. */
1215   for(pcb = tcp_tw_pcbs; pcb != NULL; pcb = pcb->next) {
1216     if ((u32_t)(tcp_ticks - pcb->tmr) >= inactivity) {
1217       inactivity = tcp_ticks - pcb->tmr;
1218       inactive = pcb;
1219     }
1220   }
1221   if (inactive != NULL) {
1222     LWIP_DEBUGF(TCP_DEBUG, ("tcp_kill_timewait: killing oldest TIME-WAIT PCB %p (%"S32_F")\n",
1223            (void *)inactive, inactivity));
1224     tcp_abort(inactive);
1225   }
1226 }
1227
1228 /**
1229  * Allocate a new tcp_pcb structure.
1230  *
1231  * @param prio priority for the new pcb
1232  * @return a new tcp_pcb that initially is in state CLOSED
1233  */
1234 struct tcp_pcb *
1235 tcp_alloc(u8_t prio)
1236 {
1237   struct tcp_pcb *pcb;
1238   u32_t iss;
1239   
1240   pcb = (struct tcp_pcb *)memp_malloc(MEMP_TCP_PCB);
1241   if (pcb == NULL) {
1242     /* Try killing oldest connection in TIME-WAIT. */
1243     LWIP_DEBUGF(TCP_DEBUG, ("tcp_alloc: killing off oldest TIME-WAIT connection\n"));
1244     tcp_kill_timewait();
1245     /* Try to allocate a tcp_pcb again. */
1246     pcb = (struct tcp_pcb *)memp_malloc(MEMP_TCP_PCB);
1247     if (pcb == NULL) {
1248       /* Try killing active connections with lower priority than the new one. */
1249       LWIP_DEBUGF(TCP_DEBUG, ("tcp_alloc: killing connection with prio lower than %d\n", prio));
1250       tcp_kill_prio(prio);
1251       /* Try to allocate a tcp_pcb again. */
1252       pcb = (struct tcp_pcb *)memp_malloc(MEMP_TCP_PCB);
1253       if (pcb != NULL) {
1254         /* adjust err stats: memp_malloc failed twice before */
1255         MEMP_STATS_DEC(err, MEMP_TCP_PCB);
1256       }
1257     }
1258     if (pcb != NULL) {
1259       /* adjust err stats: timewait PCB was freed above */
1260       MEMP_STATS_DEC(err, MEMP_TCP_PCB);
1261     }
1262   }
1263   if (pcb != NULL) {
1264     memset(pcb, 0, sizeof(struct tcp_pcb));
1265     pcb->prio = prio;
1266     pcb->snd_buf = TCP_SND_BUF;
1267     pcb->snd_queuelen = 0;
1268     pcb->rcv_wnd = TCP_WND;
1269     pcb->rcv_ann_wnd = TCP_WND;
1270     pcb->tos = 0;
1271     pcb->ttl = TCP_TTL;
1272     /* As initial send MSS, we use TCP_MSS but limit it to 536.
1273        The send MSS is updated when an MSS option is received. */
1274     pcb->mss = (TCP_MSS > 536) ? 536 : TCP_MSS;
1275     pcb->rto = 3000 / TCP_SLOW_INTERVAL;
1276     pcb->sa = 0;
1277     pcb->sv = 3000 / TCP_SLOW_INTERVAL;
1278     pcb->rtime = -1;
1279     pcb->cwnd = 1;
1280     iss = tcp_next_iss();
1281     pcb->snd_wl2 = iss;
1282     pcb->snd_nxt = iss;
1283     pcb->lastack = iss;
1284     pcb->snd_lbb = iss;   
1285     pcb->tmr = tcp_ticks;
1286
1287     pcb->polltmr = 0;
1288
1289 #if LWIP_CALLBACK_API
1290     pcb->recv = tcp_recv_null;
1291 #endif /* LWIP_CALLBACK_API */  
1292     
1293     /* Init KEEPALIVE timer */
1294     pcb->keep_idle  = TCP_KEEPIDLE_DEFAULT;
1295     
1296 #if LWIP_TCP_KEEPALIVE
1297     pcb->keep_intvl = TCP_KEEPINTVL_DEFAULT;
1298     pcb->keep_cnt   = TCP_KEEPCNT_DEFAULT;
1299 #endif /* LWIP_TCP_KEEPALIVE */
1300
1301     pcb->keep_cnt_sent = 0;
1302   }
1303   return pcb;
1304 }
1305
1306 /**
1307  * Creates a new TCP protocol control block but doesn't place it on
1308  * any of the TCP PCB lists.
1309  * The pcb is not put on any list until binding using tcp_bind().
1310  *
1311  * @internal: Maybe there should be a idle TCP PCB list where these
1312  * PCBs are put on. Port reservation using tcp_bind() is implemented but
1313  * allocated pcbs that are not bound can't be killed automatically if wanting
1314  * to allocate a pcb with higher prio (@see tcp_kill_prio())
1315  *
1316  * @return a new tcp_pcb that initially is in state CLOSED
1317  */
1318 struct tcp_pcb *
1319 tcp_new(void)
1320 {
1321   return tcp_alloc(TCP_PRIO_NORMAL);
1322 }
1323
1324 #if LWIP_IPV6
1325 /**
1326  * Creates a new TCP-over-IPv6 protocol control block but doesn't
1327  * place it on any of the TCP PCB lists.
1328  * The pcb is not put on any list until binding using tcp_bind().
1329  *
1330  * @return a new tcp_pcb that initially is in state CLOSED
1331  */
1332 struct tcp_pcb *
1333 tcp_new_ip6(void)
1334 {
1335   struct tcp_pcb * pcb;
1336   pcb = tcp_alloc(TCP_PRIO_NORMAL);
1337   ip_set_v6(pcb, 1);
1338   return pcb;
1339 }
1340 #endif /* LWIP_IPV6 */
1341
1342 /**
1343  * Used to specify the argument that should be passed callback
1344  * functions.
1345  *
1346  * @param pcb tcp_pcb to set the callback argument
1347  * @param arg void pointer argument to pass to callback functions
1348  */ 
1349 void
1350 tcp_arg(struct tcp_pcb *pcb, void *arg)
1351 {
1352   /* This function is allowed to be called for both listen pcbs and
1353      connection pcbs. */
1354   pcb->callback_arg = arg;
1355 }
1356 #if LWIP_CALLBACK_API
1357
1358 /**
1359  * Used to specify the function that should be called when a TCP
1360  * connection receives data.
1361  *
1362  * @param pcb tcp_pcb to set the recv callback
1363  * @param recv callback function to call for this pcb when data is received
1364  */ 
1365 void
1366 tcp_recv(struct tcp_pcb *pcb, tcp_recv_fn recv)
1367 {
1368   LWIP_ASSERT("invalid socket state for recv callback", pcb->state != LISTEN);
1369   pcb->recv = recv;
1370 }
1371
1372 /**
1373  * Used to specify the function that should be called when TCP data
1374  * has been successfully delivered to the remote host.
1375  *
1376  * @param pcb tcp_pcb to set the sent callback
1377  * @param sent callback function to call for this pcb when data is successfully sent
1378  */ 
1379 void
1380 tcp_sent(struct tcp_pcb *pcb, tcp_sent_fn sent)
1381 {
1382   LWIP_ASSERT("invalid socket state for sent callback", pcb->state != LISTEN);
1383   pcb->sent = sent;
1384 }
1385
1386 /**
1387  * Used to specify the function that should be called when a fatal error
1388  * has occured on the connection.
1389  *
1390  * @param pcb tcp_pcb to set the err callback
1391  * @param err callback function to call for this pcb when a fatal error
1392  *        has occured on the connection
1393  */ 
1394 void
1395 tcp_err(struct tcp_pcb *pcb, tcp_err_fn err)
1396 {
1397   LWIP_ASSERT("invalid socket state for err callback", pcb->state != LISTEN);
1398   pcb->errf = err;
1399 }
1400
1401 /**
1402  * Used for specifying the function that should be called when a
1403  * LISTENing connection has been connected to another host.
1404  *
1405  * @param pcb tcp_pcb to set the accept callback
1406  * @param accept callback function to call for this pcb when LISTENing
1407  *        connection has been connected to another host
1408  */ 
1409 void
1410 tcp_accept(struct tcp_pcb *pcb, tcp_accept_fn accept)
1411 {
1412   /* This function is allowed to be called for both listen pcbs and
1413      connection pcbs. */
1414   pcb->accept = accept;
1415 }
1416 #endif /* LWIP_CALLBACK_API */
1417
1418
1419 /**
1420  * Used to specify the function that should be called periodically
1421  * from TCP. The interval is specified in terms of the TCP coarse
1422  * timer interval, which is called twice a second.
1423  *
1424  */ 
1425 void
1426 tcp_poll(struct tcp_pcb *pcb, tcp_poll_fn poll, u8_t interval)
1427 {
1428   LWIP_ASSERT("invalid socket state for poll", pcb->state != LISTEN);
1429 #if LWIP_CALLBACK_API
1430   pcb->poll = poll;
1431 #else /* LWIP_CALLBACK_API */  
1432   LWIP_UNUSED_ARG(poll);
1433 #endif /* LWIP_CALLBACK_API */  
1434   pcb->pollinterval = interval;
1435 }
1436
1437 /**
1438  * Purges a TCP PCB. Removes any buffered data and frees the buffer memory
1439  * (pcb->ooseq, pcb->unsent and pcb->unacked are freed).
1440  *
1441  * @param pcb tcp_pcb to purge. The pcb itself is not deallocated!
1442  */
1443 void
1444 tcp_pcb_purge(struct tcp_pcb *pcb)
1445 {
1446   if (pcb->state != CLOSED &&
1447      pcb->state != TIME_WAIT &&
1448      pcb->state != LISTEN) {
1449
1450     LWIP_DEBUGF(TCP_DEBUG, ("tcp_pcb_purge\n"));
1451
1452 #if TCP_LISTEN_BACKLOG
1453     if (pcb->state == SYN_RCVD) {
1454       /* Need to find the corresponding listen_pcb and decrease its accepts_pending */
1455       struct tcp_pcb_listen *lpcb;
1456       LWIP_ASSERT("tcp_pcb_purge: pcb->state == SYN_RCVD but tcp_listen_pcbs is NULL",
1457         tcp_listen_pcbs.listen_pcbs != NULL);
1458       for (lpcb = tcp_listen_pcbs.listen_pcbs; lpcb != NULL; lpcb = lpcb->next) {
1459         if ((lpcb->local_port == pcb->local_port) &&
1460             IP_PCB_IPVER_EQ(pcb, lpcb) &&
1461             (ipX_addr_isany(PCB_ISIPV6(lpcb), &lpcb->local_ip) ||
1462              ipX_addr_cmp(PCB_ISIPV6(lpcb), &pcb->local_ip, &lpcb->local_ip))) {
1463             /* port and address of the listen pcb match the timed-out pcb */
1464             LWIP_ASSERT("tcp_pcb_purge: listen pcb does not have accepts pending",
1465               lpcb->accepts_pending > 0);
1466             lpcb->accepts_pending--;
1467             break;
1468           }
1469       }
1470     }
1471 #endif /* TCP_LISTEN_BACKLOG */
1472
1473
1474     if (pcb->refused_data != NULL) {
1475       LWIP_DEBUGF(TCP_DEBUG, ("tcp_pcb_purge: data left on ->refused_data\n"));
1476       pbuf_free(pcb->refused_data);
1477       pcb->refused_data = NULL;
1478     }
1479     if (pcb->unsent != NULL) {
1480       LWIP_DEBUGF(TCP_DEBUG, ("tcp_pcb_purge: not all data sent\n"));
1481     }
1482     if (pcb->unacked != NULL) {
1483       LWIP_DEBUGF(TCP_DEBUG, ("tcp_pcb_purge: data left on ->unacked\n"));
1484     }
1485 #if TCP_QUEUE_OOSEQ
1486     if (pcb->ooseq != NULL) {
1487       LWIP_DEBUGF(TCP_DEBUG, ("tcp_pcb_purge: data left on ->ooseq\n"));
1488     }
1489     tcp_segs_free(pcb->ooseq);
1490     pcb->ooseq = NULL;
1491 #endif /* TCP_QUEUE_OOSEQ */
1492
1493     /* Stop the retransmission timer as it will expect data on unacked
1494        queue if it fires */
1495     pcb->rtime = -1;
1496
1497     tcp_segs_free(pcb->unsent);
1498     tcp_segs_free(pcb->unacked);
1499     pcb->unacked = pcb->unsent = NULL;
1500 #if TCP_OVERSIZE
1501     pcb->unsent_oversize = 0;
1502 #endif /* TCP_OVERSIZE */
1503   }
1504 }
1505
1506 /**
1507  * Purges the PCB and removes it from a PCB list. Any delayed ACKs are sent first.
1508  *
1509  * @param pcblist PCB list to purge.
1510  * @param pcb tcp_pcb to purge. The pcb itself is NOT deallocated!
1511  */
1512 void
1513 tcp_pcb_remove(struct tcp_pcb **pcblist, struct tcp_pcb *pcb)
1514 {
1515   TCP_RMV(pcblist, pcb);
1516
1517   tcp_pcb_purge(pcb);
1518   
1519   /* if there is an outstanding delayed ACKs, send it */
1520   if (pcb->state != TIME_WAIT &&
1521      pcb->state != LISTEN &&
1522      pcb->flags & TF_ACK_DELAY) {
1523     pcb->flags |= TF_ACK_NOW;
1524     tcp_output(pcb);
1525   }
1526
1527   if (pcb->state != LISTEN) {
1528     LWIP_ASSERT("unsent segments leaking", pcb->unsent == NULL);
1529     LWIP_ASSERT("unacked segments leaking", pcb->unacked == NULL);
1530 #if TCP_QUEUE_OOSEQ
1531     LWIP_ASSERT("ooseq segments leaking", pcb->ooseq == NULL);
1532 #endif /* TCP_QUEUE_OOSEQ */
1533   }
1534
1535   pcb->state = CLOSED;
1536
1537   LWIP_ASSERT("tcp_pcb_remove: tcp_pcbs_sane()", tcp_pcbs_sane());
1538 }
1539
1540 /**
1541  * Calculates a new initial sequence number for new connections.
1542  *
1543  * @return u32_t pseudo random sequence number
1544  */
1545 u32_t
1546 tcp_next_iss(void)
1547 {
1548   static u32_t iss = 6510;
1549   
1550   iss += tcp_ticks;       /* XXX */
1551   return iss;
1552 }
1553
1554 #if TCP_CALCULATE_EFF_SEND_MSS
1555 /**
1556  * Calcluates the effective send mss that can be used for a specific IP address
1557  * by using ip_route to determin the netif used to send to the address and
1558  * calculating the minimum of TCP_MSS and that netif's mtu (if set).
1559  */
1560 u16_t
1561 tcp_eff_send_mss_impl(u16_t sendmss, ipX_addr_t *dest
1562 #if LWIP_IPV6
1563                      , ipX_addr_t *src, u8_t isipv6
1564 #endif /* LWIP_IPV6 */
1565                      )
1566 {
1567   u16_t mss_s;
1568   struct netif *outif;
1569   s16_t mtu;
1570
1571   outif = ipX_route(isipv6, src, dest);
1572 #if LWIP_IPV6
1573   if (isipv6) {
1574     /* First look in destination cache, to see if there is a Path MTU. */
1575     mtu = nd6_get_destination_mtu(ipX_2_ip6(dest), outif);
1576   } else
1577 #endif /* LWIP_IPV6 */
1578   {
1579     if (outif == NULL) {
1580       return sendmss;
1581     }
1582     mtu = outif->mtu;
1583   }
1584
1585   if (mtu != 0) {
1586     mss_s = mtu - IP_HLEN - TCP_HLEN;
1587 #if LWIP_IPV6
1588     /* for IPv6, substract the difference in header size */
1589     mss_s -= (IP6_HLEN - IP_HLEN);
1590 #endif /* LWIP_IPV6 */
1591     /* RFC 1122, chap 4.2.2.6:
1592      * Eff.snd.MSS = min(SendMSS+20, MMS_S) - TCPhdrsize - IPoptionsize
1593      * We correct for TCP options in tcp_write(), and don't support IP options.
1594      */
1595     sendmss = LWIP_MIN(sendmss, mss_s);
1596   }
1597   return sendmss;
1598 }
1599 #endif /* TCP_CALCULATE_EFF_SEND_MSS */
1600
1601 const char*
1602 tcp_debug_state_str(enum tcp_state s)
1603 {
1604   return tcp_state_str[s];
1605 }
1606
1607 #if TCP_DEBUG || TCP_INPUT_DEBUG || TCP_OUTPUT_DEBUG
1608 /**
1609  * Print a tcp header for debugging purposes.
1610  *
1611  * @param tcphdr pointer to a struct tcp_hdr
1612  */
1613 void
1614 tcp_debug_print(struct tcp_hdr *tcphdr)
1615 {
1616   LWIP_DEBUGF(TCP_DEBUG, ("TCP header:\n"));
1617   LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
1618   LWIP_DEBUGF(TCP_DEBUG, ("|    %5"U16_F"      |    %5"U16_F"      | (src port, dest port)\n",
1619          ntohs(tcphdr->src), ntohs(tcphdr->dest)));
1620   LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
1621   LWIP_DEBUGF(TCP_DEBUG, ("|           %010"U32_F"          | (seq no)\n",
1622           ntohl(tcphdr->seqno)));
1623   LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
1624   LWIP_DEBUGF(TCP_DEBUG, ("|           %010"U32_F"          | (ack no)\n",
1625          ntohl(tcphdr->ackno)));
1626   LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
1627   LWIP_DEBUGF(TCP_DEBUG, ("| %2"U16_F" |   |%"U16_F"%"U16_F"%"U16_F"%"U16_F"%"U16_F"%"U16_F"|     %5"U16_F"     | (hdrlen, flags (",
1628        TCPH_HDRLEN(tcphdr),
1629          TCPH_FLAGS(tcphdr) >> 5 & 1,
1630          TCPH_FLAGS(tcphdr) >> 4 & 1,
1631          TCPH_FLAGS(tcphdr) >> 3 & 1,
1632          TCPH_FLAGS(tcphdr) >> 2 & 1,
1633          TCPH_FLAGS(tcphdr) >> 1 & 1,
1634          TCPH_FLAGS(tcphdr) & 1,
1635          ntohs(tcphdr->wnd)));
1636   tcp_debug_print_flags(TCPH_FLAGS(tcphdr));
1637   LWIP_DEBUGF(TCP_DEBUG, ("), win)\n"));
1638   LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
1639   LWIP_DEBUGF(TCP_DEBUG, ("|    0x%04"X16_F"     |     %5"U16_F"     | (chksum, urgp)\n",
1640          ntohs(tcphdr->chksum), ntohs(tcphdr->urgp)));
1641   LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
1642 }
1643
1644 /**
1645  * Print a tcp state for debugging purposes.
1646  *
1647  * @param s enum tcp_state to print
1648  */
1649 void
1650 tcp_debug_print_state(enum tcp_state s)
1651 {
1652   LWIP_DEBUGF(TCP_DEBUG, ("State: %s\n", tcp_state_str[s]));
1653 }
1654
1655 /**
1656  * Print tcp flags for debugging purposes.
1657  *
1658  * @param flags tcp flags, all active flags are printed
1659  */
1660 void
1661 tcp_debug_print_flags(u8_t flags)
1662 {
1663   if (flags & TCP_FIN) {
1664     LWIP_DEBUGF(TCP_DEBUG, ("FIN "));
1665   }
1666   if (flags & TCP_SYN) {
1667     LWIP_DEBUGF(TCP_DEBUG, ("SYN "));
1668   }
1669   if (flags & TCP_RST) {
1670     LWIP_DEBUGF(TCP_DEBUG, ("RST "));
1671   }
1672   if (flags & TCP_PSH) {
1673     LWIP_DEBUGF(TCP_DEBUG, ("PSH "));
1674   }
1675   if (flags & TCP_ACK) {
1676     LWIP_DEBUGF(TCP_DEBUG, ("ACK "));
1677   }
1678   if (flags & TCP_URG) {
1679     LWIP_DEBUGF(TCP_DEBUG, ("URG "));
1680   }
1681   if (flags & TCP_ECE) {
1682     LWIP_DEBUGF(TCP_DEBUG, ("ECE "));
1683   }
1684   if (flags & TCP_CWR) {
1685     LWIP_DEBUGF(TCP_DEBUG, ("CWR "));
1686   }
1687   LWIP_DEBUGF(TCP_DEBUG, ("\n"));
1688 }
1689
1690 /**
1691  * Print all tcp_pcbs in every list for debugging purposes.
1692  */
1693 void
1694 tcp_debug_print_pcbs(void)
1695 {
1696   struct tcp_pcb *pcb;
1697   LWIP_DEBUGF(TCP_DEBUG, ("Active PCB states:\n"));
1698   for(pcb = tcp_active_pcbs; pcb != NULL; pcb = pcb->next) {
1699     LWIP_DEBUGF(TCP_DEBUG, ("Local port %"U16_F", foreign port %"U16_F" snd_nxt %"U32_F" rcv_nxt %"U32_F" ",
1700                        pcb->local_port, pcb->remote_port,
1701                        pcb->snd_nxt, pcb->rcv_nxt));
1702     tcp_debug_print_state(pcb->state);
1703   }    
1704   LWIP_DEBUGF(TCP_DEBUG, ("Listen PCB states:\n"));
1705   for(pcb = (struct tcp_pcb *)tcp_listen_pcbs.pcbs; pcb != NULL; pcb = pcb->next) {
1706     LWIP_DEBUGF(TCP_DEBUG, ("Local port %"U16_F", foreign port %"U16_F" snd_nxt %"U32_F" rcv_nxt %"U32_F" ",
1707                        pcb->local_port, pcb->remote_port,
1708                        pcb->snd_nxt, pcb->rcv_nxt));
1709     tcp_debug_print_state(pcb->state);
1710   }    
1711   LWIP_DEBUGF(TCP_DEBUG, ("TIME-WAIT PCB states:\n"));
1712   for(pcb = tcp_tw_pcbs; pcb != NULL; pcb = pcb->next) {
1713     LWIP_DEBUGF(TCP_DEBUG, ("Local port %"U16_F", foreign port %"U16_F" snd_nxt %"U32_F" rcv_nxt %"U32_F" ",
1714                        pcb->local_port, pcb->remote_port,
1715                        pcb->snd_nxt, pcb->rcv_nxt));
1716     tcp_debug_print_state(pcb->state);
1717   }    
1718 }
1719
1720 /**
1721  * Check state consistency of the tcp_pcb lists.
1722  */
1723 s16_t
1724 tcp_pcbs_sane(void)
1725 {
1726   struct tcp_pcb *pcb;
1727   for(pcb = tcp_active_pcbs; pcb != NULL; pcb = pcb->next) {
1728     LWIP_ASSERT("tcp_pcbs_sane: active pcb->state != CLOSED", pcb->state != CLOSED);
1729     LWIP_ASSERT("tcp_pcbs_sane: active pcb->state != LISTEN", pcb->state != LISTEN);
1730     LWIP_ASSERT("tcp_pcbs_sane: active pcb->state != TIME-WAIT", pcb->state != TIME_WAIT);
1731   }
1732   for(pcb = tcp_tw_pcbs; pcb != NULL; pcb = pcb->next) {
1733     LWIP_ASSERT("tcp_pcbs_sane: tw pcb->state == TIME-WAIT", pcb->state == TIME_WAIT);
1734   }
1735   return 1;
1736 }
1737 #endif /* TCP_DEBUG */
1738
1739 #endif /* LWIP_TCP */