]> rtime.felk.cvut.cz Git - pes-rpp/rpp-lwip.git/blob - src/core/tcp.c
BUG25622: handle return code of tcp_enqueue in tcp_listen_input()
[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
53 #include <string.h>
54
55 /* Incremented every coarse grained timer shot (typically every 500 ms). */
56 u32_t tcp_ticks;
57 const u8_t tcp_backoff[13] =
58     { 1, 2, 3, 4, 5, 6, 7, 7, 7, 7, 7, 7, 7};
59  /* Times per slowtmr hits */
60 const u8_t tcp_persist_backoff[7] = { 3, 6, 12, 24, 48, 96, 120 };
61
62 /* The TCP PCB lists. */
63
64 /** List of all TCP PCBs bound but not yet (connected || listening) */
65 struct tcp_pcb *tcp_bound_pcbs;  
66 /** List of all TCP PCBs in LISTEN state */
67 union tcp_listen_pcbs_t tcp_listen_pcbs;
68 /** List of all TCP PCBs that are in a state in which
69  * they accept or send data. */
70 struct tcp_pcb *tcp_active_pcbs;  
71 /** List of all TCP PCBs in TIME-WAIT state */
72 struct tcp_pcb *tcp_tw_pcbs;
73
74 struct tcp_pcb *tcp_tmp_pcb;
75
76 static u8_t tcp_timer;
77 static u16_t tcp_new_port(void);
78
79 /**
80  * Called periodically to dispatch TCP timers.
81  *
82  */
83 void
84 tcp_tmr(void)
85 {
86   /* Call tcp_fasttmr() every 250 ms */
87   tcp_fasttmr();
88
89   if (++tcp_timer & 1) {
90     /* Call tcp_tmr() every 500 ms, i.e., every other timer
91        tcp_tmr() is called. */
92     tcp_slowtmr();
93   }
94 }
95
96 /**
97  * Closes the connection held by the PCB.
98  *
99  * Listening pcbs are freed and may not be referenced any more.
100  * Connection pcbs are freed if not yet connected and may not be referenced
101  * any more. If a connection is established (at least SYN received or in
102  * a closing state), the connection is closed, and put in a closing state.
103  * The pcb is then automatically freed in tcp_slowtmr(). It is therefore
104  * unsafe to reference it.
105  *
106  * @param pcb the tcp_pcb to close
107  * @return ERR_OK if connection has been closed
108  *         another err_t if closing failed and pcb is not freed
109  */
110 err_t
111 tcp_close(struct tcp_pcb *pcb)
112 {
113   err_t err;
114
115 #if TCP_DEBUG
116   LWIP_DEBUGF(TCP_DEBUG, ("tcp_close: closing in "));
117   tcp_debug_print_state(pcb->state);
118 #endif /* TCP_DEBUG */
119
120   switch (pcb->state) {
121   case CLOSED:
122     /* Closing a pcb in the CLOSED state might seem erroneous,
123      * however, it is in this state once allocated and as yet unused
124      * and the user needs some way to free it should the need arise.
125      * Calling tcp_close() with a pcb that has already been closed, (i.e. twice)
126      * or for a pcb that has been used and then entered the CLOSED state 
127      * is erroneous, but this should never happen as the pcb has in those cases
128      * been freed, and so any remaining handles are bogus. */
129     err = ERR_OK;
130     TCP_RMV(&tcp_bound_pcbs, pcb);
131     memp_free(MEMP_TCP_PCB, pcb);
132     pcb = NULL;
133     break;
134   case LISTEN:
135     err = ERR_OK;
136     tcp_pcb_remove((struct tcp_pcb **)&tcp_listen_pcbs.pcbs, pcb);
137     memp_free(MEMP_TCP_PCB_LISTEN, pcb);
138     pcb = NULL;
139     break;
140   case SYN_SENT:
141     err = ERR_OK;
142     tcp_pcb_remove(&tcp_active_pcbs, pcb);
143     memp_free(MEMP_TCP_PCB, pcb);
144     pcb = NULL;
145     snmp_inc_tcpattemptfails();
146     break;
147   case SYN_RCVD:
148     err = tcp_send_ctrl(pcb, TCP_FIN);
149     if (err == ERR_OK) {
150       snmp_inc_tcpattemptfails();
151       pcb->state = FIN_WAIT_1;
152     }
153     break;
154   case ESTABLISHED:
155     err = tcp_send_ctrl(pcb, TCP_FIN);
156     if (err == ERR_OK) {
157       snmp_inc_tcpestabresets();
158       pcb->state = FIN_WAIT_1;
159     }
160     break;
161   case CLOSE_WAIT:
162     err = tcp_send_ctrl(pcb, TCP_FIN);
163     if (err == ERR_OK) {
164       snmp_inc_tcpestabresets();
165       pcb->state = LAST_ACK;
166     }
167     break;
168   default:
169     /* Has already been closed, do nothing. */
170     err = ERR_OK;
171     pcb = NULL;
172     break;
173   }
174
175   if (pcb != NULL && err == ERR_OK) {
176     /* To ensure all data has been sent when tcp_close returns, we have
177        to make sure tcp_output doesn't fail.
178        Since we don't really have to ensure all data has been sent when tcp_close
179        returns (unsent data is sent from tcp timer functions, also), we don't care
180        for the return value of tcp_output for now. */
181     /* @todo: When implementing SO_LINGER, this must be changed somehow:
182        If SOF_LINGER is set, the data should be sent when tcp_close returns. */
183     tcp_output(pcb);
184   }
185   return err;
186 }
187
188 /**
189  * Abandons a connection and optionally sends a RST to the remote
190  * host.  Deletes the local protocol control block. This is done when
191  * a connection is killed because of shortage of memory.
192  *
193  * @param pcb the tcp_pcb to abort
194  * @param reset boolean to indicate whether a reset should be sent
195  */
196 void
197 tcp_abandon(struct tcp_pcb *pcb, int reset)
198 {
199   u32_t seqno, ackno;
200   u16_t remote_port, local_port;
201   struct ip_addr remote_ip, local_ip;
202 #if LWIP_CALLBACK_API  
203   void (* errf)(void *arg, err_t err);
204 #endif /* LWIP_CALLBACK_API */
205   void *errf_arg;
206
207   
208   /* Figure out on which TCP PCB list we are, and remove us. If we
209      are in an active state, call the receive function associated with
210      the PCB with a NULL argument, and send an RST to the remote end. */
211   if (pcb->state == TIME_WAIT) {
212     tcp_pcb_remove(&tcp_tw_pcbs, pcb);
213     memp_free(MEMP_TCP_PCB, pcb);
214   } else {
215     seqno = pcb->snd_nxt;
216     ackno = pcb->rcv_nxt;
217     ip_addr_set(&local_ip, &(pcb->local_ip));
218     ip_addr_set(&remote_ip, &(pcb->remote_ip));
219     local_port = pcb->local_port;
220     remote_port = pcb->remote_port;
221 #if LWIP_CALLBACK_API
222     errf = pcb->errf;
223 #endif /* LWIP_CALLBACK_API */
224     errf_arg = pcb->callback_arg;
225     tcp_pcb_remove(&tcp_active_pcbs, pcb);
226     if (pcb->unacked != NULL) {
227       tcp_segs_free(pcb->unacked);
228     }
229     if (pcb->unsent != NULL) {
230       tcp_segs_free(pcb->unsent);
231     }
232 #if TCP_QUEUE_OOSEQ    
233     if (pcb->ooseq != NULL) {
234       tcp_segs_free(pcb->ooseq);
235     }
236 #endif /* TCP_QUEUE_OOSEQ */
237     memp_free(MEMP_TCP_PCB, pcb);
238     TCP_EVENT_ERR(errf, errf_arg, ERR_ABRT);
239     if (reset) {
240       LWIP_DEBUGF(TCP_RST_DEBUG, ("tcp_abandon: sending RST\n"));
241       tcp_rst(seqno, ackno, &local_ip, &remote_ip, local_port, remote_port);
242     }
243   }
244 }
245
246 /**
247  * Binds the connection to a local portnumber and IP address. If the
248  * IP address is not given (i.e., ipaddr == NULL), the IP address of
249  * the outgoing network interface is used instead.
250  *
251  * @param pcb the tcp_pcb to bind (no check is done whether this pcb is
252  *        already bound!)
253  * @param ipaddr the local ip address to bind to (use IP_ADDR_ANY to bind
254  *        to any local address
255  * @param port the local port to bind to
256  * @return ERR_USE if the port is already in use
257  *         ERR_OK if bound
258  */
259 err_t
260 tcp_bind(struct tcp_pcb *pcb, struct ip_addr *ipaddr, u16_t port)
261 {
262   struct tcp_pcb *cpcb;
263
264   LWIP_ERROR("tcp_bind: can only bind in state CLOSED", pcb->state == CLOSED, return ERR_ISCONN);
265
266   if (port == 0) {
267     port = tcp_new_port();
268   }
269   /* Check if the address already is in use. */
270   /* Check the listen pcbs. */
271   for(cpcb = (struct tcp_pcb *)tcp_listen_pcbs.pcbs;
272       cpcb != NULL; cpcb = cpcb->next) {
273     if (cpcb->local_port == port) {
274       if (ip_addr_isany(&(cpcb->local_ip)) ||
275           ip_addr_isany(ipaddr) ||
276           ip_addr_cmp(&(cpcb->local_ip), ipaddr)) {
277         return ERR_USE;
278       }
279     }
280   }
281   /* Check the connected pcbs. */
282   for(cpcb = tcp_active_pcbs;
283       cpcb != NULL; cpcb = cpcb->next) {
284     if (cpcb->local_port == port) {
285       if (ip_addr_isany(&(cpcb->local_ip)) ||
286           ip_addr_isany(ipaddr) ||
287           ip_addr_cmp(&(cpcb->local_ip), ipaddr)) {
288         return ERR_USE;
289       }
290     }
291   }
292   /* Check the bound, not yet connected pcbs. */
293   for(cpcb = tcp_bound_pcbs; cpcb != NULL; cpcb = cpcb->next) {
294     if (cpcb->local_port == port) {
295       if (ip_addr_isany(&(cpcb->local_ip)) ||
296           ip_addr_isany(ipaddr) ||
297           ip_addr_cmp(&(cpcb->local_ip), ipaddr)) {
298         return ERR_USE;
299       }
300     }
301   }
302   /* @todo: until SO_REUSEADDR is implemented (see task #6995 on savannah),
303    * we have to check the pcbs in TIME-WAIT state, also: */
304   for(cpcb = tcp_tw_pcbs; cpcb != NULL; cpcb = cpcb->next) {
305     if (cpcb->local_port == port) {
306       if (ip_addr_cmp(&(cpcb->local_ip), ipaddr)) {
307         return ERR_USE;
308       }
309     }
310   }
311
312   if (!ip_addr_isany(ipaddr)) {
313     pcb->local_ip = *ipaddr;
314   }
315   pcb->local_port = port;
316   TCP_REG(&tcp_bound_pcbs, pcb);
317   LWIP_DEBUGF(TCP_DEBUG, ("tcp_bind: bind to port %"U16_F"\n", port));
318   return ERR_OK;
319 }
320 #if LWIP_CALLBACK_API
321 /**
322  * Default accept callback if no accept callback is specified by the user.
323  */
324 static err_t
325 tcp_accept_null(void *arg, struct tcp_pcb *pcb, err_t err)
326 {
327   LWIP_UNUSED_ARG(arg);
328   LWIP_UNUSED_ARG(pcb);
329   LWIP_UNUSED_ARG(err);
330
331   return ERR_ABRT;
332 }
333 #endif /* LWIP_CALLBACK_API */
334
335 /**
336  * Set the state of the connection to be LISTEN, which means that it
337  * is able to accept incoming connections. The protocol control block
338  * is reallocated in order to consume less memory. Setting the
339  * connection to LISTEN is an irreversible process.
340  *
341  * @param pcb the original tcp_pcb
342  * @param backlog the incoming connections queue limit
343  * @return tcp_pcb used for listening, consumes less memory.
344  *
345  * @note The original tcp_pcb is freed. This function therefore has to be
346  *       called like this:
347  *             tpcb = tcp_listen(tpcb);
348  */
349 struct tcp_pcb *
350 tcp_listen_with_backlog(struct tcp_pcb *pcb, u8_t backlog)
351 {
352   struct tcp_pcb_listen *lpcb;
353
354   LWIP_UNUSED_ARG(backlog);
355   LWIP_ERROR("tcp_listen: pcb already connected", pcb->state == CLOSED, return NULL);
356
357   /* already listening? */
358   if (pcb->state == LISTEN) {
359     return pcb;
360   }
361   lpcb = memp_malloc(MEMP_TCP_PCB_LISTEN);
362   if (lpcb == NULL) {
363     return NULL;
364   }
365   lpcb->callback_arg = pcb->callback_arg;
366   lpcb->local_port = pcb->local_port;
367   lpcb->state = LISTEN;
368   lpcb->so_options = pcb->so_options;
369   lpcb->so_options |= SOF_ACCEPTCONN;
370   lpcb->ttl = pcb->ttl;
371   lpcb->tos = pcb->tos;
372   ip_addr_set(&lpcb->local_ip, &pcb->local_ip);
373   TCP_RMV(&tcp_bound_pcbs, pcb);
374   memp_free(MEMP_TCP_PCB, pcb);
375 #if LWIP_CALLBACK_API
376   lpcb->accept = tcp_accept_null;
377 #endif /* LWIP_CALLBACK_API */
378 #if TCP_LISTEN_BACKLOG
379   lpcb->accepts_pending = 0;
380   lpcb->backlog = (backlog ? backlog : 1);
381 #endif /* TCP_LISTEN_BACKLOG */
382   TCP_REG(&tcp_listen_pcbs.listen_pcbs, lpcb);
383   return (struct tcp_pcb *)lpcb;
384 }
385
386 /**
387  * This function should be called by the application when it has
388  * processed the data. The purpose is to advertise a larger window
389  * when the data has been processed.
390  *
391  * @param pcb the tcp_pcb for which data is read
392  * @param len the amount of bytes that have been read by the application
393  */
394 void
395 tcp_recved(struct tcp_pcb *pcb, u16_t len)
396 {
397   if ((u32_t)pcb->rcv_wnd + len > TCP_WND) {
398     pcb->rcv_wnd = TCP_WND;
399     pcb->rcv_ann_wnd = TCP_WND;
400   } else {
401     pcb->rcv_wnd += len;
402     if (pcb->rcv_wnd >= pcb->mss) {
403       pcb->rcv_ann_wnd = pcb->rcv_wnd;
404     }
405   }
406
407   if (!(pcb->flags & TF_ACK_DELAY) &&
408      !(pcb->flags & TF_ACK_NOW)) {
409     /*
410      * We send an ACK here (if one is not already pending, hence
411      * the above tests) as tcp_recved() implies that the application
412      * has processed some data, and so we can open the receiver's
413      * window to allow more to be transmitted.  This could result in
414      * two ACKs being sent for each received packet in some limited cases
415      * (where the application is only receiving data, and is slow to
416      * process it) but it is necessary to guarantee that the sender can
417      * continue to transmit.
418      */
419     tcp_ack(pcb);
420   } 
421   else if (pcb->flags & TF_ACK_DELAY && pcb->rcv_wnd >= TCP_WND/2) {
422     /* If we can send a window update such that there is a full
423      * segment available in the window, do so now.  This is sort of
424      * nagle-like in its goals, and tries to hit a compromise between
425      * sending acks each time the window is updated, and only sending
426      * window updates when a timer expires.  The "threshold" used
427      * above (currently TCP_WND/2) can be tuned to be more or less
428      * aggressive  */
429     tcp_ack_now(pcb);
430   }
431
432   LWIP_DEBUGF(TCP_DEBUG, ("tcp_recved: recveived %"U16_F" bytes, wnd %"U16_F" (%"U16_F").\n",
433          len, pcb->rcv_wnd, TCP_WND - pcb->rcv_wnd));
434 }
435
436 /**
437  * A nastly hack featuring 'goto' statements that allocates a
438  * new TCP local port.
439  *
440  * @return a new (free) local TCP port number
441  */
442 static u16_t
443 tcp_new_port(void)
444 {
445   struct tcp_pcb *pcb;
446 #ifndef TCP_LOCAL_PORT_RANGE_START
447 #define TCP_LOCAL_PORT_RANGE_START 4096
448 #define TCP_LOCAL_PORT_RANGE_END   0x7fff
449 #endif
450   static u16_t port = TCP_LOCAL_PORT_RANGE_START;
451   
452  again:
453   if (++port > TCP_LOCAL_PORT_RANGE_END) {
454     port = TCP_LOCAL_PORT_RANGE_START;
455   }
456   
457   for(pcb = tcp_active_pcbs; pcb != NULL; pcb = pcb->next) {
458     if (pcb->local_port == port) {
459       goto again;
460     }
461   }
462   for(pcb = tcp_tw_pcbs; pcb != NULL; pcb = pcb->next) {
463     if (pcb->local_port == port) {
464       goto again;
465     }
466   }
467   for(pcb = (struct tcp_pcb *)tcp_listen_pcbs.pcbs; pcb != NULL; pcb = pcb->next) {
468     if (pcb->local_port == port) {
469       goto again;
470     }
471   }
472   return port;
473 }
474
475 /**
476  * Connects to another host. The function given as the "connected"
477  * argument will be called when the connection has been established.
478  *
479  * @param pcb the tcp_pcb used to establish the connection
480  * @param ipaddr the remote ip address to connect to
481  * @param port the remote tcp port to connect to
482  * @param connected callback function to call when connected (or on error)
483  * @return ERR_VAL if invalid arguments are given
484  *         ERR_OK if connect request has been sent
485  *         other err_t values if connect request couldn't be sent
486  */
487 err_t
488 tcp_connect(struct tcp_pcb *pcb, struct ip_addr *ipaddr, u16_t port,
489       err_t (* connected)(void *arg, struct tcp_pcb *tpcb, err_t err))
490 {
491   u32_t optdata;
492   err_t ret;
493   u32_t iss;
494
495   LWIP_ERROR("tcp_connect: can only connected from state CLOSED", pcb->state == CLOSED, return ERR_ISCONN);
496
497   LWIP_DEBUGF(TCP_DEBUG, ("tcp_connect to port %"U16_F"\n", port));
498   if (ipaddr != NULL) {
499     pcb->remote_ip = *ipaddr;
500   } else {
501     return ERR_VAL;
502   }
503   pcb->remote_port = port;
504   if (pcb->local_port == 0) {
505     pcb->local_port = tcp_new_port();
506   }
507   iss = tcp_next_iss();
508   pcb->rcv_nxt = 0;
509   pcb->snd_nxt = iss;
510   pcb->lastack = iss - 1;
511   pcb->snd_lbb = iss - 1;
512   pcb->rcv_wnd = TCP_WND;
513   pcb->rcv_ann_wnd = TCP_WND;
514   pcb->snd_wnd = TCP_WND;
515   /* As initial send MSS, we use TCP_MSS but limit it to 536.
516      The send MSS is updated when an MSS option is received. */
517   pcb->mss = (TCP_MSS > 536) ? 536 : TCP_MSS;
518 #if TCP_CALCULATE_EFF_SEND_MSS
519   pcb->mss = tcp_eff_send_mss(pcb->mss, ipaddr);
520 #endif /* TCP_CALCULATE_EFF_SEND_MSS */
521   pcb->cwnd = 1;
522   pcb->ssthresh = pcb->mss * 10;
523   pcb->state = SYN_SENT;
524 #if LWIP_CALLBACK_API  
525   pcb->connected = connected;
526 #endif /* LWIP_CALLBACK_API */
527   TCP_RMV(&tcp_bound_pcbs, pcb);
528   TCP_REG(&tcp_active_pcbs, pcb);
529
530   snmp_inc_tcpactiveopens();
531   
532   /* Build an MSS option */
533   optdata = TCP_BUILD_MSS_OPTION();
534
535   ret = tcp_enqueue(pcb, NULL, 0, TCP_SYN, 0, (u8_t *)&optdata, 4);
536   if (ret == ERR_OK) { 
537     tcp_output(pcb);
538   }
539   return ret;
540
541
542 /**
543  * Called every 500 ms and implements the retransmission timer and the timer that
544  * removes PCBs that have been in TIME-WAIT for enough time. It also increments
545  * various timers such as the inactivity timer in each PCB.
546  *
547  * Automatically called from tcp_tmr().
548  */
549 void
550 tcp_slowtmr(void)
551 {
552   struct tcp_pcb *pcb, *pcb2, *prev;
553   u16_t eff_wnd;
554   u8_t pcb_remove;      /* flag if a PCB should be removed */
555   err_t err;
556
557   err = ERR_OK;
558
559   ++tcp_ticks;
560
561   /* Steps through all of the active PCBs. */
562   prev = NULL;
563   pcb = tcp_active_pcbs;
564   if (pcb == NULL) {
565     LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: no active pcbs\n"));
566   }
567   while (pcb != NULL) {
568     LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: processing active pcb\n"));
569     LWIP_ASSERT("tcp_slowtmr: active pcb->state != CLOSED\n", pcb->state != CLOSED);
570     LWIP_ASSERT("tcp_slowtmr: active pcb->state != LISTEN\n", pcb->state != LISTEN);
571     LWIP_ASSERT("tcp_slowtmr: active pcb->state != TIME-WAIT\n", pcb->state != TIME_WAIT);
572
573     pcb_remove = 0;
574
575     if (pcb->state == SYN_SENT && pcb->nrtx == TCP_SYNMAXRTX) {
576       ++pcb_remove;
577       LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: max SYN retries reached\n"));
578     }
579     else if (pcb->nrtx == TCP_MAXRTX) {
580       ++pcb_remove;
581       LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: max DATA retries reached\n"));
582     } else {
583       if (pcb->persist_backoff > 0) {
584         /* If snd_wnd is zero, use persist timer to send 1 byte probes
585          * instead of using the standard retransmission mechanism. */
586         pcb->persist_cnt++;
587         if (pcb->persist_cnt >= tcp_persist_backoff[pcb->persist_backoff-1]) {
588           pcb->persist_cnt = 0;
589           if (pcb->persist_backoff < sizeof(tcp_persist_backoff)) {
590             pcb->persist_backoff++;
591           }
592           tcp_zero_window_probe(pcb);
593         }
594       } else {
595         /* Increase the retransmission timer if it is running */
596         if(pcb->rtime >= 0)
597           ++pcb->rtime;
598
599         if (pcb->unacked != NULL && pcb->rtime >= pcb->rto) {
600           /* Time for a retransmission. */
601           LWIP_DEBUGF(TCP_RTO_DEBUG, ("tcp_slowtmr: rtime %"S16_F
602                                       " pcb->rto %"S16_F"\n",
603                                       pcb->rtime, pcb->rto));
604
605           /* Double retransmission time-out unless we are trying to
606            * connect to somebody (i.e., we are in SYN_SENT). */
607           if (pcb->state != SYN_SENT) {
608             pcb->rto = ((pcb->sa >> 3) + pcb->sv) << tcp_backoff[pcb->nrtx];
609           }
610
611           /* Reset the retransmission timer. */
612           pcb->rtime = 0;
613
614           /* Reduce congestion window and ssthresh. */
615           eff_wnd = LWIP_MIN(pcb->cwnd, pcb->snd_wnd);
616           pcb->ssthresh = eff_wnd >> 1;
617           if (pcb->ssthresh < pcb->mss) {
618             pcb->ssthresh = pcb->mss * 2;
619           }
620           pcb->cwnd = pcb->mss;
621           LWIP_DEBUGF(TCP_CWND_DEBUG, ("tcp_slowtmr: cwnd %"U16_F
622                                        " ssthresh %"U16_F"\n",
623                                        pcb->cwnd, pcb->ssthresh));
624  
625           /* The following needs to be called AFTER cwnd is set to one
626              mss - STJ */
627           tcp_rexmit_rto(pcb);
628         }
629       }
630     }
631     /* Check if this PCB has stayed too long in FIN-WAIT-2 */
632     if (pcb->state == FIN_WAIT_2) {
633       if ((u32_t)(tcp_ticks - pcb->tmr) >
634           TCP_FIN_WAIT_TIMEOUT / TCP_SLOW_INTERVAL) {
635         ++pcb_remove;
636         LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: removing pcb stuck in FIN-WAIT-2\n"));
637       }
638     }
639
640     /* Check if KEEPALIVE should be sent */
641     if((pcb->so_options & SOF_KEEPALIVE) && 
642        ((pcb->state == ESTABLISHED) || 
643         (pcb->state == CLOSE_WAIT))) {
644 #if LWIP_TCP_KEEPALIVE
645       if((u32_t)(tcp_ticks - pcb->tmr) > 
646          (pcb->keep_idle + (pcb->keep_cnt*pcb->keep_intvl))
647          / TCP_SLOW_INTERVAL)
648 #else      
649       if((u32_t)(tcp_ticks - pcb->tmr) > 
650          (pcb->keep_idle + TCP_MAXIDLE) / TCP_SLOW_INTERVAL)
651 #endif /* LWIP_TCP_KEEPALIVE */
652       {
653         LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: KEEPALIVE timeout. Aborting connection to %"U16_F".%"U16_F".%"U16_F".%"U16_F".\n",
654                                 ip4_addr1(&pcb->remote_ip), ip4_addr2(&pcb->remote_ip),
655                                 ip4_addr3(&pcb->remote_ip), ip4_addr4(&pcb->remote_ip)));
656         
657         tcp_abort(pcb);
658       }
659 #if LWIP_TCP_KEEPALIVE
660       else if((u32_t)(tcp_ticks - pcb->tmr) > 
661               (pcb->keep_idle + pcb->keep_cnt_sent * pcb->keep_intvl)
662               / TCP_SLOW_INTERVAL)
663 #else
664       else if((u32_t)(tcp_ticks - pcb->tmr) > 
665               (pcb->keep_idle + pcb->keep_cnt_sent * TCP_KEEPINTVL_DEFAULT) 
666               / TCP_SLOW_INTERVAL)
667 #endif /* LWIP_TCP_KEEPALIVE */
668       {
669         tcp_keepalive(pcb);
670         pcb->keep_cnt_sent++;
671       }
672     }
673
674     /* If this PCB has queued out of sequence data, but has been
675        inactive for too long, will drop the data (it will eventually
676        be retransmitted). */
677 #if TCP_QUEUE_OOSEQ    
678     if (pcb->ooseq != NULL &&
679         (u32_t)tcp_ticks - pcb->tmr >= pcb->rto * TCP_OOSEQ_TIMEOUT) {
680       tcp_segs_free(pcb->ooseq);
681       pcb->ooseq = NULL;
682       LWIP_DEBUGF(TCP_CWND_DEBUG, ("tcp_slowtmr: dropping OOSEQ queued data\n"));
683     }
684 #endif /* TCP_QUEUE_OOSEQ */
685
686     /* Check if this PCB has stayed too long in SYN-RCVD */
687     if (pcb->state == SYN_RCVD) {
688       if ((u32_t)(tcp_ticks - pcb->tmr) >
689           TCP_SYN_RCVD_TIMEOUT / TCP_SLOW_INTERVAL) {
690         ++pcb_remove;
691         LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: removing pcb stuck in SYN-RCVD\n"));
692       }
693     }
694
695     /* Check if this PCB has stayed too long in LAST-ACK */
696     if (pcb->state == LAST_ACK) {
697       if ((u32_t)(tcp_ticks - pcb->tmr) > 2 * TCP_MSL / TCP_SLOW_INTERVAL) {
698         ++pcb_remove;
699         LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: removing pcb stuck in LAST-ACK\n"));
700       }
701     }
702
703     /* If the PCB should be removed, do it. */
704     if (pcb_remove) {
705       tcp_pcb_purge(pcb);      
706       /* Remove PCB from tcp_active_pcbs list. */
707       if (prev != NULL) {
708         LWIP_ASSERT("tcp_slowtmr: middle tcp != tcp_active_pcbs", pcb != tcp_active_pcbs);
709         prev->next = pcb->next;
710       } else {
711         /* This PCB was the first. */
712         LWIP_ASSERT("tcp_slowtmr: first pcb == tcp_active_pcbs", tcp_active_pcbs == pcb);
713         tcp_active_pcbs = pcb->next;
714       }
715
716       TCP_EVENT_ERR(pcb->errf, pcb->callback_arg, ERR_ABRT);
717
718       pcb2 = pcb->next;
719       memp_free(MEMP_TCP_PCB, pcb);
720       pcb = pcb2;
721     } else {
722
723       /* We check if we should poll the connection. */
724       ++pcb->polltmr;
725       if (pcb->polltmr >= pcb->pollinterval) {
726         pcb->polltmr = 0;
727         LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: polling application\n"));
728         TCP_EVENT_POLL(pcb, err);
729         if (err == ERR_OK) {
730           tcp_output(pcb);
731         }
732       }
733       
734       prev = pcb;
735       pcb = pcb->next;
736     }
737   }
738
739   
740   /* Steps through all of the TIME-WAIT PCBs. */
741   prev = NULL;    
742   pcb = tcp_tw_pcbs;
743   while (pcb != NULL) {
744     LWIP_ASSERT("tcp_slowtmr: TIME-WAIT pcb->state == TIME-WAIT", pcb->state == TIME_WAIT);
745     pcb_remove = 0;
746
747     /* Check if this PCB has stayed long enough in TIME-WAIT */
748     if ((u32_t)(tcp_ticks - pcb->tmr) > 2 * TCP_MSL / TCP_SLOW_INTERVAL) {
749       ++pcb_remove;
750     }
751     
752
753
754     /* If the PCB should be removed, do it. */
755     if (pcb_remove) {
756       tcp_pcb_purge(pcb);      
757       /* Remove PCB from tcp_tw_pcbs list. */
758       if (prev != NULL) {
759         LWIP_ASSERT("tcp_slowtmr: middle tcp != tcp_tw_pcbs", pcb != tcp_tw_pcbs);
760         prev->next = pcb->next;
761       } else {
762         /* This PCB was the first. */
763         LWIP_ASSERT("tcp_slowtmr: first pcb == tcp_tw_pcbs", tcp_tw_pcbs == pcb);
764         tcp_tw_pcbs = pcb->next;
765       }
766       pcb2 = pcb->next;
767       memp_free(MEMP_TCP_PCB, pcb);
768       pcb = pcb2;
769     } else {
770       prev = pcb;
771       pcb = pcb->next;
772     }
773   }
774 }
775
776 /**
777  * Is called every TCP_FAST_INTERVAL (250 ms) and process data previously
778  * "refused" by upper layer (application) and sends delayed ACKs.
779  *
780  * Automatically called from tcp_tmr().
781  */
782 void
783 tcp_fasttmr(void)
784 {
785   struct tcp_pcb *pcb;
786
787   for(pcb = tcp_active_pcbs; pcb != NULL; pcb = pcb->next) {
788     /* If there is data which was previously "refused" by upper layer */
789     if (pcb->refused_data != NULL) {
790       /* Notify again application with data previously received. */
791       err_t err;
792       LWIP_DEBUGF(TCP_INPUT_DEBUG, ("tcp_fasttmr: notify kept packet\n"));
793       TCP_EVENT_RECV(pcb, pcb->refused_data, ERR_OK, err);
794       if (err == ERR_OK) {
795         pcb->refused_data = NULL;
796       }
797     }
798
799     /* send delayed ACKs */  
800     if (pcb->flags & TF_ACK_DELAY) {
801       LWIP_DEBUGF(TCP_DEBUG, ("tcp_fasttmr: delayed ACK\n"));
802       tcp_ack_now(pcb);
803       pcb->flags &= ~(TF_ACK_DELAY | TF_ACK_NOW);
804     }
805   }
806 }
807
808 /**
809  * Deallocates a list of TCP segments (tcp_seg structures).
810  *
811  * @param seg tcp_seg list of TCP segments to free
812  * @return the number of pbufs that were deallocated
813  */
814 u8_t
815 tcp_segs_free(struct tcp_seg *seg)
816 {
817   u8_t count = 0;
818   struct tcp_seg *next;
819   while (seg != NULL) {
820     next = seg->next;
821     count += tcp_seg_free(seg);
822     seg = next;
823   }
824   return count;
825 }
826
827 /**
828  * Frees a TCP segment (tcp_seg structure).
829  *
830  * @param seg single tcp_seg to free
831  * @return the number of pbufs that were deallocated
832  */
833 u8_t
834 tcp_seg_free(struct tcp_seg *seg)
835 {
836   u8_t count = 0;
837   
838   if (seg != NULL) {
839     if (seg->p != NULL) {
840       count = pbuf_free(seg->p);
841 #if TCP_DEBUG
842       seg->p = NULL;
843 #endif /* TCP_DEBUG */
844     }
845     memp_free(MEMP_TCP_SEG, seg);
846   }
847   return count;
848 }
849
850 /**
851  * Sets the priority of a connection.
852  *
853  * @param pcb the tcp_pcb to manipulate
854  * @param prio new priority
855  */
856 void
857 tcp_setprio(struct tcp_pcb *pcb, u8_t prio)
858 {
859   pcb->prio = prio;
860 }
861 #if TCP_QUEUE_OOSEQ
862
863 /**
864  * Returns a copy of the given TCP segment.
865  * The pbuf and data are not copied, only the pointers
866  *
867  * @param seg the old tcp_seg
868  * @return a copy of seg
869  */ 
870 struct tcp_seg *
871 tcp_seg_copy(struct tcp_seg *seg)
872 {
873   struct tcp_seg *cseg;
874
875   cseg = memp_malloc(MEMP_TCP_SEG);
876   if (cseg == NULL) {
877     return NULL;
878   }
879   SMEMCPY((u8_t *)cseg, (const u8_t *)seg, sizeof(struct tcp_seg)); 
880   pbuf_ref(cseg->p);
881   return cseg;
882 }
883 #endif
884
885 #if LWIP_CALLBACK_API
886 /**
887  * Default receive callback that is called if the user didn't register
888  * a recv callback for the pcb.
889  */
890 static err_t
891 tcp_recv_null(void *arg, struct tcp_pcb *pcb, struct pbuf *p, err_t err)
892 {
893   arg = arg;
894   if (p != NULL) {
895     pbuf_free(p);
896   } else if (err == ERR_OK) {
897     return tcp_close(pcb);
898   }
899   return ERR_OK;
900 }
901 #endif /* LWIP_CALLBACK_API */
902
903 /**
904  * Kills the oldest active connection that has lower priority than prio.
905  *
906  * @param prio minimum priority
907  */
908 static void
909 tcp_kill_prio(u8_t prio)
910 {
911   struct tcp_pcb *pcb, *inactive;
912   u32_t inactivity;
913   u8_t mprio;
914
915
916   mprio = TCP_PRIO_MAX;
917   
918   /* We kill the oldest active connection that has lower priority than prio. */
919   inactivity = 0;
920   inactive = NULL;
921   for(pcb = tcp_active_pcbs; pcb != NULL; pcb = pcb->next) {
922     if (pcb->prio <= prio &&
923        pcb->prio <= mprio &&
924        (u32_t)(tcp_ticks - pcb->tmr) >= inactivity) {
925       inactivity = tcp_ticks - pcb->tmr;
926       inactive = pcb;
927       mprio = pcb->prio;
928     }
929   }
930   if (inactive != NULL) {
931     LWIP_DEBUGF(TCP_DEBUG, ("tcp_kill_prio: killing oldest PCB %p (%"S32_F")\n",
932            (void *)inactive, inactivity));
933     tcp_abort(inactive);
934   }      
935 }
936
937 /**
938  * Kills the oldest connection that is in TIME_WAIT state.
939  * Called from tcp_alloc() if no more connections are available.
940  */
941 static void
942 tcp_kill_timewait(void)
943 {
944   struct tcp_pcb *pcb, *inactive;
945   u32_t inactivity;
946
947   inactivity = 0;
948   inactive = NULL;
949   /* Go through the list of TIME_WAIT pcbs and get the oldest pcb. */
950   for(pcb = tcp_tw_pcbs; pcb != NULL; pcb = pcb->next) {
951     if ((u32_t)(tcp_ticks - pcb->tmr) >= inactivity) {
952       inactivity = tcp_ticks - pcb->tmr;
953       inactive = pcb;
954     }
955   }
956   if (inactive != NULL) {
957     LWIP_DEBUGF(TCP_DEBUG, ("tcp_kill_timewait: killing oldest TIME-WAIT PCB %p (%"S32_F")\n",
958            (void *)inactive, inactivity));
959     tcp_abort(inactive);
960   }      
961 }
962
963 /**
964  * Allocate a new tcp_pcb structure.
965  *
966  * @param prio priority for the new pcb
967  * @return a new tcp_pcb that initially is in state CLOSED
968  */
969 struct tcp_pcb *
970 tcp_alloc(u8_t prio)
971 {
972   struct tcp_pcb *pcb;
973   u32_t iss;
974   
975   pcb = memp_malloc(MEMP_TCP_PCB);
976   if (pcb == NULL) {
977     /* Try killing oldest connection in TIME-WAIT. */
978     LWIP_DEBUGF(TCP_DEBUG, ("tcp_alloc: killing off oldest TIME-WAIT connection\n"));
979     tcp_kill_timewait();
980     /* Try to allocate a tcp_pcb again. */
981     pcb = memp_malloc(MEMP_TCP_PCB);
982     if (pcb == NULL) {
983       /* Try killing active connections with lower priority than the new one. */
984       tcp_kill_prio(prio);
985       /* Try to allocate a tcp_pcb again. */
986       pcb = memp_malloc(MEMP_TCP_PCB);
987     }
988   }
989   if (pcb != NULL) {
990     memset(pcb, 0, sizeof(struct tcp_pcb));
991     pcb->prio = TCP_PRIO_NORMAL;
992     pcb->snd_buf = TCP_SND_BUF;
993     pcb->snd_queuelen = 0;
994     pcb->rcv_wnd = TCP_WND;
995     pcb->rcv_ann_wnd = TCP_WND;
996     pcb->tos = 0;
997     pcb->ttl = TCP_TTL;
998     /* As initial send MSS, we use TCP_MSS but limit it to 536.
999        The send MSS is updated when an MSS option is received. */
1000     pcb->mss = (TCP_MSS > 536) ? 536 : TCP_MSS;
1001     pcb->rto = 3000 / TCP_SLOW_INTERVAL;
1002     pcb->sa = 0;
1003     pcb->sv = 3000 / TCP_SLOW_INTERVAL;
1004     pcb->rtime = -1;
1005     pcb->cwnd = 1;
1006     iss = tcp_next_iss();
1007     pcb->snd_wl2 = iss;
1008     pcb->snd_nxt = iss;
1009     pcb->snd_max = iss;
1010     pcb->lastack = iss;
1011     pcb->snd_lbb = iss;   
1012     pcb->tmr = tcp_ticks;
1013
1014     pcb->polltmr = 0;
1015
1016 #if LWIP_CALLBACK_API
1017     pcb->recv = tcp_recv_null;
1018 #endif /* LWIP_CALLBACK_API */  
1019     
1020     /* Init KEEPALIVE timer */
1021     pcb->keep_idle  = TCP_KEEPIDLE_DEFAULT;
1022     
1023 #if LWIP_TCP_KEEPALIVE
1024     pcb->keep_intvl = TCP_KEEPINTVL_DEFAULT;
1025     pcb->keep_cnt   = TCP_KEEPCNT_DEFAULT;
1026 #endif /* LWIP_TCP_KEEPALIVE */
1027
1028     pcb->keep_cnt_sent = 0;
1029   }
1030   return pcb;
1031 }
1032
1033 /**
1034  * Creates a new TCP protocol control block but doesn't place it on
1035  * any of the TCP PCB lists.
1036  * The pcb is not put on any list until binding using tcp_bind().
1037  *
1038  * @internal: Maybe there should be a idle TCP PCB list where these
1039  * PCBs are put on. Port reservation using tcp_bind() is implemented but
1040  * allocated pcbs that are not bound can't be killed automatically if wanting
1041  * to allocate a pcb with higher prio (@see tcp_kill_prio())
1042  *
1043  * @return a new tcp_pcb that initially is in state CLOSED
1044  */
1045 struct tcp_pcb *
1046 tcp_new(void)
1047 {
1048   return tcp_alloc(TCP_PRIO_NORMAL);
1049 }
1050
1051 /**
1052  * Used to specify the argument that should be passed callback
1053  * functions.
1054  *
1055  * @param pcb tcp_pcb to set the callback argument
1056  * @param arg void pointer argument to pass to callback functions
1057  */ 
1058 void
1059 tcp_arg(struct tcp_pcb *pcb, void *arg)
1060 {  
1061   pcb->callback_arg = arg;
1062 }
1063 #if LWIP_CALLBACK_API
1064
1065 /**
1066  * Used to specify the function that should be called when a TCP
1067  * connection receives data.
1068  *
1069  * @param pcb tcp_pcb to set the recv callback
1070  * @param recv callback function to call for this pcb when data is received
1071  */ 
1072 void
1073 tcp_recv(struct tcp_pcb *pcb,
1074    err_t (* recv)(void *arg, struct tcp_pcb *tpcb, struct pbuf *p, err_t err))
1075 {
1076   pcb->recv = recv;
1077 }
1078
1079 /**
1080  * Used to specify the function that should be called when TCP data
1081  * has been successfully delivered to the remote host.
1082  *
1083  * @param pcb tcp_pcb to set the sent callback
1084  * @param sent callback function to call for this pcb when data is successfully sent
1085  */ 
1086 void
1087 tcp_sent(struct tcp_pcb *pcb,
1088    err_t (* sent)(void *arg, struct tcp_pcb *tpcb, u16_t len))
1089 {
1090   pcb->sent = sent;
1091 }
1092
1093 /**
1094  * Used to specify the function that should be called when a fatal error
1095  * has occured on the connection.
1096  *
1097  * @param pcb tcp_pcb to set the err callback
1098  * @param errf callback function to call for this pcb when a fatal error
1099  *        has occured on the connection
1100  */ 
1101 void
1102 tcp_err(struct tcp_pcb *pcb,
1103    void (* errf)(void *arg, err_t err))
1104 {
1105   pcb->errf = errf;
1106 }
1107
1108 /**
1109  * Used for specifying the function that should be called when a
1110  * LISTENing connection has been connected to another host.
1111  *
1112  * @param pcb tcp_pcb to set the accept callback
1113  * @param accept callback function to call for this pcb when LISTENing
1114  *        connection has been connected to another host
1115  */ 
1116 void
1117 tcp_accept(struct tcp_pcb *pcb,
1118      err_t (* accept)(void *arg, struct tcp_pcb *newpcb, err_t err))
1119 {
1120   pcb->accept = accept;
1121 }
1122 #endif /* LWIP_CALLBACK_API */
1123
1124
1125 /**
1126  * Used to specify the function that should be called periodically
1127  * from TCP. The interval is specified in terms of the TCP coarse
1128  * timer interval, which is called twice a second.
1129  *
1130  */ 
1131 void
1132 tcp_poll(struct tcp_pcb *pcb,
1133    err_t (* poll)(void *arg, struct tcp_pcb *tpcb), u8_t interval)
1134 {
1135 #if LWIP_CALLBACK_API
1136   pcb->poll = poll;
1137 #endif /* LWIP_CALLBACK_API */  
1138   pcb->pollinterval = interval;
1139 }
1140
1141 /**
1142  * Purges a TCP PCB. Removes any buffered data and frees the buffer memory
1143  * (pcb->ooseq, pcb->unsent and pcb->unacked are freed).
1144  *
1145  * @param pcb tcp_pcb to purge. The pcb itself is not deallocated!
1146  */
1147 void
1148 tcp_pcb_purge(struct tcp_pcb *pcb)
1149 {
1150   if (pcb->state != CLOSED &&
1151      pcb->state != TIME_WAIT &&
1152      pcb->state != LISTEN) {
1153
1154     LWIP_DEBUGF(TCP_DEBUG, ("tcp_pcb_purge\n"));
1155
1156 #if TCP_LISTEN_BACKLOG
1157     if (pcb->state == SYN_RCVD) {
1158       /* Need to find the corresponding listen_pcb and decrease its accepts_pending */
1159       struct tcp_pcb_listen *lpcb;
1160       LWIP_ASSERT("tcp_pcb_purge: pcb->state == SYN_RCVD but tcp_listen_pcbs is NULL",
1161         tcp_listen_pcbs.listen_pcbs != NULL);
1162       for (lpcb = tcp_listen_pcbs.listen_pcbs; lpcb != NULL; lpcb = lpcb->next) {
1163         if ((lpcb->local_port == pcb->local_port) &&
1164             (ip_addr_isany(&lpcb->local_ip) ||
1165              ip_addr_cmp(&pcb->local_ip, &lpcb->local_ip))) {
1166             /* port and address of the listen pcb match the timed-out pcb */
1167             LWIP_ASSERT("tcp_pcb_purge: listen pcb does not have accepts pending",
1168               lpcb->accepts_pending > 0);
1169             lpcb->accepts_pending--;
1170             break;
1171           }
1172       }
1173     }
1174 #endif /* TCP_LISTEN_BACKLOG */
1175
1176
1177     if (pcb->refused_data != NULL) {
1178       LWIP_DEBUGF(TCP_DEBUG, ("tcp_pcb_purge: data left on ->refused_data\n"));
1179       pbuf_free(pcb->refused_data);
1180       pcb->refused_data = NULL;
1181     }
1182     if (pcb->unsent != NULL) {
1183       LWIP_DEBUGF(TCP_DEBUG, ("tcp_pcb_purge: not all data sent\n"));
1184     }
1185     if (pcb->unacked != NULL) {
1186       LWIP_DEBUGF(TCP_DEBUG, ("tcp_pcb_purge: data left on ->unacked\n"));
1187     }
1188 #if TCP_QUEUE_OOSEQ /* LW */
1189     if (pcb->ooseq != NULL) {
1190       LWIP_DEBUGF(TCP_DEBUG, ("tcp_pcb_purge: data left on ->ooseq\n"));
1191     }
1192
1193     /* Stop the retransmission timer as it will expect data on unacked
1194        queue if it fires */
1195     pcb->rtime = -1;
1196
1197     tcp_segs_free(pcb->ooseq);
1198     pcb->ooseq = NULL;
1199 #endif /* TCP_QUEUE_OOSEQ */
1200     tcp_segs_free(pcb->unsent);
1201     tcp_segs_free(pcb->unacked);
1202     pcb->unacked = pcb->unsent = NULL;
1203   }
1204 }
1205
1206 /**
1207  * Purges the PCB and removes it from a PCB list. Any delayed ACKs are sent first.
1208  *
1209  * @param pcblist PCB list to purge.
1210  * @param pcb tcp_pcb to purge. The pcb itself is also deallocated!
1211  */
1212 void
1213 tcp_pcb_remove(struct tcp_pcb **pcblist, struct tcp_pcb *pcb)
1214 {
1215   TCP_RMV(pcblist, pcb);
1216
1217   tcp_pcb_purge(pcb);
1218   
1219   /* if there is an outstanding delayed ACKs, send it */
1220   if (pcb->state != TIME_WAIT &&
1221      pcb->state != LISTEN &&
1222      pcb->flags & TF_ACK_DELAY) {
1223     pcb->flags |= TF_ACK_NOW;
1224     tcp_output(pcb);
1225   }
1226
1227   if (pcb->state != LISTEN) {
1228     LWIP_ASSERT("unsent segments leaking", pcb->unsent == NULL);
1229     LWIP_ASSERT("unacked segments leaking", pcb->unacked == NULL);
1230 #if TCP_QUEUE_OOSEQ
1231     LWIP_ASSERT("ooseq segments leaking", pcb->ooseq == NULL);
1232 #endif /* TCP_QUEUE_OOSEQ */
1233   }
1234
1235   pcb->state = CLOSED;
1236
1237   LWIP_ASSERT("tcp_pcb_remove: tcp_pcbs_sane()", tcp_pcbs_sane());
1238 }
1239
1240 /**
1241  * Calculates a new initial sequence number for new connections.
1242  *
1243  * @return u32_t pseudo random sequence number
1244  */
1245 u32_t
1246 tcp_next_iss(void)
1247 {
1248   static u32_t iss = 6510;
1249   
1250   iss += tcp_ticks;       /* XXX */
1251   return iss;
1252 }
1253
1254 #if TCP_CALCULATE_EFF_SEND_MSS
1255 /**
1256  * Calcluates the effective send mss that can be used for a specific IP address
1257  * by using ip_route to determin the netif used to send to the address and
1258  * calculating the minimum of TCP_MSS and that netif's mtu (if set).
1259  */
1260 u16_t
1261 tcp_eff_send_mss(u16_t sendmss, struct ip_addr *addr)
1262 {
1263   u16_t mss_s;
1264   struct netif *outif;
1265
1266   outif = ip_route(addr);
1267   if ((outif != NULL) && (outif->mtu != 0)) {
1268     mss_s = outif->mtu - IP_HLEN - TCP_HLEN;
1269     /* RFC 1122, chap 4.2.2.6:
1270      * Eff.snd.MSS = min(SendMSS+20, MMS_S) - TCPhdrsize - IPoptionsize
1271      * but we only send options with SYN and that is never filled with data! */
1272     sendmss = LWIP_MIN(sendmss, mss_s);
1273   }
1274   return sendmss;
1275 }
1276 #endif /* TCP_CALCULATE_EFF_SEND_MSS */
1277
1278 #if TCP_DEBUG || TCP_INPUT_DEBUG || TCP_OUTPUT_DEBUG
1279 /**
1280  * Print a tcp header for debugging purposes.
1281  *
1282  * @param tcphdr pointer to a struct tcp_hdr
1283  */
1284 void
1285 tcp_debug_print(struct tcp_hdr *tcphdr)
1286 {
1287   LWIP_DEBUGF(TCP_DEBUG, ("TCP header:\n"));
1288   LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
1289   LWIP_DEBUGF(TCP_DEBUG, ("|    %5"U16_F"      |    %5"U16_F"      | (src port, dest port)\n",
1290          ntohs(tcphdr->src), ntohs(tcphdr->dest)));
1291   LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
1292   LWIP_DEBUGF(TCP_DEBUG, ("|           %010"U32_F"          | (seq no)\n",
1293           ntohl(tcphdr->seqno)));
1294   LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
1295   LWIP_DEBUGF(TCP_DEBUG, ("|           %010"U32_F"          | (ack no)\n",
1296          ntohl(tcphdr->ackno)));
1297   LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
1298   LWIP_DEBUGF(TCP_DEBUG, ("| %2"U16_F" |   |%"U16_F"%"U16_F"%"U16_F"%"U16_F"%"U16_F"%"U16_F"|     %5"U16_F"     | (hdrlen, flags (",
1299        TCPH_HDRLEN(tcphdr),
1300          TCPH_FLAGS(tcphdr) >> 5 & 1,
1301          TCPH_FLAGS(tcphdr) >> 4 & 1,
1302          TCPH_FLAGS(tcphdr) >> 3 & 1,
1303          TCPH_FLAGS(tcphdr) >> 2 & 1,
1304          TCPH_FLAGS(tcphdr) >> 1 & 1,
1305          TCPH_FLAGS(tcphdr) & 1,
1306          ntohs(tcphdr->wnd)));
1307   tcp_debug_print_flags(TCPH_FLAGS(tcphdr));
1308   LWIP_DEBUGF(TCP_DEBUG, ("), win)\n"));
1309   LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
1310   LWIP_DEBUGF(TCP_DEBUG, ("|    0x%04"X16_F"     |     %5"U16_F"     | (chksum, urgp)\n",
1311          ntohs(tcphdr->chksum), ntohs(tcphdr->urgp)));
1312   LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
1313 }
1314
1315 /**
1316  * Print a tcp state for debugging purposes.
1317  *
1318  * @param s enum tcp_state to print
1319  */
1320 void
1321 tcp_debug_print_state(enum tcp_state s)
1322 {
1323   LWIP_DEBUGF(TCP_DEBUG, ("State: "));
1324   switch (s) {
1325   case CLOSED:
1326     LWIP_DEBUGF(TCP_DEBUG, ("CLOSED\n"));
1327     break;
1328  case LISTEN:
1329    LWIP_DEBUGF(TCP_DEBUG, ("LISTEN\n"));
1330    break;
1331   case SYN_SENT:
1332     LWIP_DEBUGF(TCP_DEBUG, ("SYN_SENT\n"));
1333     break;
1334   case SYN_RCVD:
1335     LWIP_DEBUGF(TCP_DEBUG, ("SYN_RCVD\n"));
1336     break;
1337   case ESTABLISHED:
1338     LWIP_DEBUGF(TCP_DEBUG, ("ESTABLISHED\n"));
1339     break;
1340   case FIN_WAIT_1:
1341     LWIP_DEBUGF(TCP_DEBUG, ("FIN_WAIT_1\n"));
1342     break;
1343   case FIN_WAIT_2:
1344     LWIP_DEBUGF(TCP_DEBUG, ("FIN_WAIT_2\n"));
1345     break;
1346   case CLOSE_WAIT:
1347     LWIP_DEBUGF(TCP_DEBUG, ("CLOSE_WAIT\n"));
1348     break;
1349   case CLOSING:
1350     LWIP_DEBUGF(TCP_DEBUG, ("CLOSING\n"));
1351     break;
1352   case LAST_ACK:
1353     LWIP_DEBUGF(TCP_DEBUG, ("LAST_ACK\n"));
1354     break;
1355   case TIME_WAIT:
1356     LWIP_DEBUGF(TCP_DEBUG, ("TIME_WAIT\n"));
1357    break;
1358   }
1359 }
1360
1361 /**
1362  * Print tcp flags for debugging purposes.
1363  *
1364  * @param flags tcp flags, all active flags are printed
1365  */
1366 void
1367 tcp_debug_print_flags(u8_t flags)
1368 {
1369   if (flags & TCP_FIN) {
1370     LWIP_DEBUGF(TCP_DEBUG, ("FIN "));
1371   }
1372   if (flags & TCP_SYN) {
1373     LWIP_DEBUGF(TCP_DEBUG, ("SYN "));
1374   }
1375   if (flags & TCP_RST) {
1376     LWIP_DEBUGF(TCP_DEBUG, ("RST "));
1377   }
1378   if (flags & TCP_PSH) {
1379     LWIP_DEBUGF(TCP_DEBUG, ("PSH "));
1380   }
1381   if (flags & TCP_ACK) {
1382     LWIP_DEBUGF(TCP_DEBUG, ("ACK "));
1383   }
1384   if (flags & TCP_URG) {
1385     LWIP_DEBUGF(TCP_DEBUG, ("URG "));
1386   }
1387   if (flags & TCP_ECE) {
1388     LWIP_DEBUGF(TCP_DEBUG, ("ECE "));
1389   }
1390   if (flags & TCP_CWR) {
1391     LWIP_DEBUGF(TCP_DEBUG, ("CWR "));
1392   }
1393 }
1394
1395 /**
1396  * Print all tcp_pcbs in every list for debugging purposes.
1397  */
1398 void
1399 tcp_debug_print_pcbs(void)
1400 {
1401   struct tcp_pcb *pcb;
1402   LWIP_DEBUGF(TCP_DEBUG, ("Active PCB states:\n"));
1403   for(pcb = tcp_active_pcbs; pcb != NULL; pcb = pcb->next) {
1404     LWIP_DEBUGF(TCP_DEBUG, ("Local port %"U16_F", foreign port %"U16_F" snd_nxt %"U32_F" rcv_nxt %"U32_F" ",
1405                        pcb->local_port, pcb->remote_port,
1406                        pcb->snd_nxt, pcb->rcv_nxt));
1407     tcp_debug_print_state(pcb->state);
1408   }    
1409   LWIP_DEBUGF(TCP_DEBUG, ("Listen PCB states:\n"));
1410   for(pcb = (struct tcp_pcb *)tcp_listen_pcbs.pcbs; pcb != NULL; pcb = pcb->next) {
1411     LWIP_DEBUGF(TCP_DEBUG, ("Local port %"U16_F", foreign port %"U16_F" snd_nxt %"U32_F" rcv_nxt %"U32_F" ",
1412                        pcb->local_port, pcb->remote_port,
1413                        pcb->snd_nxt, pcb->rcv_nxt));
1414     tcp_debug_print_state(pcb->state);
1415   }    
1416   LWIP_DEBUGF(TCP_DEBUG, ("TIME-WAIT PCB states:\n"));
1417   for(pcb = tcp_tw_pcbs; pcb != NULL; pcb = pcb->next) {
1418     LWIP_DEBUGF(TCP_DEBUG, ("Local port %"U16_F", foreign port %"U16_F" snd_nxt %"U32_F" rcv_nxt %"U32_F" ",
1419                        pcb->local_port, pcb->remote_port,
1420                        pcb->snd_nxt, pcb->rcv_nxt));
1421     tcp_debug_print_state(pcb->state);
1422   }    
1423 }
1424
1425 /**
1426  * Check state consistency of the tcp_pcb lists.
1427  */
1428 s16_t
1429 tcp_pcbs_sane(void)
1430 {
1431   struct tcp_pcb *pcb;
1432   for(pcb = tcp_active_pcbs; pcb != NULL; pcb = pcb->next) {
1433     LWIP_ASSERT("tcp_pcbs_sane: active pcb->state != CLOSED", pcb->state != CLOSED);
1434     LWIP_ASSERT("tcp_pcbs_sane: active pcb->state != LISTEN", pcb->state != LISTEN);
1435     LWIP_ASSERT("tcp_pcbs_sane: active pcb->state != TIME-WAIT", pcb->state != TIME_WAIT);
1436   }
1437   for(pcb = tcp_tw_pcbs; pcb != NULL; pcb = pcb->next) {
1438     LWIP_ASSERT("tcp_pcbs_sane: tw pcb->state == TIME-WAIT", pcb->state == TIME_WAIT);
1439   }
1440   return 1;
1441 }
1442 #endif /* TCP_DEBUG */
1443
1444 #endif /* LWIP_TCP */