ON Semiconductor / mbed-os

Dependents:   mbed-TFT-example-NCS36510 mbed-Accelerometer-example-NCS36510 mbed-Accelerometer-example-NCS36510

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers lwip_tcp.c Source File

lwip_tcp.c

Go to the documentation of this file.
00001 /**
00002  * @file 
00003  * Transmission Control Protocol for IP
00004  * See also @ref tcp_raw
00005  */
00006 
00007 /*
00008  * Copyright (c) 2001-2004 Swedish Institute of Computer Science.
00009  * All rights reserved.
00010  *
00011  * Redistribution and use in source and binary forms, with or without modification,
00012  * are permitted provided that the following conditions are met:
00013  *
00014  * 1. Redistributions of source code must retain the above copyright notice,
00015  *    this list of conditions and the following disclaimer.
00016  * 2. Redistributions in binary form must reproduce the above copyright notice,
00017  *    this list of conditions and the following disclaimer in the documentation
00018  *    and/or other materials provided with the distribution.
00019  * 3. The name of the author may not be used to endorse or promote products
00020  *    derived from this software without specific prior written permission.
00021  *
00022  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
00023  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
00024  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
00025  * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
00026  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
00027  * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
00028  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
00029  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
00030  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
00031  * OF SUCH DAMAGE.
00032  *
00033  * This file is part of the lwIP TCP/IP stack.
00034  *
00035  * Author: Adam Dunkels <adam@sics.se>
00036  *
00037  */
00038 
00039 /**
00040  * @defgroup tcp_raw TCP
00041  * @ingroup raw_api
00042  * Transmission Control Protocol for IP\n
00043  * @see @ref raw_api and @ref netconn
00044  *
00045  * Common functions for the TCP implementation, such as functinos
00046  * for manipulating the data structures and the TCP timer functions. TCP functions
00047  * related to input and output is found in tcp_in.c and tcp_out.c respectively.\n
00048  */
00049 
00050 #include "lwip/opt.h"
00051 
00052 #if LWIP_TCP /* don't build if not configured for use in lwipopts.h */
00053 
00054 #include "lwip/def.h"
00055 #include "lwip/mem.h"
00056 #include "lwip/memp.h"
00057 #include "lwip/tcp.h"
00058 #include "lwip/priv/tcp_priv.h"
00059 #include "lwip/debug.h"
00060 #include "lwip/stats.h"
00061 #include "lwip/ip6.h"
00062 #include "lwip/ip6_addr.h"
00063 #include "lwip/nd6.h"
00064 
00065 #include <string.h>
00066 
00067 #ifndef TCP_LOCAL_PORT_RANGE_START
00068 /* From http://www.iana.org/assignments/port-numbers:
00069    "The Dynamic and/or Private Ports are those from 49152 through 65535" */
00070 #define TCP_LOCAL_PORT_RANGE_START        0xc000
00071 #define TCP_LOCAL_PORT_RANGE_END          0xffff
00072 #define TCP_ENSURE_LOCAL_PORT_RANGE(port) ((u16_t)(((port) & ~TCP_LOCAL_PORT_RANGE_START) + TCP_LOCAL_PORT_RANGE_START))
00073 #endif
00074 
00075 #if LWIP_TCP_KEEPALIVE
00076 #define TCP_KEEP_DUR(pcb)   ((pcb)->keep_cnt * (pcb)->keep_intvl)
00077 #define TCP_KEEP_INTVL(pcb) ((pcb)->keep_intvl)
00078 #else /* LWIP_TCP_KEEPALIVE */
00079 #define TCP_KEEP_DUR(pcb)   TCP_MAXIDLE
00080 #define TCP_KEEP_INTVL(pcb) TCP_KEEPINTVL_DEFAULT
00081 #endif /* LWIP_TCP_KEEPALIVE */
00082 
00083 /* As initial send MSS, we use TCP_MSS but limit it to 536. */
00084 #if TCP_MSS > 536
00085 #define INITIAL_MSS 536
00086 #else
00087 #define INITIAL_MSS TCP_MSS
00088 #endif
00089 
00090 const char * const tcp_state_str[] = {
00091   "CLOSED",
00092   "LISTEN",
00093   "SYN_SENT",
00094   "SYN_RCVD",
00095   "ESTABLISHED",
00096   "FIN_WAIT_1",
00097   "FIN_WAIT_2",
00098   "CLOSE_WAIT",
00099   "CLOSING",
00100   "LAST_ACK",
00101   "TIME_WAIT"
00102 };
00103 
00104 /* last local TCP port */
00105 static u16_t tcp_port = TCP_LOCAL_PORT_RANGE_START;
00106 
00107 /* Incremented every coarse grained timer shot (typically every 500 ms). */
00108 u32_t tcp_ticks;
00109 const u8_t tcp_backoff[13] =
00110     { 1, 2, 3, 4, 5, 6, 7, 7, 7, 7, 7, 7, 7};
00111  /* Times per slowtmr hits */
00112 const u8_t tcp_persist_backoff[7] = { 3, 6, 12, 24, 48, 96, 120 };
00113 
00114 /* The TCP PCB lists. */
00115 
00116 /** List of all TCP PCBs bound but not yet (connected || listening) */
00117 struct tcp_pcb *tcp_bound_pcbs;
00118 /** List of all TCP PCBs in LISTEN state */
00119 union tcp_listen_pcbs_t tcp_listen_pcbs;
00120 /** List of all TCP PCBs that are in a state in which
00121  * they accept or send data. */
00122 struct tcp_pcb *tcp_active_pcbs;
00123 /** List of all TCP PCBs in TIME-WAIT state */
00124 struct tcp_pcb *tcp_tw_pcbs;
00125 
00126 /** An array with all (non-temporary) PCB lists, mainly used for smaller code size */
00127 struct tcp_pcb ** const tcp_pcb_lists[] = {&tcp_listen_pcbs.pcbs, &tcp_bound_pcbs,
00128   &tcp_active_pcbs, &tcp_tw_pcbs};
00129 
00130 u8_t tcp_active_pcbs_changed;
00131 
00132 /** Timer counter to handle calling slow-timer from tcp_tmr() */
00133 static u8_t tcp_timer;
00134 static u8_t tcp_timer_ctr;
00135 static u16_t tcp_new_port(void);
00136 
00137 /**
00138  * Initialize this module.
00139  */
00140 void
00141 tcp_init(void)
00142 {
00143 #if LWIP_RANDOMIZE_INITIAL_LOCAL_PORTS && defined(LWIP_RAND)
00144   tcp_port = TCP_ENSURE_LOCAL_PORT_RANGE(LWIP_RAND());
00145 #endif /* LWIP_RANDOMIZE_INITIAL_LOCAL_PORTS && defined(LWIP_RAND) */
00146 }
00147 
00148 /**
00149  * Called periodically to dispatch TCP timers.
00150  */
00151 void
00152 tcp_tmr(void)
00153 {
00154   /* Call tcp_fasttmr() every 250 ms */
00155   tcp_fasttmr();
00156 
00157   if (++tcp_timer & 1) {
00158     /* Call tcp_slowtmr() every 500 ms, i.e., every other timer
00159        tcp_tmr() is called. */
00160     tcp_slowtmr();
00161   }
00162 }
00163 
00164 #if LWIP_CALLBACK_API || TCP_LISTEN_BACKLOG
00165 /** Called when a listen pcb is closed. Iterates one pcb list and removes the
00166  * closed listener pcb from pcb->listener if matching.
00167  */
00168 static void
00169 tcp_remove_listener(struct tcp_pcb *list, struct tcp_pcb_listen *lpcb)
00170 {
00171    struct tcp_pcb *pcb;
00172    for (pcb = list; pcb != NULL; pcb = pcb->next) {
00173       if (pcb->listener == lpcb) {
00174          pcb->listener = NULL;
00175       }
00176    }
00177 }
00178 #endif
00179 
00180 /** Called when a listen pcb is closed. Iterates all pcb lists and removes the
00181  * closed listener pcb from pcb->listener if matching.
00182  */
00183 static void
00184 tcp_listen_closed(struct tcp_pcb *pcb)
00185 {
00186 #if LWIP_CALLBACK_API || TCP_LISTEN_BACKLOG
00187   size_t i;
00188   LWIP_ASSERT("pcb != NULL", pcb != NULL);
00189   LWIP_ASSERT("pcb->state == LISTEN", pcb->state == LISTEN);
00190   for (i = 1; i < LWIP_ARRAYSIZE(tcp_pcb_lists); i++) {
00191     tcp_remove_listener(*tcp_pcb_lists[i], (struct tcp_pcb_listen*)pcb);
00192   }
00193 #endif
00194   LWIP_UNUSED_ARG(pcb);
00195 }
00196 
00197 #if TCP_LISTEN_BACKLOG
00198 /** @ingroup tcp_raw
00199  * Delay accepting a connection in respect to the listen backlog:
00200  * the number of outstanding connections is increased until
00201  * tcp_backlog_accepted() is called.
00202  *
00203  * ATTENTION: the caller is responsible for calling tcp_backlog_accepted()
00204  * or else the backlog feature will get out of sync!
00205  *
00206  * @param pcb the connection pcb which is not fully accepted yet
00207  */
00208 void
00209 tcp_backlog_delayed(struct tcp_pcb* pcb)
00210 {
00211   LWIP_ASSERT("pcb != NULL", pcb != NULL);
00212   if ((pcb->flags & TF_BACKLOGPEND) == 0) {
00213     if (pcb->listener != NULL) {
00214       pcb->listener->accepts_pending++;
00215       LWIP_ASSERT("accepts_pending != 0", pcb->listener->accepts_pending != 0);
00216       pcb->flags |= TF_BACKLOGPEND;
00217     }
00218   }
00219 }
00220 
00221 /** @ingroup tcp_raw
00222  * A delayed-accept a connection is accepted (or closed/aborted): decreases
00223  * the number of outstanding connections after calling tcp_backlog_delayed().
00224  *
00225  * ATTENTION: the caller is responsible for calling tcp_backlog_accepted()
00226  * or else the backlog feature will get out of sync!
00227  *
00228  * @param pcb the connection pcb which is now fully accepted (or closed/aborted)
00229  */
00230 void
00231 tcp_backlog_accepted(struct tcp_pcb* pcb)
00232 {
00233   LWIP_ASSERT("pcb != NULL", pcb != NULL);
00234   if ((pcb->flags & TF_BACKLOGPEND) != 0) {
00235     if (pcb->listener != NULL) {
00236       LWIP_ASSERT("accepts_pending != 0", pcb->listener->accepts_pending != 0);
00237       pcb->listener->accepts_pending--;
00238       pcb->flags &= ~TF_BACKLOGPEND;
00239     }
00240   }
00241 }
00242 #endif /* TCP_LISTEN_BACKLOG */
00243 
00244 /**
00245  * Closes the TX side of a connection held by the PCB.
00246  * For tcp_close(), a RST is sent if the application didn't receive all data
00247  * (tcp_recved() not called for all data passed to recv callback).
00248  *
00249  * Listening pcbs are freed and may not be referenced any more.
00250  * Connection pcbs are freed if not yet connected and may not be referenced
00251  * any more. If a connection is established (at least SYN received or in
00252  * a closing state), the connection is closed, and put in a closing state.
00253  * The pcb is then automatically freed in tcp_slowtmr(). It is therefore
00254  * unsafe to reference it.
00255  *
00256  * @param pcb the tcp_pcb to close
00257  * @return ERR_OK if connection has been closed
00258  *         another err_t if closing failed and pcb is not freed
00259  */
00260 static err_t
00261 tcp_close_shutdown(struct tcp_pcb *pcb, u8_t rst_on_unacked_data)
00262 {
00263   err_t err;
00264 
00265   if (rst_on_unacked_data && ((pcb->state == ESTABLISHED) || (pcb->state == CLOSE_WAIT))) {
00266     if ((pcb->refused_data != NULL) || (pcb->rcv_wnd != TCP_WND_MAX(pcb))) {
00267       /* Not all data received by application, send RST to tell the remote
00268          side about this. */
00269       LWIP_ASSERT("pcb->flags & TF_RXCLOSED", pcb->flags & TF_RXCLOSED);
00270 
00271       /* don't call tcp_abort here: we must not deallocate the pcb since
00272          that might not be expected when calling tcp_close */
00273       tcp_rst(pcb->snd_nxt, pcb->rcv_nxt, &pcb->local_ip, &pcb->remote_ip,
00274                pcb->local_port, pcb->remote_port);
00275 
00276       tcp_pcb_purge(pcb);
00277       TCP_RMV_ACTIVE(pcb);
00278       if (pcb->state == ESTABLISHED) {
00279         /* move to TIME_WAIT since we close actively */
00280         pcb->state = TIME_WAIT;
00281         TCP_REG(&tcp_tw_pcbs, pcb);
00282       } else {
00283         /* CLOSE_WAIT: deallocate the pcb since we already sent a RST for it */
00284         if (tcp_input_pcb == pcb) {
00285           /* prevent using a deallocated pcb: free it from tcp_input later */
00286           tcp_trigger_input_pcb_close();
00287         } else {
00288           memp_free(MEMP_TCP_PCB, pcb);
00289         }
00290       }
00291       return ERR_OK;
00292     }
00293   }
00294 
00295   switch (pcb->state) {
00296   case CLOSED:
00297     /* Closing a pcb in the CLOSED state might seem erroneous,
00298      * however, it is in this state once allocated and as yet unused
00299      * and the user needs some way to free it should the need arise.
00300      * Calling tcp_close() with a pcb that has already been closed, (i.e. twice)
00301      * or for a pcb that has been used and then entered the CLOSED state
00302      * is erroneous, but this should never happen as the pcb has in those cases
00303      * been freed, and so any remaining handles are bogus. */
00304     err = ERR_OK;
00305     if (pcb->local_port != 0) {
00306       TCP_RMV(&tcp_bound_pcbs, pcb);
00307     }
00308     memp_free(MEMP_TCP_PCB, pcb);
00309     pcb = NULL;
00310     break;
00311   case LISTEN:
00312     err = ERR_OK;
00313     tcp_listen_closed(pcb);
00314     tcp_pcb_remove(&tcp_listen_pcbs.pcbs, pcb);
00315     memp_free(MEMP_TCP_PCB_LISTEN, pcb);
00316     pcb = NULL;
00317     break;
00318   case SYN_SENT:
00319     err = ERR_OK;
00320     TCP_PCB_REMOVE_ACTIVE(pcb);
00321     memp_free(MEMP_TCP_PCB, pcb);
00322     pcb = NULL;
00323     MIB2_STATS_INC(mib2.tcpattemptfails);
00324     break;
00325   case SYN_RCVD:
00326     err = tcp_send_fin(pcb);
00327     if (err == ERR_OK) {
00328       tcp_backlog_accepted(pcb);
00329       MIB2_STATS_INC(mib2.tcpattemptfails);
00330       pcb->state = FIN_WAIT_1;
00331     }
00332     break;
00333   case ESTABLISHED:
00334     err = tcp_send_fin(pcb);
00335     if (err == ERR_OK) {
00336       MIB2_STATS_INC(mib2.tcpestabresets);
00337       pcb->state = FIN_WAIT_1;
00338     }
00339     break;
00340   case CLOSE_WAIT:
00341     err = tcp_send_fin(pcb);
00342     if (err == ERR_OK) {
00343       MIB2_STATS_INC(mib2.tcpestabresets);
00344       pcb->state = LAST_ACK;
00345     }
00346     break;
00347   default:
00348     /* Has already been closed, do nothing. */
00349     err = ERR_OK;
00350     pcb = NULL;
00351     break;
00352   }
00353 
00354   if (pcb != NULL && err == ERR_OK) {
00355     /* To ensure all data has been sent when tcp_close returns, we have
00356        to make sure tcp_output doesn't fail.
00357        Since we don't really have to ensure all data has been sent when tcp_close
00358        returns (unsent data is sent from tcp timer functions, also), we don't care
00359        for the return value of tcp_output for now. */
00360     tcp_output(pcb);
00361   }
00362   return err;
00363 }
00364 
00365 /**
00366  * @ingroup tcp_raw
00367  * Closes the connection held by the PCB.
00368  *
00369  * Listening pcbs are freed and may not be referenced any more.
00370  * Connection pcbs are freed if not yet connected and may not be referenced
00371  * any more. If a connection is established (at least SYN received or in
00372  * a closing state), the connection is closed, and put in a closing state.
00373  * The pcb is then automatically freed in tcp_slowtmr(). It is therefore
00374  * unsafe to reference it (unless an error is returned).
00375  *
00376  * @param pcb the tcp_pcb to close
00377  * @return ERR_OK if connection has been closed
00378  *         another err_t if closing failed and pcb is not freed
00379  */
00380 err_t
00381 tcp_close(struct tcp_pcb *pcb)
00382 {
00383   LWIP_DEBUGF(TCP_DEBUG, ("tcp_close: closing in "));
00384   tcp_debug_print_state(pcb->state);
00385 
00386   if (pcb->state != LISTEN) {
00387     /* Set a flag not to receive any more data... */
00388     pcb->flags |= TF_RXCLOSED;
00389   }
00390   /* ... and close */
00391   return tcp_close_shutdown(pcb, 1);
00392 }
00393 
00394 /**
00395  * @ingroup tcp_raw
00396  * Causes all or part of a full-duplex connection of this PCB to be shut down.
00397  * This doesn't deallocate the PCB unless shutting down both sides!
00398  * Shutting down both sides is the same as calling tcp_close, so if it succeds,
00399  * the PCB should not be referenced any more.
00400  *
00401  * @param pcb PCB to shutdown
00402  * @param shut_rx shut down receive side if this is != 0
00403  * @param shut_tx shut down send side if this is != 0
00404  * @return ERR_OK if shutdown succeeded (or the PCB has already been shut down)
00405  *         another err_t on error.
00406  */
00407 err_t
00408 tcp_shutdown(struct tcp_pcb *pcb, int shut_rx, int shut_tx)
00409 {
00410   if (pcb->state == LISTEN) {
00411     return ERR_CONN;
00412   }
00413   if (shut_rx) {
00414     /* shut down the receive side: set a flag not to receive any more data... */
00415     pcb->flags |= TF_RXCLOSED;
00416     if (shut_tx) {
00417       /* shutting down the tx AND rx side is the same as closing for the raw API */
00418       return tcp_close_shutdown(pcb, 1);
00419     }
00420     /* ... and free buffered data */
00421     if (pcb->refused_data != NULL) {
00422       pbuf_free(pcb->refused_data);
00423       pcb->refused_data = NULL;
00424     }
00425   }
00426   if (shut_tx) {
00427     /* This can't happen twice since if it succeeds, the pcb's state is changed.
00428        Only close in these states as the others directly deallocate the PCB */
00429     switch (pcb->state) {
00430     case SYN_RCVD:
00431     case ESTABLISHED:
00432     case CLOSE_WAIT:
00433       return tcp_close_shutdown(pcb, (u8_t)shut_rx);
00434     default:
00435       /* Not (yet?) connected, cannot shutdown the TX side as that would bring us
00436         into CLOSED state, where the PCB is deallocated. */
00437       return ERR_CONN;
00438     }
00439   }
00440   return ERR_OK;
00441 }
00442 
00443 /**
00444  * Abandons a connection and optionally sends a RST to the remote
00445  * host.  Deletes the local protocol control block. This is done when
00446  * a connection is killed because of shortage of memory.
00447  *
00448  * @param pcb the tcp_pcb to abort
00449  * @param reset boolean to indicate whether a reset should be sent
00450  */
00451 void
00452 tcp_abandon(struct tcp_pcb *pcb, int reset)
00453 {
00454   u32_t seqno, ackno;
00455 #if LWIP_CALLBACK_API
00456   tcp_err_fn errf;
00457 #endif /* LWIP_CALLBACK_API */
00458   void *errf_arg;
00459 
00460   /* pcb->state LISTEN not allowed here */
00461   LWIP_ASSERT("don't call tcp_abort/tcp_abandon for listen-pcbs",
00462     pcb->state != LISTEN);
00463   /* Figure out on which TCP PCB list we are, and remove us. If we
00464      are in an active state, call the receive function associated with
00465      the PCB with a NULL argument, and send an RST to the remote end. */
00466   if (pcb->state == TIME_WAIT) {
00467     tcp_pcb_remove(&tcp_tw_pcbs, pcb);
00468     memp_free(MEMP_TCP_PCB, pcb);
00469   } else {
00470     int send_rst = 0;
00471     u16_t local_port = 0;
00472     seqno = pcb->snd_nxt;
00473     ackno = pcb->rcv_nxt;
00474 #if LWIP_CALLBACK_API
00475     errf = pcb->errf;
00476 #endif /* LWIP_CALLBACK_API */
00477     errf_arg = pcb->callback_arg;
00478     if (pcb->state == CLOSED) {
00479       if (pcb->local_port != 0) {
00480         /* bound, not yet opened */
00481         TCP_RMV(&tcp_bound_pcbs, pcb);
00482       }
00483     } else {
00484       send_rst = reset;
00485       local_port = pcb->local_port;
00486       TCP_PCB_REMOVE_ACTIVE(pcb);
00487     }
00488     if (pcb->unacked != NULL) {
00489       tcp_segs_free(pcb->unacked);
00490     }
00491     if (pcb->unsent != NULL) {
00492       tcp_segs_free(pcb->unsent);
00493     }
00494 #if TCP_QUEUE_OOSEQ
00495     if (pcb->ooseq != NULL) {
00496       tcp_segs_free(pcb->ooseq);
00497     }
00498 #endif /* TCP_QUEUE_OOSEQ */
00499     tcp_backlog_accepted(pcb);
00500     if (send_rst) {
00501       LWIP_DEBUGF(TCP_RST_DEBUG, ("tcp_abandon: sending RST\n"));
00502       tcp_rst(seqno, ackno, &pcb->local_ip, &pcb->remote_ip, local_port, pcb->remote_port);
00503     }
00504     memp_free(MEMP_TCP_PCB, pcb);
00505     TCP_EVENT_ERR(errf, errf_arg, ERR_ABRT);
00506   }
00507 }
00508 
00509 /**
00510  * @ingroup tcp_raw
00511  * Aborts the connection by sending a RST (reset) segment to the remote
00512  * host. The pcb is deallocated. This function never fails.
00513  *
00514  * ATTENTION: When calling this from one of the TCP callbacks, make
00515  * sure you always return ERR_ABRT (and never return ERR_ABRT otherwise
00516  * or you will risk accessing deallocated memory or memory leaks!
00517  *
00518  * @param pcb the tcp pcb to abort
00519  */
00520 void
00521 tcp_abort(struct tcp_pcb *pcb)
00522 {
00523   tcp_abandon(pcb, 1);
00524 }
00525 
00526 /**
00527  * @ingroup tcp_raw
00528  * Binds the connection to a local port number and IP address. If the
00529  * IP address is not given (i.e., ipaddr == NULL), the IP address of
00530  * the outgoing network interface is used instead.
00531  *
00532  * @param pcb the tcp_pcb to bind (no check is done whether this pcb is
00533  *        already bound!)
00534  * @param ipaddr the local ip address to bind to (use IP_ADDR_ANY to bind
00535  *        to any local address
00536  * @param port the local port to bind to
00537  * @return ERR_USE if the port is already in use
00538  *         ERR_VAL if bind failed because the PCB is not in a valid state
00539  *         ERR_OK if bound
00540  */
00541 err_t
00542 tcp_bind(struct tcp_pcb *pcb, const ip_addr_t *ipaddr, u16_t port)
00543 {
00544   int i;
00545   int max_pcb_list = NUM_TCP_PCB_LISTS;
00546   struct tcp_pcb *cpcb;
00547 
00548 #if LWIP_IPV4
00549   /* Don't propagate NULL pointer (IPv4 ANY) to subsequent functions */
00550   if (ipaddr == NULL) {
00551     ipaddr = IP_ADDR_ANY;
00552   }
00553 #endif /* LWIP_IPV4 */
00554 
00555   /* still need to check for ipaddr == NULL in IPv6 only case */
00556   if ((pcb == NULL) || (ipaddr == NULL) || !IP_ADDR_PCB_VERSION_MATCH_EXACT(pcb, ipaddr)) {
00557     return ERR_VAL;
00558   }
00559 
00560   LWIP_ERROR("tcp_bind: can only bind in state CLOSED", pcb->state == CLOSED, return ERR_VAL);
00561 
00562 #if SO_REUSE
00563   /* Unless the REUSEADDR flag is set,
00564      we have to check the pcbs in TIME-WAIT state, also.
00565      We do not dump TIME_WAIT pcb's; they can still be matched by incoming
00566      packets using both local and remote IP addresses and ports to distinguish.
00567    */
00568   if (ip_get_option(pcb, SOF_REUSEADDR)) {
00569     max_pcb_list = NUM_TCP_PCB_LISTS_NO_TIME_WAIT;
00570   }
00571 #endif /* SO_REUSE */
00572 
00573   if (port == 0) {
00574     port = tcp_new_port();
00575     if (port == 0) {
00576       return ERR_BUF;
00577     }
00578   } else {
00579     /* Check if the address already is in use (on all lists) */
00580     for (i = 0; i < max_pcb_list; i++) {
00581       for (cpcb = *tcp_pcb_lists[i]; cpcb != NULL; cpcb = cpcb->next) {
00582         if (cpcb->local_port == port) {
00583 #if SO_REUSE
00584           /* Omit checking for the same port if both pcbs have REUSEADDR set.
00585              For SO_REUSEADDR, the duplicate-check for a 5-tuple is done in
00586              tcp_connect. */
00587           if (!ip_get_option(pcb, SOF_REUSEADDR) ||
00588               !ip_get_option(cpcb, SOF_REUSEADDR))
00589 #endif /* SO_REUSE */
00590           {
00591             /* @todo: check accept_any_ip_version */
00592             if ((IP_IS_V6(ipaddr) == IP_IS_V6_VAL(cpcb->local_ip)) &&
00593                 (ip_addr_isany(&cpcb->local_ip) ||
00594                 ip_addr_isany(ipaddr) ||
00595                 ip_addr_cmp(&cpcb->local_ip, ipaddr))) {
00596               return ERR_USE;
00597             }
00598           }
00599         }
00600       }
00601     }
00602   }
00603 
00604   if (!ip_addr_isany(ipaddr)) {
00605     ip_addr_set(&pcb->local_ip, ipaddr);
00606   }
00607   pcb->local_port = port;
00608   TCP_REG(&tcp_bound_pcbs, pcb);
00609   LWIP_DEBUGF(TCP_DEBUG, ("tcp_bind: bind to port %"U16_F"\n", port));
00610   return ERR_OK;
00611 }
00612 #if LWIP_CALLBACK_API
00613 /**
00614  * Default accept callback if no accept callback is specified by the user.
00615  */
00616 static err_t
00617 tcp_accept_null(void *arg, struct tcp_pcb *pcb, err_t err)
00618 {
00619   LWIP_UNUSED_ARG(arg);
00620   LWIP_UNUSED_ARG(err);
00621 
00622   tcp_abort(pcb);
00623 
00624   return ERR_ABRT;
00625 }
00626 #endif /* LWIP_CALLBACK_API */
00627 
00628 /**
00629  * @ingroup tcp_raw
00630  * Set the state of the connection to be LISTEN, which means that it
00631  * is able to accept incoming connections. The protocol control block
00632  * is reallocated in order to consume less memory. Setting the
00633  * connection to LISTEN is an irreversible process.
00634  *
00635  * @param pcb the original tcp_pcb
00636  * @param backlog the incoming connections queue limit
00637  * @return tcp_pcb used for listening, consumes less memory.
00638  *
00639  * @note The original tcp_pcb is freed. This function therefore has to be
00640  *       called like this:
00641  *             tpcb = tcp_listen(tpcb);
00642  */
00643 struct tcp_pcb *
00644 tcp_listen_with_backlog(struct tcp_pcb *pcb, u8_t backlog)
00645 {
00646   struct tcp_pcb_listen *lpcb;
00647 
00648   LWIP_UNUSED_ARG(backlog);
00649   LWIP_ERROR("tcp_listen: pcb already connected", pcb->state == CLOSED, return NULL);
00650 
00651   /* already listening? */
00652   if (pcb->state == LISTEN) {
00653     return pcb;
00654   }
00655 #if SO_REUSE
00656   if (ip_get_option(pcb, SOF_REUSEADDR)) {
00657     /* Since SOF_REUSEADDR allows reusing a local address before the pcb's usage
00658        is declared (listen-/connection-pcb), we have to make sure now that
00659        this port is only used once for every local IP. */
00660     for (lpcb = tcp_listen_pcbs.listen_pcbs; lpcb != NULL; lpcb = lpcb->next) {
00661       if ((lpcb->local_port == pcb->local_port) &&
00662           ip_addr_cmp(&lpcb->local_ip, &pcb->local_ip)) {
00663         /* this address/port is already used */
00664         return NULL;
00665       }
00666     }
00667   }
00668 #endif /* SO_REUSE */
00669   lpcb = (struct tcp_pcb_listen *)memp_malloc(MEMP_TCP_PCB_LISTEN);
00670   if (lpcb == NULL) {
00671     return NULL;
00672   }
00673   lpcb->callback_arg = pcb->callback_arg;
00674   lpcb->local_port = pcb->local_port;
00675   lpcb->state = LISTEN;
00676   lpcb->prio = pcb->prio;
00677   lpcb->so_options = pcb->so_options;
00678   lpcb->ttl = pcb->ttl;
00679   lpcb->tos = pcb->tos;
00680 #if LWIP_IPV4 && LWIP_IPV6
00681   IP_SET_TYPE_VAL(lpcb->remote_ip, pcb->local_ip.type);
00682 #endif /* LWIP_IPV4 && LWIP_IPV6 */
00683   ip_addr_copy(lpcb->local_ip, pcb->local_ip);
00684   if (pcb->local_port != 0) {
00685     TCP_RMV(&tcp_bound_pcbs, pcb);
00686   }
00687   memp_free(MEMP_TCP_PCB, pcb);
00688 #if LWIP_CALLBACK_API
00689   lpcb->accept = tcp_accept_null;
00690 #endif /* LWIP_CALLBACK_API */
00691 #if TCP_LISTEN_BACKLOG
00692   lpcb->accepts_pending = 0;
00693   lpcb->backlog = backlog;
00694 #endif /* TCP_LISTEN_BACKLOG */
00695   TCP_REG(&tcp_listen_pcbs.pcbs, (struct tcp_pcb *)lpcb);
00696   return (struct tcp_pcb *)lpcb;
00697 }
00698 
00699 /**
00700  * Update the state that tracks the available window space to advertise.
00701  *
00702  * Returns how much extra window would be advertised if we sent an
00703  * update now.
00704  */
00705 u32_t
00706 tcp_update_rcv_ann_wnd(struct tcp_pcb *pcb)
00707 {
00708   u32_t new_right_edge = pcb->rcv_nxt + pcb->rcv_wnd;
00709 
00710   if (TCP_SEQ_GEQ(new_right_edge, pcb->rcv_ann_right_edge + LWIP_MIN((TCP_WND / 2), pcb->mss))) {
00711     /* we can advertise more window */
00712     pcb->rcv_ann_wnd = pcb->rcv_wnd;
00713     return new_right_edge - pcb->rcv_ann_right_edge;
00714   } else {
00715     if (TCP_SEQ_GT(pcb->rcv_nxt, pcb->rcv_ann_right_edge)) {
00716       /* Can happen due to other end sending out of advertised window,
00717        * but within actual available (but not yet advertised) window */
00718       pcb->rcv_ann_wnd = 0;
00719     } else {
00720       /* keep the right edge of window constant */
00721       u32_t new_rcv_ann_wnd = pcb->rcv_ann_right_edge - pcb->rcv_nxt;
00722 #if !LWIP_WND_SCALE
00723       LWIP_ASSERT("new_rcv_ann_wnd <= 0xffff", new_rcv_ann_wnd <= 0xffff);
00724 #endif
00725       pcb->rcv_ann_wnd = (tcpwnd_size_t)new_rcv_ann_wnd;
00726     }
00727     return 0;
00728   }
00729 }
00730 
00731 /**
00732  * @ingroup tcp_raw
00733  * This function should be called by the application when it has
00734  * processed the data. The purpose is to advertise a larger window
00735  * when the data has been processed.
00736  *
00737  * @param pcb the tcp_pcb for which data is read
00738  * @param len the amount of bytes that have been read by the application
00739  */
00740 void
00741 tcp_recved(struct tcp_pcb *pcb, u16_t len)
00742 {
00743   int wnd_inflation;
00744 
00745   /* pcb->state LISTEN not allowed here */
00746   LWIP_ASSERT("don't call tcp_recved for listen-pcbs",
00747     pcb->state != LISTEN);
00748 
00749   pcb->rcv_wnd += len;
00750   if (pcb->rcv_wnd > TCP_WND_MAX(pcb)) {
00751     pcb->rcv_wnd = TCP_WND_MAX(pcb);
00752   } else if (pcb->rcv_wnd == 0) {
00753     /* rcv_wnd overflowed */
00754     if ((pcb->state == CLOSE_WAIT) || (pcb->state == LAST_ACK)) {
00755       /* In passive close, we allow this, since the FIN bit is added to rcv_wnd
00756          by the stack itself, since it is not mandatory for an application
00757          to call tcp_recved() for the FIN bit, but e.g. the netconn API does so. */
00758       pcb->rcv_wnd = TCP_WND_MAX(pcb);
00759     } else {
00760       LWIP_ASSERT("tcp_recved: len wrapped rcv_wnd\n", 0);
00761     }
00762   }
00763 
00764   wnd_inflation = tcp_update_rcv_ann_wnd(pcb);
00765 
00766   /* If the change in the right edge of window is significant (default
00767    * watermark is TCP_WND/4), then send an explicit update now.
00768    * Otherwise wait for a packet to be sent in the normal course of
00769    * events (or more window to be available later) */
00770   if (wnd_inflation >= TCP_WND_UPDATE_THRESHOLD) {
00771     tcp_ack_now(pcb);
00772     tcp_output(pcb);
00773   }
00774 
00775   LWIP_DEBUGF(TCP_DEBUG, ("tcp_recved: received %"U16_F" bytes, wnd %"TCPWNDSIZE_F" (%"TCPWNDSIZE_F").\n",
00776          len, pcb->rcv_wnd, (u16_t)(TCP_WND_MAX(pcb) - pcb->rcv_wnd)));
00777 }
00778 
00779 /**
00780  * Allocate a new local TCP port.
00781  *
00782  * @return a new (free) local TCP port number
00783  */
00784 static u16_t
00785 tcp_new_port(void)
00786 {
00787   u8_t i;
00788   u16_t n = 0;
00789   struct tcp_pcb *pcb;
00790 
00791 again:
00792   if (tcp_port++ == TCP_LOCAL_PORT_RANGE_END) {
00793     tcp_port = TCP_LOCAL_PORT_RANGE_START;
00794   }
00795   /* Check all PCB lists. */
00796   for (i = 0; i < NUM_TCP_PCB_LISTS; i++) {
00797     for (pcb = *tcp_pcb_lists[i]; pcb != NULL; pcb = pcb->next) {
00798       if (pcb->local_port == tcp_port) {
00799         if (++n > (TCP_LOCAL_PORT_RANGE_END - TCP_LOCAL_PORT_RANGE_START)) {
00800           return 0;
00801         }
00802         goto again;
00803       }
00804     }
00805   }
00806   return tcp_port;
00807 }
00808 
00809 /**
00810  * @ingroup tcp_raw
00811  * Connects to another host. The function given as the "connected"
00812  * argument will be called when the connection has been established.
00813  *
00814  * @param pcb the tcp_pcb used to establish the connection
00815  * @param ipaddr the remote ip address to connect to
00816  * @param port the remote tcp port to connect to
00817  * @param connected callback function to call when connected (on error,
00818                     the err calback will be called)
00819  * @return ERR_VAL if invalid arguments are given
00820  *         ERR_OK if connect request has been sent
00821  *         other err_t values if connect request couldn't be sent
00822  */
00823 err_t
00824 tcp_connect(struct tcp_pcb *pcb, const ip_addr_t *ipaddr, u16_t port,
00825       tcp_connected_fn connected)
00826 {
00827   err_t ret;
00828   u32_t iss;
00829   u16_t old_local_port;
00830 
00831   if ((pcb == NULL) || (ipaddr == NULL) || !IP_ADDR_PCB_VERSION_MATCH_EXACT(pcb, ipaddr)) {
00832     return ERR_VAL;
00833   }
00834 
00835   LWIP_ERROR("tcp_connect: can only connect from state CLOSED", pcb->state == CLOSED, return ERR_ISCONN);
00836 
00837   LWIP_DEBUGF(TCP_DEBUG, ("tcp_connect to port %"U16_F"\n", port));
00838   ip_addr_set(&pcb->remote_ip, ipaddr);
00839   pcb->remote_port = port;
00840 
00841   /* check if we have a route to the remote host */
00842   if (ip_addr_isany(&pcb->local_ip)) {
00843     /* no local IP address set, yet. */
00844     struct netif *netif;
00845     const ip_addr_t *local_ip;
00846     ip_route_get_local_ip(&pcb->local_ip, &pcb->remote_ip, netif, local_ip);
00847     if ((netif == NULL) || (local_ip == NULL)) {
00848       /* Don't even try to send a SYN packet if we have no route
00849          since that will fail. */
00850       return ERR_RTE;
00851     }
00852     /* Use the address as local address of the pcb. */
00853     ip_addr_copy(pcb->local_ip, *local_ip);
00854   }
00855 
00856   old_local_port = pcb->local_port;
00857   if (pcb->local_port == 0) {
00858     pcb->local_port = tcp_new_port();
00859     if (pcb->local_port == 0) {
00860       return ERR_BUF;
00861     }
00862   } else {
00863 #if SO_REUSE
00864     if (ip_get_option(pcb, SOF_REUSEADDR)) {
00865       /* Since SOF_REUSEADDR allows reusing a local address, we have to make sure
00866          now that the 5-tuple is unique. */
00867       struct tcp_pcb *cpcb;
00868       int i;
00869       /* Don't check listen- and bound-PCBs, check active- and TIME-WAIT PCBs. */
00870       for (i = 2; i < NUM_TCP_PCB_LISTS; i++) {
00871         for (cpcb = *tcp_pcb_lists[i]; cpcb != NULL; cpcb = cpcb->next) {
00872           if ((cpcb->local_port == pcb->local_port) &&
00873               (cpcb->remote_port == port) &&
00874               ip_addr_cmp(&cpcb->local_ip, &pcb->local_ip) &&
00875               ip_addr_cmp(&cpcb->remote_ip, ipaddr)) {
00876             /* linux returns EISCONN here, but ERR_USE should be OK for us */
00877             return ERR_USE;
00878           }
00879         }
00880       }
00881     }
00882 #endif /* SO_REUSE */
00883   }
00884 
00885   iss = tcp_next_iss();
00886   pcb->rcv_nxt = 0;
00887   pcb->snd_nxt = iss;
00888   pcb->lastack = iss - 1;
00889   pcb->snd_lbb = iss - 1;
00890   /* Start with a window that does not need scaling. When window scaling is
00891      enabled and used, the window is enlarged when both sides agree on scaling. */
00892   pcb->rcv_wnd = pcb->rcv_ann_wnd = TCPWND_MIN16(TCP_WND);
00893   pcb->rcv_ann_right_edge = pcb->rcv_nxt;
00894   pcb->snd_wnd = TCP_WND;
00895   /* As initial send MSS, we use TCP_MSS but limit it to 536.
00896      The send MSS is updated when an MSS option is received. */
00897   pcb->mss = INITIAL_MSS;
00898 #if TCP_CALCULATE_EFF_SEND_MSS
00899   pcb->mss = tcp_eff_send_mss(pcb->mss, &pcb->local_ip, &pcb->remote_ip);
00900 #endif /* TCP_CALCULATE_EFF_SEND_MSS */
00901   pcb->cwnd = 1;
00902   pcb->ssthresh = TCP_WND;
00903 #if LWIP_CALLBACK_API
00904   pcb->connected = connected;
00905 #else /* LWIP_CALLBACK_API */
00906   LWIP_UNUSED_ARG(connected);
00907 #endif /* LWIP_CALLBACK_API */
00908 
00909   /* Send a SYN together with the MSS option. */
00910   ret = tcp_enqueue_flags(pcb, TCP_SYN);
00911   if (ret == ERR_OK) {
00912     /* SYN segment was enqueued, changed the pcbs state now */
00913     pcb->state = SYN_SENT;
00914     if (old_local_port != 0) {
00915       TCP_RMV(&tcp_bound_pcbs, pcb);
00916     }
00917     TCP_REG_ACTIVE(pcb);
00918     MIB2_STATS_INC(mib2.tcpactiveopens);
00919 
00920     tcp_output(pcb);
00921   }
00922   return ret;
00923 }
00924 
00925 /**
00926  * Called every 500 ms and implements the retransmission timer and the timer that
00927  * removes PCBs that have been in TIME-WAIT for enough time. It also increments
00928  * various timers such as the inactivity timer in each PCB.
00929  *
00930  * Automatically called from tcp_tmr().
00931  */
00932 void
00933 tcp_slowtmr(void)
00934 {
00935   struct tcp_pcb *pcb, *prev;
00936   tcpwnd_size_t eff_wnd;
00937   u8_t pcb_remove;      /* flag if a PCB should be removed */
00938   u8_t pcb_reset;       /* flag if a RST should be sent when removing */
00939   err_t err;
00940 
00941   err = ERR_OK;
00942 
00943   ++tcp_ticks;
00944   ++tcp_timer_ctr;
00945 
00946 tcp_slowtmr_start:
00947   /* Steps through all of the active PCBs. */
00948   prev = NULL;
00949   pcb = tcp_active_pcbs;
00950   if (pcb == NULL) {
00951     LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: no active pcbs\n"));
00952   }
00953   while (pcb != NULL) {
00954     LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: processing active pcb\n"));
00955     LWIP_ASSERT("tcp_slowtmr: active pcb->state != CLOSED\n", pcb->state != CLOSED);
00956     LWIP_ASSERT("tcp_slowtmr: active pcb->state != LISTEN\n", pcb->state != LISTEN);
00957     LWIP_ASSERT("tcp_slowtmr: active pcb->state != TIME-WAIT\n", pcb->state != TIME_WAIT);
00958     if (pcb->last_timer == tcp_timer_ctr) {
00959       /* skip this pcb, we have already processed it */
00960       pcb = pcb->next;
00961       continue;
00962     }
00963     pcb->last_timer = tcp_timer_ctr;
00964 
00965     pcb_remove = 0;
00966     pcb_reset = 0;
00967 
00968     if (pcb->state == SYN_SENT && pcb->nrtx == TCP_SYNMAXRTX) {
00969       ++pcb_remove;
00970       LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: max SYN retries reached\n"));
00971     }
00972     else if (pcb->nrtx == TCP_MAXRTX) {
00973       ++pcb_remove;
00974       LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: max DATA retries reached\n"));
00975     } else {
00976       if (pcb->persist_backoff > 0) {
00977         /* If snd_wnd is zero, use persist timer to send 1 byte probes
00978          * instead of using the standard retransmission mechanism. */
00979         u8_t backoff_cnt = tcp_persist_backoff[pcb->persist_backoff-1];
00980         if (pcb->persist_cnt < backoff_cnt) {
00981           pcb->persist_cnt++;
00982         }
00983         if (pcb->persist_cnt >= backoff_cnt) {
00984           if (tcp_zero_window_probe(pcb) == ERR_OK) {
00985             pcb->persist_cnt = 0;
00986             if (pcb->persist_backoff < sizeof(tcp_persist_backoff)) {
00987               pcb->persist_backoff++;
00988             }
00989           }
00990         }
00991       } else {
00992         /* Increase the retransmission timer if it is running */
00993         if (pcb->rtime >= 0) {
00994           ++pcb->rtime;
00995         }
00996 
00997         if (pcb->unacked != NULL && pcb->rtime >= pcb->rto) {
00998           /* Time for a retransmission. */
00999           LWIP_DEBUGF(TCP_RTO_DEBUG, ("tcp_slowtmr: rtime %"S16_F
01000                                       " pcb->rto %"S16_F"\n",
01001                                       pcb->rtime, pcb->rto));
01002 
01003           /* Double retransmission time-out unless we are trying to
01004            * connect to somebody (i.e., we are in SYN_SENT). */
01005           if (pcb->state != SYN_SENT) {
01006             pcb->rto = ((pcb->sa >> 3) + pcb->sv) << tcp_backoff[pcb->nrtx];
01007           }
01008 
01009           /* Reset the retransmission timer. */
01010           pcb->rtime = 0;
01011 
01012           /* Reduce congestion window and ssthresh. */
01013           eff_wnd = LWIP_MIN(pcb->cwnd, pcb->snd_wnd);
01014           pcb->ssthresh = eff_wnd >> 1;
01015           if (pcb->ssthresh < (tcpwnd_size_t)(pcb->mss << 1)) {
01016             pcb->ssthresh = (pcb->mss << 1);
01017           }
01018           pcb->cwnd = pcb->mss;
01019           LWIP_DEBUGF(TCP_CWND_DEBUG, ("tcp_slowtmr: cwnd %"TCPWNDSIZE_F
01020                                        " ssthresh %"TCPWNDSIZE_F"\n",
01021                                        pcb->cwnd, pcb->ssthresh));
01022 
01023           /* The following needs to be called AFTER cwnd is set to one
01024              mss - STJ */
01025           tcp_rexmit_rto(pcb);
01026         }
01027       }
01028     }
01029     /* Check if this PCB has stayed too long in FIN-WAIT-2 */
01030     if (pcb->state == FIN_WAIT_2) {
01031       /* If this PCB is in FIN_WAIT_2 because of SHUT_WR don't let it time out. */
01032       if (pcb->flags & TF_RXCLOSED) {
01033         /* PCB was fully closed (either through close() or SHUT_RDWR):
01034            normal FIN-WAIT timeout handling. */
01035         if ((u32_t)(tcp_ticks - pcb->tmr) >
01036             TCP_FIN_WAIT_TIMEOUT / TCP_SLOW_INTERVAL) {
01037           ++pcb_remove;
01038           LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: removing pcb stuck in FIN-WAIT-2\n"));
01039         }
01040       }
01041     }
01042 
01043     /* Check if KEEPALIVE should be sent */
01044     if (ip_get_option(pcb, SOF_KEEPALIVE) &&
01045        ((pcb->state == ESTABLISHED) ||
01046         (pcb->state == CLOSE_WAIT))) {
01047       if ((u32_t)(tcp_ticks - pcb->tmr) >
01048          (pcb->keep_idle + TCP_KEEP_DUR(pcb)) / TCP_SLOW_INTERVAL)
01049       {
01050         LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: KEEPALIVE timeout. Aborting connection to "));
01051         ip_addr_debug_print(TCP_DEBUG, &pcb->remote_ip);
01052         LWIP_DEBUGF(TCP_DEBUG, ("\n"));
01053 
01054         ++pcb_remove;
01055         ++pcb_reset;
01056       } else if ((u32_t)(tcp_ticks - pcb->tmr) >
01057                 (pcb->keep_idle + pcb->keep_cnt_sent * TCP_KEEP_INTVL(pcb))
01058                 / TCP_SLOW_INTERVAL)
01059       {
01060         err = tcp_keepalive(pcb);
01061         if (err == ERR_OK) {
01062           pcb->keep_cnt_sent++;
01063         }
01064       }
01065     }
01066 
01067     /* If this PCB has queued out of sequence data, but has been
01068        inactive for too long, will drop the data (it will eventually
01069        be retransmitted). */
01070 #if TCP_QUEUE_OOSEQ
01071     if (pcb->ooseq != NULL &&
01072         (u32_t)tcp_ticks - pcb->tmr >= pcb->rto * TCP_OOSEQ_TIMEOUT) {
01073       tcp_segs_free(pcb->ooseq);
01074       pcb->ooseq = NULL;
01075       LWIP_DEBUGF(TCP_CWND_DEBUG, ("tcp_slowtmr: dropping OOSEQ queued data\n"));
01076     }
01077 #endif /* TCP_QUEUE_OOSEQ */
01078 
01079     /* Check if this PCB has stayed too long in SYN-RCVD */
01080     if (pcb->state == SYN_RCVD) {
01081       if ((u32_t)(tcp_ticks - pcb->tmr) >
01082           TCP_SYN_RCVD_TIMEOUT / TCP_SLOW_INTERVAL) {
01083         ++pcb_remove;
01084         LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: removing pcb stuck in SYN-RCVD\n"));
01085       }
01086     }
01087 
01088     /* Check if this PCB has stayed too long in LAST-ACK */
01089     if (pcb->state == LAST_ACK) {
01090       if ((u32_t)(tcp_ticks - pcb->tmr) > 2 * TCP_MSL / TCP_SLOW_INTERVAL) {
01091         ++pcb_remove;
01092         LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: removing pcb stuck in LAST-ACK\n"));
01093       }
01094     }
01095 
01096     /* If the PCB should be removed, do it. */
01097     if (pcb_remove) {
01098       struct tcp_pcb *pcb2;
01099       tcp_err_fn err_fn;
01100       void *err_arg;
01101       tcp_pcb_purge(pcb);
01102       /* Remove PCB from tcp_active_pcbs list. */
01103       if (prev != NULL) {
01104         LWIP_ASSERT("tcp_slowtmr: middle tcp != tcp_active_pcbs", pcb != tcp_active_pcbs);
01105         prev->next = pcb->next;
01106       } else {
01107         /* This PCB was the first. */
01108         LWIP_ASSERT("tcp_slowtmr: first pcb == tcp_active_pcbs", tcp_active_pcbs == pcb);
01109         tcp_active_pcbs = pcb->next;
01110       }
01111 
01112       if (pcb_reset) {
01113         tcp_rst(pcb->snd_nxt, pcb->rcv_nxt, &pcb->local_ip, &pcb->remote_ip,
01114                  pcb->local_port, pcb->remote_port);
01115       }
01116 
01117       err_fn = pcb->errf;
01118       err_arg = pcb->callback_arg;
01119       pcb2 = pcb;
01120       pcb = pcb->next;
01121       memp_free(MEMP_TCP_PCB, pcb2);
01122 
01123       tcp_active_pcbs_changed = 0;
01124       TCP_EVENT_ERR(err_fn, err_arg, ERR_ABRT);
01125       if (tcp_active_pcbs_changed) {
01126         goto tcp_slowtmr_start;
01127       }
01128     } else {
01129       /* get the 'next' element now and work with 'prev' below (in case of abort) */
01130       prev = pcb;
01131       pcb = pcb->next;
01132 
01133       /* We check if we should poll the connection. */
01134       ++prev->polltmr;
01135       if (prev->polltmr >= prev->pollinterval) {
01136         prev->polltmr = 0;
01137         LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: polling application\n"));
01138         tcp_active_pcbs_changed = 0;
01139         TCP_EVENT_POLL(prev, err);
01140         if (tcp_active_pcbs_changed) {
01141           goto tcp_slowtmr_start;
01142         }
01143         /* if err == ERR_ABRT, 'prev' is already deallocated */
01144         if (err == ERR_OK) {
01145           tcp_output(prev);
01146         }
01147       }
01148     }
01149   }
01150 
01151 
01152   /* Steps through all of the TIME-WAIT PCBs. */
01153   prev = NULL;
01154   pcb = tcp_tw_pcbs;
01155   while (pcb != NULL) {
01156     LWIP_ASSERT("tcp_slowtmr: TIME-WAIT pcb->state == TIME-WAIT", pcb->state == TIME_WAIT);
01157     pcb_remove = 0;
01158 
01159     /* Check if this PCB has stayed long enough in TIME-WAIT */
01160     if ((u32_t)(tcp_ticks - pcb->tmr) > 2 * TCP_MSL / TCP_SLOW_INTERVAL) {
01161       ++pcb_remove;
01162     }
01163 
01164     /* If the PCB should be removed, do it. */
01165     if (pcb_remove) {
01166       struct tcp_pcb *pcb2;
01167       tcp_pcb_purge(pcb);
01168       /* Remove PCB from tcp_tw_pcbs list. */
01169       if (prev != NULL) {
01170         LWIP_ASSERT("tcp_slowtmr: middle tcp != tcp_tw_pcbs", pcb != tcp_tw_pcbs);
01171         prev->next = pcb->next;
01172       } else {
01173         /* This PCB was the first. */
01174         LWIP_ASSERT("tcp_slowtmr: first pcb == tcp_tw_pcbs", tcp_tw_pcbs == pcb);
01175         tcp_tw_pcbs = pcb->next;
01176       }
01177       pcb2 = pcb;
01178       pcb = pcb->next;
01179       memp_free(MEMP_TCP_PCB, pcb2);
01180     } else {
01181       prev = pcb;
01182       pcb = pcb->next;
01183     }
01184   }
01185 }
01186 
01187 /**
01188  * Is called every TCP_FAST_INTERVAL (250 ms) and process data previously
01189  * "refused" by upper layer (application) and sends delayed ACKs.
01190  *
01191  * Automatically called from tcp_tmr().
01192  */
01193 void
01194 tcp_fasttmr(void)
01195 {
01196   struct tcp_pcb *pcb;
01197 
01198   ++tcp_timer_ctr;
01199 
01200 tcp_fasttmr_start:
01201   pcb = tcp_active_pcbs;
01202 
01203   while (pcb != NULL) {
01204     if (pcb->last_timer != tcp_timer_ctr) {
01205       struct tcp_pcb *next;
01206       pcb->last_timer = tcp_timer_ctr;
01207       /* send delayed ACKs */
01208       if (pcb->flags & TF_ACK_DELAY) {
01209         LWIP_DEBUGF(TCP_DEBUG, ("tcp_fasttmr: delayed ACK\n"));
01210         tcp_ack_now(pcb);
01211         tcp_output(pcb);
01212         pcb->flags &= ~(TF_ACK_DELAY | TF_ACK_NOW);
01213       }
01214 
01215       next = pcb->next;
01216 
01217       /* If there is data which was previously "refused" by upper layer */
01218       if (pcb->refused_data != NULL) {
01219         tcp_active_pcbs_changed = 0;
01220         tcp_process_refused_data(pcb);
01221         if (tcp_active_pcbs_changed) {
01222           /* application callback has changed the pcb list: restart the loop */
01223           goto tcp_fasttmr_start;
01224         }
01225       }
01226       pcb = next;
01227     } else {
01228       pcb = pcb->next;
01229     }
01230   }
01231 }
01232 
01233 /** Call tcp_output for all active pcbs that have TF_NAGLEMEMERR set */
01234 void
01235 tcp_txnow(void)
01236 {
01237   struct tcp_pcb *pcb;
01238 
01239   for (pcb = tcp_active_pcbs; pcb != NULL; pcb = pcb->next) {
01240     if (pcb->flags & TF_NAGLEMEMERR) {
01241       tcp_output(pcb);
01242     }
01243   }
01244 }
01245 
01246 /** Pass pcb->refused_data to the recv callback */
01247 err_t
01248 tcp_process_refused_data(struct tcp_pcb *pcb)
01249 {
01250 #if TCP_QUEUE_OOSEQ && LWIP_WND_SCALE
01251   struct pbuf *rest;
01252   while (pcb->refused_data != NULL)
01253 #endif /* TCP_QUEUE_OOSEQ && LWIP_WND_SCALE */
01254   {
01255     err_t err;
01256     u8_t refused_flags = pcb->refused_data->flags;
01257     /* set pcb->refused_data to NULL in case the callback frees it and then
01258        closes the pcb */
01259     struct pbuf *refused_data = pcb->refused_data;
01260 #if TCP_QUEUE_OOSEQ && LWIP_WND_SCALE
01261     pbuf_split_64k(refused_data, &rest);
01262     pcb->refused_data = rest;
01263 #else /* TCP_QUEUE_OOSEQ && LWIP_WND_SCALE */
01264     pcb->refused_data = NULL;
01265 #endif /* TCP_QUEUE_OOSEQ && LWIP_WND_SCALE */
01266     /* Notify again application with data previously received. */
01267     LWIP_DEBUGF(TCP_INPUT_DEBUG, ("tcp_input: notify kept packet\n"));
01268     TCP_EVENT_RECV(pcb, refused_data, ERR_OK, err);
01269     if (err == ERR_OK) {
01270       /* did refused_data include a FIN? */
01271       if (refused_flags & PBUF_FLAG_TCP_FIN
01272 #if TCP_QUEUE_OOSEQ && LWIP_WND_SCALE
01273           && (rest == NULL)
01274 #endif /* TCP_QUEUE_OOSEQ && LWIP_WND_SCALE */
01275          ) {
01276         /* correct rcv_wnd as the application won't call tcp_recved()
01277            for the FIN's seqno */
01278         if (pcb->rcv_wnd != TCP_WND_MAX(pcb)) {
01279           pcb->rcv_wnd++;
01280         }
01281         TCP_EVENT_CLOSED(pcb, err);
01282         if (err == ERR_ABRT) {
01283           return ERR_ABRT;
01284         }
01285       }
01286     } else if (err == ERR_ABRT) {
01287       /* if err == ERR_ABRT, 'pcb' is already deallocated */
01288       /* Drop incoming packets because pcb is "full" (only if the incoming
01289          segment contains data). */
01290       LWIP_DEBUGF(TCP_INPUT_DEBUG, ("tcp_input: drop incoming packets, because pcb is \"full\"\n"));
01291       return ERR_ABRT;
01292     } else {
01293       /* data is still refused, pbuf is still valid (go on for ACK-only packets) */
01294 #if TCP_QUEUE_OOSEQ && LWIP_WND_SCALE
01295       if (rest != NULL) {
01296         pbuf_cat(refused_data, rest);
01297       }
01298 #endif /* TCP_QUEUE_OOSEQ && LWIP_WND_SCALE */
01299       pcb->refused_data = refused_data;
01300       return ERR_INPROGRESS;
01301     }
01302   }
01303   return ERR_OK;
01304 }
01305 
01306 /**
01307  * Deallocates a list of TCP segments (tcp_seg structures).
01308  *
01309  * @param seg tcp_seg list of TCP segments to free
01310  */
01311 void
01312 tcp_segs_free(struct tcp_seg *seg)
01313 {
01314   while (seg != NULL) {
01315     struct tcp_seg *next = seg->next;
01316     tcp_seg_free(seg);
01317     seg = next;
01318   }
01319 }
01320 
01321 /**
01322  * Frees a TCP segment (tcp_seg structure).
01323  *
01324  * @param seg single tcp_seg to free
01325  */
01326 void
01327 tcp_seg_free(struct tcp_seg *seg)
01328 {
01329   if (seg != NULL) {
01330     if (seg->p != NULL) {
01331       pbuf_free(seg->p);
01332 #if TCP_DEBUG
01333       seg->p = NULL;
01334 #endif /* TCP_DEBUG */
01335     }
01336     memp_free(MEMP_TCP_SEG, seg);
01337   }
01338 }
01339 
01340 /**
01341  * Sets the priority of a connection.
01342  *
01343  * @param pcb the tcp_pcb to manipulate
01344  * @param prio new priority
01345  */
01346 void
01347 tcp_setprio(struct tcp_pcb *pcb, u8_t prio)
01348 {
01349   pcb->prio = prio;
01350 }
01351 
01352 #if TCP_QUEUE_OOSEQ
01353 /**
01354  * Returns a copy of the given TCP segment.
01355  * The pbuf and data are not copied, only the pointers
01356  *
01357  * @param seg the old tcp_seg
01358  * @return a copy of seg
01359  */
01360 struct tcp_seg *
01361 tcp_seg_copy(struct tcp_seg *seg)
01362 {
01363   struct tcp_seg *cseg;
01364 
01365   cseg = (struct tcp_seg *)memp_malloc(MEMP_TCP_SEG);
01366   if (cseg == NULL) {
01367     return NULL;
01368   }
01369   SMEMCPY((u8_t *)cseg, (const u8_t *)seg, sizeof(struct tcp_seg));
01370   pbuf_ref(cseg->p);
01371   return cseg;
01372 }
01373 #endif /* TCP_QUEUE_OOSEQ */
01374 
01375 #if LWIP_CALLBACK_API
01376 /**
01377  * Default receive callback that is called if the user didn't register
01378  * a recv callback for the pcb.
01379  */
01380 err_t
01381 tcp_recv_null(void *arg, struct tcp_pcb *pcb, struct pbuf *p, err_t err)
01382 {
01383   LWIP_UNUSED_ARG(arg);
01384   if (p != NULL) {
01385     tcp_recved(pcb, p->tot_len);
01386     pbuf_free(p);
01387   } else if (err == ERR_OK) {
01388     return tcp_close(pcb);
01389   }
01390   return ERR_OK;
01391 }
01392 #endif /* LWIP_CALLBACK_API */
01393 
01394 /**
01395  * Kills the oldest active connection that has the same or lower priority than
01396  * 'prio'.
01397  *
01398  * @param prio minimum priority
01399  */
01400 static void
01401 tcp_kill_prio(u8_t prio)
01402 {
01403   struct tcp_pcb *pcb, *inactive;
01404   u32_t inactivity;
01405   u8_t mprio;
01406 
01407   mprio = LWIP_MIN(TCP_PRIO_MAX, prio);
01408 
01409   /* We kill the oldest active connection that has lower priority than prio. */
01410   inactivity = 0;
01411   inactive = NULL;
01412   for (pcb = tcp_active_pcbs; pcb != NULL; pcb = pcb->next) {
01413     if (pcb->prio <= mprio &&
01414        (u32_t)(tcp_ticks - pcb->tmr) >= inactivity) {
01415       inactivity = tcp_ticks - pcb->tmr;
01416       inactive = pcb;
01417       mprio = pcb->prio;
01418     }
01419   }
01420   if (inactive != NULL) {
01421     LWIP_DEBUGF(TCP_DEBUG, ("tcp_kill_prio: killing oldest PCB %p (%"S32_F")\n",
01422            (void *)inactive, inactivity));
01423     tcp_abort(inactive);
01424   }
01425 }
01426 
01427 /**
01428  * Kills the oldest connection that is in specific state.
01429  * Called from tcp_alloc() for LAST_ACK and CLOSING if no more connections are available.
01430  */
01431 static void
01432 tcp_kill_state(enum tcp_state state)
01433 {
01434   struct tcp_pcb *pcb, *inactive;
01435   u32_t inactivity;
01436 
01437   LWIP_ASSERT("invalid state", (state == CLOSING) || (state == LAST_ACK));
01438 
01439   inactivity = 0;
01440   inactive = NULL;
01441   /* Go through the list of active pcbs and get the oldest pcb that is in state
01442      CLOSING/LAST_ACK. */
01443   for (pcb = tcp_active_pcbs; pcb != NULL; pcb = pcb->next) {
01444     if (pcb->state == state) {
01445       if ((u32_t)(tcp_ticks - pcb->tmr) >= inactivity) {
01446         inactivity = tcp_ticks - pcb->tmr;
01447         inactive = pcb;
01448       }
01449     }
01450   }
01451   if (inactive != NULL) {
01452     LWIP_DEBUGF(TCP_DEBUG, ("tcp_kill_closing: killing oldest %s PCB %p (%"S32_F")\n",
01453            tcp_state_str[state], (void *)inactive, inactivity));
01454     /* Don't send a RST, since no data is lost. */
01455     tcp_abandon(inactive, 0);
01456   }
01457 }
01458 
01459 /**
01460  * Kills the oldest connection that is in TIME_WAIT state.
01461  * Called from tcp_alloc() if no more connections are available.
01462  */
01463 static void
01464 tcp_kill_timewait(void)
01465 {
01466   struct tcp_pcb *pcb, *inactive;
01467   u32_t inactivity;
01468 
01469   inactivity = 0;
01470   inactive = NULL;
01471   /* Go through the list of TIME_WAIT pcbs and get the oldest pcb. */
01472   for (pcb = tcp_tw_pcbs; pcb != NULL; pcb = pcb->next) {
01473     if ((u32_t)(tcp_ticks - pcb->tmr) >= inactivity) {
01474       inactivity = tcp_ticks - pcb->tmr;
01475       inactive = pcb;
01476     }
01477   }
01478   if (inactive != NULL) {
01479     LWIP_DEBUGF(TCP_DEBUG, ("tcp_kill_timewait: killing oldest TIME-WAIT PCB %p (%"S32_F")\n",
01480            (void *)inactive, inactivity));
01481     tcp_abort(inactive);
01482   }
01483 }
01484 
01485 /**
01486  * Allocate a new tcp_pcb structure.
01487  *
01488  * @param prio priority for the new pcb
01489  * @return a new tcp_pcb that initially is in state CLOSED
01490  */
01491 struct tcp_pcb *
01492 tcp_alloc(u8_t prio)
01493 {
01494   struct tcp_pcb *pcb;
01495   u32_t iss;
01496 
01497   pcb = (struct tcp_pcb *)memp_malloc(MEMP_TCP_PCB);
01498   if (pcb == NULL) {
01499     /* Try killing oldest connection in TIME-WAIT. */
01500     LWIP_DEBUGF(TCP_DEBUG, ("tcp_alloc: killing off oldest TIME-WAIT connection\n"));
01501     tcp_kill_timewait();
01502     /* Try to allocate a tcp_pcb again. */
01503     pcb = (struct tcp_pcb *)memp_malloc(MEMP_TCP_PCB);
01504     if (pcb == NULL) {
01505       /* Try killing oldest connection in LAST-ACK (these wouldn't go to TIME-WAIT). */
01506       LWIP_DEBUGF(TCP_DEBUG, ("tcp_alloc: killing off oldest LAST-ACK connection\n"));
01507       tcp_kill_state(LAST_ACK);
01508       /* Try to allocate a tcp_pcb again. */
01509       pcb = (struct tcp_pcb *)memp_malloc(MEMP_TCP_PCB);
01510       if (pcb == NULL) {
01511         /* Try killing oldest connection in CLOSING. */
01512         LWIP_DEBUGF(TCP_DEBUG, ("tcp_alloc: killing off oldest CLOSING connection\n"));
01513         tcp_kill_state(CLOSING);
01514         /* Try to allocate a tcp_pcb again. */
01515         pcb = (struct tcp_pcb *)memp_malloc(MEMP_TCP_PCB);
01516         if (pcb == NULL) {
01517           /* Try killing active connections with lower priority than the new one. */
01518           LWIP_DEBUGF(TCP_DEBUG, ("tcp_alloc: killing connection with prio lower than %d\n", prio));
01519           tcp_kill_prio(prio);
01520           /* Try to allocate a tcp_pcb again. */
01521           pcb = (struct tcp_pcb *)memp_malloc(MEMP_TCP_PCB);
01522           if (pcb != NULL) {
01523             /* adjust err stats: memp_malloc failed multiple times before */
01524             MEMP_STATS_DEC(err, MEMP_TCP_PCB);
01525           }
01526         }
01527         if (pcb != NULL) {
01528           /* adjust err stats: memp_malloc failed multiple times before */
01529           MEMP_STATS_DEC(err, MEMP_TCP_PCB);
01530         }
01531       }
01532       if (pcb != NULL) {
01533         /* adjust err stats: memp_malloc failed multiple times before */
01534         MEMP_STATS_DEC(err, MEMP_TCP_PCB);
01535       }
01536     }
01537     if (pcb != NULL) {
01538       /* adjust err stats: memp_malloc failed above */
01539       MEMP_STATS_DEC(err, MEMP_TCP_PCB);
01540     }
01541   }
01542   if (pcb != NULL) {
01543     /* zero out the whole pcb, so there is no need to initialize members to zero */
01544     memset(pcb, 0, sizeof(struct tcp_pcb));
01545     pcb->prio = prio;
01546     pcb->snd_buf = TCP_SND_BUF;
01547     /* Start with a window that does not need scaling. When window scaling is
01548        enabled and used, the window is enlarged when both sides agree on scaling. */
01549     pcb->rcv_wnd = pcb->rcv_ann_wnd = TCPWND_MIN16(TCP_WND);
01550     pcb->ttl = TCP_TTL;
01551     /* As initial send MSS, we use TCP_MSS but limit it to 536.
01552        The send MSS is updated when an MSS option is received. */
01553     pcb->mss = INITIAL_MSS;
01554     pcb->rto = 3000 / TCP_SLOW_INTERVAL;
01555     pcb->sv = 3000 / TCP_SLOW_INTERVAL;
01556     pcb->rtime = -1;
01557     pcb->cwnd = 1;
01558     iss = tcp_next_iss();
01559     pcb->snd_wl2 = iss;
01560     pcb->snd_nxt = iss;
01561     pcb->lastack = iss;
01562     pcb->snd_lbb = iss;
01563     pcb->tmr = tcp_ticks;
01564     pcb->last_timer = tcp_timer_ctr;
01565 
01566 #if LWIP_CALLBACK_API
01567     pcb->recv = tcp_recv_null;
01568 #endif /* LWIP_CALLBACK_API */
01569 
01570     /* Init KEEPALIVE timer */
01571     pcb->keep_idle  = TCP_KEEPIDLE_DEFAULT;
01572 
01573 #if LWIP_TCP_KEEPALIVE
01574     pcb->keep_intvl = TCP_KEEPINTVL_DEFAULT;
01575     pcb->keep_cnt   = TCP_KEEPCNT_DEFAULT;
01576 #endif /* LWIP_TCP_KEEPALIVE */
01577   }
01578   return pcb;
01579 }
01580 
01581 /**
01582  * @ingroup tcp_raw
01583  * Creates a new TCP protocol control block but doesn't place it on
01584  * any of the TCP PCB lists.
01585  * The pcb is not put on any list until binding using tcp_bind().
01586  *
01587  * @internal: Maybe there should be a idle TCP PCB list where these
01588  * PCBs are put on. Port reservation using tcp_bind() is implemented but
01589  * allocated pcbs that are not bound can't be killed automatically if wanting
01590  * to allocate a pcb with higher prio (@see tcp_kill_prio())
01591  *
01592  * @return a new tcp_pcb that initially is in state CLOSED
01593  */
01594 struct tcp_pcb *
01595 tcp_new(void)
01596 {
01597   return tcp_alloc(TCP_PRIO_NORMAL);
01598 }
01599 
01600 /**
01601  * @ingroup tcp_raw
01602  * Creates a new TCP protocol control block but doesn't
01603  * place it on any of the TCP PCB lists.
01604  * The pcb is not put on any list until binding using tcp_bind().
01605  *
01606  * @param type IP address type, see IPADDR_TYPE_XX definitions.
01607  * @return a new tcp_pcb that initially is in state CLOSED
01608  */
01609 struct tcp_pcb *
01610 tcp_new_ip_type(u8_t type)
01611 {
01612   struct tcp_pcb * pcb;
01613   pcb = tcp_alloc(TCP_PRIO_NORMAL);
01614 #if LWIP_IPV4 && LWIP_IPV6
01615   if (pcb != NULL) {
01616     IP_SET_TYPE_VAL(pcb->local_ip, type);
01617     IP_SET_TYPE_VAL(pcb->remote_ip, type);
01618   }
01619 #else
01620   LWIP_UNUSED_ARG(type);
01621 #endif /* LWIP_IPV4 && LWIP_IPV6 */
01622   return pcb;
01623 }
01624 
01625 /**
01626  * @ingroup tcp_raw
01627  * Used to specify the argument that should be passed callback
01628  * functions.
01629  *
01630  * @param pcb tcp_pcb to set the callback argument
01631  * @param arg void pointer argument to pass to callback functions
01632  */
01633 void
01634 tcp_arg(struct tcp_pcb *pcb, void *arg)
01635 {
01636   /* This function is allowed to be called for both listen pcbs and
01637      connection pcbs. */
01638   if (pcb != NULL) {
01639     pcb->callback_arg = arg;
01640   }
01641 }
01642 #if LWIP_CALLBACK_API
01643 
01644 /**
01645  * @ingroup tcp_raw
01646  * Used to specify the function that should be called when a TCP
01647  * connection receives data.
01648  *
01649  * @param pcb tcp_pcb to set the recv callback
01650  * @param recv callback function to call for this pcb when data is received
01651  */
01652 void
01653 tcp_recv(struct tcp_pcb *pcb, tcp_recv_fn recv)
01654 {
01655   if (pcb != NULL) {
01656     LWIP_ASSERT("invalid socket state for recv callback", pcb->state != LISTEN);
01657     pcb->recv = recv;
01658   }
01659 }
01660 
01661 /**
01662  * @ingroup tcp_raw
01663  * Used to specify the function that should be called when TCP data
01664  * has been successfully delivered to the remote host.
01665  *
01666  * @param pcb tcp_pcb to set the sent callback
01667  * @param sent callback function to call for this pcb when data is successfully sent
01668  */
01669 void
01670 tcp_sent(struct tcp_pcb *pcb, tcp_sent_fn sent)
01671 {
01672   if (pcb != NULL) {
01673     LWIP_ASSERT("invalid socket state for sent callback", pcb->state != LISTEN);
01674     pcb->sent = sent;
01675   }
01676 }
01677 
01678 /**
01679  * @ingroup tcp_raw
01680  * Used to specify the function that should be called when a fatal error
01681  * has occurred on the connection.
01682  *
01683  * @param pcb tcp_pcb to set the err callback
01684  * @param err callback function to call for this pcb when a fatal error
01685  *        has occurred on the connection
01686  */
01687 void
01688 tcp_err(struct tcp_pcb *pcb, tcp_err_fn err)
01689 {
01690   if (pcb != NULL) {
01691     LWIP_ASSERT("invalid socket state for err callback", pcb->state != LISTEN);
01692     pcb->errf = err;
01693   }
01694 }
01695 
01696 /**
01697  * @ingroup tcp_raw
01698  * Used for specifying the function that should be called when a
01699  * LISTENing connection has been connected to another host.
01700  *
01701  * @param pcb tcp_pcb to set the accept callback
01702  * @param accept callback function to call for this pcb when LISTENing
01703  *        connection has been connected to another host
01704  */
01705 void
01706 tcp_accept(struct tcp_pcb *pcb, tcp_accept_fn accept)
01707 {
01708   if ((pcb != NULL) && (pcb->state == LISTEN)) {
01709     struct tcp_pcb_listen *lpcb = (struct tcp_pcb_listen*)pcb;
01710     lpcb->accept = accept;
01711   }
01712 }
01713 #endif /* LWIP_CALLBACK_API */
01714 
01715 
01716 /**
01717  * @ingroup tcp_raw
01718  * Used to specify the function that should be called periodically
01719  * from TCP. The interval is specified in terms of the TCP coarse
01720  * timer interval, which is called twice a second.
01721  *
01722  */
01723 void
01724 tcp_poll(struct tcp_pcb *pcb, tcp_poll_fn poll, u8_t interval)
01725 {
01726   LWIP_ASSERT("invalid socket state for poll", pcb->state != LISTEN);
01727 #if LWIP_CALLBACK_API
01728   pcb->poll = poll;
01729 #else /* LWIP_CALLBACK_API */
01730   LWIP_UNUSED_ARG(poll);
01731 #endif /* LWIP_CALLBACK_API */
01732   pcb->pollinterval = interval;
01733 }
01734 
01735 /**
01736  * Purges a TCP PCB. Removes any buffered data and frees the buffer memory
01737  * (pcb->ooseq, pcb->unsent and pcb->unacked are freed).
01738  *
01739  * @param pcb tcp_pcb to purge. The pcb itself is not deallocated!
01740  */
01741 void
01742 tcp_pcb_purge(struct tcp_pcb *pcb)
01743 {
01744   if (pcb->state != CLOSED &&
01745      pcb->state != TIME_WAIT &&
01746      pcb->state != LISTEN) {
01747 
01748     LWIP_DEBUGF(TCP_DEBUG, ("tcp_pcb_purge\n"));
01749 
01750     tcp_backlog_accepted(pcb);
01751 
01752     if (pcb->refused_data != NULL) {
01753       LWIP_DEBUGF(TCP_DEBUG, ("tcp_pcb_purge: data left on ->refused_data\n"));
01754       pbuf_free(pcb->refused_data);
01755       pcb->refused_data = NULL;
01756     }
01757     if (pcb->unsent != NULL) {
01758       LWIP_DEBUGF(TCP_DEBUG, ("tcp_pcb_purge: not all data sent\n"));
01759     }
01760     if (pcb->unacked != NULL) {
01761       LWIP_DEBUGF(TCP_DEBUG, ("tcp_pcb_purge: data left on ->unacked\n"));
01762     }
01763 #if TCP_QUEUE_OOSEQ
01764     if (pcb->ooseq != NULL) {
01765       LWIP_DEBUGF(TCP_DEBUG, ("tcp_pcb_purge: data left on ->ooseq\n"));
01766     }
01767     tcp_segs_free(pcb->ooseq);
01768     pcb->ooseq = NULL;
01769 #endif /* TCP_QUEUE_OOSEQ */
01770 
01771     /* Stop the retransmission timer as it will expect data on unacked
01772        queue if it fires */
01773     pcb->rtime = -1;
01774 
01775     tcp_segs_free(pcb->unsent);
01776     tcp_segs_free(pcb->unacked);
01777     pcb->unacked = pcb->unsent = NULL;
01778 #if TCP_OVERSIZE
01779     pcb->unsent_oversize = 0;
01780 #endif /* TCP_OVERSIZE */
01781   }
01782 }
01783 
01784 /**
01785  * Purges the PCB and removes it from a PCB list. Any delayed ACKs are sent first.
01786  *
01787  * @param pcblist PCB list to purge.
01788  * @param pcb tcp_pcb to purge. The pcb itself is NOT deallocated!
01789  */
01790 void
01791 tcp_pcb_remove(struct tcp_pcb **pcblist, struct tcp_pcb *pcb)
01792 {
01793   TCP_RMV(pcblist, pcb);
01794 
01795   tcp_pcb_purge(pcb);
01796 
01797   /* if there is an outstanding delayed ACKs, send it */
01798   if (pcb->state != TIME_WAIT &&
01799      pcb->state != LISTEN &&
01800      pcb->flags & TF_ACK_DELAY) {
01801     pcb->flags |= TF_ACK_NOW;
01802     tcp_output(pcb);
01803   }
01804 
01805   if (pcb->state != LISTEN) {
01806     LWIP_ASSERT("unsent segments leaking", pcb->unsent == NULL);
01807     LWIP_ASSERT("unacked segments leaking", pcb->unacked == NULL);
01808 #if TCP_QUEUE_OOSEQ
01809     LWIP_ASSERT("ooseq segments leaking", pcb->ooseq == NULL);
01810 #endif /* TCP_QUEUE_OOSEQ */
01811   }
01812 
01813   pcb->state = CLOSED;
01814   /* reset the local port to prevent the pcb from being 'bound' */
01815   pcb->local_port = 0;
01816 
01817   LWIP_ASSERT("tcp_pcb_remove: tcp_pcbs_sane()", tcp_pcbs_sane());
01818 }
01819 
01820 /**
01821  * Calculates a new initial sequence number for new connections.
01822  *
01823  * @return u32_t pseudo random sequence number
01824  */
01825 u32_t
01826 tcp_next_iss(void)
01827 {
01828   static u32_t iss = 6510;
01829 
01830   iss += tcp_ticks;       /* XXX */
01831   return iss;
01832 }
01833 
01834 #if TCP_CALCULATE_EFF_SEND_MSS
01835 /**
01836  * Calculates the effective send mss that can be used for a specific IP address
01837  * by using ip_route to determine the netif used to send to the address and
01838  * calculating the minimum of TCP_MSS and that netif's mtu (if set).
01839  */
01840 u16_t
01841 tcp_eff_send_mss_impl(u16_t sendmss, const ip_addr_t *dest
01842 #if LWIP_IPV6 || LWIP_IPV4_SRC_ROUTING
01843                      , const ip_addr_t *src
01844 #endif /* LWIP_IPV6 || LWIP_IPV4_SRC_ROUTING */
01845                      )
01846 {
01847   u16_t mss_s;
01848   struct netif *outif;
01849   s16_t mtu;
01850 
01851   outif = ip_route(src, dest);
01852 #if LWIP_IPV6
01853 #if LWIP_IPV4
01854   if (IP_IS_V6(dest))
01855 #endif /* LWIP_IPV4 */
01856   {
01857     /* First look in destination cache, to see if there is a Path MTU. */
01858     mtu = nd6_get_destination_mtu(ip_2_ip6(dest), outif);
01859   }
01860 #if LWIP_IPV4
01861   else
01862 #endif /* LWIP_IPV4 */
01863 #endif /* LWIP_IPV6 */
01864 #if LWIP_IPV4
01865   {
01866     if (outif == NULL) {
01867       return sendmss;
01868     }
01869     mtu = outif->mtu;
01870   }
01871 #endif /* LWIP_IPV4 */
01872 
01873   if (mtu != 0) {
01874 #if LWIP_IPV6
01875 #if LWIP_IPV4
01876     if (IP_IS_V6(dest))
01877 #endif /* LWIP_IPV4 */
01878     {
01879       mss_s = mtu - IP6_HLEN - TCP_HLEN;
01880     }
01881 #if LWIP_IPV4
01882     else
01883 #endif /* LWIP_IPV4 */
01884 #endif /* LWIP_IPV6 */
01885 #if LWIP_IPV4
01886     {
01887       mss_s = mtu - IP_HLEN - TCP_HLEN;
01888     }
01889 #endif /* LWIP_IPV4 */
01890     /* RFC 1122, chap 4.2.2.6:
01891      * Eff.snd.MSS = min(SendMSS+20, MMS_S) - TCPhdrsize - IPoptionsize
01892      * We correct for TCP options in tcp_write(), and don't support IP options.
01893      */
01894     sendmss = LWIP_MIN(sendmss, mss_s);
01895   }
01896   return sendmss;
01897 }
01898 #endif /* TCP_CALCULATE_EFF_SEND_MSS */
01899 
01900 #if LWIP_IPV4
01901 /** Helper function for tcp_netif_ipv4_addr_changed() that iterates a pcb list */
01902 static void
01903 tcp_netif_ipv4_addr_changed_pcblist(const ip4_addr_t* old_addr, struct tcp_pcb* pcb_list)
01904 {
01905   struct tcp_pcb *pcb;
01906   pcb = pcb_list;
01907   while (pcb != NULL) {
01908     /* PCB bound to current local interface address? */
01909     if (IP_IS_V4_VAL(pcb->local_ip) && ip4_addr_cmp(ip_2_ip4(&pcb->local_ip), old_addr)
01910 #if LWIP_AUTOIP
01911       /* connections to link-local addresses must persist (RFC3927 ch. 1.9) */
01912       && !ip4_addr_islinklocal(ip_2_ip4(&pcb->local_ip))
01913 #endif /* LWIP_AUTOIP */
01914       ) {
01915       /* this connection must be aborted */
01916       struct tcp_pcb *next = pcb->next;
01917       LWIP_DEBUGF(NETIF_DEBUG | LWIP_DBG_STATE, ("netif_set_ipaddr: aborting TCP pcb %p\n", (void *)pcb));
01918       tcp_abort(pcb);
01919       pcb = next;
01920     } else {
01921       pcb = pcb->next;
01922     }
01923   }
01924 }
01925 
01926 /** This function is called from netif.c when address is changed or netif is removed
01927  *
01928  * @param old_addr IPv4 address of the netif before change
01929  * @param new_addr IPv4 address of the netif after change or NULL if netif has been removed
01930  */
01931 void
01932 tcp_netif_ipv4_addr_changed(const ip4_addr_t* old_addr, const ip4_addr_t* new_addr)
01933 {
01934   struct tcp_pcb_listen *lpcb, *next;
01935 
01936   tcp_netif_ipv4_addr_changed_pcblist(old_addr, tcp_active_pcbs);
01937   tcp_netif_ipv4_addr_changed_pcblist(old_addr, tcp_bound_pcbs);
01938 
01939   if (!ip4_addr_isany(new_addr)) {
01940     /* PCB bound to current local interface address? */
01941     for (lpcb = tcp_listen_pcbs.listen_pcbs; lpcb != NULL; lpcb = next) {
01942       next = lpcb->next;
01943       /* Is this an IPv4 pcb? */
01944       if (IP_IS_V4_VAL(lpcb->local_ip)) {
01945         /* PCB bound to current local interface address? */
01946         if ((!(ip4_addr_isany(ip_2_ip4(&lpcb->local_ip)))) &&
01947             (ip4_addr_cmp(ip_2_ip4(&lpcb->local_ip), old_addr))) {
01948           /* The PCB is listening to the old ipaddr and
01949            * is set to listen to the new one instead */
01950           ip_addr_copy_from_ip4(lpcb->local_ip, *new_addr);
01951         }
01952       }
01953     }
01954   }
01955 }
01956 #endif /* LWIP_IPV4 */
01957 
01958 const char*
01959 tcp_debug_state_str(enum tcp_state s)
01960 {
01961   return tcp_state_str[s];
01962 }
01963 
01964 #if TCP_DEBUG || TCP_INPUT_DEBUG || TCP_OUTPUT_DEBUG
01965 /**
01966  * Print a tcp header for debugging purposes.
01967  *
01968  * @param tcphdr pointer to a struct tcp_hdr
01969  */
01970 void
01971 tcp_debug_print(struct tcp_hdr *tcphdr)
01972 {
01973   LWIP_DEBUGF(TCP_DEBUG, ("TCP header:\n"));
01974   LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
01975   LWIP_DEBUGF(TCP_DEBUG, ("|    %5"U16_F"      |    %5"U16_F"      | (src port, dest port)\n",
01976          ntohs(tcphdr->src), ntohs(tcphdr->dest)));
01977   LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
01978   LWIP_DEBUGF(TCP_DEBUG, ("|           %010"U32_F"          | (seq no)\n",
01979           ntohl(tcphdr->seqno)));
01980   LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
01981   LWIP_DEBUGF(TCP_DEBUG, ("|           %010"U32_F"          | (ack no)\n",
01982          ntohl(tcphdr->ackno)));
01983   LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
01984   LWIP_DEBUGF(TCP_DEBUG, ("| %2"U16_F" |   |%"U16_F"%"U16_F"%"U16_F"%"U16_F"%"U16_F"%"U16_F"|     %5"U16_F"     | (hdrlen, flags (",
01985        TCPH_HDRLEN(tcphdr),
01986          (u16_t)(TCPH_FLAGS(tcphdr) >> 5 & 1),
01987          (u16_t)(TCPH_FLAGS(tcphdr) >> 4 & 1),
01988          (u16_t)(TCPH_FLAGS(tcphdr) >> 3 & 1),
01989          (u16_t)(TCPH_FLAGS(tcphdr) >> 2 & 1),
01990          (u16_t)(TCPH_FLAGS(tcphdr) >> 1 & 1),
01991          (u16_t)(TCPH_FLAGS(tcphdr)      & 1),
01992          ntohs(tcphdr->wnd)));
01993   tcp_debug_print_flags(TCPH_FLAGS(tcphdr));
01994   LWIP_DEBUGF(TCP_DEBUG, ("), win)\n"));
01995   LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
01996   LWIP_DEBUGF(TCP_DEBUG, ("|    0x%04"X16_F"     |     %5"U16_F"     | (chksum, urgp)\n",
01997          ntohs(tcphdr->chksum), ntohs(tcphdr->urgp)));
01998   LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
01999 }
02000 
02001 /**
02002  * Print a tcp state for debugging purposes.
02003  *
02004  * @param s enum tcp_state to print
02005  */
02006 void
02007 tcp_debug_print_state(enum tcp_state s)
02008 {
02009   LWIP_DEBUGF(TCP_DEBUG, ("State: %s\n", tcp_state_str[s]));
02010 }
02011 
02012 /**
02013  * Print tcp flags for debugging purposes.
02014  *
02015  * @param flags tcp flags, all active flags are printed
02016  */
02017 void
02018 tcp_debug_print_flags(u8_t flags)
02019 {
02020   if (flags & TCP_FIN) {
02021     LWIP_DEBUGF(TCP_DEBUG, ("FIN "));
02022   }
02023   if (flags & TCP_SYN) {
02024     LWIP_DEBUGF(TCP_DEBUG, ("SYN "));
02025   }
02026   if (flags & TCP_RST) {
02027     LWIP_DEBUGF(TCP_DEBUG, ("RST "));
02028   }
02029   if (flags & TCP_PSH) {
02030     LWIP_DEBUGF(TCP_DEBUG, ("PSH "));
02031   }
02032   if (flags & TCP_ACK) {
02033     LWIP_DEBUGF(TCP_DEBUG, ("ACK "));
02034   }
02035   if (flags & TCP_URG) {
02036     LWIP_DEBUGF(TCP_DEBUG, ("URG "));
02037   }
02038   if (flags & TCP_ECE) {
02039     LWIP_DEBUGF(TCP_DEBUG, ("ECE "));
02040   }
02041   if (flags & TCP_CWR) {
02042     LWIP_DEBUGF(TCP_DEBUG, ("CWR "));
02043   }
02044   LWIP_DEBUGF(TCP_DEBUG, ("\n"));
02045 }
02046 
02047 /**
02048  * Print all tcp_pcbs in every list for debugging purposes.
02049  */
02050 void
02051 tcp_debug_print_pcbs(void)
02052 {
02053   struct tcp_pcb *pcb;
02054   struct tcp_pcb_listen *pcbl;
02055 
02056   LWIP_DEBUGF(TCP_DEBUG, ("Active PCB states:\n"));
02057   for (pcb = tcp_active_pcbs; pcb != NULL; pcb = pcb->next) {
02058     LWIP_DEBUGF(TCP_DEBUG, ("Local port %"U16_F", foreign port %"U16_F" snd_nxt %"U32_F" rcv_nxt %"U32_F" ",
02059                        pcb->local_port, pcb->remote_port,
02060                        pcb->snd_nxt, pcb->rcv_nxt));
02061     tcp_debug_print_state(pcb->state);
02062   }
02063 
02064   LWIP_DEBUGF(TCP_DEBUG, ("Listen PCB states:\n"));
02065   for (pcbl = tcp_listen_pcbs.listen_pcbs; pcbl != NULL; pcbl = pcbl->next) {
02066     LWIP_DEBUGF(TCP_DEBUG, ("Local port %"U16_F" ", pcbl->local_port));
02067     tcp_debug_print_state(pcbl->state);
02068   }
02069 
02070   LWIP_DEBUGF(TCP_DEBUG, ("TIME-WAIT PCB states:\n"));
02071   for (pcb = tcp_tw_pcbs; pcb != NULL; pcb = pcb->next) {
02072     LWIP_DEBUGF(TCP_DEBUG, ("Local port %"U16_F", foreign port %"U16_F" snd_nxt %"U32_F" rcv_nxt %"U32_F" ",
02073                        pcb->local_port, pcb->remote_port,
02074                        pcb->snd_nxt, pcb->rcv_nxt));
02075     tcp_debug_print_state(pcb->state);
02076   }
02077 }
02078 
02079 /**
02080  * Check state consistency of the tcp_pcb lists.
02081  */
02082 s16_t
02083 tcp_pcbs_sane(void)
02084 {
02085   struct tcp_pcb *pcb;
02086   for (pcb = tcp_active_pcbs; pcb != NULL; pcb = pcb->next) {
02087     LWIP_ASSERT("tcp_pcbs_sane: active pcb->state != CLOSED", pcb->state != CLOSED);
02088     LWIP_ASSERT("tcp_pcbs_sane: active pcb->state != LISTEN", pcb->state != LISTEN);
02089     LWIP_ASSERT("tcp_pcbs_sane: active pcb->state != TIME-WAIT", pcb->state != TIME_WAIT);
02090   }
02091   for (pcb = tcp_tw_pcbs; pcb != NULL; pcb = pcb->next) {
02092     LWIP_ASSERT("tcp_pcbs_sane: tw pcb->state == TIME-WAIT", pcb->state == TIME_WAIT);
02093   }
02094   return 1;
02095 }
02096 #endif /* TCP_DEBUG */
02097 
02098 #endif /* LWIP_TCP */