Back to home page

Quest Cross Reference

 
 

    


Warning, cross-references for /kernel/lwip/core/tcp.c need to be fixed.

0001 /**
0002  * @file
0003  * Transmission Control Protocol for IP
0004  *
0005  * This file contains common functions for the TCP implementation, such as functinos
0006  * for manipulating the data structures and the TCP timer functions. TCP functions
0007  * related to input and output is found in tcp_in.c and tcp_out.c respectively.
0008  *
0009  */
0010 
0011 /*
0012  * Copyright (c) 2001-2004 Swedish Institute of Computer Science.
0013  * All rights reserved. 
0014  * 
0015  * Redistribution and use in source and binary forms, with or without modification, 
0016  * are permitted provided that the following conditions are met:
0017  *
0018  * 1. Redistributions of source code must retain the above copyright notice,
0019  *    this list of conditions and the following disclaimer.
0020  * 2. Redistributions in binary form must reproduce the above copyright notice,
0021  *    this list of conditions and the following disclaimer in the documentation
0022  *    and/or other materials provided with the distribution.
0023  * 3. The name of the author may not be used to endorse or promote products
0024  *    derived from this software without specific prior written permission. 
0025  *
0026  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED 
0027  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
0028  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT 
0029  * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 
0030  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT 
0031  * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
0032  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
0033  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING 
0034  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY 
0035  * OF SUCH DAMAGE.
0036  *
0037  * This file is part of the lwIP TCP/IP stack.
0038  * 
0039  * Author: Adam Dunkels <adam@sics.se>
0040  *
0041  */
0042 
0043 #include "lwip/opt.h"
0044 
0045 #if LWIP_TCP /* don't build if not configured for use in lwipopts.h */
0046 
0047 #include "lwip/def.h"
0048 #include "lwip/mem.h"
0049 #include "lwip/memp.h"
0050 #include "lwip/snmp.h"
0051 #include "lwip/tcp.h"
0052 #include "lwip/debug.h"
0053 #include "lwip/stats.h"
0054 
0055 #include <string.h>
0056 
0057 const char *tcp_state_str[] = {
0058   "CLOSED",      
0059   "LISTEN",      
0060   "SYN_SENT",    
0061   "SYN_RCVD",    
0062   "ESTABLISHED", 
0063   "FIN_WAIT_1",  
0064   "FIN_WAIT_2",  
0065   "CLOSE_WAIT",  
0066   "CLOSING",     
0067   "LAST_ACK",    
0068   "TIME_WAIT"   
0069 };
0070 
0071 /* Incremented every coarse grained timer shot (typically every 500 ms). */
0072 u32_t tcp_ticks;
0073 const u8_t tcp_backoff[13] =
0074     { 1, 2, 3, 4, 5, 6, 7, 7, 7, 7, 7, 7, 7};
0075  /* Times per slowtmr hits */
0076 const u8_t tcp_persist_backoff[7] = { 3, 6, 12, 24, 48, 96, 120 };
0077 
0078 /* The TCP PCB lists. */
0079 
0080 /** List of all TCP PCBs bound but not yet (connected || listening) */
0081 struct tcp_pcb *tcp_bound_pcbs;  
0082 /** List of all TCP PCBs in LISTEN state */
0083 union tcp_listen_pcbs_t tcp_listen_pcbs;
0084 /** List of all TCP PCBs that are in a state in which
0085  * they accept or send data. */
0086 struct tcp_pcb *tcp_active_pcbs;  
0087 /** List of all TCP PCBs in TIME-WAIT state */
0088 struct tcp_pcb *tcp_tw_pcbs;
0089 
0090 struct tcp_pcb *tcp_tmp_pcb;
0091 
0092 static u8_t tcp_timer;
0093 static u16_t tcp_new_port(void);
0094 
0095 /**
0096  * Called periodically to dispatch TCP timers.
0097  *
0098  */
0099 void
0100 tcp_tmr(void)
0101 {
0102   /* Call tcp_fasttmr() every 250 ms */
0103   tcp_fasttmr();
0104 
0105   if (++tcp_timer & 1) {
0106     /* Call tcp_tmr() every 500 ms, i.e., every other timer
0107        tcp_tmr() is called. */
0108     tcp_slowtmr();
0109   }
0110 }
0111 
0112 /**
0113  * Closes the connection held by the PCB.
0114  *
0115  * Listening pcbs are freed and may not be referenced any more.
0116  * Connection pcbs are freed if not yet connected and may not be referenced
0117  * any more. If a connection is established (at least SYN received or in
0118  * a closing state), the connection is closed, and put in a closing state.
0119  * The pcb is then automatically freed in tcp_slowtmr(). It is therefore
0120  * unsafe to reference it.
0121  *
0122  * @param pcb the tcp_pcb to close
0123  * @return ERR_OK if connection has been closed
0124  *         another err_t if closing failed and pcb is not freed
0125  */
0126 err_t
0127 tcp_close(struct tcp_pcb *pcb)
0128 {
0129   err_t err;
0130 
0131 #if TCP_DEBUG
0132   LWIP_DEBUGF(TCP_DEBUG, ("tcp_close: closing in "));
0133   tcp_debug_print_state(pcb->state);
0134 #endif /* TCP_DEBUG */
0135 
0136   switch (pcb->state) {
0137   case CLOSED:
0138     /* Closing a pcb in the CLOSED state might seem erroneous,
0139      * however, it is in this state once allocated and as yet unused
0140      * and the user needs some way to free it should the need arise.
0141      * Calling tcp_close() with a pcb that has already been closed, (i.e. twice)
0142      * or for a pcb that has been used and then entered the CLOSED state 
0143      * is erroneous, but this should never happen as the pcb has in those cases
0144      * been freed, and so any remaining handles are bogus. */
0145     err = ERR_OK;
0146     TCP_RMV(&tcp_bound_pcbs, pcb);
0147     memp_free(MEMP_TCP_PCB, pcb);
0148     pcb = NULL;
0149     break;
0150   case LISTEN:
0151     err = ERR_OK;
0152     tcp_pcb_remove((struct tcp_pcb **)&tcp_listen_pcbs.pcbs, pcb);
0153     memp_free(MEMP_TCP_PCB_LISTEN, pcb);
0154     pcb = NULL;
0155     break;
0156   case SYN_SENT:
0157     err = ERR_OK;
0158     tcp_pcb_remove(&tcp_active_pcbs, pcb);
0159     memp_free(MEMP_TCP_PCB, pcb);
0160     pcb = NULL;
0161     snmp_inc_tcpattemptfails();
0162     break;
0163   case SYN_RCVD:
0164     err = tcp_send_ctrl(pcb, TCP_FIN);
0165     if (err == ERR_OK) {
0166       snmp_inc_tcpattemptfails();
0167       pcb->state = FIN_WAIT_1;
0168     }
0169     break;
0170   case ESTABLISHED:
0171     err = tcp_send_ctrl(pcb, TCP_FIN);
0172     if (err == ERR_OK) {
0173       snmp_inc_tcpestabresets();
0174       pcb->state = FIN_WAIT_1;
0175     }
0176     break;
0177   case CLOSE_WAIT:
0178     err = tcp_send_ctrl(pcb, TCP_FIN);
0179     if (err == ERR_OK) {
0180       snmp_inc_tcpestabresets();
0181       pcb->state = LAST_ACK;
0182     }
0183     break;
0184   default:
0185     /* Has already been closed, do nothing. */
0186     err = ERR_OK;
0187     pcb = NULL;
0188     break;
0189   }
0190 
0191   if (pcb != NULL && err == ERR_OK) {
0192     /* To ensure all data has been sent when tcp_close returns, we have
0193        to make sure tcp_output doesn't fail.
0194        Since we don't really have to ensure all data has been sent when tcp_close
0195        returns (unsent data is sent from tcp timer functions, also), we don't care
0196        for the return value of tcp_output for now. */
0197     /* @todo: When implementing SO_LINGER, this must be changed somehow:
0198        If SOF_LINGER is set, the data should be sent when tcp_close returns. */
0199     tcp_output(pcb);
0200   }
0201   return err;
0202 }
0203 
0204 /**
0205  * Abandons a connection and optionally sends a RST to the remote
0206  * host.  Deletes the local protocol control block. This is done when
0207  * a connection is killed because of shortage of memory.
0208  *
0209  * @param pcb the tcp_pcb to abort
0210  * @param reset boolean to indicate whether a reset should be sent
0211  */
0212 void
0213 tcp_abandon(struct tcp_pcb *pcb, int reset)
0214 {
0215   u32_t seqno, ackno;
0216   u16_t remote_port, local_port;
0217   struct ip_addr remote_ip, local_ip;
0218 #if LWIP_CALLBACK_API  
0219   void (* errf)(void *arg, err_t err);
0220 #endif /* LWIP_CALLBACK_API */
0221   void *errf_arg;
0222 
0223   
0224   /* Figure out on which TCP PCB list we are, and remove us. If we
0225      are in an active state, call the receive function associated with
0226      the PCB with a NULL argument, and send an RST to the remote end. */
0227   if (pcb->state == TIME_WAIT) {
0228     tcp_pcb_remove(&tcp_tw_pcbs, pcb);
0229     memp_free(MEMP_TCP_PCB, pcb);
0230   } else {
0231     seqno = pcb->snd_nxt;
0232     ackno = pcb->rcv_nxt;
0233     ip_addr_set(&local_ip, &(pcb->local_ip));
0234     ip_addr_set(&remote_ip, &(pcb->remote_ip));
0235     local_port = pcb->local_port;
0236     remote_port = pcb->remote_port;
0237 #if LWIP_CALLBACK_API
0238     errf = pcb->errf;
0239 #endif /* LWIP_CALLBACK_API */
0240     errf_arg = pcb->callback_arg;
0241     tcp_pcb_remove(&tcp_active_pcbs, pcb);
0242     if (pcb->unacked != NULL) {
0243       tcp_segs_free(pcb->unacked);
0244     }
0245     if (pcb->unsent != NULL) {
0246       tcp_segs_free(pcb->unsent);
0247     }
0248 #if TCP_QUEUE_OOSEQ    
0249     if (pcb->ooseq != NULL) {
0250       tcp_segs_free(pcb->ooseq);
0251     }
0252 #endif /* TCP_QUEUE_OOSEQ */
0253     memp_free(MEMP_TCP_PCB, pcb);
0254     TCP_EVENT_ERR(errf, errf_arg, ERR_ABRT);
0255     if (reset) {
0256       LWIP_DEBUGF(TCP_RST_DEBUG, ("tcp_abandon: sending RST\n"));
0257       tcp_rst(seqno, ackno, &local_ip, &remote_ip, local_port, remote_port);
0258     }
0259   }
0260 }
0261 
0262 /**
0263  * Binds the connection to a local portnumber and IP address. If the
0264  * IP address is not given (i.e., ipaddr == NULL), the IP address of
0265  * the outgoing network interface is used instead.
0266  *
0267  * @param pcb the tcp_pcb to bind (no check is done whether this pcb is
0268  *        already bound!)
0269  * @param ipaddr the local ip address to bind to (use IP_ADDR_ANY to bind
0270  *        to any local address
0271  * @param port the local port to bind to
0272  * @return ERR_USE if the port is already in use
0273  *         ERR_OK if bound
0274  */
0275 err_t
0276 tcp_bind(struct tcp_pcb *pcb, struct ip_addr *ipaddr, u16_t port)
0277 {
0278   struct tcp_pcb *cpcb;
0279 
0280   LWIP_ERROR("tcp_bind: can only bind in state CLOSED", pcb->state == CLOSED, return ERR_ISCONN);
0281 
0282   if (port == 0) {
0283     port = tcp_new_port();
0284   }
0285   /* Check if the address already is in use. */
0286   /* Check the listen pcbs. */
0287   for(cpcb = (struct tcp_pcb *)tcp_listen_pcbs.pcbs;
0288       cpcb != NULL; cpcb = cpcb->next) {
0289     if (cpcb->local_port == port) {
0290       if (ip_addr_isany(&(cpcb->local_ip)) ||
0291           ip_addr_isany(ipaddr) ||
0292           ip_addr_cmp(&(cpcb->local_ip), ipaddr)) {
0293         return ERR_USE;
0294       }
0295     }
0296   }
0297   /* Check the connected pcbs. */
0298   for(cpcb = tcp_active_pcbs;
0299       cpcb != NULL; cpcb = cpcb->next) {
0300     if (cpcb->local_port == port) {
0301       if (ip_addr_isany(&(cpcb->local_ip)) ||
0302           ip_addr_isany(ipaddr) ||
0303           ip_addr_cmp(&(cpcb->local_ip), ipaddr)) {
0304         return ERR_USE;
0305       }
0306     }
0307   }
0308   /* Check the bound, not yet connected pcbs. */
0309   for(cpcb = tcp_bound_pcbs; cpcb != NULL; cpcb = cpcb->next) {
0310     if (cpcb->local_port == port) {
0311       if (ip_addr_isany(&(cpcb->local_ip)) ||
0312           ip_addr_isany(ipaddr) ||
0313           ip_addr_cmp(&(cpcb->local_ip), ipaddr)) {
0314         return ERR_USE;
0315       }
0316     }
0317   }
0318   /* @todo: until SO_REUSEADDR is implemented (see task #6995 on savannah),
0319    * we have to check the pcbs in TIME-WAIT state, also: */
0320   for(cpcb = tcp_tw_pcbs; cpcb != NULL; cpcb = cpcb->next) {
0321     if (cpcb->local_port == port) {
0322       if (ip_addr_cmp(&(cpcb->local_ip), ipaddr)) {
0323         return ERR_USE;
0324       }
0325     }
0326   }
0327 
0328   if (!ip_addr_isany(ipaddr)) {
0329     pcb->local_ip = *ipaddr;
0330   }
0331   pcb->local_port = port;
0332   TCP_REG(&tcp_bound_pcbs, pcb);
0333   LWIP_DEBUGF(TCP_DEBUG, ("tcp_bind: bind to port %"U16_F"\n", port));
0334   return ERR_OK;
0335 }
0336 #if LWIP_CALLBACK_API
0337 /**
0338  * Default accept callback if no accept callback is specified by the user.
0339  */
0340 static err_t
0341 tcp_accept_null(void *arg, struct tcp_pcb *pcb, err_t err)
0342 {
0343   LWIP_UNUSED_ARG(arg);
0344   LWIP_UNUSED_ARG(pcb);
0345   LWIP_UNUSED_ARG(err);
0346 
0347   return ERR_ABRT;
0348 }
0349 #endif /* LWIP_CALLBACK_API */
0350 
0351 /**
0352  * Set the state of the connection to be LISTEN, which means that it
0353  * is able to accept incoming connections. The protocol control block
0354  * is reallocated in order to consume less memory. Setting the
0355  * connection to LISTEN is an irreversible process.
0356  *
0357  * @param pcb the original tcp_pcb
0358  * @param backlog the incoming connections queue limit
0359  * @return tcp_pcb used for listening, consumes less memory.
0360  *
0361  * @note The original tcp_pcb is freed. This function therefore has to be
0362  *       called like this:
0363  *             tpcb = tcp_listen(tpcb);
0364  */
0365 struct tcp_pcb *
0366 tcp_listen_with_backlog(struct tcp_pcb *pcb, u8_t backlog)
0367 {
0368   struct tcp_pcb_listen *lpcb;
0369 
0370   LWIP_UNUSED_ARG(backlog);
0371   LWIP_ERROR("tcp_listen: pcb already connected", pcb->state == CLOSED, return NULL);
0372 
0373   /* already listening? */
0374   if (pcb->state == LISTEN) {
0375     return pcb;
0376   }
0377   lpcb = memp_malloc(MEMP_TCP_PCB_LISTEN);
0378   if (lpcb == NULL) {
0379     return NULL;
0380   }
0381   lpcb->callback_arg = pcb->callback_arg;
0382   lpcb->local_port = pcb->local_port;
0383   lpcb->state = LISTEN;
0384   lpcb->so_options = pcb->so_options;
0385   lpcb->so_options |= SOF_ACCEPTCONN;
0386   lpcb->ttl = pcb->ttl;
0387   lpcb->tos = pcb->tos;
0388   ip_addr_set(&lpcb->local_ip, &pcb->local_ip);
0389   TCP_RMV(&tcp_bound_pcbs, pcb);
0390   memp_free(MEMP_TCP_PCB, pcb);
0391 #if LWIP_CALLBACK_API
0392   lpcb->accept = tcp_accept_null;
0393 #endif /* LWIP_CALLBACK_API */
0394 #if TCP_LISTEN_BACKLOG
0395   lpcb->accepts_pending = 0;
0396   lpcb->backlog = (backlog ? backlog : 1);
0397 #endif /* TCP_LISTEN_BACKLOG */
0398   TCP_REG(&tcp_listen_pcbs.listen_pcbs, lpcb);
0399   return (struct tcp_pcb *)lpcb;
0400 }
0401 
0402 /** 
0403  * Update the state that tracks the available window space to advertise.
0404  *
0405  * Returns how much extra window would be advertised if we sent an
0406  * update now.
0407  */
0408 u32_t tcp_update_rcv_ann_wnd(struct tcp_pcb *pcb)
0409 {
0410   u32_t new_right_edge = pcb->rcv_nxt + pcb->rcv_wnd;
0411 
0412   if (TCP_SEQ_GEQ(new_right_edge, pcb->rcv_ann_right_edge + LWIP_MIN((TCP_WND / 2), pcb->mss))) {
0413     /* we can advertise more window */
0414     pcb->rcv_ann_wnd = pcb->rcv_wnd;
0415     return new_right_edge - pcb->rcv_ann_right_edge;
0416   } else {
0417     if (TCP_SEQ_GT(pcb->rcv_nxt, pcb->rcv_ann_right_edge)) {
0418       /* Can happen due to other end sending out of advertised window,
0419        * but within actual available (but not yet advertised) window */
0420       pcb->rcv_ann_wnd = 0;
0421     } else {
0422       /* keep the right edge of window constant */
0423       pcb->rcv_ann_wnd = pcb->rcv_ann_right_edge - pcb->rcv_nxt;
0424     }
0425     return 0;
0426   }
0427 }
0428 
0429 /**
0430  * This function should be called by the application when it has
0431  * processed the data. The purpose is to advertise a larger window
0432  * when the data has been processed.
0433  *
0434  * @param pcb the tcp_pcb for which data is read
0435  * @param len the amount of bytes that have been read by the application
0436  */
0437 void
0438 tcp_recved(struct tcp_pcb *pcb, u16_t len)
0439 {
0440   int wnd_inflation;
0441 
0442   LWIP_ASSERT("tcp_recved: len would wrap rcv_wnd\n",
0443               len <= 0xffff - pcb->rcv_wnd );
0444 
0445   pcb->rcv_wnd += len;
0446   if (pcb->rcv_wnd > TCP_WND)
0447     pcb->rcv_wnd = TCP_WND;
0448 
0449   wnd_inflation = tcp_update_rcv_ann_wnd(pcb);
0450 
0451   /* If the change in the right edge of window is significant (default
0452    * watermark is TCP_WND/2), then send an explicit update now.
0453    * Otherwise wait for a packet to be sent in the normal course of
0454    * events (or more window to be available later) */
0455   if (wnd_inflation >= TCP_WND_UPDATE_THRESHOLD) 
0456     tcp_ack_now(pcb);
0457 
0458   LWIP_DEBUGF(TCP_DEBUG, ("tcp_recved: recveived %"U16_F" bytes, wnd %"U16_F" (%"U16_F").\n",
0459          len, pcb->rcv_wnd, TCP_WND - pcb->rcv_wnd));
0460 }
0461 
0462 /**
0463  * A nastly hack featuring 'goto' statements that allocates a
0464  * new TCP local port.
0465  *
0466  * @return a new (free) local TCP port number
0467  */
0468 static u16_t
0469 tcp_new_port(void)
0470 {
0471   struct tcp_pcb *pcb;
0472 #ifndef TCP_LOCAL_PORT_RANGE_START
0473 #define TCP_LOCAL_PORT_RANGE_START 4096
0474 #define TCP_LOCAL_PORT_RANGE_END   0x7fff
0475 #endif
0476   static u16_t port = TCP_LOCAL_PORT_RANGE_START;
0477   
0478  again:
0479   if (++port > TCP_LOCAL_PORT_RANGE_END) {
0480     port = TCP_LOCAL_PORT_RANGE_START;
0481   }
0482   
0483   for(pcb = tcp_active_pcbs; pcb != NULL; pcb = pcb->next) {
0484     if (pcb->local_port == port) {
0485       goto again;
0486     }
0487   }
0488   for(pcb = tcp_tw_pcbs; pcb != NULL; pcb = pcb->next) {
0489     if (pcb->local_port == port) {
0490       goto again;
0491     }
0492   }
0493   for(pcb = (struct tcp_pcb *)tcp_listen_pcbs.pcbs; pcb != NULL; pcb = pcb->next) {
0494     if (pcb->local_port == port) {
0495       goto again;
0496     }
0497   }
0498   return port;
0499 }
0500 
0501 /**
0502  * Connects to another host. The function given as the "connected"
0503  * argument will be called when the connection has been established.
0504  *
0505  * @param pcb the tcp_pcb used to establish the connection
0506  * @param ipaddr the remote ip address to connect to
0507  * @param port the remote tcp port to connect to
0508  * @param connected callback function to call when connected (or on error)
0509  * @return ERR_VAL if invalid arguments are given
0510  *         ERR_OK if connect request has been sent
0511  *         other err_t values if connect request couldn't be sent
0512  */
0513 err_t
0514 tcp_connect(struct tcp_pcb *pcb, struct ip_addr *ipaddr, u16_t port,
0515       err_t (* connected)(void *arg, struct tcp_pcb *tpcb, err_t err))
0516 {
0517   err_t ret;
0518   u32_t iss;
0519 
0520   LWIP_ERROR("tcp_connect: can only connected from state CLOSED", pcb->state == CLOSED, return ERR_ISCONN);
0521 
0522   LWIP_DEBUGF(TCP_DEBUG, ("tcp_connect to port %"U16_F"\n", port));
0523   if (ipaddr != NULL) {
0524     pcb->remote_ip = *ipaddr;
0525   } else {
0526     return ERR_VAL;
0527   }
0528   pcb->remote_port = port;
0529   if (pcb->local_port == 0) {
0530     pcb->local_port = tcp_new_port();
0531   }
0532   iss = tcp_next_iss();
0533   pcb->rcv_nxt = 0;
0534   pcb->snd_nxt = iss;
0535   pcb->lastack = iss - 1;
0536   pcb->snd_lbb = iss - 1;
0537   pcb->rcv_wnd = TCP_WND;
0538   pcb->rcv_ann_wnd = TCP_WND;
0539   pcb->rcv_ann_right_edge = pcb->rcv_nxt;
0540   pcb->snd_wnd = TCP_WND;
0541   /* As initial send MSS, we use TCP_MSS but limit it to 536.
0542      The send MSS is updated when an MSS option is received. */
0543   pcb->mss = (TCP_MSS > 536) ? 536 : TCP_MSS;
0544 #if TCP_CALCULATE_EFF_SEND_MSS
0545   pcb->mss = tcp_eff_send_mss(pcb->mss, ipaddr);
0546 #endif /* TCP_CALCULATE_EFF_SEND_MSS */
0547   pcb->cwnd = 1;
0548   pcb->ssthresh = pcb->mss * 10;
0549   pcb->state = SYN_SENT;
0550 #if LWIP_CALLBACK_API  
0551   pcb->connected = connected;
0552 #endif /* LWIP_CALLBACK_API */
0553   TCP_RMV(&tcp_bound_pcbs, pcb);
0554   TCP_REG(&tcp_active_pcbs, pcb);
0555 
0556   snmp_inc_tcpactiveopens();
0557   
0558   ret = tcp_enqueue(pcb, NULL, 0, TCP_SYN, 0, TF_SEG_OPTS_MSS
0559 #if LWIP_TCP_TIMESTAMPS
0560                     | TF_SEG_OPTS_TS
0561 #endif
0562                     );
0563   if (ret == ERR_OK) { 
0564     tcp_output(pcb);
0565   }
0566   return ret;
0567 } 
0568 
0569 /**
0570  * Called every 500 ms and implements the retransmission timer and the timer that
0571  * removes PCBs that have been in TIME-WAIT for enough time. It also increments
0572  * various timers such as the inactivity timer in each PCB.
0573  *
0574  * Automatically called from tcp_tmr().
0575  */
0576 void
0577 tcp_slowtmr(void)
0578 {
0579   struct tcp_pcb *pcb, *pcb2, *prev;
0580   u16_t eff_wnd;
0581   u8_t pcb_remove;      /* flag if a PCB should be removed */
0582   u8_t pcb_reset;       /* flag if a RST should be sent when removing */
0583   err_t err;
0584 
0585   err = ERR_OK;
0586 
0587   ++tcp_ticks;
0588 
0589   /* Steps through all of the active PCBs. */
0590   prev = NULL;
0591   pcb = tcp_active_pcbs;
0592   if (pcb == NULL) {
0593     LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: no active pcbs\n"));
0594   }
0595   while (pcb != NULL) {
0596     LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: processing active pcb\n"));
0597     LWIP_ASSERT("tcp_slowtmr: active pcb->state != CLOSED\n", pcb->state != CLOSED);
0598     LWIP_ASSERT("tcp_slowtmr: active pcb->state != LISTEN\n", pcb->state != LISTEN);
0599     LWIP_ASSERT("tcp_slowtmr: active pcb->state != TIME-WAIT\n", pcb->state != TIME_WAIT);
0600 
0601     pcb_remove = 0;
0602     pcb_reset = 0;
0603 
0604     if (pcb->state == SYN_SENT && pcb->nrtx == TCP_SYNMAXRTX) {
0605       ++pcb_remove;
0606       LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: max SYN retries reached\n"));
0607     }
0608     else if (pcb->nrtx == TCP_MAXRTX) {
0609       ++pcb_remove;
0610       LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: max DATA retries reached\n"));
0611     } else {
0612       if (pcb->persist_backoff > 0) {
0613         /* If snd_wnd is zero, use persist timer to send 1 byte probes
0614          * instead of using the standard retransmission mechanism. */
0615         pcb->persist_cnt++;
0616         if (pcb->persist_cnt >= tcp_persist_backoff[pcb->persist_backoff-1]) {
0617           pcb->persist_cnt = 0;
0618           if (pcb->persist_backoff < sizeof(tcp_persist_backoff)) {
0619             pcb->persist_backoff++;
0620           }
0621           tcp_zero_window_probe(pcb);
0622         }
0623       } else {
0624         /* Increase the retransmission timer if it is running */
0625         if(pcb->rtime >= 0)
0626           ++pcb->rtime;
0627 
0628         if (pcb->unacked != NULL && pcb->rtime >= pcb->rto) {
0629           /* Time for a retransmission. */
0630           LWIP_DEBUGF(TCP_RTO_DEBUG, ("tcp_slowtmr: rtime %"S16_F
0631                                       " pcb->rto %"S16_F"\n",
0632                                       pcb->rtime, pcb->rto));
0633 
0634           /* Double retransmission time-out unless we are trying to
0635            * connect to somebody (i.e., we are in SYN_SENT). */
0636           if (pcb->state != SYN_SENT) {
0637             pcb->rto = ((pcb->sa >> 3) + pcb->sv) << tcp_backoff[pcb->nrtx];
0638           }
0639 
0640           /* Reset the retransmission timer. */
0641           pcb->rtime = 0;
0642 
0643           /* Reduce congestion window and ssthresh. */
0644           eff_wnd = LWIP_MIN(pcb->cwnd, pcb->snd_wnd);
0645           pcb->ssthresh = eff_wnd >> 1;
0646           if (pcb->ssthresh < pcb->mss) {
0647             pcb->ssthresh = pcb->mss * 2;
0648           }
0649           pcb->cwnd = pcb->mss;
0650           LWIP_DEBUGF(TCP_CWND_DEBUG, ("tcp_slowtmr: cwnd %"U16_F
0651                                        " ssthresh %"U16_F"\n",
0652                                        pcb->cwnd, pcb->ssthresh));
0653  
0654           /* The following needs to be called AFTER cwnd is set to one
0655              mss - STJ */
0656           tcp_rexmit_rto(pcb);
0657         }
0658       }
0659     }
0660     /* Check if this PCB has stayed too long in FIN-WAIT-2 */
0661     if (pcb->state == FIN_WAIT_2) {
0662       if ((u32_t)(tcp_ticks - pcb->tmr) >
0663           TCP_FIN_WAIT_TIMEOUT / TCP_SLOW_INTERVAL) {
0664         ++pcb_remove;
0665         LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: removing pcb stuck in FIN-WAIT-2\n"));
0666       }
0667     }
0668 
0669     /* Check if KEEPALIVE should be sent */
0670     if((pcb->so_options & SOF_KEEPALIVE) && 
0671        ((pcb->state == ESTABLISHED) || 
0672         (pcb->state == CLOSE_WAIT))) {
0673 #if LWIP_TCP_KEEPALIVE
0674       if((u32_t)(tcp_ticks - pcb->tmr) > 
0675          (pcb->keep_idle + (pcb->keep_cnt*pcb->keep_intvl))
0676          / TCP_SLOW_INTERVAL)
0677 #else      
0678       if((u32_t)(tcp_ticks - pcb->tmr) > 
0679          (pcb->keep_idle + TCP_MAXIDLE) / TCP_SLOW_INTERVAL)
0680 #endif /* LWIP_TCP_KEEPALIVE */
0681       {
0682         LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: KEEPALIVE timeout. Aborting connection to %"U16_F".%"U16_F".%"U16_F".%"U16_F".\n",
0683                                 ip4_addr1(&pcb->remote_ip), ip4_addr2(&pcb->remote_ip),
0684                                 ip4_addr3(&pcb->remote_ip), ip4_addr4(&pcb->remote_ip)));
0685         
0686         ++pcb_remove;
0687         ++pcb_reset;
0688       }
0689 #if LWIP_TCP_KEEPALIVE
0690       else if((u32_t)(tcp_ticks - pcb->tmr) > 
0691               (pcb->keep_idle + pcb->keep_cnt_sent * pcb->keep_intvl)
0692               / TCP_SLOW_INTERVAL)
0693 #else
0694       else if((u32_t)(tcp_ticks - pcb->tmr) > 
0695               (pcb->keep_idle + pcb->keep_cnt_sent * TCP_KEEPINTVL_DEFAULT) 
0696               / TCP_SLOW_INTERVAL)
0697 #endif /* LWIP_TCP_KEEPALIVE */
0698       {
0699         tcp_keepalive(pcb);
0700         pcb->keep_cnt_sent++;
0701       }
0702     }
0703 
0704     /* If this PCB has queued out of sequence data, but has been
0705        inactive for too long, will drop the data (it will eventually
0706        be retransmitted). */
0707 #if TCP_QUEUE_OOSEQ    
0708     if (pcb->ooseq != NULL &&
0709         (u32_t)tcp_ticks - pcb->tmr >= pcb->rto * TCP_OOSEQ_TIMEOUT) {
0710       tcp_segs_free(pcb->ooseq);
0711       pcb->ooseq = NULL;
0712       LWIP_DEBUGF(TCP_CWND_DEBUG, ("tcp_slowtmr: dropping OOSEQ queued data\n"));
0713     }
0714 #endif /* TCP_QUEUE_OOSEQ */
0715 
0716     /* Check if this PCB has stayed too long in SYN-RCVD */
0717     if (pcb->state == SYN_RCVD) {
0718       if ((u32_t)(tcp_ticks - pcb->tmr) >
0719           TCP_SYN_RCVD_TIMEOUT / TCP_SLOW_INTERVAL) {
0720         ++pcb_remove;
0721         LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: removing pcb stuck in SYN-RCVD\n"));
0722       }
0723     }
0724 
0725     /* Check if this PCB has stayed too long in LAST-ACK */
0726     if (pcb->state == LAST_ACK) {
0727       if ((u32_t)(tcp_ticks - pcb->tmr) > 2 * TCP_MSL / TCP_SLOW_INTERVAL) {
0728         ++pcb_remove;
0729         LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: removing pcb stuck in LAST-ACK\n"));
0730       }
0731     }
0732 
0733     /* If the PCB should be removed, do it. */
0734     if (pcb_remove) {
0735       tcp_pcb_purge(pcb);      
0736       /* Remove PCB from tcp_active_pcbs list. */
0737       if (prev != NULL) {
0738         LWIP_ASSERT("tcp_slowtmr: middle tcp != tcp_active_pcbs", pcb != tcp_active_pcbs);
0739         prev->next = pcb->next;
0740       } else {
0741         /* This PCB was the first. */
0742         LWIP_ASSERT("tcp_slowtmr: first pcb == tcp_active_pcbs", tcp_active_pcbs == pcb);
0743         tcp_active_pcbs = pcb->next;
0744       }
0745 
0746       TCP_EVENT_ERR(pcb->errf, pcb->callback_arg, ERR_ABRT);
0747       if (pcb_reset) {
0748         tcp_rst(pcb->snd_nxt, pcb->rcv_nxt, &pcb->local_ip, &pcb->remote_ip,
0749           pcb->local_port, pcb->remote_port);
0750       }
0751 
0752       pcb2 = pcb->next;
0753       memp_free(MEMP_TCP_PCB, pcb);
0754       pcb = pcb2;
0755     } else {
0756 
0757       /* We check if we should poll the connection. */
0758       ++pcb->polltmr;
0759       if (pcb->polltmr >= pcb->pollinterval) {
0760         pcb->polltmr = 0;
0761         LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: polling application\n"));
0762         TCP_EVENT_POLL(pcb, err);
0763         if (err == ERR_OK) {
0764           tcp_output(pcb);
0765         }
0766       }
0767       
0768       prev = pcb;
0769       pcb = pcb->next;
0770     }
0771   }
0772 
0773   
0774   /* Steps through all of the TIME-WAIT PCBs. */
0775   prev = NULL;    
0776   pcb = tcp_tw_pcbs;
0777   while (pcb != NULL) {
0778     LWIP_ASSERT("tcp_slowtmr: TIME-WAIT pcb->state == TIME-WAIT", pcb->state == TIME_WAIT);
0779     pcb_remove = 0;
0780 
0781     /* Check if this PCB has stayed long enough in TIME-WAIT */
0782     if ((u32_t)(tcp_ticks - pcb->tmr) > 2 * TCP_MSL / TCP_SLOW_INTERVAL) {
0783       ++pcb_remove;
0784     }
0785     
0786 
0787 
0788     /* If the PCB should be removed, do it. */
0789     if (pcb_remove) {
0790       tcp_pcb_purge(pcb);      
0791       /* Remove PCB from tcp_tw_pcbs list. */
0792       if (prev != NULL) {
0793         LWIP_ASSERT("tcp_slowtmr: middle tcp != tcp_tw_pcbs", pcb != tcp_tw_pcbs);
0794         prev->next = pcb->next;
0795       } else {
0796         /* This PCB was the first. */
0797         LWIP_ASSERT("tcp_slowtmr: first pcb == tcp_tw_pcbs", tcp_tw_pcbs == pcb);
0798         tcp_tw_pcbs = pcb->next;
0799       }
0800       pcb2 = pcb->next;
0801       memp_free(MEMP_TCP_PCB, pcb);
0802       pcb = pcb2;
0803     } else {
0804       prev = pcb;
0805       pcb = pcb->next;
0806     }
0807   }
0808 }
0809 
0810 /**
0811  * Is called every TCP_FAST_INTERVAL (250 ms) and process data previously
0812  * "refused" by upper layer (application) and sends delayed ACKs.
0813  *
0814  * Automatically called from tcp_tmr().
0815  */
0816 void
0817 tcp_fasttmr(void)
0818 {
0819   struct tcp_pcb *pcb;
0820 
0821   for(pcb = tcp_active_pcbs; pcb != NULL; pcb = pcb->next) {
0822     /* If there is data which was previously "refused" by upper layer */
0823     if (pcb->refused_data != NULL) {
0824       /* Notify again application with data previously received. */
0825       err_t err;
0826       LWIP_DEBUGF(TCP_INPUT_DEBUG, ("tcp_fasttmr: notify kept packet\n"));
0827       TCP_EVENT_RECV(pcb, pcb->refused_data, ERR_OK, err);
0828       if (err == ERR_OK) {
0829         pcb->refused_data = NULL;
0830       }
0831     }
0832 
0833     /* send delayed ACKs */  
0834     if (pcb->flags & TF_ACK_DELAY) {
0835       LWIP_DEBUGF(TCP_DEBUG, ("tcp_fasttmr: delayed ACK\n"));
0836       tcp_ack_now(pcb);
0837       pcb->flags &= ~(TF_ACK_DELAY | TF_ACK_NOW);
0838     }
0839   }
0840 }
0841 
0842 /**
0843  * Deallocates a list of TCP segments (tcp_seg structures).
0844  *
0845  * @param seg tcp_seg list of TCP segments to free
0846  * @return the number of pbufs that were deallocated
0847  */
0848 u8_t
0849 tcp_segs_free(struct tcp_seg *seg)
0850 {
0851   u8_t count = 0;
0852   struct tcp_seg *next;
0853   while (seg != NULL) {
0854     next = seg->next;
0855     count += tcp_seg_free(seg);
0856     seg = next;
0857   }
0858   return count;
0859 }
0860 
0861 /**
0862  * Frees a TCP segment (tcp_seg structure).
0863  *
0864  * @param seg single tcp_seg to free
0865  * @return the number of pbufs that were deallocated
0866  */
0867 u8_t
0868 tcp_seg_free(struct tcp_seg *seg)
0869 {
0870   u8_t count = 0;
0871   
0872   if (seg != NULL) {
0873     if (seg->p != NULL) {
0874       count = pbuf_free(seg->p);
0875 #if TCP_DEBUG
0876       seg->p = NULL;
0877 #endif /* TCP_DEBUG */
0878     }
0879     memp_free(MEMP_TCP_SEG, seg);
0880   }
0881   return count;
0882 }
0883 
0884 /**
0885  * Sets the priority of a connection.
0886  *
0887  * @param pcb the tcp_pcb to manipulate
0888  * @param prio new priority
0889  */
0890 void
0891 tcp_setprio(struct tcp_pcb *pcb, u8_t prio)
0892 {
0893   pcb->prio = prio;
0894 }
0895 #if TCP_QUEUE_OOSEQ
0896 
0897 /**
0898  * Returns a copy of the given TCP segment.
0899  * The pbuf and data are not copied, only the pointers
0900  *
0901  * @param seg the old tcp_seg
0902  * @return a copy of seg
0903  */ 
0904 struct tcp_seg *
0905 tcp_seg_copy(struct tcp_seg *seg)
0906 {
0907   struct tcp_seg *cseg;
0908 
0909   cseg = memp_malloc(MEMP_TCP_SEG);
0910   if (cseg == NULL) {
0911     return NULL;
0912   }
0913   SMEMCPY((u8_t *)cseg, (const u8_t *)seg, sizeof(struct tcp_seg)); 
0914   pbuf_ref(cseg->p);
0915   return cseg;
0916 }
0917 #endif
0918 
0919 #if LWIP_CALLBACK_API
0920 /**
0921  * Default receive callback that is called if the user didn't register
0922  * a recv callback for the pcb.
0923  */
0924 err_t
0925 tcp_recv_null(void *arg, struct tcp_pcb *pcb, struct pbuf *p, err_t err)
0926 {
0927   LWIP_UNUSED_ARG(arg);
0928   if (p != NULL) {
0929     tcp_recved(pcb, p->tot_len);
0930     pbuf_free(p);
0931   } else if (err == ERR_OK) {
0932     return tcp_close(pcb);
0933   }
0934   return ERR_OK;
0935 }
0936 #endif /* LWIP_CALLBACK_API */
0937 
0938 /**
0939  * Kills the oldest active connection that has lower priority than prio.
0940  *
0941  * @param prio minimum priority
0942  */
0943 static void
0944 tcp_kill_prio(u8_t prio)
0945 {
0946   struct tcp_pcb *pcb, *inactive;
0947   u32_t inactivity;
0948   u8_t mprio;
0949 
0950 
0951   mprio = TCP_PRIO_MAX;
0952   
0953   /* We kill the oldest active connection that has lower priority than prio. */
0954   inactivity = 0;
0955   inactive = NULL;
0956   for(pcb = tcp_active_pcbs; pcb != NULL; pcb = pcb->next) {
0957     if (pcb->prio <= prio &&
0958        pcb->prio <= mprio &&
0959        (u32_t)(tcp_ticks - pcb->tmr) >= inactivity) {
0960       inactivity = tcp_ticks - pcb->tmr;
0961       inactive = pcb;
0962       mprio = pcb->prio;
0963     }
0964   }
0965   if (inactive != NULL) {
0966     LWIP_DEBUGF(TCP_DEBUG, ("tcp_kill_prio: killing oldest PCB %p (%"S32_F")\n",
0967            (void *)inactive, inactivity));
0968     tcp_abort(inactive);
0969   }      
0970 }
0971 
0972 /**
0973  * Kills the oldest connection that is in TIME_WAIT state.
0974  * Called from tcp_alloc() if no more connections are available.
0975  */
0976 static void
0977 tcp_kill_timewait(void)
0978 {
0979   struct tcp_pcb *pcb, *inactive;
0980   u32_t inactivity;
0981 
0982   inactivity = 0;
0983   inactive = NULL;
0984   /* Go through the list of TIME_WAIT pcbs and get the oldest pcb. */
0985   for(pcb = tcp_tw_pcbs; pcb != NULL; pcb = pcb->next) {
0986     if ((u32_t)(tcp_ticks - pcb->tmr) >= inactivity) {
0987       inactivity = tcp_ticks - pcb->tmr;
0988       inactive = pcb;
0989     }
0990   }
0991   if (inactive != NULL) {
0992     LWIP_DEBUGF(TCP_DEBUG, ("tcp_kill_timewait: killing oldest TIME-WAIT PCB %p (%"S32_F")\n",
0993            (void *)inactive, inactivity));
0994     tcp_abort(inactive);
0995   }      
0996 }
0997 
0998 /**
0999  * Allocate a new tcp_pcb structure.
1000  *
1001  * @param prio priority for the new pcb
1002  * @return a new tcp_pcb that initially is in state CLOSED
1003  */
1004 struct tcp_pcb *
1005 tcp_alloc(u8_t prio)
1006 {
1007   struct tcp_pcb *pcb;
1008   u32_t iss;
1009   
1010   pcb = memp_malloc(MEMP_TCP_PCB);
1011   if (pcb == NULL) {
1012     /* Try killing oldest connection in TIME-WAIT. */
1013     LWIP_DEBUGF(TCP_DEBUG, ("tcp_alloc: killing off oldest TIME-WAIT connection\n"));
1014     tcp_kill_timewait();
1015     /* Try to allocate a tcp_pcb again. */
1016     pcb = memp_malloc(MEMP_TCP_PCB);
1017     if (pcb == NULL) {
1018       /* Try killing active connections with lower priority than the new one. */
1019       LWIP_DEBUGF(TCP_DEBUG, ("tcp_alloc: killing connection with prio lower than %d\n", prio));
1020       tcp_kill_prio(prio);
1021       /* Try to allocate a tcp_pcb again. */
1022       pcb = memp_malloc(MEMP_TCP_PCB);
1023       if (pcb != NULL) {
1024         /* adjust err stats: memp_malloc failed twice before */
1025         MEMP_STATS_DEC(err, MEMP_TCP_PCB);
1026       }
1027     }
1028     if (pcb != NULL) {
1029       /* adjust err stats: timewait PCB was freed above */
1030       MEMP_STATS_DEC(err, MEMP_TCP_PCB);
1031     }
1032   }
1033   if (pcb != NULL) {
1034     memset(pcb, 0, sizeof(struct tcp_pcb));
1035     pcb->prio = TCP_PRIO_NORMAL;
1036     pcb->snd_buf = TCP_SND_BUF;
1037     pcb->snd_queuelen = 0;
1038     pcb->rcv_wnd = TCP_WND;
1039     pcb->rcv_ann_wnd = TCP_WND;
1040     pcb->tos = 0;
1041     pcb->ttl = TCP_TTL;
1042     /* As initial send MSS, we use TCP_MSS but limit it to 536.
1043        The send MSS is updated when an MSS option is received. */
1044     pcb->mss = (TCP_MSS > 536) ? 536 : TCP_MSS;
1045     pcb->rto = 3000 / TCP_SLOW_INTERVAL;
1046     pcb->sa = 0;
1047     pcb->sv = 3000 / TCP_SLOW_INTERVAL;
1048     pcb->rtime = -1;
1049     pcb->cwnd = 1;
1050     iss = tcp_next_iss();
1051     pcb->snd_wl2 = iss;
1052     pcb->snd_nxt = iss;
1053     pcb->lastack = iss;
1054     pcb->snd_lbb = iss;   
1055     pcb->tmr = tcp_ticks;
1056 
1057     pcb->polltmr = 0;
1058 
1059 #if LWIP_CALLBACK_API
1060     pcb->recv = tcp_recv_null;
1061 #endif /* LWIP_CALLBACK_API */  
1062     
1063     /* Init KEEPALIVE timer */
1064     pcb->keep_idle  = TCP_KEEPIDLE_DEFAULT;
1065     
1066 #if LWIP_TCP_KEEPALIVE
1067     pcb->keep_intvl = TCP_KEEPINTVL_DEFAULT;
1068     pcb->keep_cnt   = TCP_KEEPCNT_DEFAULT;
1069 #endif /* LWIP_TCP_KEEPALIVE */
1070 
1071     pcb->keep_cnt_sent = 0;
1072   }
1073   return pcb;
1074 }
1075 
1076 /**
1077  * Creates a new TCP protocol control block but doesn't place it on
1078  * any of the TCP PCB lists.
1079  * The pcb is not put on any list until binding using tcp_bind().
1080  *
1081  * @internal: Maybe there should be a idle TCP PCB list where these
1082  * PCBs are put on. Port reservation using tcp_bind() is implemented but
1083  * allocated pcbs that are not bound can't be killed automatically if wanting
1084  * to allocate a pcb with higher prio (@see tcp_kill_prio())
1085  *
1086  * @return a new tcp_pcb that initially is in state CLOSED
1087  */
1088 struct tcp_pcb *
1089 tcp_new(void)
1090 {
1091   return tcp_alloc(TCP_PRIO_NORMAL);
1092 }
1093 
1094 /**
1095  * Used to specify the argument that should be passed callback
1096  * functions.
1097  *
1098  * @param pcb tcp_pcb to set the callback argument
1099  * @param arg void pointer argument to pass to callback functions
1100  */ 
1101 void
1102 tcp_arg(struct tcp_pcb *pcb, void *arg)
1103 {  
1104   pcb->callback_arg = arg;
1105 }
1106 #if LWIP_CALLBACK_API
1107 
1108 /**
1109  * Used to specify the function that should be called when a TCP
1110  * connection receives data.
1111  *
1112  * @param pcb tcp_pcb to set the recv callback
1113  * @param recv callback function to call for this pcb when data is received
1114  */ 
1115 void
1116 tcp_recv(struct tcp_pcb *pcb,
1117    err_t (* recv)(void *arg, struct tcp_pcb *tpcb, struct pbuf *p, err_t err))
1118 {
1119   pcb->recv = recv;
1120 }
1121 
1122 /**
1123  * Used to specify the function that should be called when TCP data
1124  * has been successfully delivered to the remote host.
1125  *
1126  * @param pcb tcp_pcb to set the sent callback
1127  * @param sent callback function to call for this pcb when data is successfully sent
1128  */ 
1129 void
1130 tcp_sent(struct tcp_pcb *pcb,
1131    err_t (* sent)(void *arg, struct tcp_pcb *tpcb, u16_t len))
1132 {
1133   pcb->sent = sent;
1134 }
1135 
1136 /**
1137  * Used to specify the function that should be called when a fatal error
1138  * has occured on the connection.
1139  *
1140  * @param pcb tcp_pcb to set the err callback
1141  * @param errf callback function to call for this pcb when a fatal error
1142  *        has occured on the connection
1143  */ 
1144 void
1145 tcp_err(struct tcp_pcb *pcb,
1146    void (* errf)(void *arg, err_t err))
1147 {
1148   pcb->errf = errf;
1149 }
1150 
1151 /**
1152  * Used for specifying the function that should be called when a
1153  * LISTENing connection has been connected to another host.
1154  *
1155  * @param pcb tcp_pcb to set the accept callback
1156  * @param accept callback function to call for this pcb when LISTENing
1157  *        connection has been connected to another host
1158  */ 
1159 void
1160 tcp_accept(struct tcp_pcb *pcb,
1161      err_t (* accept)(void *arg, struct tcp_pcb *newpcb, err_t err))
1162 {
1163   pcb->accept = accept;
1164 }
1165 #endif /* LWIP_CALLBACK_API */
1166 
1167 
1168 /**
1169  * Used to specify the function that should be called periodically
1170  * from TCP. The interval is specified in terms of the TCP coarse
1171  * timer interval, which is called twice a second.
1172  *
1173  */ 
1174 void
1175 tcp_poll(struct tcp_pcb *pcb,
1176    err_t (* poll)(void *arg, struct tcp_pcb *tpcb), u8_t interval)
1177 {
1178 #if LWIP_CALLBACK_API
1179   pcb->poll = poll;
1180 #endif /* LWIP_CALLBACK_API */  
1181   pcb->pollinterval = interval;
1182 }
1183 
1184 /**
1185  * Purges a TCP PCB. Removes any buffered data and frees the buffer memory
1186  * (pcb->ooseq, pcb->unsent and pcb->unacked are freed).
1187  *
1188  * @param pcb tcp_pcb to purge. The pcb itself is not deallocated!
1189  */
1190 void
1191 tcp_pcb_purge(struct tcp_pcb *pcb)
1192 {
1193   if (pcb->state != CLOSED &&
1194      pcb->state != TIME_WAIT &&
1195      pcb->state != LISTEN) {
1196 
1197     LWIP_DEBUGF(TCP_DEBUG, ("tcp_pcb_purge\n"));
1198 
1199 #if TCP_LISTEN_BACKLOG
1200     if (pcb->state == SYN_RCVD) {
1201       /* Need to find the corresponding listen_pcb and decrease its accepts_pending */
1202       struct tcp_pcb_listen *lpcb;
1203       LWIP_ASSERT("tcp_pcb_purge: pcb->state == SYN_RCVD but tcp_listen_pcbs is NULL",
1204         tcp_listen_pcbs.listen_pcbs != NULL);
1205       for (lpcb = tcp_listen_pcbs.listen_pcbs; lpcb != NULL; lpcb = lpcb->next) {
1206         if ((lpcb->local_port == pcb->local_port) &&
1207             (ip_addr_isany(&lpcb->local_ip) ||
1208              ip_addr_cmp(&pcb->local_ip, &lpcb->local_ip))) {
1209             /* port and address of the listen pcb match the timed-out pcb */
1210             LWIP_ASSERT("tcp_pcb_purge: listen pcb does not have accepts pending",
1211               lpcb->accepts_pending > 0);
1212             lpcb->accepts_pending--;
1213             break;
1214           }
1215       }
1216     }
1217 #endif /* TCP_LISTEN_BACKLOG */
1218 
1219 
1220     if (pcb->refused_data != NULL) {
1221       LWIP_DEBUGF(TCP_DEBUG, ("tcp_pcb_purge: data left on ->refused_data\n"));
1222       pbuf_free(pcb->refused_data);
1223       pcb->refused_data = NULL;
1224     }
1225     if (pcb->unsent != NULL) {
1226       LWIP_DEBUGF(TCP_DEBUG, ("tcp_pcb_purge: not all data sent\n"));
1227     }
1228     if (pcb->unacked != NULL) {
1229       LWIP_DEBUGF(TCP_DEBUG, ("tcp_pcb_purge: data left on ->unacked\n"));
1230     }
1231 #if TCP_QUEUE_OOSEQ /* LW */
1232     if (pcb->ooseq != NULL) {
1233       LWIP_DEBUGF(TCP_DEBUG, ("tcp_pcb_purge: data left on ->ooseq\n"));
1234     }
1235 
1236     /* Stop the retransmission timer as it will expect data on unacked
1237        queue if it fires */
1238     pcb->rtime = -1;
1239 
1240     tcp_segs_free(pcb->ooseq);
1241     pcb->ooseq = NULL;
1242 #endif /* TCP_QUEUE_OOSEQ */
1243     tcp_segs_free(pcb->unsent);
1244     tcp_segs_free(pcb->unacked);
1245     pcb->unacked = pcb->unsent = NULL;
1246   }
1247 }
1248 
1249 /**
1250  * Purges the PCB and removes it from a PCB list. Any delayed ACKs are sent first.
1251  *
1252  * @param pcblist PCB list to purge.
1253  * @param pcb tcp_pcb to purge. The pcb itself is NOT deallocated!
1254  */
1255 void
1256 tcp_pcb_remove(struct tcp_pcb **pcblist, struct tcp_pcb *pcb)
1257 {
1258   TCP_RMV(pcblist, pcb);
1259 
1260   tcp_pcb_purge(pcb);
1261   
1262   /* if there is an outstanding delayed ACKs, send it */
1263   if (pcb->state != TIME_WAIT &&
1264      pcb->state != LISTEN &&
1265      pcb->flags & TF_ACK_DELAY) {
1266     pcb->flags |= TF_ACK_NOW;
1267     tcp_output(pcb);
1268   }
1269 
1270   if (pcb->state != LISTEN) {
1271     LWIP_ASSERT("unsent segments leaking", pcb->unsent == NULL);
1272     LWIP_ASSERT("unacked segments leaking", pcb->unacked == NULL);
1273 #if TCP_QUEUE_OOSEQ
1274     LWIP_ASSERT("ooseq segments leaking", pcb->ooseq == NULL);
1275 #endif /* TCP_QUEUE_OOSEQ */
1276   }
1277 
1278   pcb->state = CLOSED;
1279 
1280   LWIP_ASSERT("tcp_pcb_remove: tcp_pcbs_sane()", tcp_pcbs_sane());
1281 }
1282 
1283 /**
1284  * Calculates a new initial sequence number for new connections.
1285  *
1286  * @return u32_t pseudo random sequence number
1287  */
1288 u32_t
1289 tcp_next_iss(void)
1290 {
1291   static u32_t iss = 6510;
1292   
1293   iss += tcp_ticks;       /* XXX */
1294   return iss;
1295 }
1296 
1297 #if TCP_CALCULATE_EFF_SEND_MSS
1298 /**
1299  * Calcluates the effective send mss that can be used for a specific IP address
1300  * by using ip_route to determin the netif used to send to the address and
1301  * calculating the minimum of TCP_MSS and that netif's mtu (if set).
1302  */
1303 u16_t
1304 tcp_eff_send_mss(u16_t sendmss, struct ip_addr *addr)
1305 {
1306   u16_t mss_s;
1307   struct netif *outif;
1308 
1309   outif = ip_route(addr);
1310   if ((outif != NULL) && (outif->mtu != 0)) {
1311     mss_s = outif->mtu - IP_HLEN - TCP_HLEN;
1312     /* RFC 1122, chap 4.2.2.6:
1313      * Eff.snd.MSS = min(SendMSS+20, MMS_S) - TCPhdrsize - IPoptionsize
1314      * We correct for TCP options in tcp_enqueue(), and don't support
1315      * IP options
1316      */
1317     sendmss = LWIP_MIN(sendmss, mss_s);
1318   }
1319   return sendmss;
1320 }
1321 #endif /* TCP_CALCULATE_EFF_SEND_MSS */
1322 
1323 const char*
1324 tcp_debug_state_str(enum tcp_state s)
1325 {
1326   return tcp_state_str[s];
1327 }
1328 
1329 #if TCP_DEBUG || TCP_INPUT_DEBUG || TCP_OUTPUT_DEBUG
1330 /**
1331  * Print a tcp header for debugging purposes.
1332  *
1333  * @param tcphdr pointer to a struct tcp_hdr
1334  */
1335 void
1336 tcp_debug_print(struct tcp_hdr *tcphdr)
1337 {
1338   LWIP_DEBUGF(TCP_DEBUG, ("TCP header:\n"));
1339   LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
1340   LWIP_DEBUGF(TCP_DEBUG, ("|    %5"U16_F"      |    %5"U16_F"      | (src port, dest port)\n",
1341          ntohs(tcphdr->src), ntohs(tcphdr->dest)));
1342   LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
1343   LWIP_DEBUGF(TCP_DEBUG, ("|           %010"U32_F"          | (seq no)\n",
1344           ntohl(tcphdr->seqno)));
1345   LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
1346   LWIP_DEBUGF(TCP_DEBUG, ("|           %010"U32_F"          | (ack no)\n",
1347          ntohl(tcphdr->ackno)));
1348   LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
1349   LWIP_DEBUGF(TCP_DEBUG, ("| %2"U16_F" |   |%"U16_F"%"U16_F"%"U16_F"%"U16_F"%"U16_F"%"U16_F"|     %5"U16_F"     | (hdrlen, flags (",
1350        TCPH_HDRLEN(tcphdr),
1351          TCPH_FLAGS(tcphdr) >> 5 & 1,
1352          TCPH_FLAGS(tcphdr) >> 4 & 1,
1353          TCPH_FLAGS(tcphdr) >> 3 & 1,
1354          TCPH_FLAGS(tcphdr) >> 2 & 1,
1355          TCPH_FLAGS(tcphdr) >> 1 & 1,
1356          TCPH_FLAGS(tcphdr) & 1,
1357          ntohs(tcphdr->wnd)));
1358   tcp_debug_print_flags(TCPH_FLAGS(tcphdr));
1359   LWIP_DEBUGF(TCP_DEBUG, ("), win)\n"));
1360   LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
1361   LWIP_DEBUGF(TCP_DEBUG, ("|    0x%04"X16_F"     |     %5"U16_F"     | (chksum, urgp)\n",
1362          ntohs(tcphdr->chksum), ntohs(tcphdr->urgp)));
1363   LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
1364 }
1365 
1366 /**
1367  * Print a tcp state for debugging purposes.
1368  *
1369  * @param s enum tcp_state to print
1370  */
1371 void
1372 tcp_debug_print_state(enum tcp_state s)
1373 {
1374   LWIP_DEBUGF(TCP_DEBUG, ("State: %s\n", tcp_state_str[s]));
1375 }
1376 
1377 /**
1378  * Print tcp flags for debugging purposes.
1379  *
1380  * @param flags tcp flags, all active flags are printed
1381  */
1382 void
1383 tcp_debug_print_flags(u8_t flags)
1384 {
1385   if (flags & TCP_FIN) {
1386     LWIP_DEBUGF(TCP_DEBUG, ("FIN "));
1387   }
1388   if (flags & TCP_SYN) {
1389     LWIP_DEBUGF(TCP_DEBUG, ("SYN "));
1390   }
1391   if (flags & TCP_RST) {
1392     LWIP_DEBUGF(TCP_DEBUG, ("RST "));
1393   }
1394   if (flags & TCP_PSH) {
1395     LWIP_DEBUGF(TCP_DEBUG, ("PSH "));
1396   }
1397   if (flags & TCP_ACK) {
1398     LWIP_DEBUGF(TCP_DEBUG, ("ACK "));
1399   }
1400   if (flags & TCP_URG) {
1401     LWIP_DEBUGF(TCP_DEBUG, ("URG "));
1402   }
1403   if (flags & TCP_ECE) {
1404     LWIP_DEBUGF(TCP_DEBUG, ("ECE "));
1405   }
1406   if (flags & TCP_CWR) {
1407     LWIP_DEBUGF(TCP_DEBUG, ("CWR "));
1408   }
1409   LWIP_DEBUGF(TCP_DEBUG, ("\n"));
1410 }
1411 
1412 /**
1413  * Print all tcp_pcbs in every list for debugging purposes.
1414  */
1415 void
1416 tcp_debug_print_pcbs(void)
1417 {
1418   struct tcp_pcb *pcb;
1419   LWIP_DEBUGF(TCP_DEBUG, ("Active PCB states:\n"));
1420   for(pcb = tcp_active_pcbs; pcb != NULL; pcb = pcb->next) {
1421     LWIP_DEBUGF(TCP_DEBUG, ("Local port %"U16_F", foreign port %"U16_F" snd_nxt %"U32_F" rcv_nxt %"U32_F" ",
1422                        pcb->local_port, pcb->remote_port,
1423                        pcb->snd_nxt, pcb->rcv_nxt));
1424     tcp_debug_print_state(pcb->state);
1425   }    
1426   LWIP_DEBUGF(TCP_DEBUG, ("Listen PCB states:\n"));
1427   for(pcb = (struct tcp_pcb *)tcp_listen_pcbs.pcbs; pcb != NULL; pcb = pcb->next) {
1428     LWIP_DEBUGF(TCP_DEBUG, ("Local port %"U16_F", foreign port %"U16_F" snd_nxt %"U32_F" rcv_nxt %"U32_F" ",
1429                        pcb->local_port, pcb->remote_port,
1430                        pcb->snd_nxt, pcb->rcv_nxt));
1431     tcp_debug_print_state(pcb->state);
1432   }    
1433   LWIP_DEBUGF(TCP_DEBUG, ("TIME-WAIT PCB states:\n"));
1434   for(pcb = tcp_tw_pcbs; pcb != NULL; pcb = pcb->next) {
1435     LWIP_DEBUGF(TCP_DEBUG, ("Local port %"U16_F", foreign port %"U16_F" snd_nxt %"U32_F" rcv_nxt %"U32_F" ",
1436                        pcb->local_port, pcb->remote_port,
1437                        pcb->snd_nxt, pcb->rcv_nxt));
1438     tcp_debug_print_state(pcb->state);
1439   }    
1440 }
1441 
1442 /**
1443  * Check state consistency of the tcp_pcb lists.
1444  */
1445 s16_t
1446 tcp_pcbs_sane(void)
1447 {
1448   struct tcp_pcb *pcb;
1449   for(pcb = tcp_active_pcbs; pcb != NULL; pcb = pcb->next) {
1450     LWIP_ASSERT("tcp_pcbs_sane: active pcb->state != CLOSED", pcb->state != CLOSED);
1451     LWIP_ASSERT("tcp_pcbs_sane: active pcb->state != LISTEN", pcb->state != LISTEN);
1452     LWIP_ASSERT("tcp_pcbs_sane: active pcb->state != TIME-WAIT", pcb->state != TIME_WAIT);
1453   }
1454   for(pcb = tcp_tw_pcbs; pcb != NULL; pcb = pcb->next) {
1455     LWIP_ASSERT("tcp_pcbs_sane: tw pcb->state == TIME-WAIT", pcb->state == TIME_WAIT);
1456   }
1457   return 1;
1458 }
1459 #endif /* TCP_DEBUG */
1460 
1461 #endif /* LWIP_TCP */