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