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