1/**
2 * @file
3 * Transmission Control Protocol for IP
4 * See also @ref tcp_raw
5 *
6 * @defgroup tcp_raw TCP
7 * @ingroup callbackstyle_api
8 * Transmission Control Protocol for IP\n
9 * @see @ref raw_api and @ref netconn
10 *
11 * Common functions for the TCP implementation, such as functinos
12 * for manipulating the data structures and the TCP timer functions. TCP functions
13 * related to input and output is found in tcp_in.c and tcp_out.c respectively.\n
14 */
15
16/*
17 * Copyright (c) 2001-2004 Swedish Institute of Computer Science.
18 * All rights reserved.
19 *
20 * Redistribution and use in source and binary forms, with or without modification,
21 * are permitted provided that the following conditions are met:
22 *
23 * 1. Redistributions of source code must retain the above copyright notice,
24 *    this list of conditions and the following disclaimer.
25 * 2. Redistributions in binary form must reproduce the above copyright notice,
26 *    this list of conditions and the following disclaimer in the documentation
27 *    and/or other materials provided with the distribution.
28 * 3. The name of the author may not be used to endorse or promote products
29 *    derived from this software without specific prior written permission.
30 *
31 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
32 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
33 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
34 * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
35 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
36 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
37 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
38 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
39 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
40 * OF SUCH DAMAGE.
41 *
42 * This file is part of the lwIP TCP/IP stack.
43 *
44 * Author: Adam Dunkels <adam@sics.se>
45 *
46 */
47
48#include "lwip/opt.h"
49
50#if LWIP_TCP /* don't build if not configured for use in lwipopts.h */
51
52#include "lwip/def.h"
53#include "lwip/mem.h"
54#include "lwip/memp.h"
55#include "lwip/tcp.h"
56#include "lwip/priv/tcp_priv.h"
57#include "lwip/debug.h"
58#include "lwip/stats.h"
59#include "lwip/ip6.h"
60#include "lwip/ip6_addr.h"
61#include "lwip/nd6.h"
62
63#include <string.h>
64
65#ifdef LWIP_HOOK_FILENAME
66#include LWIP_HOOK_FILENAME
67#endif
68
69#ifndef TCP_LOCAL_PORT_RANGE_START
70/* From http://www.iana.org/assignments/port-numbers:
71   "The Dynamic and/or Private Ports are those from 49152 through 65535" */
72#define TCP_LOCAL_PORT_RANGE_START        0xc000
73#define TCP_LOCAL_PORT_RANGE_END          0xffff
74#define TCP_ENSURE_LOCAL_PORT_RANGE(port) ((u16_t)(((port) & ~TCP_LOCAL_PORT_RANGE_START) + TCP_LOCAL_PORT_RANGE_START))
75#endif
76
77#if LWIP_TCP_KEEPALIVE
78#define TCP_KEEP_DUR(pcb)   ((pcb)->keep_cnt * (pcb)->keep_intvl)
79#define TCP_KEEP_INTVL(pcb) ((pcb)->keep_intvl)
80#else /* LWIP_TCP_KEEPALIVE */
81#define TCP_KEEP_DUR(pcb)   TCP_MAXIDLE
82#define TCP_KEEP_INTVL(pcb) TCP_KEEPINTVL_DEFAULT
83#endif /* LWIP_TCP_KEEPALIVE */
84
85/* As initial send MSS, we use TCP_MSS but limit it to 536. */
86#if TCP_MSS > 536
87#define INITIAL_MSS 536
88#else
89#define INITIAL_MSS TCP_MSS
90#endif
91
92static const char * const tcp_state_str[] = {
93  "CLOSED",
94  "LISTEN",
95  "SYN_SENT",
96  "SYN_RCVD",
97  "ESTABLISHED",
98  "FIN_WAIT_1",
99  "FIN_WAIT_2",
100  "CLOSE_WAIT",
101  "CLOSING",
102  "LAST_ACK",
103  "TIME_WAIT"
104};
105
106/* last local TCP port */
107static u16_t tcp_port = TCP_LOCAL_PORT_RANGE_START;
108
109/* Incremented every coarse grained timer shot (typically every 500 ms). */
110u32_t tcp_ticks;
111static const u8_t tcp_backoff[13] =
112    { 1, 2, 3, 4, 5, 6, 7, 7, 7, 7, 7, 7, 7};
113 /* Times per slowtmr hits */
114static const u8_t tcp_persist_backoff[7] = { 3, 6, 12, 24, 48, 96, 120 };
115
116/* The TCP PCB lists. */
117
118/** List of all TCP PCBs bound but not yet (connected || listening) */
119struct tcp_pcb *tcp_bound_pcbs;
120/** List of all TCP PCBs in LISTEN state */
121union tcp_listen_pcbs_t tcp_listen_pcbs;
122/** List of all TCP PCBs that are in a state in which
123 * they accept or send data. */
124struct tcp_pcb *tcp_active_pcbs;
125/** List of all TCP PCBs in TIME-WAIT state */
126struct tcp_pcb *tcp_tw_pcbs;
127
128/** An array with all (non-temporary) PCB lists, mainly used for smaller code size */
129struct tcp_pcb ** const tcp_pcb_lists[] = {&tcp_listen_pcbs.pcbs, &tcp_bound_pcbs,
130  &tcp_active_pcbs, &tcp_tw_pcbs};
131
132u8_t tcp_active_pcbs_changed;
133
134/** Timer counter to handle calling slow-timer from tcp_tmr() */
135static u8_t tcp_timer;
136static u8_t tcp_timer_ctr;
137static u16_t tcp_new_port(void);
138
139static err_t tcp_close_shutdown_fin(struct tcp_pcb *pcb);
140
141/**
142 * Initialize this module.
143 */
144void
145tcp_init(void)
146{
147#if LWIP_RANDOMIZE_INITIAL_LOCAL_PORTS && defined(LWIP_RAND)
148  tcp_port = TCP_ENSURE_LOCAL_PORT_RANGE(LWIP_RAND());
149#endif /* LWIP_RANDOMIZE_INITIAL_LOCAL_PORTS && defined(LWIP_RAND) */
150}
151
152/**
153 * Called periodically to dispatch TCP timers.
154 */
155void
156tcp_tmr(void)
157{
158  /* Call tcp_fasttmr() every 250 ms */
159  tcp_fasttmr();
160
161  if (++tcp_timer & 1) {
162    /* Call tcp_slowtmr() every 500 ms, i.e., every other timer
163       tcp_tmr() is called. */
164    tcp_slowtmr();
165  }
166}
167
168#if LWIP_CALLBACK_API || TCP_LISTEN_BACKLOG
169/** Called when a listen pcb is closed. Iterates one pcb list and removes the
170 * closed listener pcb from pcb->listener if matching.
171 */
172static void
173tcp_remove_listener(struct tcp_pcb *list, struct tcp_pcb_listen *lpcb)
174{
175   struct tcp_pcb *pcb;
176   for (pcb = list; pcb != NULL; pcb = pcb->next) {
177      if (pcb->listener == lpcb) {
178         pcb->listener = NULL;
179      }
180   }
181}
182#endif
183
184/** Called when a listen pcb is closed. Iterates all pcb lists and removes the
185 * closed listener pcb from pcb->listener if matching.
186 */
187static void
188tcp_listen_closed(struct tcp_pcb *pcb)
189{
190#if LWIP_CALLBACK_API || TCP_LISTEN_BACKLOG
191  size_t i;
192  LWIP_ASSERT("pcb != NULL", pcb != NULL);
193  LWIP_ASSERT("pcb->state == LISTEN", pcb->state == LISTEN);
194  for (i = 1; i < LWIP_ARRAYSIZE(tcp_pcb_lists); i++) {
195    tcp_remove_listener(*tcp_pcb_lists[i], (struct tcp_pcb_listen*)pcb);
196  }
197#endif
198  LWIP_UNUSED_ARG(pcb);
199}
200
201#if TCP_LISTEN_BACKLOG
202/** @ingroup tcp_raw
203 * Delay accepting a connection in respect to the listen backlog:
204 * the number of outstanding connections is increased until
205 * tcp_backlog_accepted() is called.
206 *
207 * ATTENTION: the caller is responsible for calling tcp_backlog_accepted()
208 * or else the backlog feature will get out of sync!
209 *
210 * @param pcb the connection pcb which is not fully accepted yet
211 */
212void
213tcp_backlog_delayed(struct tcp_pcb* pcb)
214{
215  LWIP_ASSERT("pcb != NULL", pcb != NULL);
216  if ((pcb->flags & TF_BACKLOGPEND) == 0) {
217    if (pcb->listener != NULL) {
218      pcb->listener->accepts_pending++;
219      LWIP_ASSERT("accepts_pending != 0", pcb->listener->accepts_pending != 0);
220      pcb->flags |= TF_BACKLOGPEND;
221    }
222  }
223}
224
225/** @ingroup tcp_raw
226 * A delayed-accept a connection is accepted (or closed/aborted): decreases
227 * the number of outstanding connections after calling tcp_backlog_delayed().
228 *
229 * ATTENTION: the caller is responsible for calling tcp_backlog_accepted()
230 * or else the backlog feature will get out of sync!
231 *
232 * @param pcb the connection pcb which is now fully accepted (or closed/aborted)
233 */
234void
235tcp_backlog_accepted(struct tcp_pcb* pcb)
236{
237  LWIP_ASSERT("pcb != NULL", pcb != NULL);
238  if ((pcb->flags & TF_BACKLOGPEND) != 0) {
239    if (pcb->listener != NULL) {
240      LWIP_ASSERT("accepts_pending != 0", pcb->listener->accepts_pending != 0);
241      pcb->listener->accepts_pending--;
242      pcb->flags &= ~TF_BACKLOGPEND;
243    }
244  }
245}
246#endif /* TCP_LISTEN_BACKLOG */
247
248/**
249 * Closes the TX side of a connection held by the PCB.
250 * For tcp_close(), a RST is sent if the application didn't receive all data
251 * (tcp_recved() not called for all data passed to recv callback).
252 *
253 * Listening pcbs are freed and may not be referenced any more.
254 * Connection pcbs are freed if not yet connected and may not be referenced
255 * any more. If a connection is established (at least SYN received or in
256 * a closing state), the connection is closed, and put in a closing state.
257 * The pcb is then automatically freed in tcp_slowtmr(). It is therefore
258 * unsafe to reference it.
259 *
260 * @param pcb the tcp_pcb to close
261 * @return ERR_OK if connection has been closed
262 *         another err_t if closing failed and pcb is not freed
263 */
264static err_t
265tcp_close_shutdown(struct tcp_pcb *pcb, u8_t rst_on_unacked_data)
266{
267  if (rst_on_unacked_data && ((pcb->state == ESTABLISHED) || (pcb->state == CLOSE_WAIT))) {
268    if ((pcb->refused_data != NULL) || (pcb->rcv_wnd != TCP_WND_MAX(pcb))) {
269      /* Not all data received by application, send RST to tell the remote
270         side about this. */
271      LWIP_ASSERT("pcb->flags & TF_RXCLOSED", pcb->flags & TF_RXCLOSED);
272
273      /* don't call tcp_abort here: we must not deallocate the pcb since
274         that might not be expected when calling tcp_close */
275      tcp_rst(pcb->snd_nxt, pcb->rcv_nxt, &pcb->local_ip, &pcb->remote_ip,
276               pcb->local_port, pcb->remote_port);
277
278      tcp_pcb_purge(pcb);
279      TCP_RMV_ACTIVE(pcb);
280      if (pcb->state == ESTABLISHED) {
281        /* move to TIME_WAIT since we close actively */
282        pcb->state = TIME_WAIT;
283        TCP_REG(&tcp_tw_pcbs, pcb);
284      } else {
285        /* CLOSE_WAIT: deallocate the pcb since we already sent a RST for it */
286        if (tcp_input_pcb == pcb) {
287          /* prevent using a deallocated pcb: free it from tcp_input later */
288          tcp_trigger_input_pcb_close();
289        } else {
290          memp_free(MEMP_TCP_PCB, pcb);
291        }
292      }
293      return ERR_OK;
294    }
295  }
296
297  /* - states which free the pcb are handled here,
298     - states which send FIN and change state are handled in tcp_close_shutdown_fin() */
299  switch (pcb->state) {
300  case CLOSED:
301    /* Closing a pcb in the CLOSED state might seem erroneous,
302     * however, it is in this state once allocated and as yet unused
303     * and the user needs some way to free it should the need arise.
304     * Calling tcp_close() with a pcb that has already been closed, (i.e. twice)
305     * or for a pcb that has been used and then entered the CLOSED state
306     * is erroneous, but this should never happen as the pcb has in those cases
307     * been freed, and so any remaining handles are bogus. */
308    if (pcb->local_port != 0) {
309      TCP_RMV(&tcp_bound_pcbs, pcb);
310    }
311    memp_free(MEMP_TCP_PCB, pcb);
312    break;
313  case LISTEN:
314    tcp_listen_closed(pcb);
315    tcp_pcb_remove(&tcp_listen_pcbs.pcbs, pcb);
316    memp_free(MEMP_TCP_PCB_LISTEN, pcb);
317    break;
318  case SYN_SENT:
319    TCP_PCB_REMOVE_ACTIVE(pcb);
320    memp_free(MEMP_TCP_PCB, pcb);
321    MIB2_STATS_INC(mib2.tcpattemptfails);
322    break;
323  default:
324    return tcp_close_shutdown_fin(pcb);
325  }
326  return ERR_OK;
327}
328
329static err_t
330tcp_close_shutdown_fin(struct tcp_pcb *pcb)
331{
332  err_t err;
333  LWIP_ASSERT("pcb != NULL", pcb != NULL);
334
335  switch (pcb->state) {
336  case SYN_RCVD:
337    err = tcp_send_fin(pcb);
338    if (err == ERR_OK) {
339      tcp_backlog_accepted(pcb);
340      MIB2_STATS_INC(mib2.tcpattemptfails);
341      pcb->state = FIN_WAIT_1;
342    }
343    break;
344  case ESTABLISHED:
345    err = tcp_send_fin(pcb);
346    if (err == ERR_OK) {
347      MIB2_STATS_INC(mib2.tcpestabresets);
348      pcb->state = FIN_WAIT_1;
349    }
350    break;
351  case CLOSE_WAIT:
352    err = tcp_send_fin(pcb);
353    if (err == ERR_OK) {
354      MIB2_STATS_INC(mib2.tcpestabresets);
355      pcb->state = LAST_ACK;
356    }
357    break;
358  default:
359    /* Has already been closed, do nothing. */
360    return ERR_OK;
361    break;
362  }
363
364  if (err == ERR_OK) {
365    /* To ensure all data has been sent when tcp_close returns, we have
366       to make sure tcp_output doesn't fail.
367       Since we don't really have to ensure all data has been sent when tcp_close
368       returns (unsent data is sent from tcp timer functions, also), we don't care
369       for the return value of tcp_output for now. */
370    tcp_output(pcb);
371  } else if (err == ERR_MEM) {
372    /* Mark this pcb for closing. Closing is retried from tcp_tmr. */
373    pcb->flags |= TF_CLOSEPEND;
374  }
375  return err;
376}
377
378/**
379 * @ingroup tcp_raw
380 * Closes the connection held by the PCB.
381 *
382 * Listening pcbs are freed and may not be referenced any more.
383 * Connection pcbs are freed if not yet connected and may not be referenced
384 * any more. If a connection is established (at least SYN received or in
385 * a closing state), the connection is closed, and put in a closing state.
386 * The pcb is then automatically freed in tcp_slowtmr(). It is therefore
387 * unsafe to reference it (unless an error is returned).
388 *
389 * @param pcb the tcp_pcb to close
390 * @return ERR_OK if connection has been closed
391 *         another err_t if closing failed and pcb is not freed
392 */
393err_t
394tcp_close(struct tcp_pcb *pcb)
395{
396  LWIP_DEBUGF(TCP_DEBUG, ("tcp_close: closing in "));
397  tcp_debug_print_state(pcb->state);
398
399  if (pcb->state != LISTEN) {
400    /* Set a flag not to receive any more data... */
401    pcb->flags |= TF_RXCLOSED;
402  }
403  /* ... and close */
404  return tcp_close_shutdown(pcb, 1);
405}
406
407/**
408 * @ingroup tcp_raw
409 * Causes all or part of a full-duplex connection of this PCB to be shut down.
410 * This doesn't deallocate the PCB unless shutting down both sides!
411 * Shutting down both sides is the same as calling tcp_close, so if it succeds,
412 * the PCB should not be referenced any more.
413 *
414 * @param pcb PCB to shutdown
415 * @param shut_rx shut down receive side if this is != 0
416 * @param shut_tx shut down send side if this is != 0
417 * @return ERR_OK if shutdown succeeded (or the PCB has already been shut down)
418 *         another err_t on error.
419 */
420err_t
421tcp_shutdown(struct tcp_pcb *pcb, int shut_rx, int shut_tx)
422{
423  if (pcb->state == LISTEN) {
424    return ERR_CONN;
425  }
426  if (shut_rx) {
427    /* shut down the receive side: set a flag not to receive any more data... */
428    pcb->flags |= TF_RXCLOSED;
429    if (shut_tx) {
430      /* shutting down the tx AND rx side is the same as closing for the raw API */
431      return tcp_close_shutdown(pcb, 1);
432    }
433    /* ... and free buffered data */
434    if (pcb->refused_data != NULL) {
435      pbuf_free(pcb->refused_data);
436      pcb->refused_data = NULL;
437    }
438  }
439  if (shut_tx) {
440    /* This can't happen twice since if it succeeds, the pcb's state is changed.
441       Only close in these states as the others directly deallocate the PCB */
442    switch (pcb->state) {
443    case SYN_RCVD:
444    case ESTABLISHED:
445    case CLOSE_WAIT:
446      return tcp_close_shutdown(pcb, (u8_t)shut_rx);
447    default:
448      /* Not (yet?) connected, cannot shutdown the TX side as that would bring us
449        into CLOSED state, where the PCB is deallocated. */
450      return ERR_CONN;
451    }
452  }
453  return ERR_OK;
454}
455
456/**
457 * Abandons a connection and optionally sends a RST to the remote
458 * host.  Deletes the local protocol control block. This is done when
459 * a connection is killed because of shortage of memory.
460 *
461 * @param pcb the tcp_pcb to abort
462 * @param reset boolean to indicate whether a reset should be sent
463 */
464void
465tcp_abandon(struct tcp_pcb *pcb, int reset)
466{
467  u32_t seqno, ackno;
468#if LWIP_CALLBACK_API
469  tcp_err_fn errf;
470#endif /* LWIP_CALLBACK_API */
471  void *errf_arg;
472
473  /* pcb->state LISTEN not allowed here */
474  LWIP_ASSERT("don't call tcp_abort/tcp_abandon for listen-pcbs",
475    pcb->state != LISTEN);
476  /* Figure out on which TCP PCB list we are, and remove us. If we
477     are in an active state, call the receive function associated with
478     the PCB with a NULL argument, and send an RST to the remote end. */
479  if (pcb->state == TIME_WAIT) {
480    tcp_pcb_remove(&tcp_tw_pcbs, pcb);
481    memp_free(MEMP_TCP_PCB, pcb);
482  } else {
483    int send_rst = 0;
484    u16_t local_port = 0;
485    enum tcp_state last_state;
486    seqno = pcb->snd_nxt;
487    ackno = pcb->rcv_nxt;
488#if LWIP_CALLBACK_API
489    errf = pcb->errf;
490#endif /* LWIP_CALLBACK_API */
491    errf_arg = pcb->callback_arg;
492    if (pcb->state == CLOSED) {
493      if (pcb->local_port != 0) {
494        /* bound, not yet opened */
495        TCP_RMV(&tcp_bound_pcbs, pcb);
496      }
497    } else {
498      send_rst = reset;
499      local_port = pcb->local_port;
500      TCP_PCB_REMOVE_ACTIVE(pcb);
501    }
502    if (pcb->unacked != NULL) {
503      tcp_segs_free(pcb->unacked);
504    }
505    if (pcb->unsent != NULL) {
506      tcp_segs_free(pcb->unsent);
507    }
508#if TCP_QUEUE_OOSEQ
509    if (pcb->ooseq != NULL) {
510      tcp_segs_free(pcb->ooseq);
511    }
512#endif /* TCP_QUEUE_OOSEQ */
513    tcp_backlog_accepted(pcb);
514    if (send_rst) {
515      LWIP_DEBUGF(TCP_RST_DEBUG, ("tcp_abandon: sending RST\n"));
516      tcp_rst(seqno, ackno, &pcb->local_ip, &pcb->remote_ip, local_port, pcb->remote_port);
517    }
518    last_state = pcb->state;
519    memp_free(MEMP_TCP_PCB, pcb);
520    TCP_EVENT_ERR(last_state, errf, errf_arg, ERR_ABRT);
521  }
522}
523
524/**
525 * @ingroup tcp_raw
526 * Aborts the connection by sending a RST (reset) segment to the remote
527 * host. The pcb is deallocated. This function never fails.
528 *
529 * ATTENTION: When calling this from one of the TCP callbacks, make
530 * sure you always return ERR_ABRT (and never return ERR_ABRT otherwise
531 * or you will risk accessing deallocated memory or memory leaks!
532 *
533 * @param pcb the tcp pcb to abort
534 */
535void
536tcp_abort(struct tcp_pcb *pcb)
537{
538  tcp_abandon(pcb, 1);
539}
540
541/**
542 * @ingroup tcp_raw
543 * Binds the connection to a local port number and IP address. If the
544 * IP address is not given (i.e., ipaddr == NULL), the IP address of
545 * the outgoing network interface is used instead.
546 *
547 * @param pcb the tcp_pcb to bind (no check is done whether this pcb is
548 *        already bound!)
549 * @param ipaddr the local ip address to bind to (use IP4_ADDR_ANY to bind
550 *        to any local address
551 * @param port the local port to bind to
552 * @return ERR_USE if the port is already in use
553 *         ERR_VAL if bind failed because the PCB is not in a valid state
554 *         ERR_OK if bound
555 */
556err_t
557tcp_bind(struct tcp_pcb *pcb, const ip_addr_t *ipaddr, u16_t port)
558{
559  int i;
560  int max_pcb_list = NUM_TCP_PCB_LISTS;
561  struct tcp_pcb *cpcb;
562
563#if LWIP_IPV4
564  /* Don't propagate NULL pointer (IPv4 ANY) to subsequent functions */
565  if (ipaddr == NULL) {
566    ipaddr = IP4_ADDR_ANY;
567  }
568#endif /* LWIP_IPV4 */
569
570  /* still need to check for ipaddr == NULL in IPv6 only case */
571  if ((pcb == NULL) || (ipaddr == NULL)) {
572    return ERR_VAL;
573  }
574
575  LWIP_ERROR("tcp_bind: can only bind in state CLOSED", pcb->state == CLOSED, return ERR_VAL);
576
577#if SO_REUSE
578  /* Unless the REUSEADDR flag is set,
579     we have to check the pcbs in TIME-WAIT state, also.
580     We do not dump TIME_WAIT pcb's; they can still be matched by incoming
581     packets using both local and remote IP addresses and ports to distinguish.
582   */
583  if (ip_get_option(pcb, SOF_REUSEADDR)) {
584    max_pcb_list = NUM_TCP_PCB_LISTS_NO_TIME_WAIT;
585  }
586#endif /* SO_REUSE */
587
588  if (port == 0) {
589    port = tcp_new_port();
590    if (port == 0) {
591      return ERR_BUF;
592    }
593  } else {
594    /* Check if the address already is in use (on all lists) */
595    for (i = 0; i < max_pcb_list; i++) {
596      for (cpcb = *tcp_pcb_lists[i]; cpcb != NULL; cpcb = cpcb->next) {
597        if (cpcb->local_port == port) {
598#if SO_REUSE
599          /* Omit checking for the same port if both pcbs have REUSEADDR set.
600             For SO_REUSEADDR, the duplicate-check for a 5-tuple is done in
601             tcp_connect. */
602          if (!ip_get_option(pcb, SOF_REUSEADDR) ||
603              !ip_get_option(cpcb, SOF_REUSEADDR))
604#endif /* SO_REUSE */
605          {
606            /* @todo: check accept_any_ip_version */
607            if ((IP_IS_V6(ipaddr) == IP_IS_V6_VAL(cpcb->local_ip)) &&
608                (ip_addr_isany(&cpcb->local_ip) ||
609                ip_addr_isany(ipaddr) ||
610                ip_addr_cmp(&cpcb->local_ip, ipaddr))) {
611              return ERR_USE;
612            }
613          }
614        }
615      }
616    }
617  }
618
619  if (!ip_addr_isany(ipaddr)) {
620    ip_addr_set(&pcb->local_ip, ipaddr);
621  }
622  pcb->local_port = port;
623  TCP_REG(&tcp_bound_pcbs, pcb);
624  LWIP_DEBUGF(TCP_DEBUG, ("tcp_bind: bind to port %"U16_F"\n", port));
625  return ERR_OK;
626}
627#if LWIP_CALLBACK_API
628/**
629 * Default accept callback if no accept callback is specified by the user.
630 */
631static err_t
632tcp_accept_null(void *arg, struct tcp_pcb *pcb, err_t err)
633{
634  LWIP_UNUSED_ARG(arg);
635  LWIP_UNUSED_ARG(err);
636
637  tcp_abort(pcb);
638
639  return ERR_ABRT;
640}
641#endif /* LWIP_CALLBACK_API */
642
643/**
644 * @ingroup tcp_raw
645 * Set the state of the connection to be LISTEN, which means that it
646 * is able to accept incoming connections. The protocol control block
647 * is reallocated in order to consume less memory. Setting the
648 * connection to LISTEN is an irreversible process.
649 *
650 * @param pcb the original tcp_pcb
651 * @param backlog the incoming connections queue limit
652 * @return tcp_pcb used for listening, consumes less memory.
653 *
654 * @note The original tcp_pcb is freed. This function therefore has to be
655 *       called like this:
656 *             tpcb = tcp_listen_with_backlog(tpcb, backlog);
657 */
658struct tcp_pcb *
659tcp_listen_with_backlog(struct tcp_pcb *pcb, u8_t backlog)
660{
661  return tcp_listen_with_backlog_and_err(pcb, backlog, NULL);
662}
663
664/**
665 * @ingroup tcp_raw
666 * Set the state of the connection to be LISTEN, which means that it
667 * is able to accept incoming connections. The protocol control block
668 * is reallocated in order to consume less memory. Setting the
669 * connection to LISTEN is an irreversible process.
670 *
671 * @param pcb the original tcp_pcb
672 * @param backlog the incoming connections queue limit
673 * @param err when NULL is returned, this contains the error reason
674 * @return tcp_pcb used for listening, consumes less memory.
675 *
676 * @note The original tcp_pcb is freed. This function therefore has to be
677 *       called like this:
678 *             tpcb = tcp_listen_with_backlog_and_err(tpcb, backlog, &err);
679 */
680struct tcp_pcb *
681tcp_listen_with_backlog_and_err(struct tcp_pcb *pcb, u8_t backlog, err_t *err)
682{
683  struct tcp_pcb_listen *lpcb = NULL;
684  err_t res;
685
686  LWIP_UNUSED_ARG(backlog);
687  LWIP_ERROR("tcp_listen: pcb already connected", pcb->state == CLOSED, res = ERR_CLSD; goto done);
688
689  /* already listening? */
690  if (pcb->state == LISTEN) {
691    lpcb = (struct tcp_pcb_listen*)pcb;
692    res = ERR_ALREADY;
693    goto done;
694  }
695#if SO_REUSE
696  if (ip_get_option(pcb, SOF_REUSEADDR)) {
697    /* Since SOF_REUSEADDR allows reusing a local address before the pcb's usage
698       is declared (listen-/connection-pcb), we have to make sure now that
699       this port is only used once for every local IP. */
700    for (lpcb = tcp_listen_pcbs.listen_pcbs; lpcb != NULL; lpcb = lpcb->next) {
701      if ((lpcb->local_port == pcb->local_port) &&
702          ip_addr_cmp(&lpcb->local_ip, &pcb->local_ip)) {
703        /* this address/port is already used */
704        lpcb = NULL;
705        res = ERR_USE;
706        goto done;
707      }
708    }
709  }
710#endif /* SO_REUSE */
711  lpcb = (struct tcp_pcb_listen *)memp_malloc(MEMP_TCP_PCB_LISTEN);
712  if (lpcb == NULL) {
713    res = ERR_MEM;
714    goto done;
715  }
716  lpcb->callback_arg = pcb->callback_arg;
717  lpcb->local_port = pcb->local_port;
718  lpcb->state = LISTEN;
719  lpcb->prio = pcb->prio;
720  lpcb->so_options = pcb->so_options;
721  lpcb->ttl = pcb->ttl;
722  lpcb->tos = pcb->tos;
723#if LWIP_IPV4 && LWIP_IPV6
724  IP_SET_TYPE_VAL(lpcb->remote_ip, pcb->local_ip.type);
725#endif /* LWIP_IPV4 && LWIP_IPV6 */
726  ip_addr_copy(lpcb->local_ip, pcb->local_ip);
727  if (pcb->local_port != 0) {
728    TCP_RMV(&tcp_bound_pcbs, pcb);
729  }
730  memp_free(MEMP_TCP_PCB, pcb);
731#if LWIP_CALLBACK_API
732  lpcb->accept = tcp_accept_null;
733#endif /* LWIP_CALLBACK_API */
734#if TCP_LISTEN_BACKLOG
735  lpcb->accepts_pending = 0;
736  tcp_backlog_set(lpcb, backlog);
737#endif /* TCP_LISTEN_BACKLOG */
738  TCP_REG(&tcp_listen_pcbs.pcbs, (struct tcp_pcb *)lpcb);
739  res = ERR_OK;
740done:
741  if (err != NULL) {
742    *err = res;
743  }
744  return (struct tcp_pcb *)lpcb;
745}
746
747/**
748 * Update the state that tracks the available window space to advertise.
749 *
750 * Returns how much extra window would be advertised if we sent an
751 * update now.
752 */
753u32_t
754tcp_update_rcv_ann_wnd(struct tcp_pcb *pcb)
755{
756  u32_t new_right_edge = pcb->rcv_nxt + pcb->rcv_wnd;
757
758  if (TCP_SEQ_GEQ(new_right_edge, pcb->rcv_ann_right_edge + LWIP_MIN((TCP_WND / 2), pcb->mss))) {
759    /* we can advertise more window */
760    pcb->rcv_ann_wnd = pcb->rcv_wnd;
761    return new_right_edge - pcb->rcv_ann_right_edge;
762  } else {
763    if (TCP_SEQ_GT(pcb->rcv_nxt, pcb->rcv_ann_right_edge)) {
764      /* Can happen due to other end sending out of advertised window,
765       * but within actual available (but not yet advertised) window */
766      pcb->rcv_ann_wnd = 0;
767    } else {
768      /* keep the right edge of window constant */
769      u32_t new_rcv_ann_wnd = pcb->rcv_ann_right_edge - pcb->rcv_nxt;
770#if !LWIP_WND_SCALE
771      LWIP_ASSERT("new_rcv_ann_wnd <= 0xffff", new_rcv_ann_wnd <= 0xffff);
772#endif
773      pcb->rcv_ann_wnd = (tcpwnd_size_t)new_rcv_ann_wnd;
774    }
775    return 0;
776  }
777}
778
779/**
780 * @ingroup tcp_raw
781 * This function should be called by the application when it has
782 * processed the data. The purpose is to advertise a larger window
783 * when the data has been processed.
784 *
785 * @param pcb the tcp_pcb for which data is read
786 * @param len the amount of bytes that have been read by the application
787 */
788void
789tcp_recved(struct tcp_pcb *pcb, u16_t len)
790{
791  int wnd_inflation;
792
793  /* pcb->state LISTEN not allowed here */
794  LWIP_ASSERT("don't call tcp_recved for listen-pcbs",
795    pcb->state != LISTEN);
796
797  pcb->rcv_wnd += len;
798  if (pcb->rcv_wnd > TCP_WND_MAX(pcb)) {
799    pcb->rcv_wnd = TCP_WND_MAX(pcb);
800  } else if (pcb->rcv_wnd == 0) {
801    /* rcv_wnd overflowed */
802    if ((pcb->state == CLOSE_WAIT) || (pcb->state == LAST_ACK)) {
803      /* In passive close, we allow this, since the FIN bit is added to rcv_wnd
804         by the stack itself, since it is not mandatory for an application
805         to call tcp_recved() for the FIN bit, but e.g. the netconn API does so. */
806      pcb->rcv_wnd = TCP_WND_MAX(pcb);
807    } else {
808      LWIP_ASSERT("tcp_recved: len wrapped rcv_wnd\n", 0);
809    }
810  }
811
812  wnd_inflation = tcp_update_rcv_ann_wnd(pcb);
813
814  /* If the change in the right edge of window is significant (default
815   * watermark is TCP_WND/4), then send an explicit update now.
816   * Otherwise wait for a packet to be sent in the normal course of
817   * events (or more window to be available later) */
818  if (wnd_inflation >= TCP_WND_UPDATE_THRESHOLD) {
819    tcp_ack_now(pcb);
820    tcp_output(pcb);
821  }
822
823  LWIP_DEBUGF(TCP_DEBUG, ("tcp_recved: received %"U16_F" bytes, wnd %"TCPWNDSIZE_F" (%"TCPWNDSIZE_F").\n",
824         len, pcb->rcv_wnd, (u16_t)(TCP_WND_MAX(pcb) - pcb->rcv_wnd)));
825}
826
827/**
828 * Allocate a new local TCP port.
829 *
830 * @return a new (free) local TCP port number
831 */
832static u16_t
833tcp_new_port(void)
834{
835  u8_t i;
836  u16_t n = 0;
837  struct tcp_pcb *pcb;
838
839again:
840  if (tcp_port++ == TCP_LOCAL_PORT_RANGE_END) {
841    tcp_port = TCP_LOCAL_PORT_RANGE_START;
842  }
843  /* Check all PCB lists. */
844  for (i = 0; i < NUM_TCP_PCB_LISTS; i++) {
845    for (pcb = *tcp_pcb_lists[i]; pcb != NULL; pcb = pcb->next) {
846      if (pcb->local_port == tcp_port) {
847        if (++n > (TCP_LOCAL_PORT_RANGE_END - TCP_LOCAL_PORT_RANGE_START)) {
848          return 0;
849        }
850        goto again;
851      }
852    }
853  }
854  return tcp_port;
855}
856
857/**
858 * @ingroup tcp_raw
859 * Connects to another host. The function given as the "connected"
860 * argument will be called when the connection has been established.
861 *
862 * @param pcb the tcp_pcb used to establish the connection
863 * @param ipaddr the remote ip address to connect to
864 * @param port the remote tcp port to connect to
865 * @param connected callback function to call when connected (on error,
866                    the err calback will be called)
867 * @return ERR_VAL if invalid arguments are given
868 *         ERR_OK if connect request has been sent
869 *         other err_t values if connect request couldn't be sent
870 */
871err_t
872tcp_connect(struct tcp_pcb *pcb, const ip_addr_t *ipaddr, u16_t port,
873      tcp_connected_fn connected)
874{
875  err_t ret;
876  u32_t iss;
877  u16_t old_local_port;
878
879  if ((pcb == NULL) || (ipaddr == NULL)) {
880    return ERR_VAL;
881  }
882
883  LWIP_ERROR("tcp_connect: can only connect from state CLOSED", pcb->state == CLOSED, return ERR_ISCONN);
884
885  LWIP_DEBUGF(TCP_DEBUG, ("tcp_connect to port %"U16_F"\n", port));
886  ip_addr_set(&pcb->remote_ip, ipaddr);
887  pcb->remote_port = port;
888
889  /* check if we have a route to the remote host */
890  if (ip_addr_isany(&pcb->local_ip)) {
891    /* no local IP address set, yet. */
892    struct netif *netif;
893    const ip_addr_t *local_ip;
894    ip_route_get_local_ip(&pcb->local_ip, &pcb->remote_ip, netif, local_ip);
895    if ((netif == NULL) || (local_ip == NULL)) {
896      /* Don't even try to send a SYN packet if we have no route
897         since that will fail. */
898      return ERR_RTE;
899    }
900    /* Use the address as local address of the pcb. */
901    ip_addr_copy(pcb->local_ip, *local_ip);
902  }
903
904  old_local_port = pcb->local_port;
905  if (pcb->local_port == 0) {
906    pcb->local_port = tcp_new_port();
907    if (pcb->local_port == 0) {
908      return ERR_BUF;
909    }
910  } else {
911#if SO_REUSE
912    if (ip_get_option(pcb, SOF_REUSEADDR)) {
913      /* Since SOF_REUSEADDR allows reusing a local address, we have to make sure
914         now that the 5-tuple is unique. */
915      struct tcp_pcb *cpcb;
916      int i;
917      /* Don't check listen- and bound-PCBs, check active- and TIME-WAIT PCBs. */
918      for (i = 2; i < NUM_TCP_PCB_LISTS; i++) {
919        for (cpcb = *tcp_pcb_lists[i]; cpcb != NULL; cpcb = cpcb->next) {
920          if ((cpcb->local_port == pcb->local_port) &&
921              (cpcb->remote_port == port) &&
922              ip_addr_cmp(&cpcb->local_ip, &pcb->local_ip) &&
923              ip_addr_cmp(&cpcb->remote_ip, ipaddr)) {
924            /* linux returns EISCONN here, but ERR_USE should be OK for us */
925            return ERR_USE;
926          }
927        }
928      }
929    }
930#endif /* SO_REUSE */
931  }
932
933  iss = tcp_next_iss(pcb);
934  pcb->rcv_nxt = 0;
935  pcb->snd_nxt = iss;
936  pcb->lastack = iss - 1;
937  pcb->snd_wl2 = iss - 1;
938  pcb->snd_lbb = iss - 1;
939  /* Start with a window that does not need scaling. When window scaling is
940     enabled and used, the window is enlarged when both sides agree on scaling. */
941  pcb->rcv_wnd = pcb->rcv_ann_wnd = TCPWND_MIN16(TCP_WND);
942  pcb->rcv_ann_right_edge = pcb->rcv_nxt;
943  pcb->snd_wnd = TCP_WND;
944  /* As initial send MSS, we use TCP_MSS but limit it to 536.
945     The send MSS is updated when an MSS option is received. */
946  pcb->mss = INITIAL_MSS;
947#if TCP_CALCULATE_EFF_SEND_MSS
948  pcb->mss = tcp_eff_send_mss(pcb->mss, &pcb->local_ip, &pcb->remote_ip);
949#endif /* TCP_CALCULATE_EFF_SEND_MSS */
950  pcb->cwnd = 1;
951#if LWIP_CALLBACK_API
952  pcb->connected = connected;
953#else /* LWIP_CALLBACK_API */
954  LWIP_UNUSED_ARG(connected);
955#endif /* LWIP_CALLBACK_API */
956
957  /* Send a SYN together with the MSS option. */
958  ret = tcp_enqueue_flags(pcb, TCP_SYN);
959  if (ret == ERR_OK) {
960    /* SYN segment was enqueued, changed the pcbs state now */
961    pcb->state = SYN_SENT;
962    if (old_local_port != 0) {
963      TCP_RMV(&tcp_bound_pcbs, pcb);
964    }
965    TCP_REG_ACTIVE(pcb);
966    MIB2_STATS_INC(mib2.tcpactiveopens);
967
968    tcp_output(pcb);
969  }
970  return ret;
971}
972
973/**
974 * Called every 500 ms and implements the retransmission timer and the timer that
975 * removes PCBs that have been in TIME-WAIT for enough time. It also increments
976 * various timers such as the inactivity timer in each PCB.
977 *
978 * Automatically called from tcp_tmr().
979 */
980void
981tcp_slowtmr(void)
982{
983  struct tcp_pcb *pcb, *prev;
984  tcpwnd_size_t eff_wnd;
985  u8_t pcb_remove;      /* flag if a PCB should be removed */
986  u8_t pcb_reset;       /* flag if a RST should be sent when removing */
987  err_t err;
988
989  err = ERR_OK;
990
991  ++tcp_ticks;
992  ++tcp_timer_ctr;
993
994tcp_slowtmr_start:
995  /* Steps through all of the active PCBs. */
996  prev = NULL;
997  pcb = tcp_active_pcbs;
998  if (pcb == NULL) {
999    LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: no active pcbs\n"));
1000  }
1001  while (pcb != NULL) {
1002    LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: processing active pcb\n"));
1003    LWIP_ASSERT("tcp_slowtmr: active pcb->state != CLOSED\n", pcb->state != CLOSED);
1004    LWIP_ASSERT("tcp_slowtmr: active pcb->state != LISTEN\n", pcb->state != LISTEN);
1005    LWIP_ASSERT("tcp_slowtmr: active pcb->state != TIME-WAIT\n", pcb->state != TIME_WAIT);
1006    if (pcb->last_timer == tcp_timer_ctr) {
1007      /* skip this pcb, we have already processed it */
1008      pcb = pcb->next;
1009      continue;
1010    }
1011    pcb->last_timer = tcp_timer_ctr;
1012
1013    pcb_remove = 0;
1014    pcb_reset = 0;
1015
1016    if (pcb->state == SYN_SENT && pcb->nrtx >= TCP_SYNMAXRTX) {
1017      ++pcb_remove;
1018      LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: max SYN retries reached\n"));
1019    }
1020    else if (pcb->nrtx >= TCP_MAXRTX) {
1021      ++pcb_remove;
1022      LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: max DATA retries reached\n"));
1023    } else {
1024      if (pcb->persist_backoff > 0) {
1025        /* If snd_wnd is zero, use persist timer to send 1 byte probes
1026         * instead of using the standard retransmission mechanism. */
1027        u8_t backoff_cnt = tcp_persist_backoff[pcb->persist_backoff-1];
1028        if (pcb->persist_cnt < backoff_cnt) {
1029          pcb->persist_cnt++;
1030        }
1031        if (pcb->persist_cnt >= backoff_cnt) {
1032          if (tcp_zero_window_probe(pcb) == ERR_OK) {
1033            pcb->persist_cnt = 0;
1034            if (pcb->persist_backoff < sizeof(tcp_persist_backoff)) {
1035              pcb->persist_backoff++;
1036            }
1037          }
1038        }
1039      } else {
1040        /* Increase the retransmission timer if it is running */
1041        if (pcb->rtime >= 0) {
1042          ++pcb->rtime;
1043        }
1044
1045        if (pcb->unacked != NULL && pcb->rtime >= pcb->rto) {
1046          /* Time for a retransmission. */
1047          LWIP_DEBUGF(TCP_RTO_DEBUG, ("tcp_slowtmr: rtime %"S16_F
1048                                      " pcb->rto %"S16_F"\n",
1049                                      pcb->rtime, pcb->rto));
1050
1051          /* Double retransmission time-out unless we are trying to
1052           * connect to somebody (i.e., we are in SYN_SENT). */
1053          if (pcb->state != SYN_SENT) {
1054            u8_t backoff_idx = LWIP_MIN(pcb->nrtx, sizeof(tcp_backoff)-1);
1055            pcb->rto = ((pcb->sa >> 3) + pcb->sv) << tcp_backoff[backoff_idx];
1056          }
1057
1058          /* Reset the retransmission timer. */
1059          pcb->rtime = 0;
1060
1061          /* Reduce congestion window and ssthresh. */
1062          eff_wnd = LWIP_MIN(pcb->cwnd, pcb->snd_wnd);
1063          pcb->ssthresh = eff_wnd >> 1;
1064          if (pcb->ssthresh < (tcpwnd_size_t)(pcb->mss << 1)) {
1065            pcb->ssthresh = (pcb->mss << 1);
1066          }
1067          pcb->cwnd = pcb->mss;
1068          LWIP_DEBUGF(TCP_CWND_DEBUG, ("tcp_slowtmr: cwnd %"TCPWNDSIZE_F
1069                                       " ssthresh %"TCPWNDSIZE_F"\n",
1070                                       pcb->cwnd, pcb->ssthresh));
1071
1072          /* The following needs to be called AFTER cwnd is set to one
1073             mss - STJ */
1074          tcp_rexmit_rto(pcb);
1075        }
1076      }
1077    }
1078    /* Check if this PCB has stayed too long in FIN-WAIT-2 */
1079    if (pcb->state == FIN_WAIT_2) {
1080      /* If this PCB is in FIN_WAIT_2 because of SHUT_WR don't let it time out. */
1081      if (pcb->flags & TF_RXCLOSED) {
1082        /* PCB was fully closed (either through close() or SHUT_RDWR):
1083           normal FIN-WAIT timeout handling. */
1084        if ((u32_t)(tcp_ticks - pcb->tmr) >
1085            TCP_FIN_WAIT_TIMEOUT / TCP_SLOW_INTERVAL) {
1086          ++pcb_remove;
1087          LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: removing pcb stuck in FIN-WAIT-2\n"));
1088        }
1089      }
1090    }
1091
1092    /* Check if KEEPALIVE should be sent */
1093    if (ip_get_option(pcb, SOF_KEEPALIVE) &&
1094       ((pcb->state == ESTABLISHED) ||
1095        (pcb->state == CLOSE_WAIT))) {
1096      if ((u32_t)(tcp_ticks - pcb->tmr) >
1097         (pcb->keep_idle + TCP_KEEP_DUR(pcb)) / TCP_SLOW_INTERVAL)
1098      {
1099        LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: KEEPALIVE timeout. Aborting connection to "));
1100        ip_addr_debug_print(TCP_DEBUG, &pcb->remote_ip);
1101        LWIP_DEBUGF(TCP_DEBUG, ("\n"));
1102
1103        ++pcb_remove;
1104        ++pcb_reset;
1105      } else if ((u32_t)(tcp_ticks - pcb->tmr) >
1106                (pcb->keep_idle + pcb->keep_cnt_sent * TCP_KEEP_INTVL(pcb))
1107                / TCP_SLOW_INTERVAL)
1108      {
1109        err = tcp_keepalive(pcb);
1110        if (err == ERR_OK) {
1111          pcb->keep_cnt_sent++;
1112        }
1113      }
1114    }
1115
1116    /* If this PCB has queued out of sequence data, but has been
1117       inactive for too long, will drop the data (it will eventually
1118       be retransmitted). */
1119#if TCP_QUEUE_OOSEQ
1120    if (pcb->ooseq != NULL &&
1121        (u32_t)tcp_ticks - pcb->tmr >= pcb->rto * TCP_OOSEQ_TIMEOUT) {
1122      tcp_segs_free(pcb->ooseq);
1123      pcb->ooseq = NULL;
1124      LWIP_DEBUGF(TCP_CWND_DEBUG, ("tcp_slowtmr: dropping OOSEQ queued data\n"));
1125    }
1126#endif /* TCP_QUEUE_OOSEQ */
1127
1128    /* Check if this PCB has stayed too long in SYN-RCVD */
1129    if (pcb->state == SYN_RCVD) {
1130      if ((u32_t)(tcp_ticks - pcb->tmr) >
1131          TCP_SYN_RCVD_TIMEOUT / TCP_SLOW_INTERVAL) {
1132        ++pcb_remove;
1133        LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: removing pcb stuck in SYN-RCVD\n"));
1134      }
1135    }
1136
1137    /* Check if this PCB has stayed too long in LAST-ACK */
1138    if (pcb->state == LAST_ACK) {
1139      if ((u32_t)(tcp_ticks - pcb->tmr) > 2 * TCP_MSL / TCP_SLOW_INTERVAL) {
1140        ++pcb_remove;
1141        LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: removing pcb stuck in LAST-ACK\n"));
1142      }
1143    }
1144
1145    /* If the PCB should be removed, do it. */
1146    if (pcb_remove) {
1147      struct tcp_pcb *pcb2;
1148#if LWIP_CALLBACK_API
1149      tcp_err_fn err_fn = pcb->errf;
1150#endif /* LWIP_CALLBACK_API */
1151      void *err_arg;
1152      enum tcp_state last_state;
1153      tcp_pcb_purge(pcb);
1154      /* Remove PCB from tcp_active_pcbs list. */
1155      if (prev != NULL) {
1156        LWIP_ASSERT("tcp_slowtmr: middle tcp != tcp_active_pcbs", pcb != tcp_active_pcbs);
1157        prev->next = pcb->next;
1158      } else {
1159        /* This PCB was the first. */
1160        LWIP_ASSERT("tcp_slowtmr: first pcb == tcp_active_pcbs", tcp_active_pcbs == pcb);
1161        tcp_active_pcbs = pcb->next;
1162      }
1163
1164      if (pcb_reset) {
1165        tcp_rst(pcb->snd_nxt, pcb->rcv_nxt, &pcb->local_ip, &pcb->remote_ip,
1166                 pcb->local_port, pcb->remote_port);
1167      }
1168
1169      err_arg = pcb->callback_arg;
1170      last_state = pcb->state;
1171      pcb2 = pcb;
1172      pcb = pcb->next;
1173      memp_free(MEMP_TCP_PCB, pcb2);
1174
1175      tcp_active_pcbs_changed = 0;
1176      TCP_EVENT_ERR(last_state, err_fn, err_arg, ERR_ABRT);
1177      if (tcp_active_pcbs_changed) {
1178        goto tcp_slowtmr_start;
1179      }
1180    } else {
1181      /* get the 'next' element now and work with 'prev' below (in case of abort) */
1182      prev = pcb;
1183      pcb = pcb->next;
1184
1185      /* We check if we should poll the connection. */
1186      ++prev->polltmr;
1187      if (prev->polltmr >= prev->pollinterval) {
1188        prev->polltmr = 0;
1189        LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: polling application\n"));
1190        tcp_active_pcbs_changed = 0;
1191        TCP_EVENT_POLL(prev, err);
1192        if (tcp_active_pcbs_changed) {
1193          goto tcp_slowtmr_start;
1194        }
1195        /* if err == ERR_ABRT, 'prev' is already deallocated */
1196        if (err == ERR_OK) {
1197          tcp_output(prev);
1198        }
1199      }
1200    }
1201  }
1202
1203
1204  /* Steps through all of the TIME-WAIT PCBs. */
1205  prev = NULL;
1206  pcb = tcp_tw_pcbs;
1207  while (pcb != NULL) {
1208    LWIP_ASSERT("tcp_slowtmr: TIME-WAIT pcb->state == TIME-WAIT", pcb->state == TIME_WAIT);
1209    pcb_remove = 0;
1210
1211    /* Check if this PCB has stayed long enough in TIME-WAIT */
1212    if ((u32_t)(tcp_ticks - pcb->tmr) > 2 * TCP_MSL / TCP_SLOW_INTERVAL) {
1213      ++pcb_remove;
1214    }
1215
1216    /* If the PCB should be removed, do it. */
1217    if (pcb_remove) {
1218      struct tcp_pcb *pcb2;
1219      tcp_pcb_purge(pcb);
1220      /* Remove PCB from tcp_tw_pcbs list. */
1221      if (prev != NULL) {
1222        LWIP_ASSERT("tcp_slowtmr: middle tcp != tcp_tw_pcbs", pcb != tcp_tw_pcbs);
1223        prev->next = pcb->next;
1224      } else {
1225        /* This PCB was the first. */
1226        LWIP_ASSERT("tcp_slowtmr: first pcb == tcp_tw_pcbs", tcp_tw_pcbs == pcb);
1227        tcp_tw_pcbs = pcb->next;
1228      }
1229      pcb2 = pcb;
1230      pcb = pcb->next;
1231      memp_free(MEMP_TCP_PCB, pcb2);
1232    } else {
1233      prev = pcb;
1234      pcb = pcb->next;
1235    }
1236  }
1237}
1238
1239/**
1240 * Is called every TCP_FAST_INTERVAL (250 ms) and process data previously
1241 * "refused" by upper layer (application) and sends delayed ACKs.
1242 *
1243 * Automatically called from tcp_tmr().
1244 */
1245void
1246tcp_fasttmr(void)
1247{
1248  struct tcp_pcb *pcb;
1249
1250  ++tcp_timer_ctr;
1251
1252tcp_fasttmr_start:
1253  pcb = tcp_active_pcbs;
1254
1255  while (pcb != NULL) {
1256    if (pcb->last_timer != tcp_timer_ctr) {
1257      struct tcp_pcb *next;
1258      pcb->last_timer = tcp_timer_ctr;
1259      /* send delayed ACKs */
1260      if (pcb->flags & TF_ACK_DELAY) {
1261        LWIP_DEBUGF(TCP_DEBUG, ("tcp_fasttmr: delayed ACK\n"));
1262        tcp_ack_now(pcb);
1263        tcp_output(pcb);
1264        pcb->flags &= ~(TF_ACK_DELAY | TF_ACK_NOW);
1265      }
1266      /* send pending FIN */
1267      if (pcb->flags & TF_CLOSEPEND) {
1268        LWIP_DEBUGF(TCP_DEBUG, ("tcp_fasttmr: pending FIN\n"));
1269        pcb->flags &= ~(TF_CLOSEPEND);
1270        tcp_close_shutdown_fin(pcb);
1271      }
1272
1273      next = pcb->next;
1274
1275      /* If there is data which was previously "refused" by upper layer */
1276      if (pcb->refused_data != NULL) {
1277        tcp_active_pcbs_changed = 0;
1278        tcp_process_refused_data(pcb);
1279        if (tcp_active_pcbs_changed) {
1280          /* application callback has changed the pcb list: restart the loop */
1281          goto tcp_fasttmr_start;
1282        }
1283      }
1284      pcb = next;
1285    } else {
1286      pcb = pcb->next;
1287    }
1288  }
1289}
1290
1291/** Call tcp_output for all active pcbs that have TF_NAGLEMEMERR set */
1292void
1293tcp_txnow(void)
1294{
1295  struct tcp_pcb *pcb;
1296
1297  for (pcb = tcp_active_pcbs; pcb != NULL; pcb = pcb->next) {
1298    if (pcb->flags & TF_NAGLEMEMERR) {
1299      tcp_output(pcb);
1300    }
1301  }
1302}
1303
1304/** Pass pcb->refused_data to the recv callback */
1305err_t
1306tcp_process_refused_data(struct tcp_pcb *pcb)
1307{
1308#if TCP_QUEUE_OOSEQ && LWIP_WND_SCALE
1309  struct pbuf *rest;
1310  while (pcb->refused_data != NULL)
1311#endif /* TCP_QUEUE_OOSEQ && LWIP_WND_SCALE */
1312  {
1313    err_t err;
1314    u8_t refused_flags = pcb->refused_data->flags;
1315    /* set pcb->refused_data to NULL in case the callback frees it and then
1316       closes the pcb */
1317    struct pbuf *refused_data = pcb->refused_data;
1318#if TCP_QUEUE_OOSEQ && LWIP_WND_SCALE
1319    pbuf_split_64k(refused_data, &rest);
1320    pcb->refused_data = rest;
1321#else /* TCP_QUEUE_OOSEQ && LWIP_WND_SCALE */
1322    pcb->refused_data = NULL;
1323#endif /* TCP_QUEUE_OOSEQ && LWIP_WND_SCALE */
1324    /* Notify again application with data previously received. */
1325    LWIP_DEBUGF(TCP_INPUT_DEBUG, ("tcp_input: notify kept packet\n"));
1326    TCP_EVENT_RECV(pcb, refused_data, ERR_OK, err);
1327    if (err == ERR_OK) {
1328      /* did refused_data include a FIN? */
1329      if (refused_flags & PBUF_FLAG_TCP_FIN
1330#if TCP_QUEUE_OOSEQ && LWIP_WND_SCALE
1331          && (rest == NULL)
1332#endif /* TCP_QUEUE_OOSEQ && LWIP_WND_SCALE */
1333         ) {
1334        /* correct rcv_wnd as the application won't call tcp_recved()
1335           for the FIN's seqno */
1336        if (pcb->rcv_wnd != TCP_WND_MAX(pcb)) {
1337          pcb->rcv_wnd++;
1338        }
1339        TCP_EVENT_CLOSED(pcb, err);
1340        if (err == ERR_ABRT) {
1341          return ERR_ABRT;
1342        }
1343      }
1344    } else if (err == ERR_ABRT) {
1345      /* if err == ERR_ABRT, 'pcb' is already deallocated */
1346      /* Drop incoming packets because pcb is "full" (only if the incoming
1347         segment contains data). */
1348      LWIP_DEBUGF(TCP_INPUT_DEBUG, ("tcp_input: drop incoming packets, because pcb is \"full\"\n"));
1349      return ERR_ABRT;
1350    } else {
1351      /* data is still refused, pbuf is still valid (go on for ACK-only packets) */
1352#if TCP_QUEUE_OOSEQ && LWIP_WND_SCALE
1353      if (rest != NULL) {
1354        pbuf_cat(refused_data, rest);
1355      }
1356#endif /* TCP_QUEUE_OOSEQ && LWIP_WND_SCALE */
1357      pcb->refused_data = refused_data;
1358      return ERR_INPROGRESS;
1359    }
1360  }
1361  return ERR_OK;
1362}
1363
1364/**
1365 * Deallocates a list of TCP segments (tcp_seg structures).
1366 *
1367 * @param seg tcp_seg list of TCP segments to free
1368 */
1369void
1370tcp_segs_free(struct tcp_seg *seg)
1371{
1372  while (seg != NULL) {
1373    struct tcp_seg *next = seg->next;
1374    tcp_seg_free(seg);
1375    seg = next;
1376  }
1377}
1378
1379/**
1380 * Frees a TCP segment (tcp_seg structure).
1381 *
1382 * @param seg single tcp_seg to free
1383 */
1384void
1385tcp_seg_free(struct tcp_seg *seg)
1386{
1387  if (seg != NULL) {
1388    if (seg->p != NULL) {
1389      pbuf_free(seg->p);
1390#if TCP_DEBUG
1391      seg->p = NULL;
1392#endif /* TCP_DEBUG */
1393    }
1394    memp_free(MEMP_TCP_SEG, seg);
1395  }
1396}
1397
1398/**
1399 * Sets the priority of a connection.
1400 *
1401 * @param pcb the tcp_pcb to manipulate
1402 * @param prio new priority
1403 */
1404void
1405tcp_setprio(struct tcp_pcb *pcb, u8_t prio)
1406{
1407  pcb->prio = prio;
1408}
1409
1410#if TCP_QUEUE_OOSEQ
1411/**
1412 * Returns a copy of the given TCP segment.
1413 * The pbuf and data are not copied, only the pointers
1414 *
1415 * @param seg the old tcp_seg
1416 * @return a copy of seg
1417 */
1418struct tcp_seg *
1419tcp_seg_copy(struct tcp_seg *seg)
1420{
1421  struct tcp_seg *cseg;
1422
1423  cseg = (struct tcp_seg *)memp_malloc(MEMP_TCP_SEG);
1424  if (cseg == NULL) {
1425    return NULL;
1426  }
1427  SMEMCPY((u8_t *)cseg, (const u8_t *)seg, sizeof(struct tcp_seg));
1428  pbuf_ref(cseg->p);
1429  return cseg;
1430}
1431#endif /* TCP_QUEUE_OOSEQ */
1432
1433#if LWIP_CALLBACK_API
1434/**
1435 * Default receive callback that is called if the user didn't register
1436 * a recv callback for the pcb.
1437 */
1438err_t
1439tcp_recv_null(void *arg, struct tcp_pcb *pcb, struct pbuf *p, err_t err)
1440{
1441  LWIP_UNUSED_ARG(arg);
1442  if (p != NULL) {
1443    tcp_recved(pcb, p->tot_len);
1444    pbuf_free(p);
1445  } else if (err == ERR_OK) {
1446    return tcp_close(pcb);
1447  }
1448  return ERR_OK;
1449}
1450#endif /* LWIP_CALLBACK_API */
1451
1452/**
1453 * Kills the oldest active connection that has the same or lower priority than
1454 * 'prio'.
1455 *
1456 * @param prio minimum priority
1457 */
1458static void
1459tcp_kill_prio(u8_t prio)
1460{
1461  struct tcp_pcb *pcb, *inactive;
1462  u32_t inactivity;
1463  u8_t mprio;
1464
1465  mprio = LWIP_MIN(TCP_PRIO_MAX, prio);
1466
1467  /* We kill the oldest active connection that has lower priority than prio. */
1468  inactivity = 0;
1469  inactive = NULL;
1470  for (pcb = tcp_active_pcbs; pcb != NULL; pcb = pcb->next) {
1471    if (pcb->prio <= mprio &&
1472       (u32_t)(tcp_ticks - pcb->tmr) >= inactivity) {
1473      inactivity = tcp_ticks - pcb->tmr;
1474      inactive = pcb;
1475      mprio = pcb->prio;
1476    }
1477  }
1478  if (inactive != NULL) {
1479    LWIP_DEBUGF(TCP_DEBUG, ("tcp_kill_prio: killing oldest PCB %p (%"S32_F")\n",
1480           (void *)inactive, inactivity));
1481    tcp_abort(inactive);
1482  }
1483}
1484
1485/**
1486 * Kills the oldest connection that is in specific state.
1487 * Called from tcp_alloc() for LAST_ACK and CLOSING if no more connections are available.
1488 */
1489static void
1490tcp_kill_state(enum tcp_state state)
1491{
1492  struct tcp_pcb *pcb, *inactive;
1493  u32_t inactivity;
1494
1495  LWIP_ASSERT("invalid state", (state == CLOSING) || (state == LAST_ACK));
1496
1497  inactivity = 0;
1498  inactive = NULL;
1499  /* Go through the list of active pcbs and get the oldest pcb that is in state
1500     CLOSING/LAST_ACK. */
1501  for (pcb = tcp_active_pcbs; pcb != NULL; pcb = pcb->next) {
1502    if (pcb->state == state) {
1503      if ((u32_t)(tcp_ticks - pcb->tmr) >= inactivity) {
1504        inactivity = tcp_ticks - pcb->tmr;
1505        inactive = pcb;
1506      }
1507    }
1508  }
1509  if (inactive != NULL) {
1510    LWIP_DEBUGF(TCP_DEBUG, ("tcp_kill_closing: killing oldest %s PCB %p (%"S32_F")\n",
1511           tcp_state_str[state], (void *)inactive, inactivity));
1512    /* Don't send a RST, since no data is lost. */
1513    tcp_abandon(inactive, 0);
1514  }
1515}
1516
1517/**
1518 * Kills the oldest connection that is in TIME_WAIT state.
1519 * Called from tcp_alloc() if no more connections are available.
1520 */
1521static void
1522tcp_kill_timewait(void)
1523{
1524  struct tcp_pcb *pcb, *inactive;
1525  u32_t inactivity;
1526
1527  inactivity = 0;
1528  inactive = NULL;
1529  /* Go through the list of TIME_WAIT pcbs and get the oldest pcb. */
1530  for (pcb = tcp_tw_pcbs; pcb != NULL; pcb = pcb->next) {
1531    if ((u32_t)(tcp_ticks - pcb->tmr) >= inactivity) {
1532      inactivity = tcp_ticks - pcb->tmr;
1533      inactive = pcb;
1534    }
1535  }
1536  if (inactive != NULL) {
1537    LWIP_DEBUGF(TCP_DEBUG, ("tcp_kill_timewait: killing oldest TIME-WAIT PCB %p (%"S32_F")\n",
1538           (void *)inactive, inactivity));
1539    tcp_abort(inactive);
1540  }
1541}
1542
1543/**
1544 * Allocate a new tcp_pcb structure.
1545 *
1546 * @param prio priority for the new pcb
1547 * @return a new tcp_pcb that initially is in state CLOSED
1548 */
1549struct tcp_pcb *
1550tcp_alloc(u8_t prio)
1551{
1552  struct tcp_pcb *pcb;
1553
1554  pcb = (struct tcp_pcb *)memp_malloc(MEMP_TCP_PCB);
1555  if (pcb == NULL) {
1556    /* Try killing oldest connection in TIME-WAIT. */
1557    LWIP_DEBUGF(TCP_DEBUG, ("tcp_alloc: killing off oldest TIME-WAIT connection\n"));
1558    tcp_kill_timewait();
1559    /* Try to allocate a tcp_pcb again. */
1560    pcb = (struct tcp_pcb *)memp_malloc(MEMP_TCP_PCB);
1561    if (pcb == NULL) {
1562      /* Try killing oldest connection in LAST-ACK (these wouldn't go to TIME-WAIT). */
1563      LWIP_DEBUGF(TCP_DEBUG, ("tcp_alloc: killing off oldest LAST-ACK connection\n"));
1564      tcp_kill_state(LAST_ACK);
1565      /* Try to allocate a tcp_pcb again. */
1566      pcb = (struct tcp_pcb *)memp_malloc(MEMP_TCP_PCB);
1567      if (pcb == NULL) {
1568        /* Try killing oldest connection in CLOSING. */
1569        LWIP_DEBUGF(TCP_DEBUG, ("tcp_alloc: killing off oldest CLOSING connection\n"));
1570        tcp_kill_state(CLOSING);
1571        /* Try to allocate a tcp_pcb again. */
1572        pcb = (struct tcp_pcb *)memp_malloc(MEMP_TCP_PCB);
1573        if (pcb == NULL) {
1574          /* Try killing active connections with lower priority than the new one. */
1575          LWIP_DEBUGF(TCP_DEBUG, ("tcp_alloc: killing connection with prio lower than %d\n", prio));
1576          tcp_kill_prio(prio);
1577          /* Try to allocate a tcp_pcb again. */
1578          pcb = (struct tcp_pcb *)memp_malloc(MEMP_TCP_PCB);
1579          if (pcb != NULL) {
1580            /* adjust err stats: memp_malloc failed multiple times before */
1581            MEMP_STATS_DEC(err, MEMP_TCP_PCB);
1582          }
1583        }
1584        if (pcb != NULL) {
1585          /* adjust err stats: memp_malloc failed multiple times before */
1586          MEMP_STATS_DEC(err, MEMP_TCP_PCB);
1587        }
1588      }
1589      if (pcb != NULL) {
1590        /* adjust err stats: memp_malloc failed multiple times before */
1591        MEMP_STATS_DEC(err, MEMP_TCP_PCB);
1592      }
1593    }
1594    if (pcb != NULL) {
1595      /* adjust err stats: memp_malloc failed above */
1596      MEMP_STATS_DEC(err, MEMP_TCP_PCB);
1597    }
1598  }
1599  if (pcb != NULL) {
1600    /* zero out the whole pcb, so there is no need to initialize members to zero */
1601    memset(pcb, 0, sizeof(struct tcp_pcb));
1602    pcb->prio = prio;
1603    pcb->snd_buf = TCP_SND_BUF;
1604    /* Start with a window that does not need scaling. When window scaling is
1605       enabled and used, the window is enlarged when both sides agree on scaling. */
1606    pcb->rcv_wnd = pcb->rcv_ann_wnd = TCPWND_MIN16(TCP_WND);
1607    pcb->ttl = TCP_TTL;
1608    /* As initial send MSS, we use TCP_MSS but limit it to 536.
1609       The send MSS is updated when an MSS option is received. */
1610    pcb->mss = INITIAL_MSS;
1611    pcb->rto = 3000 / TCP_SLOW_INTERVAL;
1612    pcb->sv = 3000 / TCP_SLOW_INTERVAL;
1613    pcb->rtime = -1;
1614    pcb->cwnd = 1;
1615    pcb->tmr = tcp_ticks;
1616    pcb->last_timer = tcp_timer_ctr;
1617
1618    /* RFC 5681 recommends setting ssthresh abritrarily high and gives an example
1619    of using the largest advertised receive window.  We've seen complications with
1620    receiving TCPs that use window scaling and/or window auto-tuning where the
1621    initial advertised window is very small and then grows rapidly once the
1622    connection is established. To avoid these complications, we set ssthresh to the
1623    largest effective cwnd (amount of in-flight data) that the sender can have. */
1624    pcb->ssthresh = TCP_SND_BUF;
1625
1626#if LWIP_CALLBACK_API
1627    pcb->recv = tcp_recv_null;
1628#endif /* LWIP_CALLBACK_API */
1629
1630    /* Init KEEPALIVE timer */
1631    pcb->keep_idle  = TCP_KEEPIDLE_DEFAULT;
1632
1633#if LWIP_TCP_KEEPALIVE
1634    pcb->keep_intvl = TCP_KEEPINTVL_DEFAULT;
1635    pcb->keep_cnt   = TCP_KEEPCNT_DEFAULT;
1636#endif /* LWIP_TCP_KEEPALIVE */
1637  }
1638  return pcb;
1639}
1640
1641/**
1642 * @ingroup tcp_raw
1643 * Creates a new TCP protocol control block but doesn't place it on
1644 * any of the TCP PCB lists.
1645 * The pcb is not put on any list until binding using tcp_bind().
1646 *
1647 * @internal: Maybe there should be a idle TCP PCB list where these
1648 * PCBs are put on. Port reservation using tcp_bind() is implemented but
1649 * allocated pcbs that are not bound can't be killed automatically if wanting
1650 * to allocate a pcb with higher prio (@see tcp_kill_prio())
1651 *
1652 * @return a new tcp_pcb that initially is in state CLOSED
1653 */
1654struct tcp_pcb *
1655tcp_new(void)
1656{
1657  return tcp_alloc(TCP_PRIO_NORMAL);
1658}
1659
1660/**
1661 * @ingroup tcp_raw
1662 * Creates a new TCP protocol control block but doesn't
1663 * place it on any of the TCP PCB lists.
1664 * The pcb is not put on any list until binding using tcp_bind().
1665 *
1666 * @param type IP address type, see @ref lwip_ip_addr_type definitions.
1667 * If you want to listen to IPv4 and IPv6 (dual-stack) connections,
1668 * supply @ref IPADDR_TYPE_ANY as argument and bind to @ref IP_ANY_TYPE.
1669 * @return a new tcp_pcb that initially is in state CLOSED
1670 */
1671struct tcp_pcb *
1672tcp_new_ip_type(u8_t type)
1673{
1674  struct tcp_pcb * pcb;
1675  pcb = tcp_alloc(TCP_PRIO_NORMAL);
1676#if LWIP_IPV4 && LWIP_IPV6
1677  if (pcb != NULL) {
1678    IP_SET_TYPE_VAL(pcb->local_ip, type);
1679    IP_SET_TYPE_VAL(pcb->remote_ip, type);
1680  }
1681#else
1682  LWIP_UNUSED_ARG(type);
1683#endif /* LWIP_IPV4 && LWIP_IPV6 */
1684  return pcb;
1685}
1686
1687/**
1688 * @ingroup tcp_raw
1689 * Used to specify the argument that should be passed callback
1690 * functions.
1691 *
1692 * @param pcb tcp_pcb to set the callback argument
1693 * @param arg void pointer argument to pass to callback functions
1694 */
1695void
1696tcp_arg(struct tcp_pcb *pcb, void *arg)
1697{
1698  /* This function is allowed to be called for both listen pcbs and
1699     connection pcbs. */
1700  if (pcb != NULL) {
1701    pcb->callback_arg = arg;
1702  }
1703}
1704#if LWIP_CALLBACK_API
1705
1706/**
1707 * @ingroup tcp_raw
1708 * Used to specify the function that should be called when a TCP
1709 * connection receives data.
1710 *
1711 * @param pcb tcp_pcb to set the recv callback
1712 * @param recv callback function to call for this pcb when data is received
1713 */
1714void
1715tcp_recv(struct tcp_pcb *pcb, tcp_recv_fn recv)
1716{
1717  if (pcb != NULL) {
1718    LWIP_ASSERT("invalid socket state for recv callback", pcb->state != LISTEN);
1719    pcb->recv = recv;
1720  }
1721}
1722
1723/**
1724 * @ingroup tcp_raw
1725 * Used to specify the function that should be called when TCP data
1726 * has been successfully delivered to the remote host.
1727 *
1728 * @param pcb tcp_pcb to set the sent callback
1729 * @param sent callback function to call for this pcb when data is successfully sent
1730 */
1731void
1732tcp_sent(struct tcp_pcb *pcb, tcp_sent_fn sent)
1733{
1734  if (pcb != NULL) {
1735    LWIP_ASSERT("invalid socket state for sent callback", pcb->state != LISTEN);
1736    pcb->sent = sent;
1737  }
1738}
1739
1740/**
1741 * @ingroup tcp_raw
1742 * Used to specify the function that should be called when a fatal error
1743 * has occurred on the connection.
1744 *
1745 * @note The corresponding pcb is already freed when this callback is called!
1746 *
1747 * @param pcb tcp_pcb to set the err callback
1748 * @param err callback function to call for this pcb when a fatal error
1749 *        has occurred on the connection
1750 */
1751void
1752tcp_err(struct tcp_pcb *pcb, tcp_err_fn err)
1753{
1754  if (pcb != NULL) {
1755    LWIP_ASSERT("invalid socket state for err callback", pcb->state != LISTEN);
1756    pcb->errf = err;
1757  }
1758}
1759
1760/**
1761 * @ingroup tcp_raw
1762 * Used for specifying the function that should be called when a
1763 * LISTENing connection has been connected to another host.
1764 *
1765 * @param pcb tcp_pcb to set the accept callback
1766 * @param accept callback function to call for this pcb when LISTENing
1767 *        connection has been connected to another host
1768 */
1769void
1770tcp_accept(struct tcp_pcb *pcb, tcp_accept_fn accept)
1771{
1772  if ((pcb != NULL) && (pcb->state == LISTEN)) {
1773    struct tcp_pcb_listen *lpcb = (struct tcp_pcb_listen*)pcb;
1774    lpcb->accept = accept;
1775  }
1776}
1777#endif /* LWIP_CALLBACK_API */
1778
1779
1780/**
1781 * @ingroup tcp_raw
1782 * Used to specify the function that should be called periodically
1783 * from TCP. The interval is specified in terms of the TCP coarse
1784 * timer interval, which is called twice a second.
1785 *
1786 */
1787void
1788tcp_poll(struct tcp_pcb *pcb, tcp_poll_fn poll, u8_t interval)
1789{
1790  LWIP_ASSERT("invalid socket state for poll", pcb->state != LISTEN);
1791#if LWIP_CALLBACK_API
1792  pcb->poll = poll;
1793#else /* LWIP_CALLBACK_API */
1794  LWIP_UNUSED_ARG(poll);
1795#endif /* LWIP_CALLBACK_API */
1796  pcb->pollinterval = interval;
1797}
1798
1799/**
1800 * Purges a TCP PCB. Removes any buffered data and frees the buffer memory
1801 * (pcb->ooseq, pcb->unsent and pcb->unacked are freed).
1802 *
1803 * @param pcb tcp_pcb to purge. The pcb itself is not deallocated!
1804 */
1805void
1806tcp_pcb_purge(struct tcp_pcb *pcb)
1807{
1808  if (pcb->state != CLOSED &&
1809     pcb->state != TIME_WAIT &&
1810     pcb->state != LISTEN) {
1811
1812    LWIP_DEBUGF(TCP_DEBUG, ("tcp_pcb_purge\n"));
1813
1814    tcp_backlog_accepted(pcb);
1815
1816    if (pcb->refused_data != NULL) {
1817      LWIP_DEBUGF(TCP_DEBUG, ("tcp_pcb_purge: data left on ->refused_data\n"));
1818      pbuf_free(pcb->refused_data);
1819      pcb->refused_data = NULL;
1820    }
1821    if (pcb->unsent != NULL) {
1822      LWIP_DEBUGF(TCP_DEBUG, ("tcp_pcb_purge: not all data sent\n"));
1823    }
1824    if (pcb->unacked != NULL) {
1825      LWIP_DEBUGF(TCP_DEBUG, ("tcp_pcb_purge: data left on ->unacked\n"));
1826    }
1827#if TCP_QUEUE_OOSEQ
1828    if (pcb->ooseq != NULL) {
1829      LWIP_DEBUGF(TCP_DEBUG, ("tcp_pcb_purge: data left on ->ooseq\n"));
1830    }
1831    tcp_segs_free(pcb->ooseq);
1832    pcb->ooseq = NULL;
1833#endif /* TCP_QUEUE_OOSEQ */
1834
1835    /* Stop the retransmission timer as it will expect data on unacked
1836       queue if it fires */
1837    pcb->rtime = -1;
1838
1839    tcp_segs_free(pcb->unsent);
1840    tcp_segs_free(pcb->unacked);
1841    pcb->unacked = pcb->unsent = NULL;
1842#if TCP_OVERSIZE
1843    pcb->unsent_oversize = 0;
1844#endif /* TCP_OVERSIZE */
1845  }
1846}
1847
1848/**
1849 * Purges the PCB and removes it from a PCB list. Any delayed ACKs are sent first.
1850 *
1851 * @param pcblist PCB list to purge.
1852 * @param pcb tcp_pcb to purge. The pcb itself is NOT deallocated!
1853 */
1854void
1855tcp_pcb_remove(struct tcp_pcb **pcblist, struct tcp_pcb *pcb)
1856{
1857  TCP_RMV(pcblist, pcb);
1858
1859  tcp_pcb_purge(pcb);
1860
1861  /* if there is an outstanding delayed ACKs, send it */
1862  if (pcb->state != TIME_WAIT &&
1863     pcb->state != LISTEN &&
1864     pcb->flags & TF_ACK_DELAY) {
1865    pcb->flags |= TF_ACK_NOW;
1866    tcp_output(pcb);
1867  }
1868
1869  if (pcb->state != LISTEN) {
1870    LWIP_ASSERT("unsent segments leaking", pcb->unsent == NULL);
1871    LWIP_ASSERT("unacked segments leaking", pcb->unacked == NULL);
1872#if TCP_QUEUE_OOSEQ
1873    LWIP_ASSERT("ooseq segments leaking", pcb->ooseq == NULL);
1874#endif /* TCP_QUEUE_OOSEQ */
1875  }
1876
1877  pcb->state = CLOSED;
1878  /* reset the local port to prevent the pcb from being 'bound' */
1879  pcb->local_port = 0;
1880
1881  LWIP_ASSERT("tcp_pcb_remove: tcp_pcbs_sane()", tcp_pcbs_sane());
1882}
1883
1884/**
1885 * Calculates a new initial sequence number for new connections.
1886 *
1887 * @return u32_t pseudo random sequence number
1888 */
1889u32_t
1890tcp_next_iss(struct tcp_pcb *pcb)
1891{
1892#ifdef LWIP_HOOK_TCP_ISN
1893  return LWIP_HOOK_TCP_ISN(&pcb->local_ip, pcb->local_port, &pcb->remote_ip, pcb->remote_port);
1894#else /* LWIP_HOOK_TCP_ISN */
1895  static u32_t iss = 6510;
1896
1897  LWIP_UNUSED_ARG(pcb);
1898
1899  iss += tcp_ticks;       /* XXX */
1900  return iss;
1901#endif /* LWIP_HOOK_TCP_ISN */
1902}
1903
1904#if TCP_CALCULATE_EFF_SEND_MSS
1905/**
1906 * Calculates the effective send mss that can be used for a specific IP address
1907 * by using ip_route to determine the netif used to send to the address and
1908 * calculating the minimum of TCP_MSS and that netif's mtu (if set).
1909 */
1910u16_t
1911tcp_eff_send_mss_impl(u16_t sendmss, const ip_addr_t *dest
1912#if LWIP_IPV6 || LWIP_IPV4_SRC_ROUTING
1913                     , const ip_addr_t *src
1914#endif /* LWIP_IPV6 || LWIP_IPV4_SRC_ROUTING */
1915                     )
1916{
1917  u16_t mss_s;
1918  struct netif *outif;
1919  s16_t mtu;
1920
1921  outif = ip_route(src, dest);
1922#if LWIP_IPV6
1923#if LWIP_IPV4
1924  if (IP_IS_V6(dest))
1925#endif /* LWIP_IPV4 */
1926  {
1927    /* First look in destination cache, to see if there is a Path MTU. */
1928    mtu = nd6_get_destination_mtu(ip_2_ip6(dest), outif);
1929  }
1930#if LWIP_IPV4
1931  else
1932#endif /* LWIP_IPV4 */
1933#endif /* LWIP_IPV6 */
1934#if LWIP_IPV4
1935  {
1936    if (outif == NULL) {
1937      return sendmss;
1938    }
1939    mtu = outif->mtu;
1940  }
1941#endif /* LWIP_IPV4 */
1942
1943  if (mtu != 0) {
1944#if LWIP_IPV6
1945#if LWIP_IPV4
1946    if (IP_IS_V6(dest))
1947#endif /* LWIP_IPV4 */
1948    {
1949      mss_s = mtu - IP6_HLEN - TCP_HLEN;
1950    }
1951#if LWIP_IPV4
1952    else
1953#endif /* LWIP_IPV4 */
1954#endif /* LWIP_IPV6 */
1955#if LWIP_IPV4
1956    {
1957      mss_s = mtu - IP_HLEN - TCP_HLEN;
1958    }
1959#endif /* LWIP_IPV4 */
1960    /* RFC 1122, chap 4.2.2.6:
1961     * Eff.snd.MSS = min(SendMSS+20, MMS_S) - TCPhdrsize - IPoptionsize
1962     * We correct for TCP options in tcp_write(), and don't support IP options.
1963     */
1964    sendmss = LWIP_MIN(sendmss, mss_s);
1965  }
1966  return sendmss;
1967}
1968#endif /* TCP_CALCULATE_EFF_SEND_MSS */
1969
1970/** Helper function for tcp_netif_ip_addr_changed() that iterates a pcb list */
1971static void
1972tcp_netif_ip_addr_changed_pcblist(const ip_addr_t* old_addr, struct tcp_pcb* pcb_list)
1973{
1974  struct tcp_pcb *pcb;
1975  pcb = pcb_list;
1976  while (pcb != NULL) {
1977    /* PCB bound to current local interface address? */
1978    if (ip_addr_cmp(&pcb->local_ip, old_addr)
1979#if LWIP_AUTOIP
1980      /* connections to link-local addresses must persist (RFC3927 ch. 1.9) */
1981      && (!IP_IS_V4_VAL(pcb->local_ip) || !ip4_addr_islinklocal(ip_2_ip4(&pcb->local_ip)))
1982#endif /* LWIP_AUTOIP */
1983      ) {
1984      /* this connection must be aborted */
1985      struct tcp_pcb *next = pcb->next;
1986      LWIP_DEBUGF(NETIF_DEBUG | LWIP_DBG_STATE, ("netif_set_ipaddr: aborting TCP pcb %p\n", (void *)pcb));
1987      tcp_abort(pcb);
1988      pcb = next;
1989    } else {
1990      pcb = pcb->next;
1991    }
1992  }
1993}
1994
1995/** This function is called from netif.c when address is changed or netif is removed
1996 *
1997 * @param old_addr IP address of the netif before change
1998 * @param new_addr IP address of the netif after change or NULL if netif has been removed
1999 */
2000void
2001tcp_netif_ip_addr_changed(const ip_addr_t* old_addr, const ip_addr_t* new_addr)
2002{
2003  struct tcp_pcb_listen *lpcb, *next;
2004
2005  if (!ip_addr_isany(old_addr)) {
2006    tcp_netif_ip_addr_changed_pcblist(old_addr, tcp_active_pcbs);
2007    tcp_netif_ip_addr_changed_pcblist(old_addr, tcp_bound_pcbs);
2008
2009    if (!ip_addr_isany(new_addr)) {
2010      /* PCB bound to current local interface address? */
2011      for (lpcb = tcp_listen_pcbs.listen_pcbs; lpcb != NULL; lpcb = next) {
2012        next = lpcb->next;
2013        /* PCB bound to current local interface address? */
2014        if (ip_addr_cmp(&lpcb->local_ip, old_addr)) {
2015          /* The PCB is listening to the old ipaddr and
2016            * is set to listen to the new one instead */
2017          ip_addr_copy(lpcb->local_ip, *new_addr);
2018        }
2019      }
2020    }
2021  }
2022}
2023
2024const char*
2025tcp_debug_state_str(enum tcp_state s)
2026{
2027  return tcp_state_str[s];
2028}
2029
2030#if TCP_DEBUG || TCP_INPUT_DEBUG || TCP_OUTPUT_DEBUG
2031/**
2032 * Print a tcp header for debugging purposes.
2033 *
2034 * @param tcphdr pointer to a struct tcp_hdr
2035 */
2036void
2037tcp_debug_print(struct tcp_hdr *tcphdr)
2038{
2039  LWIP_DEBUGF(TCP_DEBUG, ("TCP header:\n"));
2040  LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
2041  LWIP_DEBUGF(TCP_DEBUG, ("|    %5"U16_F"      |    %5"U16_F"      | (src port, dest port)\n",
2042         lwip_ntohs(tcphdr->src), lwip_ntohs(tcphdr->dest)));
2043  LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
2044  LWIP_DEBUGF(TCP_DEBUG, ("|           %010"U32_F"          | (seq no)\n",
2045          lwip_ntohl(tcphdr->seqno)));
2046  LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
2047  LWIP_DEBUGF(TCP_DEBUG, ("|           %010"U32_F"          | (ack no)\n",
2048         lwip_ntohl(tcphdr->ackno)));
2049  LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
2050  LWIP_DEBUGF(TCP_DEBUG, ("| %2"U16_F" |   |%"U16_F"%"U16_F"%"U16_F"%"U16_F"%"U16_F"%"U16_F"|     %5"U16_F"     | (hdrlen, flags (",
2051       TCPH_HDRLEN(tcphdr),
2052         (u16_t)(TCPH_FLAGS(tcphdr) >> 5 & 1),
2053         (u16_t)(TCPH_FLAGS(tcphdr) >> 4 & 1),
2054         (u16_t)(TCPH_FLAGS(tcphdr) >> 3 & 1),
2055         (u16_t)(TCPH_FLAGS(tcphdr) >> 2 & 1),
2056         (u16_t)(TCPH_FLAGS(tcphdr) >> 1 & 1),
2057         (u16_t)(TCPH_FLAGS(tcphdr)      & 1),
2058         lwip_ntohs(tcphdr->wnd)));
2059  tcp_debug_print_flags(TCPH_FLAGS(tcphdr));
2060  LWIP_DEBUGF(TCP_DEBUG, ("), win)\n"));
2061  LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
2062  LWIP_DEBUGF(TCP_DEBUG, ("|    0x%04"X16_F"     |     %5"U16_F"     | (chksum, urgp)\n",
2063         lwip_ntohs(tcphdr->chksum), lwip_ntohs(tcphdr->urgp)));
2064  LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
2065}
2066
2067/**
2068 * Print a tcp state for debugging purposes.
2069 *
2070 * @param s enum tcp_state to print
2071 */
2072void
2073tcp_debug_print_state(enum tcp_state s)
2074{
2075  LWIP_DEBUGF(TCP_DEBUG, ("State: %s\n", tcp_state_str[s]));
2076}
2077
2078/**
2079 * Print tcp flags for debugging purposes.
2080 *
2081 * @param flags tcp flags, all active flags are printed
2082 */
2083void
2084tcp_debug_print_flags(u8_t flags)
2085{
2086  if (flags & TCP_FIN) {
2087    LWIP_DEBUGF(TCP_DEBUG, ("FIN "));
2088  }
2089  if (flags & TCP_SYN) {
2090    LWIP_DEBUGF(TCP_DEBUG, ("SYN "));
2091  }
2092  if (flags & TCP_RST) {
2093    LWIP_DEBUGF(TCP_DEBUG, ("RST "));
2094  }
2095  if (flags & TCP_PSH) {
2096    LWIP_DEBUGF(TCP_DEBUG, ("PSH "));
2097  }
2098  if (flags & TCP_ACK) {
2099    LWIP_DEBUGF(TCP_DEBUG, ("ACK "));
2100  }
2101  if (flags & TCP_URG) {
2102    LWIP_DEBUGF(TCP_DEBUG, ("URG "));
2103  }
2104  if (flags & TCP_ECE) {
2105    LWIP_DEBUGF(TCP_DEBUG, ("ECE "));
2106  }
2107  if (flags & TCP_CWR) {
2108    LWIP_DEBUGF(TCP_DEBUG, ("CWR "));
2109  }
2110  LWIP_DEBUGF(TCP_DEBUG, ("\n"));
2111}
2112
2113/**
2114 * Print all tcp_pcbs in every list for debugging purposes.
2115 */
2116void
2117tcp_debug_print_pcbs(void)
2118{
2119  struct tcp_pcb *pcb;
2120  struct tcp_pcb_listen *pcbl;
2121
2122  LWIP_DEBUGF(TCP_DEBUG, ("Active PCB states:\n"));
2123  for (pcb = tcp_active_pcbs; pcb != NULL; pcb = pcb->next) {
2124    LWIP_DEBUGF(TCP_DEBUG, ("Local port %"U16_F", foreign port %"U16_F" snd_nxt %"U32_F" rcv_nxt %"U32_F" ",
2125                       pcb->local_port, pcb->remote_port,
2126                       pcb->snd_nxt, pcb->rcv_nxt));
2127    tcp_debug_print_state(pcb->state);
2128  }
2129
2130  LWIP_DEBUGF(TCP_DEBUG, ("Listen PCB states:\n"));
2131  for (pcbl = tcp_listen_pcbs.listen_pcbs; pcbl != NULL; pcbl = pcbl->next) {
2132    LWIP_DEBUGF(TCP_DEBUG, ("Local port %"U16_F" ", pcbl->local_port));
2133    tcp_debug_print_state(pcbl->state);
2134  }
2135
2136  LWIP_DEBUGF(TCP_DEBUG, ("TIME-WAIT PCB states:\n"));
2137  for (pcb = tcp_tw_pcbs; pcb != NULL; pcb = pcb->next) {
2138    LWIP_DEBUGF(TCP_DEBUG, ("Local port %"U16_F", foreign port %"U16_F" snd_nxt %"U32_F" rcv_nxt %"U32_F" ",
2139                       pcb->local_port, pcb->remote_port,
2140                       pcb->snd_nxt, pcb->rcv_nxt));
2141    tcp_debug_print_state(pcb->state);
2142  }
2143}
2144
2145/**
2146 * Check state consistency of the tcp_pcb lists.
2147 */
2148s16_t
2149tcp_pcbs_sane(void)
2150{
2151  struct tcp_pcb *pcb;
2152  for (pcb = tcp_active_pcbs; pcb != NULL; pcb = pcb->next) {
2153    LWIP_ASSERT("tcp_pcbs_sane: active pcb->state != CLOSED", pcb->state != CLOSED);
2154    LWIP_ASSERT("tcp_pcbs_sane: active pcb->state != LISTEN", pcb->state != LISTEN);
2155    LWIP_ASSERT("tcp_pcbs_sane: active pcb->state != TIME-WAIT", pcb->state != TIME_WAIT);
2156  }
2157  for (pcb = tcp_tw_pcbs; pcb != NULL; pcb = pcb->next) {
2158    LWIP_ASSERT("tcp_pcbs_sane: tw pcb->state == TIME-WAIT", pcb->state == TIME_WAIT);
2159  }
2160  return 1;
2161}
2162#endif /* TCP_DEBUG */
2163
2164#endif /* LWIP_TCP */
2165