• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 api
10  *
11  * Common functions for the TCP implementation, such as functions
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  * TCP connection setup
16  * --------------------
17  * The functions used for setting up connections is similar to that of
18  * the sequential API and of the BSD socket API. A new TCP connection
19  * identifier (i.e., a protocol control block - PCB) is created with the
20  * tcp_new() function. This PCB can then be either set to listen for new
21  * incoming connections or be explicitly connected to another host.
22  * - tcp_new()
23  * - tcp_bind()
24  * - tcp_listen() and tcp_listen_with_backlog()
25  * - tcp_accept()
26  * - tcp_connect()
27  *
28  * Sending TCP data
29  * ----------------
30  * TCP data is sent by enqueueing the data with a call to tcp_write() and
31  * triggering to send by calling tcp_output(). When the data is successfully
32  * transmitted to the remote host, the application will be notified with a
33  * call to a specified callback function.
34  * - tcp_write()
35  * - tcp_output()
36  * - tcp_sent()
37  *
38  * Receiving TCP data
39  * ------------------
40  * TCP data reception is callback based - an application specified
41  * callback function is called when new data arrives. When the
42  * application has taken the data, it has to call the tcp_recved()
43  * function to indicate that TCP can advertise increase the receive
44  * window.
45  * - tcp_recv()
46  * - tcp_recved()
47  *
48  * Application polling
49  * -------------------
50  * When a connection is idle (i.e., no data is either transmitted or
51  * received), lwIP will repeatedly poll the application by calling a
52  * specified callback function. This can be used either as a watchdog
53  * timer for killing connections that have stayed idle for too long, or
54  * as a method of waiting for memory to become available. For instance,
55  * if a call to tcp_write() has failed because memory wasn't available,
56  * the application may use the polling functionality to call tcp_write()
57  * again when the connection has been idle for a while.
58  * - tcp_poll()
59  *
60  * Closing and aborting connections
61  * --------------------------------
62  * - tcp_close()
63  * - tcp_abort()
64  * - tcp_err()
65  *
66  */
67 
68 /*
69  * Copyright (c) 2001-2004 Swedish Institute of Computer Science.
70  * All rights reserved.
71  *
72  * Redistribution and use in source and binary forms, with or without modification,
73  * are permitted provided that the following conditions are met:
74  *
75  * 1. Redistributions of source code must retain the above copyright notice,
76  *    this list of conditions and the following disclaimer.
77  * 2. Redistributions in binary form must reproduce the above copyright notice,
78  *    this list of conditions and the following disclaimer in the documentation
79  *    and/or other materials provided with the distribution.
80  * 3. The name of the author may not be used to endorse or promote products
81  *    derived from this software without specific prior written permission.
82  *
83  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
84  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
85  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
86  * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
87  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
88  * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
89  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
90  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
91  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
92  * OF SUCH DAMAGE.
93  *
94  * This file is part of the lwIP TCP/IP stack.
95  *
96  * Author: Adam Dunkels <adam@sics.se>
97  *
98  */
99 
100 #include "lwip/opt.h"
101 
102 #if LWIP_TCP /* don't build if not configured for use in lwipopts.h */
103 
104 #include "lwip/def.h"
105 #include "lwip/mem.h"
106 #include "lwip/memp.h"
107 #include "lwip/tcp.h"
108 #include "lwip/priv/tcp_priv.h"
109 #include "lwip/debug.h"
110 #include "lwip/stats.h"
111 #include "lwip/ip6.h"
112 #include "lwip/ip6_addr.h"
113 #include "lwip/nd6.h"
114 #if LWIP_LOWPOWER
115 #include "lwip/priv/api_msg.h"
116 #endif
117 
118 #include <string.h>
119 
120 #ifdef LWIP_HOOK_FILENAME
121 #include LWIP_HOOK_FILENAME
122 #endif
123 
124 #ifndef TCP_LOCAL_PORT_RANGE_START
125 /* From http://www.iana.org/assignments/port-numbers:
126    "The Dynamic and/or Private Ports are those from 49152 through 65535" */
127 #define TCP_LOCAL_PORT_RANGE_START        0xc000
128 #define TCP_LOCAL_PORT_RANGE_END          0xffff
129 #define TCP_ENSURE_LOCAL_PORT_RANGE(port) ((u16_t)(((port) & (u16_t)~TCP_LOCAL_PORT_RANGE_START) + TCP_LOCAL_PORT_RANGE_START))
130 #endif
131 
132 #if LWIP_TCP_KEEPALIVE
133 #define TCP_KEEP_DUR(pcb)   ((pcb)->keep_cnt * (pcb)->keep_intvl)
134 #define TCP_KEEP_INTVL(pcb) ((pcb)->keep_intvl)
135 #else /* LWIP_TCP_KEEPALIVE */
136 #define TCP_KEEP_DUR(pcb)   TCP_MAXIDLE
137 #define TCP_KEEP_INTVL(pcb) TCP_KEEPINTVL_DEFAULT
138 #endif /* LWIP_TCP_KEEPALIVE */
139 
140 /* As initial send MSS, we use TCP_MSS but limit it to 536. */
141 #if TCP_MSS > 536
142 #define INITIAL_MSS 536
143 #else
144 #define INITIAL_MSS TCP_MSS
145 #endif
146 
147 static const char *const tcp_state_str[] = {
148   "CLOSED",
149   "LISTEN",
150   "SYN_SENT",
151   "SYN_RCVD",
152   "ESTABLISHED",
153   "FIN_WAIT_1",
154   "FIN_WAIT_2",
155   "CLOSE_WAIT",
156   "CLOSING",
157   "LAST_ACK",
158   "TIME_WAIT"
159 };
160 
161 /* last local TCP port */
162 static volatile u16_t tcp_port = TCP_LOCAL_PORT_RANGE_START;
163 
164 /* Incremented every coarse grained timer shot (typically every 500 ms). */
165 u32_t tcp_ticks;
166 static const u8_t tcp_backoff[13] =
167 { 1, 2, 3, 4, 5, 6, 7, 7, 7, 7, 7, 7, 7};
168 /* Times per slowtmr hits */
169 static const u8_t tcp_persist_backoff[7] = { 3, 6, 12, 24, 48, 96, 120 };
170 
171 /* The TCP PCB lists. */
172 
173 /** List of all TCP PCBs bound but not yet (connected || listening) */
174 struct tcp_pcb *tcp_bound_pcbs;
175 /** List of all TCP PCBs in LISTEN state */
176 union tcp_listen_pcbs_t tcp_listen_pcbs;
177 /** List of all TCP PCBs that are in a state in which
178  * they accept or send data. */
179 struct tcp_pcb *tcp_active_pcbs;
180 /** List of all TCP PCBs in TIME-WAIT state */
181 struct tcp_pcb *tcp_tw_pcbs;
182 
183 /** An array with all (non-temporary) PCB lists, mainly used for smaller code size */
184 struct tcp_pcb **const tcp_pcb_lists[] = {&tcp_listen_pcbs.pcbs, &tcp_bound_pcbs,
185          &tcp_active_pcbs, &tcp_tw_pcbs
186 };
187 
188 u8_t tcp_active_pcbs_changed;
189 
190 /** Timer counter to handle calling slow-timer from tcp_tmr() */
191 static u8_t tcp_timer;
192 static u8_t tcp_timer_ctr;
193 static u16_t tcp_new_port(void);
194 
195 static err_t tcp_close_shutdown_fin(struct tcp_pcb *pcb);
196 #if LWIP_TCP_PCB_NUM_EXT_ARGS
197 static void tcp_ext_arg_invoke_callbacks_destroyed(struct tcp_pcb_ext_args *ext_args);
198 #endif
199 
200 #ifdef LOSCFG_NET_CONTAINER
set_tcp_pcb_net_group(struct tcp_pcb * pcb,struct net_group * group)201 void set_tcp_pcb_net_group(struct tcp_pcb *pcb, struct net_group *group)
202 {
203   set_ippcb_net_group((struct ip_pcb *)pcb, group);
204 }
205 
get_net_group_from_tcp_pcb(const struct tcp_pcb * pcb)206 struct net_group *get_net_group_from_tcp_pcb(const struct tcp_pcb *pcb)
207 {
208   return get_net_group_from_ippcb((struct ip_pcb *)pcb);
209 }
210 #endif
211 /**
212  * Initialize this module.
213  */
214 void
tcp_init(void)215 tcp_init(void)
216 {
217 #ifdef LWIP_RAND
218   tcp_port = TCP_ENSURE_LOCAL_PORT_RANGE(LWIP_RAND());
219 #endif /* LWIP_RAND */
220 }
221 
222 /** Free a tcp pcb */
223 void
tcp_free(struct tcp_pcb * pcb)224 tcp_free(struct tcp_pcb *pcb)
225 {
226   LWIP_ASSERT("tcp_free: LISTEN", pcb->state != LISTEN);
227 #if LWIP_TCP_PCB_NUM_EXT_ARGS
228   tcp_ext_arg_invoke_callbacks_destroyed(pcb->ext_args);
229 #endif
230   memp_free(MEMP_TCP_PCB, pcb);
231 }
232 
233 /** Free a tcp listen pcb */
234 static void
tcp_free_listen(struct tcp_pcb * pcb)235 tcp_free_listen(struct tcp_pcb *pcb)
236 {
237   LWIP_ASSERT("tcp_free_listen: !LISTEN", pcb->state != LISTEN);
238 #if LWIP_TCP_PCB_NUM_EXT_ARGS
239   tcp_ext_arg_invoke_callbacks_destroyed(pcb->ext_args);
240 #endif
241   memp_free(MEMP_TCP_PCB_LISTEN, pcb);
242 }
243 
244 /**
245  * Called periodically to dispatch TCP timers.
246  */
247 void
tcp_tmr(void)248 tcp_tmr(void)
249 {
250   /* Call tcp_fasttmr() every 250 ms */
251   tcp_fasttmr();
252 
253   if (++tcp_timer & 1) {
254     /* Call tcp_slowtmr() every 500 ms, i.e., every other timer
255        tcp_tmr() is called. */
256     tcp_slowtmr();
257   }
258 }
259 
260 #if LWIP_LOWPOWER
261 #include "lwip/lowpower.h"
262 
263 static u32_t
tcp_set_timer_tick_by_persist(struct tcp_pcb * pcb,u32_t tick)264 tcp_set_timer_tick_by_persist(struct tcp_pcb *pcb, u32_t tick)
265 {
266   u32_t val;
267 
268   if (pcb->persist_backoff > 0) {
269     u8_t backoff_cnt = tcp_persist_backoff[pcb->persist_backoff - 1];
270     SET_TMR_TICK(tick, backoff_cnt);
271     return tick;
272   }
273 
274   /* timer not running */
275   if (pcb->rtime >= 0) {
276     val = pcb->rto - pcb->rtime;
277     if (val == 0) {
278       val = 1;
279     }
280     SET_TMR_TICK(tick, val);
281   }
282   return tick;
283 }
284 
285 static u32_t
tcp_set_timer_tick_by_keepalive(struct tcp_pcb * pcb,u32_t tick)286 tcp_set_timer_tick_by_keepalive(struct tcp_pcb *pcb, u32_t tick)
287 {
288   u32_t val;
289 
290   if (ip_get_option(pcb, SOF_KEEPALIVE) &&
291       ((pcb->state == ESTABLISHED) ||
292        (pcb->state == CLOSE_WAIT))) {
293     u32_t idle = (pcb->keep_idle) / TCP_SLOW_INTERVAL;
294     if (pcb->keep_cnt_sent == 0) {
295       val = idle - (tcp_ticks - pcb->tmr);
296     } else {
297       val = (tcp_ticks - pcb->tmr) - idle;
298       idle = (TCP_KEEP_INTVL(pcb) / TCP_SLOW_INTERVAL);
299       val  = idle - (val % idle);
300     }
301     /* need add 1 to trig timer */
302     val++;
303     SET_TMR_TICK(tick, val);
304   }
305 
306   return tick;
307 }
308 
tcp_set_timer_tick_by_tcp_state(struct tcp_pcb * pcb,u32_t tick)309 static u32_t tcp_set_timer_tick_by_tcp_state(struct tcp_pcb *pcb, u32_t tick)
310 {
311   u32_t val;
312 
313   /* Check if this PCB has stayed too long in FIN-WAIT-2 */
314   if (pcb->state == FIN_WAIT_2) {
315     /* If this PCB is in FIN_WAIT_2 because of SHUT_WR don't let it time out. */
316     if (pcb->flags & TF_RXCLOSED) {
317       val = TCP_FIN_WAIT_TIMEOUT / TCP_SLOW_INTERVAL;
318       SET_TMR_TICK(tick, val);
319     }
320   }
321 
322   /* Check if this PCB has stayed too long in SYN-RCVD */
323   if (pcb->state == SYN_RCVD) {
324     val = TCP_SYN_RCVD_TIMEOUT / TCP_SLOW_INTERVAL;
325     SET_TMR_TICK(tick, val);
326   }
327 
328   /* Check if this PCB has stayed too long in LAST-ACK */
329   if (pcb->state == LAST_ACK) {
330     /*
331      * In a TCP connection the end that performs the active close
332      * is required to stay in TIME_WAIT state for 2MSL of time
333      */
334     val = (2 * TCP_MSL) / TCP_SLOW_INTERVAL;
335     SET_TMR_TICK(tick, val);
336   }
337 
338   return tick;
339 }
340 
341 u32_t
tcp_slow_tmr_tick(void)342 tcp_slow_tmr_tick(void)
343 {
344   struct tcp_pcb *pcb = NULL;
345   u32_t tick = 0;
346 
347   pcb = tcp_active_pcbs;
348   while (pcb != NULL) {
349     if (((pcb->state == SYN_SENT) && (pcb->nrtx >= TCP_SYNMAXRTX)) ||
350         ((pcb->state == FIN_WAIT_1) || (pcb->state == CLOSING)) ||
351         (pcb->nrtx >= TCP_MAXRTX)) {
352       return 1;
353     }
354 
355     tick = tcp_set_timer_tick_by_persist(pcb, tick);
356     tick = tcp_set_timer_tick_by_keepalive(pcb, tick);
357 
358     /*
359      * If this PCB has queued out of sequence data, but has been
360      * inactive for too long, will drop the data (it will eventually
361      * be retransmitted).
362      */
363 #if TCP_QUEUE_OOSEQ
364     if (pcb->ooseq != NULL) {
365       SET_TMR_TICK(tick, 1);
366     }
367 #endif /* TCP_QUEUE_OOSEQ */
368 
369     tick = tcp_set_timer_tick_by_tcp_state(pcb, tick);
370 
371     u8_t ret = poll_tcp_needed(pcb->callback_arg, pcb);
372     if ((pcb->poll != NULL) && (ret != 0)) {
373       SET_TMR_TICK(tick, 1);
374     }
375     pcb = pcb->next;
376   }
377 
378   LWIP_DEBUGF(LOWPOWER_DEBUG, ("%s tmr tick: %u\n", "tcp_slow_tmr_tick", tick));
379   return tick;
380 }
381 
382 u32_t
tcp_fast_tmr_tick(void)383 tcp_fast_tmr_tick(void)
384 {
385   struct tcp_pcb *pcb = NULL;
386 
387   pcb = tcp_active_pcbs;
388   while (pcb != NULL) {
389     /* send delayed ACKs or send pending FIN */
390     if ((pcb->flags & TF_ACK_DELAY) ||
391         (pcb->flags & TF_CLOSEPEND) ||
392         (pcb->refused_data != NULL)
393        ) {
394       LWIP_DEBUGF(LOWPOWER_DEBUG, ("%s tmr tick: 1\n", "tcp_fast_tmr_tick"));
395       return 1;
396     }
397     pcb = pcb->next;
398   }
399   LWIP_DEBUGF(LOWPOWER_DEBUG, ("%s tmr tick: 0\n", "tcp_fast_tmr_tick"));
400   return 0;
401 }
402 #endif /* LWIP_LOWPOWER */
403 
404 #if LWIP_CALLBACK_API || TCP_LISTEN_BACKLOG
405 /** Called when a listen pcb is closed. Iterates one pcb list and removes the
406  * closed listener pcb from pcb->listener if matching.
407  */
408 static void
tcp_remove_listener(struct tcp_pcb * list,struct tcp_pcb_listen * lpcb)409 tcp_remove_listener(struct tcp_pcb *list, struct tcp_pcb_listen *lpcb)
410 {
411   struct tcp_pcb *pcb;
412 
413   LWIP_ASSERT("tcp_remove_listener: invalid listener", lpcb != NULL);
414 
415   for (pcb = list; pcb != NULL; pcb = pcb->next) {
416     if (pcb->listener == lpcb) {
417       pcb->listener = NULL;
418     }
419   }
420 }
421 #endif
422 
423 /** Called when a listen pcb is closed. Iterates all pcb lists and removes the
424  * closed listener pcb from pcb->listener if matching.
425  */
426 static void
tcp_listen_closed(struct tcp_pcb * pcb)427 tcp_listen_closed(struct tcp_pcb *pcb)
428 {
429 #if LWIP_CALLBACK_API || TCP_LISTEN_BACKLOG
430   size_t i;
431   LWIP_ASSERT("pcb != NULL", pcb != NULL);
432   LWIP_ASSERT("pcb->state == LISTEN", pcb->state == LISTEN);
433   for (i = 1; i < LWIP_ARRAYSIZE(tcp_pcb_lists); i++) {
434     tcp_remove_listener(*tcp_pcb_lists[i], (struct tcp_pcb_listen *)pcb);
435   }
436 #endif
437   LWIP_UNUSED_ARG(pcb);
438 }
439 
440 #if TCP_LISTEN_BACKLOG
441 /** @ingroup tcp_raw
442  * Delay accepting a connection in respect to the listen backlog:
443  * the number of outstanding connections is increased until
444  * tcp_backlog_accepted() is called.
445  *
446  * ATTENTION: the caller is responsible for calling tcp_backlog_accepted()
447  * or else the backlog feature will get out of sync!
448  *
449  * @param pcb the connection pcb which is not fully accepted yet
450  */
451 void
tcp_backlog_delayed(struct tcp_pcb * pcb)452 tcp_backlog_delayed(struct tcp_pcb *pcb)
453 {
454   LWIP_ASSERT("pcb != NULL", pcb != NULL);
455   LWIP_ASSERT_CORE_LOCKED();
456   if ((pcb->flags & TF_BACKLOGPEND) == 0) {
457     if (pcb->listener != NULL) {
458       pcb->listener->accepts_pending++;
459       LWIP_ASSERT("accepts_pending != 0", pcb->listener->accepts_pending != 0);
460       tcp_set_flags(pcb, TF_BACKLOGPEND);
461     }
462   }
463 }
464 
465 /** @ingroup tcp_raw
466  * A delayed-accept a connection is accepted (or closed/aborted): decreases
467  * the number of outstanding connections after calling tcp_backlog_delayed().
468  *
469  * ATTENTION: the caller is responsible for calling tcp_backlog_accepted()
470  * or else the backlog feature will get out of sync!
471  *
472  * @param pcb the connection pcb which is now fully accepted (or closed/aborted)
473  */
474 void
tcp_backlog_accepted(struct tcp_pcb * pcb)475 tcp_backlog_accepted(struct tcp_pcb *pcb)
476 {
477   LWIP_ASSERT("pcb != NULL", pcb != NULL);
478   LWIP_ASSERT_CORE_LOCKED();
479   if ((pcb->flags & TF_BACKLOGPEND) != 0) {
480     if (pcb->listener != NULL) {
481       LWIP_ASSERT("accepts_pending != 0", pcb->listener->accepts_pending != 0);
482       pcb->listener->accepts_pending--;
483       tcp_clear_flags(pcb, TF_BACKLOGPEND);
484     }
485   }
486 }
487 #endif /* TCP_LISTEN_BACKLOG */
488 
489 /**
490  * Closes the TX side of a connection held by the PCB.
491  * For tcp_close(), a RST is sent if the application didn't receive all data
492  * (tcp_recved() not called for all data passed to recv callback).
493  *
494  * Listening pcbs are freed and may not be referenced any more.
495  * Connection pcbs are freed if not yet connected and may not be referenced
496  * any more. If a connection is established (at least SYN received or in
497  * a closing state), the connection is closed, and put in a closing state.
498  * The pcb is then automatically freed in tcp_slowtmr(). It is therefore
499  * unsafe to reference it.
500  *
501  * @param pcb the tcp_pcb to close
502  * @return ERR_OK if connection has been closed
503  *         another err_t if closing failed and pcb is not freed
504  */
505 static err_t
tcp_close_shutdown(struct tcp_pcb * pcb,u8_t rst_on_unacked_data)506 tcp_close_shutdown(struct tcp_pcb *pcb, u8_t rst_on_unacked_data)
507 {
508   LWIP_ASSERT("tcp_close_shutdown: invalid pcb", pcb != NULL);
509 
510   if (rst_on_unacked_data && ((pcb->state == ESTABLISHED) || (pcb->state == CLOSE_WAIT))) {
511     if ((pcb->refused_data != NULL) || (pcb->rcv_wnd != TCP_WND_MAX(pcb))) {
512       /* Not all data received by application, send RST to tell the remote
513          side about this. */
514       LWIP_ASSERT("pcb->flags & TF_RXCLOSED", pcb->flags & TF_RXCLOSED);
515 
516       /* don't call tcp_abort here: we must not deallocate the pcb since
517          that might not be expected when calling tcp_close */
518       tcp_rst(pcb, pcb->snd_nxt, pcb->rcv_nxt, &pcb->local_ip, &pcb->remote_ip,
519               pcb->local_port, pcb->remote_port);
520 
521       tcp_pcb_purge(pcb);
522       TCP_RMV_ACTIVE(pcb);
523       /* Deallocate the pcb since we already sent a RST for it */
524       if (tcp_input_pcb == pcb) {
525         /* prevent using a deallocated pcb: free it from tcp_input later */
526         tcp_trigger_input_pcb_close();
527       } else {
528         tcp_free(pcb);
529       }
530       return ERR_OK;
531     }
532   }
533 
534   /* - states which free the pcb are handled here,
535      - states which send FIN and change state are handled in tcp_close_shutdown_fin() */
536   switch (pcb->state) {
537     case CLOSED:
538       /* Closing a pcb in the CLOSED state might seem erroneous,
539        * however, it is in this state once allocated and as yet unused
540        * and the user needs some way to free it should the need arise.
541        * Calling tcp_close() with a pcb that has already been closed, (i.e. twice)
542        * or for a pcb that has been used and then entered the CLOSED state
543        * is erroneous, but this should never happen as the pcb has in those cases
544        * been freed, and so any remaining handles are bogus. */
545       if (pcb->local_port != 0) {
546         TCP_RMV(&tcp_bound_pcbs, pcb);
547       }
548       tcp_free(pcb);
549       break;
550     case LISTEN:
551       tcp_listen_closed(pcb);
552       tcp_pcb_remove(&tcp_listen_pcbs.pcbs, pcb);
553       tcp_free_listen(pcb);
554       break;
555     case SYN_SENT:
556       TCP_PCB_REMOVE_ACTIVE(pcb);
557       tcp_free(pcb);
558       MIB2_STATS_INC(mib2.tcpattemptfails);
559       break;
560     default:
561       return tcp_close_shutdown_fin(pcb);
562   }
563   return ERR_OK;
564 }
565 
566 static err_t
tcp_close_shutdown_fin(struct tcp_pcb * pcb)567 tcp_close_shutdown_fin(struct tcp_pcb *pcb)
568 {
569   err_t err;
570   LWIP_ASSERT("pcb != NULL", pcb != NULL);
571 
572   switch (pcb->state) {
573     case SYN_RCVD:
574       err = tcp_send_fin(pcb);
575       if (err == ERR_OK) {
576         tcp_backlog_accepted(pcb);
577         MIB2_STATS_INC(mib2.tcpattemptfails);
578         pcb->state = FIN_WAIT_1;
579       }
580       break;
581     case ESTABLISHED:
582       err = tcp_send_fin(pcb);
583       if (err == ERR_OK) {
584         MIB2_STATS_INC(mib2.tcpestabresets);
585         pcb->state = FIN_WAIT_1;
586       }
587       break;
588     case CLOSE_WAIT:
589       err = tcp_send_fin(pcb);
590       if (err == ERR_OK) {
591         MIB2_STATS_INC(mib2.tcpestabresets);
592         pcb->state = LAST_ACK;
593       }
594       break;
595     default:
596       /* Has already been closed, do nothing. */
597       return ERR_OK;
598   }
599 
600   if (err == ERR_OK) {
601     /* To ensure all data has been sent when tcp_close returns, we have
602        to make sure tcp_output doesn't fail.
603        Since we don't really have to ensure all data has been sent when tcp_close
604        returns (unsent data is sent from tcp timer functions, also), we don't care
605        for the return value of tcp_output for now. */
606     tcp_output(pcb);
607   } else if (err == ERR_MEM) {
608     /* Mark this pcb for closing. Closing is retried from tcp_tmr. */
609     tcp_set_flags(pcb, TF_CLOSEPEND);
610     /* We have to return ERR_OK from here to indicate to the callers that this
611        pcb should not be used any more as it will be freed soon via tcp_tmr.
612        This is OK here since sending FIN does not guarantee a time frime for
613        actually freeing the pcb, either (it is left in closure states for
614        remote ACK or timeout) */
615     return ERR_OK;
616   }
617   return err;
618 }
619 
620 /**
621  * @ingroup tcp_raw
622  * Closes the connection held by the PCB.
623  *
624  * Listening pcbs are freed and may not be referenced any more.
625  * Connection pcbs are freed if not yet connected and may not be referenced
626  * any more. If a connection is established (at least SYN received or in
627  * a closing state), the connection is closed, and put in a closing state.
628  * The pcb is then automatically freed in tcp_slowtmr(). It is therefore
629  * unsafe to reference it (unless an error is returned).
630  *
631  * The function may return ERR_MEM if no memory
632  * was available for closing the connection. If so, the application
633  * should wait and try again either by using the acknowledgment
634  * callback or the polling functionality. If the close succeeds, the
635  * function returns ERR_OK.
636  *
637  * @param pcb the tcp_pcb to close
638  * @return ERR_OK if connection has been closed
639  *         another err_t if closing failed and pcb is not freed
640  */
641 err_t
tcp_close(struct tcp_pcb * pcb)642 tcp_close(struct tcp_pcb *pcb)
643 {
644   LWIP_ASSERT_CORE_LOCKED();
645 
646   LWIP_ERROR("tcp_close: invalid pcb", pcb != NULL, return ERR_ARG);
647   LWIP_DEBUGF(TCP_DEBUG, ("tcp_close: closing in "));
648 
649   tcp_debug_print_state(pcb->state);
650 
651   if (pcb->state != LISTEN) {
652     /* Set a flag not to receive any more data... */
653     tcp_set_flags(pcb, TF_RXCLOSED);
654   }
655   /* ... and close */
656   return tcp_close_shutdown(pcb, 1);
657 }
658 
659 /**
660  * @ingroup tcp_raw
661  * Causes all or part of a full-duplex connection of this PCB to be shut down.
662  * This doesn't deallocate the PCB unless shutting down both sides!
663  * Shutting down both sides is the same as calling tcp_close, so if it succeds
664  * (i.e. returns ER_OK), the PCB must not be referenced any more!
665  *
666  * @param pcb PCB to shutdown
667  * @param shut_rx shut down receive side if this is != 0
668  * @param shut_tx shut down send side if this is != 0
669  * @return ERR_OK if shutdown succeeded (or the PCB has already been shut down)
670  *         another err_t on error.
671  */
672 err_t
tcp_shutdown(struct tcp_pcb * pcb,int shut_rx,int shut_tx)673 tcp_shutdown(struct tcp_pcb *pcb, int shut_rx, int shut_tx)
674 {
675   LWIP_ASSERT_CORE_LOCKED();
676 
677   LWIP_ERROR("tcp_shutdown: invalid pcb", pcb != NULL, return ERR_ARG);
678 
679   if (pcb->state == LISTEN) {
680     return ERR_CONN;
681   }
682   if (shut_rx) {
683     /* shut down the receive side: set a flag not to receive any more data... */
684     tcp_set_flags(pcb, TF_RXCLOSED);
685     if (shut_tx) {
686       /* shutting down the tx AND rx side is the same as closing for the raw API */
687       return tcp_close_shutdown(pcb, 1);
688     }
689     /* ... and free buffered data */
690     if (pcb->refused_data != NULL) {
691       pbuf_free(pcb->refused_data);
692       pcb->refused_data = NULL;
693     }
694   }
695   if (shut_tx) {
696     /* This can't happen twice since if it succeeds, the pcb's state is changed.
697        Only close in these states as the others directly deallocate the PCB */
698     switch (pcb->state) {
699       case SYN_RCVD:
700       case ESTABLISHED:
701       case CLOSE_WAIT:
702         return tcp_close_shutdown(pcb, (u8_t)shut_rx);
703       default:
704         /* Not (yet?) connected, cannot shutdown the TX side as that would bring us
705           into CLOSED state, where the PCB is deallocated. */
706         return ERR_CONN;
707     }
708   }
709   return ERR_OK;
710 }
711 
712 /**
713  * Abandons a connection and optionally sends a RST to the remote
714  * host.  Deletes the local protocol control block. This is done when
715  * a connection is killed because of shortage of memory.
716  *
717  * @param pcb the tcp_pcb to abort
718  * @param reset boolean to indicate whether a reset should be sent
719  */
720 void
tcp_abandon(struct tcp_pcb * pcb,int reset)721 tcp_abandon(struct tcp_pcb *pcb, int reset)
722 {
723   u32_t seqno, ackno;
724 #if LWIP_CALLBACK_API
725   tcp_err_fn errf;
726 #endif /* LWIP_CALLBACK_API */
727   void *errf_arg;
728 
729   LWIP_ASSERT_CORE_LOCKED();
730 
731   LWIP_ERROR("tcp_abandon: invalid pcb", pcb != NULL, return);
732 
733   /* pcb->state LISTEN not allowed here */
734   LWIP_ASSERT("don't call tcp_abort/tcp_abandon for listen-pcbs",
735               pcb->state != LISTEN);
736   /* Figure out on which TCP PCB list we are, and remove us. If we
737      are in an active state, call the receive function associated with
738      the PCB with a NULL argument, and send an RST to the remote end. */
739   if (pcb->state == TIME_WAIT) {
740     tcp_pcb_remove(&tcp_tw_pcbs, pcb);
741     tcp_free(pcb);
742   } else {
743     int send_rst = 0;
744     u16_t local_port = 0;
745     enum tcp_state last_state;
746     seqno = pcb->snd_nxt;
747     ackno = pcb->rcv_nxt;
748 #if LWIP_CALLBACK_API
749     errf = pcb->errf;
750 #endif /* LWIP_CALLBACK_API */
751     errf_arg = pcb->callback_arg;
752     if (pcb->state == CLOSED) {
753       if (pcb->local_port != 0) {
754         /* bound, not yet opened */
755         TCP_RMV(&tcp_bound_pcbs, pcb);
756       }
757     } else {
758       send_rst = reset;
759       local_port = pcb->local_port;
760       TCP_PCB_REMOVE_ACTIVE(pcb);
761     }
762     if (pcb->unacked != NULL) {
763       tcp_segs_free(pcb->unacked);
764     }
765     if (pcb->unsent != NULL) {
766       tcp_segs_free(pcb->unsent);
767     }
768 #if TCP_QUEUE_OOSEQ
769     if (pcb->ooseq != NULL) {
770       tcp_segs_free(pcb->ooseq);
771     }
772 #endif /* TCP_QUEUE_OOSEQ */
773     tcp_backlog_accepted(pcb);
774     if (send_rst) {
775       LWIP_DEBUGF(TCP_RST_DEBUG, ("tcp_abandon: sending RST\n"));
776       tcp_rst(pcb, seqno, ackno, &pcb->local_ip, &pcb->remote_ip, local_port, pcb->remote_port);
777     }
778     last_state = pcb->state;
779     tcp_free(pcb);
780     TCP_EVENT_ERR(last_state, errf, errf_arg, ERR_ABRT);
781   }
782 }
783 
784 /**
785  * @ingroup tcp_raw
786  * Aborts the connection by sending a RST (reset) segment to the remote
787  * host. The pcb is deallocated. This function never fails.
788  *
789  * ATTENTION: When calling this from one of the TCP callbacks, make
790  * sure you always return ERR_ABRT (and never return ERR_ABRT otherwise
791  * or you will risk accessing deallocated memory or memory leaks!
792  *
793  * @param pcb the tcp pcb to abort
794  */
795 void
tcp_abort(struct tcp_pcb * pcb)796 tcp_abort(struct tcp_pcb *pcb)
797 {
798   tcp_abandon(pcb, 1);
799 }
800 
801 /**
802  * @ingroup tcp_raw
803  * Binds the connection to a local port number and IP address. If the
804  * IP address is not given (i.e., ipaddr == IP_ANY_TYPE), the connection is
805  * bound to all local IP addresses.
806  * If another connection is bound to the same port, the function will
807  * return ERR_USE, otherwise ERR_OK is returned.
808  * @see MEMP_NUM_TCP_PCB_LISTEN and MEMP_NUM_TCP_PCB
809  *
810  * @param pcb the tcp_pcb to bind (no check is done whether this pcb is
811  *        already bound!)
812  * @param ipaddr the local ip address to bind to (use IPx_ADDR_ANY to bind
813  *        to any local address
814  * @param port the local port to bind to
815  * @return ERR_USE if the port is already in use
816  *         ERR_VAL if bind failed because the PCB is not in a valid state
817  *         ERR_OK if bound
818  */
819 err_t
tcp_bind(struct tcp_pcb * pcb,const ip_addr_t * ipaddr,u16_t port)820 tcp_bind(struct tcp_pcb *pcb, const ip_addr_t *ipaddr, u16_t port)
821 {
822   int i;
823   int max_pcb_list = NUM_TCP_PCB_LISTS;
824   struct tcp_pcb *cpcb;
825 #if LWIP_IPV6 && LWIP_IPV6_SCOPES
826   ip_addr_t zoned_ipaddr;
827 #endif /* LWIP_IPV6 && LWIP_IPV6_SCOPES */
828 
829   LWIP_ASSERT_CORE_LOCKED();
830 
831 #if LWIP_IPV4
832   /* Don't propagate NULL pointer (IPv4 ANY) to subsequent functions */
833   if (ipaddr == NULL) {
834     ipaddr = IP4_ADDR_ANY;
835   }
836 #else /* LWIP_IPV4 */
837   LWIP_ERROR("tcp_bind: invalid ipaddr", ipaddr != NULL, return ERR_ARG);
838 #endif /* LWIP_IPV4 */
839 
840   LWIP_ERROR("tcp_bind: invalid pcb", pcb != NULL, return ERR_ARG);
841 
842   LWIP_ERROR("tcp_bind: can only bind in state CLOSED", pcb->state == CLOSED, return ERR_VAL);
843 
844 #if SO_REUSE
845   /* Unless the REUSEADDR flag is set,
846      we have to check the pcbs in TIME-WAIT state, also.
847      We do not dump TIME_WAIT pcb's; they can still be matched by incoming
848      packets using both local and remote IP addresses and ports to distinguish.
849    */
850   if (ip_get_option(pcb, SOF_REUSEADDR)) {
851     max_pcb_list = NUM_TCP_PCB_LISTS_NO_TIME_WAIT;
852   }
853 #endif /* SO_REUSE */
854 
855 #if LWIP_IPV6 && LWIP_IPV6_SCOPES
856   /* If the given IP address should have a zone but doesn't, assign one now.
857    * This is legacy support: scope-aware callers should always provide properly
858    * zoned source addresses. Do the zone selection before the address-in-use
859    * check below; as such we have to make a temporary copy of the address. */
860   if (IP_IS_V6(ipaddr) && ip6_addr_lacks_zone(ip_2_ip6(ipaddr), IP6_UNICAST)) {
861     ip_addr_copy(zoned_ipaddr, *ipaddr);
862     ip6_addr_select_zone(ip_2_ip6(&zoned_ipaddr), ip_2_ip6(&zoned_ipaddr));
863     ipaddr = &zoned_ipaddr;
864   }
865 #endif /* LWIP_IPV6 && LWIP_IPV6_SCOPES */
866 
867   if (port == 0) {
868     port = tcp_new_port();
869     if (port == 0) {
870       return ERR_BUF;
871     }
872   } else {
873     /* Check if the address already is in use (on all lists) */
874     for (i = 0; i < max_pcb_list; i++) {
875       for (cpcb = *tcp_pcb_lists[i]; cpcb != NULL; cpcb = cpcb->next) {
876 #ifdef LOSCFG_NET_CONTAINER
877         if (cpcb->local_port == port && (get_net_group_from_tcp_pcb(pcb) == get_net_group_from_tcp_pcb(cpcb))) {
878 #else
879         if (cpcb->local_port == port) {
880 #endif
881 #if SO_REUSE
882           /* Omit checking for the same port if both pcbs have REUSEADDR set.
883              For SO_REUSEADDR, the duplicate-check for a 5-tuple is done in
884              tcp_connect. */
885           if (!ip_get_option(pcb, SOF_REUSEADDR) ||
886               !ip_get_option(cpcb, SOF_REUSEADDR))
887 #endif /* SO_REUSE */
888           {
889             /* @todo: check accept_any_ip_version */
890             if ((IP_IS_V6(ipaddr) == IP_IS_V6_VAL(cpcb->local_ip)) &&
891                 (ip_addr_isany(&cpcb->local_ip) ||
892                  ip_addr_isany(ipaddr) ||
893                  ip_addr_cmp(&cpcb->local_ip, ipaddr))) {
894               return ERR_USE;
895             }
896           }
897         }
898       }
899     }
900   }
901 
902   if (!ip_addr_isany(ipaddr)
903 #if LWIP_IPV4 && LWIP_IPV6
904       || (IP_GET_TYPE(ipaddr) != IP_GET_TYPE(&pcb->local_ip))
905 #endif /* LWIP_IPV4 && LWIP_IPV6 */
906      ) {
907     ip_addr_set(&pcb->local_ip, ipaddr);
908   }
909   pcb->local_port = port;
910   TCP_REG(&tcp_bound_pcbs, pcb);
911   LWIP_DEBUGF(TCP_DEBUG, ("tcp_bind: bind to port %"U16_F"\n", port));
912   return ERR_OK;
913 }
914 
915 /**
916  * @ingroup tcp_raw
917  * Binds the connection to a netif and IP address.
918  * After calling this function, all packets received via this PCB
919  * are guaranteed to have come in via the specified netif, and all
920  * outgoing packets will go out via the specified netif.
921  *
922  * @param pcb the tcp_pcb to bind.
923  * @param netif the netif to bind to. Can be NULL.
924  */
925 void
926 tcp_bind_netif(struct tcp_pcb *pcb, const struct netif *netif)
927 {
928   LWIP_ASSERT_CORE_LOCKED();
929   if (netif != NULL) {
930     pcb->netif_idx = netif_get_index(netif);
931   } else {
932     pcb->netif_idx = NETIF_NO_INDEX;
933   }
934 }
935 
936 #if LWIP_CALLBACK_API
937 /**
938  * Default accept callback if no accept callback is specified by the user.
939  */
940 static err_t
941 tcp_accept_null(void *arg, struct tcp_pcb *pcb, err_t err)
942 {
943   LWIP_UNUSED_ARG(arg);
944   LWIP_UNUSED_ARG(err);
945 
946   LWIP_ASSERT("tcp_accept_null: invalid pcb", pcb != NULL);
947 
948   tcp_abort(pcb);
949 
950   return ERR_ABRT;
951 }
952 #endif /* LWIP_CALLBACK_API */
953 
954 /**
955  * @ingroup tcp_raw
956  * Set the state of the connection to be LISTEN, which means that it
957  * is able to accept incoming connections. The protocol control block
958  * is reallocated in order to consume less memory. Setting the
959  * connection to LISTEN is an irreversible process.
960  * When an incoming connection is accepted, the function specified with
961  * the tcp_accept() function will be called. The pcb has to be bound
962  * to a local port with the tcp_bind() function.
963  *
964  * The tcp_listen() function returns a new connection identifier, and
965  * the one passed as an argument to the function will be
966  * deallocated. The reason for this behavior is that less memory is
967  * needed for a connection that is listening, so tcp_listen() will
968  * reclaim the memory needed for the original connection and allocate a
969  * new smaller memory block for the listening connection.
970  *
971  * tcp_listen() may return NULL if no memory was available for the
972  * listening connection. If so, the memory associated with the pcb
973  * passed as an argument to tcp_listen() will not be deallocated.
974  *
975  * The backlog limits the number of outstanding connections
976  * in the listen queue to the value specified by the backlog argument.
977  * To use it, your need to set TCP_LISTEN_BACKLOG=1 in your lwipopts.h.
978  *
979  * @param pcb the original tcp_pcb
980  * @param backlog the incoming connections queue limit
981  * @return tcp_pcb used for listening, consumes less memory.
982  *
983  * @note The original tcp_pcb is freed. This function therefore has to be
984  *       called like this:
985  *             tpcb = tcp_listen_with_backlog(tpcb, backlog);
986  */
987 struct tcp_pcb *
988 tcp_listen_with_backlog(struct tcp_pcb *pcb, u8_t backlog)
989 {
990   LWIP_ASSERT_CORE_LOCKED();
991   return tcp_listen_with_backlog_and_err(pcb, backlog, NULL);
992 }
993 
994 /**
995  * @ingroup tcp_raw
996  * Set the state of the connection to be LISTEN, which means that it
997  * is able to accept incoming connections. The protocol control block
998  * is reallocated in order to consume less memory. Setting the
999  * connection to LISTEN is an irreversible process.
1000  *
1001  * @param pcb the original tcp_pcb
1002  * @param backlog the incoming connections queue limit
1003  * @param err when NULL is returned, this contains the error reason
1004  * @return tcp_pcb used for listening, consumes less memory.
1005  *
1006  * @note The original tcp_pcb is freed. This function therefore has to be
1007  *       called like this:
1008  *             tpcb = tcp_listen_with_backlog_and_err(tpcb, backlog, &err);
1009  */
1010 struct tcp_pcb *
1011 tcp_listen_with_backlog_and_err(struct tcp_pcb *pcb, u8_t backlog, err_t *err)
1012 {
1013   struct tcp_pcb_listen *lpcb = NULL;
1014   err_t res;
1015 
1016   LWIP_UNUSED_ARG(backlog);
1017 
1018   LWIP_ASSERT_CORE_LOCKED();
1019 
1020   LWIP_ERROR("tcp_listen_with_backlog_and_err: invalid pcb", pcb != NULL, res = ERR_ARG; goto done);
1021   LWIP_ERROR("tcp_listen_with_backlog_and_err: pcb already connected", pcb->state == CLOSED, res = ERR_CLSD; goto done);
1022 
1023   /* already listening? */
1024   if (pcb->state == LISTEN) {
1025     lpcb = (struct tcp_pcb_listen *)pcb;
1026     res = ERR_ALREADY;
1027     goto done;
1028   }
1029 #if SO_REUSE
1030   if (ip_get_option(pcb, SOF_REUSEADDR)) {
1031     /* Since SOF_REUSEADDR allows reusing a local address before the pcb's usage
1032        is declared (listen-/connection-pcb), we have to make sure now that
1033        this port is only used once for every local IP. */
1034     for (lpcb = tcp_listen_pcbs.listen_pcbs; lpcb != NULL; lpcb = lpcb->next) {
1035       if ((lpcb->local_port == pcb->local_port) &&
1036           ip_addr_cmp(&lpcb->local_ip, &pcb->local_ip)) {
1037         /* this address/port is already used */
1038         lpcb = NULL;
1039         res = ERR_USE;
1040         goto done;
1041       }
1042     }
1043   }
1044 #endif /* SO_REUSE */
1045   lpcb = (struct tcp_pcb_listen *)memp_malloc(MEMP_TCP_PCB_LISTEN);
1046   if (lpcb == NULL) {
1047     res = ERR_MEM;
1048     goto done;
1049   }
1050 #ifdef LOSCFG_NET_CONTAINER
1051   set_tcp_pcb_net_group((struct tcp_pcb *)lpcb, get_net_group_from_tcp_pcb(pcb));
1052 #endif
1053   lpcb->callback_arg = pcb->callback_arg;
1054   lpcb->local_port = pcb->local_port;
1055   lpcb->state = LISTEN;
1056   lpcb->prio = pcb->prio;
1057   lpcb->so_options = pcb->so_options;
1058   lpcb->netif_idx = pcb->netif_idx;
1059   lpcb->ttl = pcb->ttl;
1060   lpcb->tos = pcb->tos;
1061 #if LWIP_IPV4 && LWIP_IPV6
1062   IP_SET_TYPE_VAL(lpcb->remote_ip, pcb->local_ip.type);
1063 #endif /* LWIP_IPV4 && LWIP_IPV6 */
1064   ip_addr_copy(lpcb->local_ip, pcb->local_ip);
1065   if (pcb->local_port != 0) {
1066     TCP_RMV(&tcp_bound_pcbs, pcb);
1067   }
1068 #if LWIP_TCP_PCB_NUM_EXT_ARGS
1069   /* copy over ext_args to listening pcb  */
1070   memcpy(&lpcb->ext_args, &pcb->ext_args, sizeof(pcb->ext_args));
1071 #endif
1072   tcp_free(pcb);
1073 #if LWIP_CALLBACK_API
1074   lpcb->accept = tcp_accept_null;
1075 #endif /* LWIP_CALLBACK_API */
1076 #if TCP_LISTEN_BACKLOG
1077   lpcb->accepts_pending = 0;
1078   tcp_backlog_set(lpcb, backlog);
1079 #endif /* TCP_LISTEN_BACKLOG */
1080   TCP_REG(&tcp_listen_pcbs.pcbs, (struct tcp_pcb *)lpcb);
1081   res = ERR_OK;
1082 done:
1083   if (err != NULL) {
1084     *err = res;
1085   }
1086   return (struct tcp_pcb *)lpcb;
1087 }
1088 
1089 /**
1090  * Update the state that tracks the available window space to advertise.
1091  *
1092  * Returns how much extra window would be advertised if we sent an
1093  * update now.
1094  */
1095 u32_t
1096 tcp_update_rcv_ann_wnd(struct tcp_pcb *pcb)
1097 {
1098   u32_t new_right_edge;
1099 
1100   LWIP_ASSERT("tcp_update_rcv_ann_wnd: invalid pcb", pcb != NULL);
1101   new_right_edge = pcb->rcv_nxt + pcb->rcv_wnd;
1102 
1103   if (TCP_SEQ_GEQ(new_right_edge, pcb->rcv_ann_right_edge + LWIP_MIN((TCP_WND / 2), pcb->mss))) {
1104     /* we can advertise more window */
1105     pcb->rcv_ann_wnd = pcb->rcv_wnd;
1106     return new_right_edge - pcb->rcv_ann_right_edge;
1107   } else {
1108     if (TCP_SEQ_GT(pcb->rcv_nxt, pcb->rcv_ann_right_edge)) {
1109       /* Can happen due to other end sending out of advertised window,
1110        * but within actual available (but not yet advertised) window */
1111       pcb->rcv_ann_wnd = 0;
1112     } else {
1113       /* keep the right edge of window constant */
1114       u32_t new_rcv_ann_wnd = pcb->rcv_ann_right_edge - pcb->rcv_nxt;
1115 #if !LWIP_WND_SCALE
1116       LWIP_ASSERT("new_rcv_ann_wnd <= 0xffff", new_rcv_ann_wnd <= 0xffff);
1117 #endif
1118       pcb->rcv_ann_wnd = (tcpwnd_size_t)new_rcv_ann_wnd;
1119     }
1120     return 0;
1121   }
1122 }
1123 
1124 /**
1125  * @ingroup tcp_raw
1126  * This function should be called by the application when it has
1127  * processed the data. The purpose is to advertise a larger window
1128  * when the data has been processed.
1129  *
1130  * @param pcb the tcp_pcb for which data is read
1131  * @param len the amount of bytes that have been read by the application
1132  */
1133 void
1134 tcp_recved(struct tcp_pcb *pcb, u16_t len)
1135 {
1136   u32_t wnd_inflation;
1137   tcpwnd_size_t rcv_wnd;
1138 
1139   LWIP_ASSERT_CORE_LOCKED();
1140 
1141   LWIP_ERROR("tcp_recved: invalid pcb", pcb != NULL, return);
1142 
1143   /* pcb->state LISTEN not allowed here */
1144   LWIP_ASSERT("don't call tcp_recved for listen-pcbs",
1145               pcb->state != LISTEN);
1146 
1147   rcv_wnd = (tcpwnd_size_t)(pcb->rcv_wnd + len);
1148   if ((rcv_wnd > TCP_WND_MAX(pcb)) || (rcv_wnd < pcb->rcv_wnd)) {
1149     /* window got too big or tcpwnd_size_t overflow */
1150     LWIP_DEBUGF(TCP_DEBUG, ("tcp_recved: window got too big or tcpwnd_size_t overflow\n"));
1151     pcb->rcv_wnd = TCP_WND_MAX(pcb);
1152   } else  {
1153     pcb->rcv_wnd = rcv_wnd;
1154   }
1155 
1156   wnd_inflation = tcp_update_rcv_ann_wnd(pcb);
1157 
1158   /* If the change in the right edge of window is significant (default
1159    * watermark is TCP_WND/4), then send an explicit update now.
1160    * Otherwise wait for a packet to be sent in the normal course of
1161    * events (or more window to be available later) */
1162   if (wnd_inflation >= TCP_WND_UPDATE_THRESHOLD) {
1163     tcp_ack_now(pcb);
1164     tcp_output(pcb);
1165   }
1166 
1167   LWIP_DEBUGF(TCP_DEBUG, ("tcp_recved: received %"U16_F" bytes, wnd %"TCPWNDSIZE_F" (%"TCPWNDSIZE_F").\n",
1168                           len, pcb->rcv_wnd, (u16_t)(TCP_WND_MAX(pcb) - pcb->rcv_wnd)));
1169 }
1170 
1171 /**
1172  * Allocate a new local TCP port.
1173  *
1174  * @return a new (free) local TCP port number
1175  */
1176 static u16_t
1177 tcp_new_port(void)
1178 {
1179   u8_t i;
1180   u16_t n = 0;
1181   struct tcp_pcb *pcb;
1182 
1183 again:
1184   tcp_port++;
1185   if (tcp_port == TCP_LOCAL_PORT_RANGE_END) {
1186     tcp_port = TCP_LOCAL_PORT_RANGE_START;
1187   }
1188   /* Check all PCB lists. */
1189   for (i = 0; i < NUM_TCP_PCB_LISTS; i++) {
1190     for (pcb = *tcp_pcb_lists[i]; pcb != NULL; pcb = pcb->next) {
1191       if (pcb->local_port == tcp_port) {
1192         n++;
1193         if (n > (TCP_LOCAL_PORT_RANGE_END - TCP_LOCAL_PORT_RANGE_START)) {
1194           return 0;
1195         }
1196         goto again;
1197       }
1198     }
1199   }
1200   return tcp_port;
1201 }
1202 
1203 /**
1204  * @ingroup tcp_raw
1205  * Connects to another host. The function given as the "connected"
1206  * argument will be called when the connection has been established.
1207  *  Sets up the pcb to connect to the remote host and sends the
1208  * initial SYN segment which opens the connection.
1209  *
1210  * The tcp_connect() function returns immediately; it does not wait for
1211  * the connection to be properly setup. Instead, it will call the
1212  * function specified as the fourth argument (the "connected" argument)
1213  * when the connection is established. If the connection could not be
1214  * properly established, either because the other host refused the
1215  * connection or because the other host didn't answer, the "err"
1216  * callback function of this pcb (registered with tcp_err, see below)
1217  * will be called.
1218  *
1219  * The tcp_connect() function can return ERR_MEM if no memory is
1220  * available for enqueueing the SYN segment. If the SYN indeed was
1221  * enqueued successfully, the tcp_connect() function returns ERR_OK.
1222  *
1223  * @param pcb the tcp_pcb used to establish the connection
1224  * @param ipaddr the remote ip address to connect to
1225  * @param port the remote tcp port to connect to
1226  * @param connected callback function to call when connected (on error,
1227                     the err calback will be called)
1228  * @return ERR_VAL if invalid arguments are given
1229  *         ERR_OK if connect request has been sent
1230  *         other err_t values if connect request couldn't be sent
1231  */
1232 err_t
1233 tcp_connect(struct tcp_pcb *pcb, const ip_addr_t *ipaddr, u16_t port,
1234             tcp_connected_fn connected)
1235 {
1236   struct netif *netif = NULL;
1237   err_t ret;
1238   u32_t iss;
1239   u16_t old_local_port;
1240 
1241   LWIP_ASSERT_CORE_LOCKED();
1242 
1243   LWIP_ERROR("tcp_connect: invalid pcb", pcb != NULL, return ERR_ARG);
1244   LWIP_ERROR("tcp_connect: invalid ipaddr", ipaddr != NULL, return ERR_ARG);
1245 
1246   LWIP_ERROR("tcp_connect: can only connect from state CLOSED", pcb->state == CLOSED, return ERR_ISCONN);
1247 
1248 #ifdef LOSCFG_NET_CONTAINER
1249   struct net_group *group = get_net_group_from_tcp_pcb(pcb);
1250   LWIP_ERROR("tcp_connect: invalid net group", group != NULL, return ERR_RTE);
1251 #endif
1252   LWIP_DEBUGF(TCP_DEBUG, ("tcp_connect to port %"U16_F"\n", port));
1253   ip_addr_set(&pcb->remote_ip, ipaddr);
1254   pcb->remote_port = port;
1255 
1256   if (pcb->netif_idx != NETIF_NO_INDEX) {
1257 #ifdef LOSCFG_NET_CONTAINER
1258     netif = netif_get_by_index(pcb->netif_idx, group);
1259 #else
1260     netif = netif_get_by_index(pcb->netif_idx);
1261 #endif
1262   } else {
1263     /* check if we have a route to the remote host */
1264 #ifdef LOSCFG_NET_CONTAINER
1265     netif = ip_route(&pcb->local_ip, &pcb->remote_ip, group);
1266 #else
1267     netif = ip_route(&pcb->local_ip, &pcb->remote_ip);
1268 #endif
1269   }
1270   if (netif == NULL) {
1271     /* Don't even try to send a SYN packet if we have no route since that will fail. */
1272     return ERR_RTE;
1273   }
1274 
1275   /* check if local IP has been assigned to pcb, if not, get one */
1276   if (ip_addr_isany(&pcb->local_ip)) {
1277     const ip_addr_t *local_ip = ip_netif_get_local_ip(netif, ipaddr);
1278     if (local_ip == NULL) {
1279       return ERR_RTE;
1280     }
1281     ip_addr_copy(pcb->local_ip, *local_ip);
1282   }
1283 
1284 #if LWIP_IPV6 && LWIP_IPV6_SCOPES
1285   /* If the given IP address should have a zone but doesn't, assign one now.
1286    * Given that we already have the target netif, this is easy and cheap. */
1287   if (IP_IS_V6(&pcb->remote_ip) &&
1288       ip6_addr_lacks_zone(ip_2_ip6(&pcb->remote_ip), IP6_UNICAST)) {
1289     ip6_addr_assign_zone(ip_2_ip6(&pcb->remote_ip), IP6_UNICAST, netif);
1290   }
1291 #endif /* LWIP_IPV6 && LWIP_IPV6_SCOPES */
1292 
1293   old_local_port = pcb->local_port;
1294   if (pcb->local_port == 0) {
1295     pcb->local_port = tcp_new_port();
1296     if (pcb->local_port == 0) {
1297       return ERR_BUF;
1298     }
1299   } else {
1300 #if SO_REUSE
1301     if (ip_get_option(pcb, SOF_REUSEADDR)) {
1302       /* Since SOF_REUSEADDR allows reusing a local address, we have to make sure
1303          now that the 5-tuple is unique. */
1304       struct tcp_pcb *cpcb;
1305       int i;
1306       /* Don't check listen- and bound-PCBs, check active- and TIME-WAIT PCBs. */
1307       for (i = 2; i < NUM_TCP_PCB_LISTS; i++) {
1308         for (cpcb = *tcp_pcb_lists[i]; cpcb != NULL; cpcb = cpcb->next) {
1309           if ((cpcb->local_port == pcb->local_port) &&
1310               (cpcb->remote_port == port) &&
1311               ip_addr_cmp(&cpcb->local_ip, &pcb->local_ip) &&
1312               ip_addr_cmp(&cpcb->remote_ip, ipaddr)) {
1313             /* linux returns EISCONN here, but ERR_USE should be OK for us */
1314             return ERR_USE;
1315           }
1316         }
1317       }
1318     }
1319 #endif /* SO_REUSE */
1320   }
1321 
1322   iss = tcp_next_iss(pcb);
1323   pcb->rcv_nxt = 0;
1324   pcb->snd_nxt = iss;
1325   pcb->lastack = iss - 1;
1326   pcb->snd_wl2 = iss - 1;
1327   pcb->snd_lbb = iss - 1;
1328   /* Start with a window that does not need scaling. When window scaling is
1329      enabled and used, the window is enlarged when both sides agree on scaling. */
1330   pcb->rcv_wnd = pcb->rcv_ann_wnd = TCPWND_MIN16(TCP_WND);
1331   pcb->rcv_ann_right_edge = pcb->rcv_nxt;
1332   pcb->snd_wnd = TCP_WND;
1333   /* As initial send MSS, we use TCP_MSS but limit it to 536.
1334      The send MSS is updated when an MSS option is received. */
1335   pcb->mss = INITIAL_MSS;
1336 #if TCP_CALCULATE_EFF_SEND_MSS
1337   pcb->mss = tcp_eff_send_mss_netif(pcb->mss, netif, &pcb->remote_ip);
1338 #endif /* TCP_CALCULATE_EFF_SEND_MSS */
1339   pcb->cwnd = 1;
1340 #if LWIP_CALLBACK_API
1341   pcb->connected = connected;
1342 #else /* LWIP_CALLBACK_API */
1343   LWIP_UNUSED_ARG(connected);
1344 #endif /* LWIP_CALLBACK_API */
1345 
1346   /* Send a SYN together with the MSS option. */
1347   ret = tcp_enqueue_flags(pcb, TCP_SYN);
1348   if (ret == ERR_OK) {
1349     /* SYN segment was enqueued, changed the pcbs state now */
1350     pcb->state = SYN_SENT;
1351     if (old_local_port != 0) {
1352       TCP_RMV(&tcp_bound_pcbs, pcb);
1353     }
1354     TCP_REG_ACTIVE(pcb);
1355     MIB2_STATS_INC(mib2.tcpactiveopens);
1356 
1357     tcp_output(pcb);
1358   }
1359   return ret;
1360 }
1361 
1362 /**
1363  * Called every 500 ms and implements the retransmission timer and the timer that
1364  * removes PCBs that have been in TIME-WAIT for enough time. It also increments
1365  * various timers such as the inactivity timer in each PCB.
1366  *
1367  * Automatically called from tcp_tmr().
1368  */
1369 void
1370 tcp_slowtmr(void)
1371 {
1372   struct tcp_pcb *pcb, *prev;
1373   tcpwnd_size_t eff_wnd;
1374   u8_t pcb_remove;      /* flag if a PCB should be removed */
1375   u8_t pcb_reset;       /* flag if a RST should be sent when removing */
1376   err_t err;
1377 
1378   err = ERR_OK;
1379 
1380   ++tcp_ticks;
1381   ++tcp_timer_ctr;
1382 
1383 tcp_slowtmr_start:
1384   /* Steps through all of the active PCBs. */
1385   prev = NULL;
1386   pcb = tcp_active_pcbs;
1387   if (pcb == NULL) {
1388     LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: no active pcbs\n"));
1389   }
1390   while (pcb != NULL) {
1391     LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: processing active pcb\n"));
1392     LWIP_ASSERT("tcp_slowtmr: active pcb->state != CLOSED\n", pcb->state != CLOSED);
1393     LWIP_ASSERT("tcp_slowtmr: active pcb->state != LISTEN\n", pcb->state != LISTEN);
1394     LWIP_ASSERT("tcp_slowtmr: active pcb->state != TIME-WAIT\n", pcb->state != TIME_WAIT);
1395     if (pcb->last_timer == tcp_timer_ctr) {
1396       /* skip this pcb, we have already processed it */
1397       prev = pcb;
1398       pcb = pcb->next;
1399       continue;
1400     }
1401     pcb->last_timer = tcp_timer_ctr;
1402 
1403     pcb_remove = 0;
1404     pcb_reset = 0;
1405 
1406     if (pcb->state == SYN_SENT && pcb->nrtx >= TCP_SYNMAXRTX) {
1407       ++pcb_remove;
1408       LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: max SYN retries reached\n"));
1409     } else if (pcb->nrtx >= TCP_MAXRTX) {
1410       ++pcb_remove;
1411       LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: max DATA retries reached\n"));
1412     } else {
1413       if (pcb->persist_backoff > 0) {
1414         LWIP_ASSERT("tcp_slowtimr: persist ticking with in-flight data", pcb->unacked == NULL);
1415         LWIP_ASSERT("tcp_slowtimr: persist ticking with empty send buffer", pcb->unsent != NULL);
1416         if (pcb->persist_probe >= TCP_MAXRTX) {
1417           ++pcb_remove; /* max probes reached */
1418         } else {
1419           u8_t backoff_cnt = tcp_persist_backoff[pcb->persist_backoff - 1];
1420           if (pcb->persist_cnt < backoff_cnt) {
1421             pcb->persist_cnt++;
1422           }
1423           if (pcb->persist_cnt >= backoff_cnt) {
1424             int next_slot = 1; /* increment timer to next slot */
1425             /* If snd_wnd is zero, send 1 byte probes */
1426             if (pcb->snd_wnd == 0) {
1427               if (tcp_zero_window_probe(pcb) != ERR_OK) {
1428                 next_slot = 0; /* try probe again with current slot */
1429               }
1430               /* snd_wnd not fully closed, split unsent head and fill window */
1431             } else {
1432               if (tcp_split_unsent_seg(pcb, (u16_t)pcb->snd_wnd) == ERR_OK) {
1433                 if (tcp_output(pcb) == ERR_OK) {
1434                   /* sending will cancel persist timer, else retry with current slot */
1435                   next_slot = 0;
1436                 }
1437               }
1438             }
1439             if (next_slot) {
1440               pcb->persist_cnt = 0;
1441               if (pcb->persist_backoff < sizeof(tcp_persist_backoff)) {
1442                 pcb->persist_backoff++;
1443               }
1444             }
1445           }
1446         }
1447       } else {
1448         /* Increase the retransmission timer if it is running */
1449         if ((pcb->rtime >= 0) && (pcb->rtime < 0x7FFF)) {
1450           ++pcb->rtime;
1451         }
1452 
1453         if (pcb->rtime >= pcb->rto) {
1454           /* Time for a retransmission. */
1455           LWIP_DEBUGF(TCP_RTO_DEBUG, ("tcp_slowtmr: rtime %"S16_F
1456                                       " pcb->rto %"S16_F"\n",
1457                                       pcb->rtime, pcb->rto));
1458           /* If prepare phase fails but we have unsent data but no unacked data,
1459              still execute the backoff calculations below, as this means we somehow
1460              failed to send segment. */
1461           if ((tcp_rexmit_rto_prepare(pcb) == ERR_OK) || ((pcb->unacked == NULL) && (pcb->unsent != NULL))) {
1462             /* Double retransmission time-out unless we are trying to
1463              * connect to somebody (i.e., we are in SYN_SENT). */
1464             if (pcb->state != SYN_SENT) {
1465               u8_t backoff_idx = LWIP_MIN(pcb->nrtx, sizeof(tcp_backoff) - 1);
1466               int calc_rto = ((pcb->sa >> 3) + pcb->sv) << tcp_backoff[backoff_idx];
1467               pcb->rto = (s16_t)LWIP_MIN(calc_rto, 0x7FFF);
1468             }
1469 
1470             /* Reset the retransmission timer. */
1471             pcb->rtime = 0;
1472 
1473             /* Reduce congestion window and ssthresh. */
1474             eff_wnd = LWIP_MIN(pcb->cwnd, pcb->snd_wnd);
1475             pcb->ssthresh = eff_wnd >> 1;
1476             if (pcb->ssthresh < (tcpwnd_size_t)(pcb->mss << 1)) {
1477               pcb->ssthresh = (tcpwnd_size_t)(pcb->mss << 1);
1478             }
1479             pcb->cwnd = pcb->mss;
1480             LWIP_DEBUGF(TCP_CWND_DEBUG, ("tcp_slowtmr: cwnd %"TCPWNDSIZE_F
1481                                          " ssthresh %"TCPWNDSIZE_F"\n",
1482                                          pcb->cwnd, pcb->ssthresh));
1483             pcb->bytes_acked = 0;
1484 
1485             /* The following needs to be called AFTER cwnd is set to one
1486                mss - STJ */
1487             tcp_rexmit_rto_commit(pcb);
1488           }
1489         }
1490       }
1491     }
1492     /* Check if this PCB has stayed too long in FIN-WAIT-2 */
1493     if (pcb->state == FIN_WAIT_2) {
1494       /* If this PCB is in FIN_WAIT_2 because of SHUT_WR don't let it time out. */
1495       if (pcb->flags & TF_RXCLOSED) {
1496         /* PCB was fully closed (either through close() or SHUT_RDWR):
1497            normal FIN-WAIT timeout handling. */
1498         if ((u32_t)(tcp_ticks - pcb->tmr) >
1499             TCP_FIN_WAIT_TIMEOUT / TCP_SLOW_INTERVAL) {
1500           ++pcb_remove;
1501           LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: removing pcb stuck in FIN-WAIT-2\n"));
1502         }
1503       }
1504     }
1505 
1506     /* Check if KEEPALIVE should be sent */
1507     if (ip_get_option(pcb, SOF_KEEPALIVE) &&
1508         ((pcb->state == ESTABLISHED) ||
1509          (pcb->state == CLOSE_WAIT))) {
1510       if ((u32_t)(tcp_ticks - pcb->tmr) >
1511           (pcb->keep_idle + TCP_KEEP_DUR(pcb)) / TCP_SLOW_INTERVAL) {
1512         LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: KEEPALIVE timeout. Aborting connection to "));
1513         ip_addr_debug_print_val(TCP_DEBUG, pcb->remote_ip);
1514         LWIP_DEBUGF(TCP_DEBUG, ("\n"));
1515 
1516         ++pcb_remove;
1517         ++pcb_reset;
1518       } else if ((u32_t)(tcp_ticks - pcb->tmr) >
1519                  (pcb->keep_idle + pcb->keep_cnt_sent * TCP_KEEP_INTVL(pcb))
1520                  / TCP_SLOW_INTERVAL) {
1521         err = tcp_keepalive(pcb);
1522         if (err == ERR_OK) {
1523           pcb->keep_cnt_sent++;
1524         }
1525       }
1526     }
1527 
1528     /* If this PCB has queued out of sequence data, but has been
1529        inactive for too long, will drop the data (it will eventually
1530        be retransmitted). */
1531 #if TCP_QUEUE_OOSEQ
1532     if (pcb->ooseq != NULL &&
1533         (tcp_ticks - pcb->tmr >= (u32_t)pcb->rto * TCP_OOSEQ_TIMEOUT)) {
1534       LWIP_DEBUGF(TCP_CWND_DEBUG, ("tcp_slowtmr: dropping OOSEQ queued data\n"));
1535       tcp_free_ooseq(pcb);
1536     }
1537 #endif /* TCP_QUEUE_OOSEQ */
1538 
1539     /* Check if this PCB has stayed too long in SYN-RCVD */
1540     if (pcb->state == SYN_RCVD) {
1541       if ((u32_t)(tcp_ticks - pcb->tmr) >
1542           TCP_SYN_RCVD_TIMEOUT / TCP_SLOW_INTERVAL) {
1543         ++pcb_remove;
1544         LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: removing pcb stuck in SYN-RCVD\n"));
1545       }
1546     }
1547 
1548     /* Check if this PCB has stayed too long in LAST-ACK */
1549     if (pcb->state == LAST_ACK) {
1550       if ((u32_t)(tcp_ticks - pcb->tmr) > 2 * TCP_MSL / TCP_SLOW_INTERVAL) {
1551         ++pcb_remove;
1552         LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: removing pcb stuck in LAST-ACK\n"));
1553       }
1554     }
1555 
1556     /* If the PCB should be removed, do it. */
1557     if (pcb_remove) {
1558       struct tcp_pcb *pcb2;
1559 #if LWIP_CALLBACK_API
1560       tcp_err_fn err_fn = pcb->errf;
1561 #endif /* LWIP_CALLBACK_API */
1562       void *err_arg;
1563       enum tcp_state last_state;
1564       tcp_pcb_purge(pcb);
1565       /* Remove PCB from tcp_active_pcbs list. */
1566       if (prev != NULL) {
1567         LWIP_ASSERT("tcp_slowtmr: middle tcp != tcp_active_pcbs", pcb != tcp_active_pcbs);
1568         prev->next = pcb->next;
1569       } else {
1570         /* This PCB was the first. */
1571         LWIP_ASSERT("tcp_slowtmr: first pcb == tcp_active_pcbs", tcp_active_pcbs == pcb);
1572         tcp_active_pcbs = pcb->next;
1573       }
1574 
1575       if (pcb_reset) {
1576         tcp_rst(pcb, pcb->snd_nxt, pcb->rcv_nxt, &pcb->local_ip, &pcb->remote_ip,
1577                 pcb->local_port, pcb->remote_port);
1578       }
1579 
1580       err_arg = pcb->callback_arg;
1581       last_state = pcb->state;
1582       pcb2 = pcb;
1583       pcb = pcb->next;
1584       tcp_free(pcb2);
1585 
1586       tcp_active_pcbs_changed = 0;
1587       TCP_EVENT_ERR(last_state, err_fn, err_arg, ERR_ABRT);
1588       if (tcp_active_pcbs_changed) {
1589         goto tcp_slowtmr_start;
1590       }
1591     } else {
1592       /* get the 'next' element now and work with 'prev' below (in case of abort) */
1593       prev = pcb;
1594       pcb = pcb->next;
1595 
1596       /* We check if we should poll the connection. */
1597       ++prev->polltmr;
1598       if (prev->polltmr >= prev->pollinterval) {
1599         prev->polltmr = 0;
1600         LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: polling application\n"));
1601         tcp_active_pcbs_changed = 0;
1602         TCP_EVENT_POLL(prev, err);
1603         if (tcp_active_pcbs_changed) {
1604           goto tcp_slowtmr_start;
1605         }
1606         /* if err == ERR_ABRT, 'prev' is already deallocated */
1607         if (err == ERR_OK) {
1608           tcp_output(prev);
1609         }
1610       }
1611     }
1612   }
1613 
1614 
1615   /* Steps through all of the TIME-WAIT PCBs. */
1616   prev = NULL;
1617   pcb = tcp_tw_pcbs;
1618   while (pcb != NULL) {
1619     LWIP_ASSERT("tcp_slowtmr: TIME-WAIT pcb->state == TIME-WAIT", pcb->state == TIME_WAIT);
1620     pcb_remove = 0;
1621 
1622     /* Check if this PCB has stayed long enough in TIME-WAIT */
1623     if ((u32_t)(tcp_ticks - pcb->tmr) > 2 * TCP_MSL / TCP_SLOW_INTERVAL) {
1624       ++pcb_remove;
1625     }
1626 
1627     /* If the PCB should be removed, do it. */
1628     if (pcb_remove) {
1629       struct tcp_pcb *pcb2;
1630       tcp_pcb_purge(pcb);
1631       /* Remove PCB from tcp_tw_pcbs list. */
1632       if (prev != NULL) {
1633         LWIP_ASSERT("tcp_slowtmr: middle tcp != tcp_tw_pcbs", pcb != tcp_tw_pcbs);
1634         prev->next = pcb->next;
1635       } else {
1636         /* This PCB was the first. */
1637         LWIP_ASSERT("tcp_slowtmr: first pcb == tcp_tw_pcbs", tcp_tw_pcbs == pcb);
1638         tcp_tw_pcbs = pcb->next;
1639       }
1640       pcb2 = pcb;
1641       pcb = pcb->next;
1642       tcp_free(pcb2);
1643     } else {
1644       prev = pcb;
1645       pcb = pcb->next;
1646     }
1647   }
1648 }
1649 
1650 /**
1651  * Is called every TCP_FAST_INTERVAL (250 ms) and process data previously
1652  * "refused" by upper layer (application) and sends delayed ACKs or pending FINs.
1653  *
1654  * Automatically called from tcp_tmr().
1655  */
1656 void
1657 tcp_fasttmr(void)
1658 {
1659   struct tcp_pcb *pcb;
1660 
1661   ++tcp_timer_ctr;
1662 
1663 tcp_fasttmr_start:
1664   pcb = tcp_active_pcbs;
1665 
1666   while (pcb != NULL) {
1667     if (pcb->last_timer != tcp_timer_ctr) {
1668       struct tcp_pcb *next;
1669       pcb->last_timer = tcp_timer_ctr;
1670       /* send delayed ACKs */
1671       if (pcb->flags & TF_ACK_DELAY) {
1672         LWIP_DEBUGF(TCP_DEBUG, ("tcp_fasttmr: delayed ACK\n"));
1673         tcp_ack_now(pcb);
1674         tcp_output(pcb);
1675         tcp_clear_flags(pcb, TF_ACK_DELAY | TF_ACK_NOW);
1676       }
1677       /* send pending FIN */
1678       if (pcb->flags & TF_CLOSEPEND) {
1679         LWIP_DEBUGF(TCP_DEBUG, ("tcp_fasttmr: pending FIN\n"));
1680         tcp_clear_flags(pcb, TF_CLOSEPEND);
1681         tcp_close_shutdown_fin(pcb);
1682       }
1683 
1684       next = pcb->next;
1685 
1686       /* If there is data which was previously "refused" by upper layer */
1687       if (pcb->refused_data != NULL) {
1688         tcp_active_pcbs_changed = 0;
1689         tcp_process_refused_data(pcb);
1690         if (tcp_active_pcbs_changed) {
1691           /* application callback has changed the pcb list: restart the loop */
1692           goto tcp_fasttmr_start;
1693         }
1694       }
1695       pcb = next;
1696     } else {
1697       pcb = pcb->next;
1698     }
1699   }
1700 }
1701 
1702 /** Call tcp_output for all active pcbs that have TF_NAGLEMEMERR set */
1703 void
1704 tcp_txnow(void)
1705 {
1706   struct tcp_pcb *pcb;
1707 
1708   for (pcb = tcp_active_pcbs; pcb != NULL; pcb = pcb->next) {
1709     if (pcb->flags & TF_NAGLEMEMERR) {
1710       tcp_output(pcb);
1711     }
1712   }
1713 }
1714 
1715 /** Pass pcb->refused_data to the recv callback */
1716 err_t
1717 tcp_process_refused_data(struct tcp_pcb *pcb)
1718 {
1719 #if TCP_QUEUE_OOSEQ && LWIP_WND_SCALE
1720   struct pbuf *rest;
1721 #endif /* TCP_QUEUE_OOSEQ && LWIP_WND_SCALE */
1722 
1723   LWIP_ERROR("tcp_process_refused_data: invalid pcb", pcb != NULL, return ERR_ARG);
1724 
1725 #if TCP_QUEUE_OOSEQ && LWIP_WND_SCALE
1726   while (pcb->refused_data != NULL)
1727 #endif /* TCP_QUEUE_OOSEQ && LWIP_WND_SCALE */
1728   {
1729     err_t err;
1730     u8_t refused_flags = pcb->refused_data->flags;
1731     /* set pcb->refused_data to NULL in case the callback frees it and then
1732        closes the pcb */
1733     struct pbuf *refused_data = pcb->refused_data;
1734 #if TCP_QUEUE_OOSEQ && LWIP_WND_SCALE
1735     pbuf_split_64k(refused_data, &rest);
1736     pcb->refused_data = rest;
1737 #else /* TCP_QUEUE_OOSEQ && LWIP_WND_SCALE */
1738     pcb->refused_data = NULL;
1739 #endif /* TCP_QUEUE_OOSEQ && LWIP_WND_SCALE */
1740     /* Notify again application with data previously received. */
1741     LWIP_DEBUGF(TCP_INPUT_DEBUG, ("tcp_input: notify kept packet\n"));
1742     TCP_EVENT_RECV(pcb, refused_data, ERR_OK, err);
1743     if (err == ERR_OK) {
1744       /* did refused_data include a FIN? */
1745       if ((refused_flags & PBUF_FLAG_TCP_FIN)
1746 #if TCP_QUEUE_OOSEQ && LWIP_WND_SCALE
1747           && (rest == NULL)
1748 #endif /* TCP_QUEUE_OOSEQ && LWIP_WND_SCALE */
1749          ) {
1750         /* correct rcv_wnd as the application won't call tcp_recved()
1751            for the FIN's seqno */
1752         if (pcb->rcv_wnd != TCP_WND_MAX(pcb)) {
1753           pcb->rcv_wnd++;
1754         }
1755         TCP_EVENT_CLOSED(pcb, err);
1756         if (err == ERR_ABRT) {
1757           return ERR_ABRT;
1758         }
1759       }
1760     } else if (err == ERR_ABRT) {
1761       /* if err == ERR_ABRT, 'pcb' is already deallocated */
1762       /* Drop incoming packets because pcb is "full" (only if the incoming
1763          segment contains data). */
1764       LWIP_DEBUGF(TCP_INPUT_DEBUG, ("tcp_input: drop incoming packets, because pcb is \"full\"\n"));
1765       return ERR_ABRT;
1766     } else {
1767       /* data is still refused, pbuf is still valid (go on for ACK-only packets) */
1768 #if TCP_QUEUE_OOSEQ && LWIP_WND_SCALE
1769       if (rest != NULL) {
1770         pbuf_cat(refused_data, rest);
1771       }
1772 #endif /* TCP_QUEUE_OOSEQ && LWIP_WND_SCALE */
1773       pcb->refused_data = refused_data;
1774       return ERR_INPROGRESS;
1775     }
1776   }
1777   return ERR_OK;
1778 }
1779 
1780 /**
1781  * Deallocates a list of TCP segments (tcp_seg structures).
1782  *
1783  * @param seg tcp_seg list of TCP segments to free
1784  */
1785 void
1786 tcp_segs_free(struct tcp_seg *seg)
1787 {
1788   while (seg != NULL) {
1789     struct tcp_seg *next = seg->next;
1790     tcp_seg_free(seg);
1791     seg = next;
1792   }
1793 }
1794 
1795 /**
1796  * Frees a TCP segment (tcp_seg structure).
1797  *
1798  * @param seg single tcp_seg to free
1799  */
1800 void
1801 tcp_seg_free(struct tcp_seg *seg)
1802 {
1803   if (seg != NULL) {
1804     if (seg->p != NULL) {
1805       pbuf_free(seg->p);
1806 #if TCP_DEBUG
1807       seg->p = NULL;
1808 #endif /* TCP_DEBUG */
1809     }
1810     memp_free(MEMP_TCP_SEG, seg);
1811   }
1812 }
1813 
1814 /**
1815  * @ingroup tcp
1816  * Sets the priority of a connection.
1817  *
1818  * @param pcb the tcp_pcb to manipulate
1819  * @param prio new priority
1820  */
1821 void
1822 tcp_setprio(struct tcp_pcb *pcb, u8_t prio)
1823 {
1824   LWIP_ASSERT_CORE_LOCKED();
1825 
1826   LWIP_ERROR("tcp_setprio: invalid pcb", pcb != NULL, return);
1827 
1828   pcb->prio = prio;
1829 }
1830 
1831 #if TCP_QUEUE_OOSEQ
1832 /**
1833  * Returns a copy of the given TCP segment.
1834  * The pbuf and data are not copied, only the pointers
1835  *
1836  * @param seg the old tcp_seg
1837  * @return a copy of seg
1838  */
1839 struct tcp_seg *
1840 tcp_seg_copy(struct tcp_seg *seg)
1841 {
1842   struct tcp_seg *cseg;
1843 
1844   LWIP_ASSERT("tcp_seg_copy: invalid seg", seg != NULL);
1845 
1846   cseg = (struct tcp_seg *)memp_malloc(MEMP_TCP_SEG);
1847   if (cseg == NULL) {
1848     return NULL;
1849   }
1850   SMEMCPY((u8_t *)cseg, (const u8_t *)seg, sizeof(struct tcp_seg));
1851   pbuf_ref(cseg->p);
1852   return cseg;
1853 }
1854 #endif /* TCP_QUEUE_OOSEQ */
1855 
1856 #if LWIP_CALLBACK_API
1857 /**
1858  * Default receive callback that is called if the user didn't register
1859  * a recv callback for the pcb.
1860  */
1861 err_t
1862 tcp_recv_null(void *arg, struct tcp_pcb *pcb, struct pbuf *p, err_t err)
1863 {
1864   LWIP_UNUSED_ARG(arg);
1865 
1866   LWIP_ERROR("tcp_recv_null: invalid pcb", pcb != NULL, return ERR_ARG);
1867 
1868   if (p != NULL) {
1869     tcp_recved(pcb, p->tot_len);
1870     pbuf_free(p);
1871   } else if (err == ERR_OK) {
1872     return tcp_close(pcb);
1873   }
1874   return ERR_OK;
1875 }
1876 #endif /* LWIP_CALLBACK_API */
1877 
1878 /**
1879  * Kills the oldest active connection that has a lower priority than 'prio'.
1880  *
1881  * @param prio minimum priority
1882  */
1883 static void
1884 tcp_kill_prio(u8_t prio)
1885 {
1886   struct tcp_pcb *pcb, *inactive;
1887   u32_t inactivity;
1888   u8_t mprio;
1889 
1890   mprio = LWIP_MIN(TCP_PRIO_MAX, prio);
1891 
1892   /* We want to kill connections with a lower prio, so bail out if
1893    * supplied prio is 0 - there can never be a lower prio
1894    */
1895   if (mprio == 0) {
1896     return;
1897   }
1898 
1899   /* We only want kill connections with a lower prio, so decrement prio by one
1900    * and start searching for oldest connection with same or lower priority than mprio.
1901    * We want to find the connections with the lowest possible prio, and among
1902    * these the one with the longest inactivity time.
1903    */
1904   mprio--;
1905 
1906   inactivity = 0;
1907   inactive = NULL;
1908   for (pcb = tcp_active_pcbs; pcb != NULL; pcb = pcb->next) {
1909         /* lower prio is always a kill candidate */
1910     if ((pcb->prio < mprio) ||
1911         /* longer inactivity is also a kill candidate */
1912         ((pcb->prio == mprio) && ((u32_t)(tcp_ticks - pcb->tmr) >= inactivity))) {
1913       inactivity = tcp_ticks - pcb->tmr;
1914       inactive   = pcb;
1915       mprio      = pcb->prio;
1916     }
1917   }
1918   if (inactive != NULL) {
1919     LWIP_DEBUGF(TCP_DEBUG, ("tcp_kill_prio: killing oldest PCB %p (%"S32_F")\n",
1920                             (void *)inactive, inactivity));
1921     tcp_abort(inactive);
1922   }
1923 }
1924 
1925 /**
1926  * Kills the oldest connection that is in specific state.
1927  * Called from tcp_alloc() for LAST_ACK and CLOSING if no more connections are available.
1928  */
1929 static void
1930 tcp_kill_state(enum tcp_state state)
1931 {
1932   struct tcp_pcb *pcb, *inactive;
1933   u32_t inactivity;
1934 
1935   LWIP_ASSERT("invalid state", (state == CLOSING) || (state == LAST_ACK));
1936 
1937   inactivity = 0;
1938   inactive = NULL;
1939   /* Go through the list of active pcbs and get the oldest pcb that is in state
1940      CLOSING/LAST_ACK. */
1941   for (pcb = tcp_active_pcbs; pcb != NULL; pcb = pcb->next) {
1942     if (pcb->state == state) {
1943       if ((u32_t)(tcp_ticks - pcb->tmr) >= inactivity) {
1944         inactivity = tcp_ticks - pcb->tmr;
1945         inactive = pcb;
1946       }
1947     }
1948   }
1949   if (inactive != NULL) {
1950     LWIP_DEBUGF(TCP_DEBUG, ("tcp_kill_closing: killing oldest %s PCB %p (%"S32_F")\n",
1951                             tcp_state_str[state], (void *)inactive, inactivity));
1952     /* Don't send a RST, since no data is lost. */
1953     tcp_abandon(inactive, 0);
1954   }
1955 }
1956 
1957 /**
1958  * Kills the oldest connection that is in TIME_WAIT state.
1959  * Called from tcp_alloc() if no more connections are available.
1960  */
1961 static void
1962 tcp_kill_timewait(void)
1963 {
1964   struct tcp_pcb *pcb, *inactive;
1965   u32_t inactivity;
1966 
1967   inactivity = 0;
1968   inactive = NULL;
1969   /* Go through the list of TIME_WAIT pcbs and get the oldest pcb. */
1970   for (pcb = tcp_tw_pcbs; pcb != NULL; pcb = pcb->next) {
1971     if ((u32_t)(tcp_ticks - pcb->tmr) >= inactivity) {
1972       inactivity = tcp_ticks - pcb->tmr;
1973       inactive = pcb;
1974     }
1975   }
1976   if (inactive != NULL) {
1977     LWIP_DEBUGF(TCP_DEBUG, ("tcp_kill_timewait: killing oldest TIME-WAIT PCB %p (%"S32_F")\n",
1978                             (void *)inactive, inactivity));
1979     tcp_abort(inactive);
1980   }
1981 }
1982 
1983 /* Called when allocating a pcb fails.
1984  * In this case, we want to handle all pcbs that want to close first: if we can
1985  * now send the FIN (which failed before), the pcb might be in a state that is
1986  * OK for us to now free it.
1987  */
1988 static void
1989 tcp_handle_closepend(void)
1990 {
1991   struct tcp_pcb *pcb = tcp_active_pcbs;
1992 
1993   while (pcb != NULL) {
1994     struct tcp_pcb *next = pcb->next;
1995     /* send pending FIN */
1996     if (pcb->flags & TF_CLOSEPEND) {
1997       LWIP_DEBUGF(TCP_DEBUG, ("tcp_handle_closepend: pending FIN\n"));
1998       tcp_clear_flags(pcb, TF_CLOSEPEND);
1999       tcp_close_shutdown_fin(pcb);
2000     }
2001     pcb = next;
2002   }
2003 }
2004 
2005 /**
2006  * Allocate a new tcp_pcb structure.
2007  *
2008  * @param prio priority for the new pcb
2009  * @return a new tcp_pcb that initially is in state CLOSED
2010  */
2011 struct tcp_pcb *
2012 tcp_alloc(u8_t prio)
2013 {
2014   struct tcp_pcb *pcb;
2015 
2016   LWIP_ASSERT_CORE_LOCKED();
2017 
2018   pcb = (struct tcp_pcb *)memp_malloc(MEMP_TCP_PCB);
2019   if (pcb == NULL) {
2020     /* Try to send FIN for all pcbs stuck in TF_CLOSEPEND first */
2021     tcp_handle_closepend();
2022 
2023     /* Try killing oldest connection in TIME-WAIT. */
2024     LWIP_DEBUGF(TCP_DEBUG, ("tcp_alloc: killing off oldest TIME-WAIT connection\n"));
2025     tcp_kill_timewait();
2026     /* Try to allocate a tcp_pcb again. */
2027     pcb = (struct tcp_pcb *)memp_malloc(MEMP_TCP_PCB);
2028     if (pcb == NULL) {
2029       /* Try killing oldest connection in LAST-ACK (these wouldn't go to TIME-WAIT). */
2030       LWIP_DEBUGF(TCP_DEBUG, ("tcp_alloc: killing off oldest LAST-ACK connection\n"));
2031       tcp_kill_state(LAST_ACK);
2032       /* Try to allocate a tcp_pcb again. */
2033       pcb = (struct tcp_pcb *)memp_malloc(MEMP_TCP_PCB);
2034       if (pcb == NULL) {
2035         /* Try killing oldest connection in CLOSING. */
2036         LWIP_DEBUGF(TCP_DEBUG, ("tcp_alloc: killing off oldest CLOSING connection\n"));
2037         tcp_kill_state(CLOSING);
2038         /* Try to allocate a tcp_pcb again. */
2039         pcb = (struct tcp_pcb *)memp_malloc(MEMP_TCP_PCB);
2040         if (pcb == NULL) {
2041           /* Try killing oldest active connection with lower priority than the new one. */
2042           LWIP_DEBUGF(TCP_DEBUG, ("tcp_alloc: killing oldest connection with prio lower than %d\n", prio));
2043           tcp_kill_prio(prio);
2044           /* Try to allocate a tcp_pcb again. */
2045           pcb = (struct tcp_pcb *)memp_malloc(MEMP_TCP_PCB);
2046           if (pcb != NULL) {
2047             /* adjust err stats: memp_malloc failed multiple times before */
2048             MEMP_STATS_DEC(err, MEMP_TCP_PCB);
2049           }
2050         }
2051         if (pcb != NULL) {
2052           /* adjust err stats: memp_malloc failed multiple times before */
2053           MEMP_STATS_DEC(err, MEMP_TCP_PCB);
2054         }
2055       }
2056       if (pcb != NULL) {
2057         /* adjust err stats: memp_malloc failed multiple times before */
2058         MEMP_STATS_DEC(err, MEMP_TCP_PCB);
2059       }
2060     }
2061     if (pcb != NULL) {
2062       /* adjust err stats: memp_malloc failed above */
2063       MEMP_STATS_DEC(err, MEMP_TCP_PCB);
2064     }
2065   }
2066   if (pcb != NULL) {
2067     /* zero out the whole pcb, so there is no need to initialize members to zero */
2068     memset(pcb, 0, sizeof(struct tcp_pcb));
2069     pcb->prio = prio;
2070     pcb->snd_buf = TCP_SND_BUF;
2071     /* Start with a window that does not need scaling. When window scaling is
2072        enabled and used, the window is enlarged when both sides agree on scaling. */
2073     pcb->rcv_wnd = pcb->rcv_ann_wnd = TCPWND_MIN16(TCP_WND);
2074     pcb->ttl = TCP_TTL;
2075     /* As initial send MSS, we use TCP_MSS but limit it to 536.
2076        The send MSS is updated when an MSS option is received. */
2077     pcb->mss = INITIAL_MSS;
2078     pcb->rto = 3000 / TCP_SLOW_INTERVAL;
2079     pcb->sv = 3000 / TCP_SLOW_INTERVAL;
2080     pcb->rtime = -1;
2081     pcb->cwnd = 1;
2082     pcb->tmr = tcp_ticks;
2083     pcb->last_timer = tcp_timer_ctr;
2084 
2085     /* RFC 5681 recommends setting ssthresh abritrarily high and gives an example
2086     of using the largest advertised receive window.  We've seen complications with
2087     receiving TCPs that use window scaling and/or window auto-tuning where the
2088     initial advertised window is very small and then grows rapidly once the
2089     connection is established. To avoid these complications, we set ssthresh to the
2090     largest effective cwnd (amount of in-flight data) that the sender can have. */
2091     pcb->ssthresh = TCP_SND_BUF;
2092 
2093 #if LWIP_CALLBACK_API
2094     pcb->recv = tcp_recv_null;
2095 #endif /* LWIP_CALLBACK_API */
2096 
2097     /* Init KEEPALIVE timer */
2098     pcb->keep_idle  = TCP_KEEPIDLE_DEFAULT;
2099 
2100 #if LWIP_TCP_KEEPALIVE
2101     pcb->keep_intvl = TCP_KEEPINTVL_DEFAULT;
2102     pcb->keep_cnt   = TCP_KEEPCNT_DEFAULT;
2103 #endif /* LWIP_TCP_KEEPALIVE */
2104   }
2105   return pcb;
2106 }
2107 
2108 /**
2109  * @ingroup tcp_raw
2110  * Creates a new TCP protocol control block but doesn't place it on
2111  * any of the TCP PCB lists.
2112  * The pcb is not put on any list until binding using tcp_bind().
2113  * If memory is not available for creating the new pcb, NULL is returned.
2114  * @see MEMP_NUM_TCP_PCB_LISTEN and MEMP_NUM_TCP_PCB
2115  *
2116  * @internal: Maybe there should be a idle TCP PCB list where these
2117  * PCBs are put on. Port reservation using tcp_bind() is implemented but
2118  * allocated pcbs that are not bound can't be killed automatically if wanting
2119  * to allocate a pcb with higher prio (@see tcp_kill_prio())
2120  *
2121  * @return a new tcp_pcb that initially is in state CLOSED
2122  */
2123 struct tcp_pcb *
2124 tcp_new(void)
2125 {
2126   return tcp_alloc(TCP_PRIO_NORMAL);
2127 }
2128 
2129 /**
2130  * @ingroup tcp_raw
2131  * Creates a new TCP protocol control block but doesn't
2132  * place it on any of the TCP PCB lists.
2133  * The pcb is not put on any list until binding using tcp_bind().
2134  * @see MEMP_NUM_TCP_PCB_LISTEN and MEMP_NUM_TCP_PCB
2135  *
2136  * @param type IP address type, see @ref lwip_ip_addr_type definitions.
2137  * If you want to listen to IPv4 and IPv6 (dual-stack) connections,
2138  * supply @ref IPADDR_TYPE_ANY as argument and bind to @ref IP_ANY_TYPE.
2139  * @return a new tcp_pcb that initially is in state CLOSED
2140  */
2141 struct tcp_pcb *
2142 tcp_new_ip_type(u8_t type)
2143 {
2144   struct tcp_pcb *pcb;
2145   pcb = tcp_alloc(TCP_PRIO_NORMAL);
2146 #if LWIP_IPV4 && LWIP_IPV6
2147   if (pcb != NULL) {
2148     IP_SET_TYPE_VAL(pcb->local_ip, type);
2149     IP_SET_TYPE_VAL(pcb->remote_ip, type);
2150   }
2151 #else
2152   LWIP_UNUSED_ARG(type);
2153 #endif /* LWIP_IPV4 && LWIP_IPV6 */
2154   return pcb;
2155 }
2156 
2157 /**
2158  * @ingroup tcp_raw
2159  * Specifies the program specific state that should be passed to all
2160  * other callback functions. The "pcb" argument is the current TCP
2161  * connection control block, and the "arg" argument is the argument
2162  * that will be passed to the callbacks.
2163  *
2164  * @param pcb tcp_pcb to set the callback argument
2165  * @param arg void pointer argument to pass to callback functions
2166  */
2167 void
2168 tcp_arg(struct tcp_pcb *pcb, void *arg)
2169 {
2170   LWIP_ASSERT_CORE_LOCKED();
2171   /* This function is allowed to be called for both listen pcbs and
2172      connection pcbs. */
2173   if (pcb != NULL) {
2174     pcb->callback_arg = arg;
2175   }
2176 }
2177 #if LWIP_CALLBACK_API
2178 
2179 /**
2180  * @ingroup tcp_raw
2181  * Sets the callback function that will be called when new data
2182  * arrives. The callback function will be passed a NULL pbuf to
2183  * indicate that the remote host has closed the connection. If the
2184  * callback function returns ERR_OK or ERR_ABRT it must have
2185  * freed the pbuf, otherwise it must not have freed it.
2186  *
2187  * @param pcb tcp_pcb to set the recv callback
2188  * @param recv callback function to call for this pcb when data is received
2189  */
2190 void
2191 tcp_recv(struct tcp_pcb *pcb, tcp_recv_fn recv)
2192 {
2193   LWIP_ASSERT_CORE_LOCKED();
2194   if (pcb != NULL) {
2195     LWIP_ASSERT("invalid socket state for recv callback", pcb->state != LISTEN);
2196     pcb->recv = recv;
2197   }
2198 }
2199 
2200 /**
2201  * @ingroup tcp_raw
2202  * Specifies the callback function that should be called when data has
2203  * successfully been received (i.e., acknowledged) by the remote
2204  * host. The len argument passed to the callback function gives the
2205  * amount bytes that was acknowledged by the last acknowledgment.
2206  *
2207  * @param pcb tcp_pcb to set the sent callback
2208  * @param sent callback function to call for this pcb when data is successfully sent
2209  */
2210 void
2211 tcp_sent(struct tcp_pcb *pcb, tcp_sent_fn sent)
2212 {
2213   LWIP_ASSERT_CORE_LOCKED();
2214   if (pcb != NULL) {
2215     LWIP_ASSERT("invalid socket state for sent callback", pcb->state != LISTEN);
2216     pcb->sent = sent;
2217   }
2218 }
2219 
2220 /**
2221  * @ingroup tcp_raw
2222  * Used to specify the function that should be called when a fatal error
2223  * has occurred on the connection.
2224  *
2225  * If a connection is aborted because of an error, the application is
2226  * alerted of this event by the err callback. Errors that might abort a
2227  * connection are when there is a shortage of memory. The callback
2228  * function to be called is set using the tcp_err() function.
2229  *
2230  * @note The corresponding pcb is already freed when this callback is called!
2231  *
2232  * @param pcb tcp_pcb to set the err callback
2233  * @param err callback function to call for this pcb when a fatal error
2234  *        has occurred on the connection
2235  */
2236 void
2237 tcp_err(struct tcp_pcb *pcb, tcp_err_fn err)
2238 {
2239   LWIP_ASSERT_CORE_LOCKED();
2240   if (pcb != NULL) {
2241     LWIP_ASSERT("invalid socket state for err callback", pcb->state != LISTEN);
2242     pcb->errf = err;
2243   }
2244 }
2245 
2246 /**
2247  * @ingroup tcp_raw
2248  * Used for specifying the function that should be called when a
2249  * LISTENing connection has been connected to another host.
2250  * @see MEMP_NUM_TCP_PCB_LISTEN and MEMP_NUM_TCP_PCB
2251  *
2252  * @param pcb tcp_pcb to set the accept callback
2253  * @param accept callback function to call for this pcb when LISTENing
2254  *        connection has been connected to another host
2255  */
2256 void
2257 tcp_accept(struct tcp_pcb *pcb, tcp_accept_fn accept)
2258 {
2259   LWIP_ASSERT_CORE_LOCKED();
2260   if ((pcb != NULL) && (pcb->state == LISTEN)) {
2261     struct tcp_pcb_listen *lpcb = (struct tcp_pcb_listen *)pcb;
2262     lpcb->accept = accept;
2263   }
2264 }
2265 #endif /* LWIP_CALLBACK_API */
2266 
2267 
2268 /**
2269  * @ingroup tcp_raw
2270  * Specifies the polling interval and the callback function that should
2271  * be called to poll the application. The interval is specified in
2272  * number of TCP coarse grained timer shots, which typically occurs
2273  * twice a second. An interval of 10 means that the application would
2274  * be polled every 5 seconds.
2275  *
2276  * When a connection is idle (i.e., no data is either transmitted or
2277  * received), lwIP will repeatedly poll the application by calling a
2278  * specified callback function. This can be used either as a watchdog
2279  * timer for killing connections that have stayed idle for too long, or
2280  * as a method of waiting for memory to become available. For instance,
2281  * if a call to tcp_write() has failed because memory wasn't available,
2282  * the application may use the polling functionality to call tcp_write()
2283  * again when the connection has been idle for a while.
2284  */
2285 void
2286 tcp_poll(struct tcp_pcb *pcb, tcp_poll_fn poll, u8_t interval)
2287 {
2288   LWIP_ASSERT_CORE_LOCKED();
2289 
2290   LWIP_ERROR("tcp_poll: invalid pcb", pcb != NULL, return);
2291   LWIP_ASSERT("invalid socket state for poll", pcb->state != LISTEN);
2292 
2293 #if LWIP_CALLBACK_API
2294   pcb->poll = poll;
2295 #else /* LWIP_CALLBACK_API */
2296   LWIP_UNUSED_ARG(poll);
2297 #endif /* LWIP_CALLBACK_API */
2298   pcb->pollinterval = interval;
2299 }
2300 
2301 /**
2302  * Purges a TCP PCB. Removes any buffered data and frees the buffer memory
2303  * (pcb->ooseq, pcb->unsent and pcb->unacked are freed).
2304  *
2305  * @param pcb tcp_pcb to purge. The pcb itself is not deallocated!
2306  */
2307 void
2308 tcp_pcb_purge(struct tcp_pcb *pcb)
2309 {
2310   LWIP_ERROR("tcp_pcb_purge: invalid pcb", pcb != NULL, return);
2311 
2312   if (pcb->state != CLOSED &&
2313       pcb->state != TIME_WAIT &&
2314       pcb->state != LISTEN) {
2315 
2316     LWIP_DEBUGF(TCP_DEBUG, ("tcp_pcb_purge\n"));
2317 
2318     tcp_backlog_accepted(pcb);
2319 
2320     if (pcb->refused_data != NULL) {
2321       LWIP_DEBUGF(TCP_DEBUG, ("tcp_pcb_purge: data left on ->refused_data\n"));
2322       pbuf_free(pcb->refused_data);
2323       pcb->refused_data = NULL;
2324     }
2325     if (pcb->unsent != NULL) {
2326       LWIP_DEBUGF(TCP_DEBUG, ("tcp_pcb_purge: not all data sent\n"));
2327     }
2328     if (pcb->unacked != NULL) {
2329       LWIP_DEBUGF(TCP_DEBUG, ("tcp_pcb_purge: data left on ->unacked\n"));
2330     }
2331 #if TCP_QUEUE_OOSEQ
2332     if (pcb->ooseq != NULL) {
2333       LWIP_DEBUGF(TCP_DEBUG, ("tcp_pcb_purge: data left on ->ooseq\n"));
2334       tcp_free_ooseq(pcb);
2335     }
2336 #endif /* TCP_QUEUE_OOSEQ */
2337 
2338     /* Stop the retransmission timer as it will expect data on unacked
2339        queue if it fires */
2340     pcb->rtime = -1;
2341 
2342     tcp_segs_free(pcb->unsent);
2343     tcp_segs_free(pcb->unacked);
2344     pcb->unacked = pcb->unsent = NULL;
2345 #if TCP_OVERSIZE
2346     pcb->unsent_oversize = 0;
2347 #endif /* TCP_OVERSIZE */
2348   }
2349 }
2350 
2351 /**
2352  * Purges the PCB and removes it from a PCB list. Any delayed ACKs are sent first.
2353  *
2354  * @param pcblist PCB list to purge.
2355  * @param pcb tcp_pcb to purge. The pcb itself is NOT deallocated!
2356  */
2357 void
2358 tcp_pcb_remove(struct tcp_pcb **pcblist, struct tcp_pcb *pcb)
2359 {
2360   LWIP_ASSERT("tcp_pcb_remove: invalid pcb", pcb != NULL);
2361   LWIP_ASSERT("tcp_pcb_remove: invalid pcblist", pcblist != NULL);
2362 
2363   TCP_RMV(pcblist, pcb);
2364 
2365   tcp_pcb_purge(pcb);
2366 
2367   /* if there is an outstanding delayed ACKs, send it */
2368   if ((pcb->state != TIME_WAIT) &&
2369       (pcb->state != LISTEN) &&
2370       (pcb->flags & TF_ACK_DELAY)) {
2371     tcp_ack_now(pcb);
2372     tcp_output(pcb);
2373   }
2374 
2375   if (pcb->state != LISTEN) {
2376     LWIP_ASSERT("unsent segments leaking", pcb->unsent == NULL);
2377     LWIP_ASSERT("unacked segments leaking", pcb->unacked == NULL);
2378 #if TCP_QUEUE_OOSEQ
2379     LWIP_ASSERT("ooseq segments leaking", pcb->ooseq == NULL);
2380 #endif /* TCP_QUEUE_OOSEQ */
2381   }
2382 
2383   pcb->state = CLOSED;
2384   /* reset the local port to prevent the pcb from being 'bound' */
2385   pcb->local_port = 0;
2386 
2387   LWIP_ASSERT("tcp_pcb_remove: tcp_pcbs_sane()", tcp_pcbs_sane());
2388 }
2389 
2390 /**
2391  * Calculates a new initial sequence number for new connections.
2392  *
2393  * @return u32_t pseudo random sequence number
2394  */
2395 u32_t
2396 tcp_next_iss(struct tcp_pcb *pcb)
2397 {
2398 #ifdef LWIP_HOOK_TCP_ISN
2399   LWIP_ASSERT("tcp_next_iss: invalid pcb", pcb != NULL);
2400   return LWIP_HOOK_TCP_ISN(&pcb->local_ip, pcb->local_port, &pcb->remote_ip, pcb->remote_port);
2401 #else /* LWIP_HOOK_TCP_ISN */
2402   static u32_t iss = 6510;
2403 
2404   LWIP_ASSERT("tcp_next_iss: invalid pcb", pcb != NULL);
2405   LWIP_UNUSED_ARG(pcb);
2406 
2407   iss += tcp_ticks;       /* XXX */
2408   return iss;
2409 #endif /* LWIP_HOOK_TCP_ISN */
2410 }
2411 
2412 #if TCP_CALCULATE_EFF_SEND_MSS
2413 /**
2414  * Calculates the effective send mss that can be used for a specific IP address
2415  * by calculating the minimum of TCP_MSS and the mtu (if set) of the target
2416  * netif (if not NULL).
2417  */
2418 u16_t
2419 tcp_eff_send_mss_netif(u16_t sendmss, struct netif *outif, const ip_addr_t *dest)
2420 {
2421   u16_t mss_s;
2422   u16_t mtu;
2423 
2424   LWIP_UNUSED_ARG(dest); /* in case IPv6 is disabled */
2425 
2426   LWIP_ASSERT("tcp_eff_send_mss_netif: invalid dst_ip", dest != NULL);
2427 
2428 #if LWIP_IPV6
2429 #if LWIP_IPV4
2430   if (IP_IS_V6(dest))
2431 #endif /* LWIP_IPV4 */
2432   {
2433     /* First look in destination cache, to see if there is a Path MTU. */
2434     mtu = nd6_get_destination_mtu(ip_2_ip6(dest), outif);
2435   }
2436 #if LWIP_IPV4
2437   else
2438 #endif /* LWIP_IPV4 */
2439 #endif /* LWIP_IPV6 */
2440 #if LWIP_IPV4
2441   {
2442     if (outif == NULL) {
2443       return sendmss;
2444     }
2445     mtu = outif->mtu;
2446   }
2447 #endif /* LWIP_IPV4 */
2448 
2449   if (mtu != 0) {
2450     u16_t offset;
2451 #if LWIP_IPV6
2452 #if LWIP_IPV4
2453     if (IP_IS_V6(dest))
2454 #endif /* LWIP_IPV4 */
2455     {
2456       offset = IP6_HLEN + TCP_HLEN;
2457     }
2458 #if LWIP_IPV4
2459     else
2460 #endif /* LWIP_IPV4 */
2461 #endif /* LWIP_IPV6 */
2462 #if LWIP_IPV4
2463     {
2464       offset = IP_HLEN + TCP_HLEN;
2465     }
2466 #endif /* LWIP_IPV4 */
2467     mss_s = (mtu > offset) ? (u16_t)(mtu - offset) : 0;
2468     /* RFC 1122, chap 4.2.2.6:
2469      * Eff.snd.MSS = min(SendMSS+20, MMS_S) - TCPhdrsize - IPoptionsize
2470      * We correct for TCP options in tcp_write(), and don't support IP options.
2471      */
2472     sendmss = LWIP_MIN(sendmss, mss_s);
2473   }
2474   return sendmss;
2475 }
2476 #endif /* TCP_CALCULATE_EFF_SEND_MSS */
2477 
2478 /** Helper function for tcp_netif_ip_addr_changed() that iterates a pcb list */
2479 static void
2480 tcp_netif_ip_addr_changed_pcblist(const ip_addr_t *old_addr, struct tcp_pcb *pcb_list)
2481 {
2482   struct tcp_pcb *pcb;
2483   pcb = pcb_list;
2484 
2485   LWIP_ASSERT("tcp_netif_ip_addr_changed_pcblist: invalid old_addr", old_addr != NULL);
2486 
2487   while (pcb != NULL) {
2488     /* PCB bound to current local interface address? */
2489     if (ip_addr_cmp(&pcb->local_ip, old_addr)
2490 #if LWIP_AUTOIP
2491         /* connections to link-local addresses must persist (RFC3927 ch. 1.9) */
2492         && (!IP_IS_V4_VAL(pcb->local_ip) || !ip4_addr_islinklocal(ip_2_ip4(&pcb->local_ip)))
2493 #endif /* LWIP_AUTOIP */
2494        ) {
2495       /* this connection must be aborted */
2496       struct tcp_pcb *next = pcb->next;
2497       LWIP_DEBUGF(NETIF_DEBUG | LWIP_DBG_STATE, ("netif_set_ipaddr: aborting TCP pcb %p\n", (void *)pcb));
2498       tcp_abort(pcb);
2499       pcb = next;
2500     } else {
2501       pcb = pcb->next;
2502     }
2503   }
2504 }
2505 
2506 /** This function is called from netif.c when address is changed or netif is removed
2507  *
2508  * @param old_addr IP address of the netif before change
2509  * @param new_addr IP address of the netif after change or NULL if netif has been removed
2510  */
2511 void
2512 tcp_netif_ip_addr_changed(const ip_addr_t *old_addr, const ip_addr_t *new_addr)
2513 {
2514   struct tcp_pcb_listen *lpcb;
2515 
2516   if (!ip_addr_isany(old_addr)) {
2517     tcp_netif_ip_addr_changed_pcblist(old_addr, tcp_active_pcbs);
2518     tcp_netif_ip_addr_changed_pcblist(old_addr, tcp_bound_pcbs);
2519 
2520     if (!ip_addr_isany(new_addr)) {
2521       /* PCB bound to current local interface address? */
2522       for (lpcb = tcp_listen_pcbs.listen_pcbs; lpcb != NULL; lpcb = lpcb->next) {
2523         /* PCB bound to current local interface address? */
2524         if (ip_addr_cmp(&lpcb->local_ip, old_addr)) {
2525           /* The PCB is listening to the old ipaddr and
2526             * is set to listen to the new one instead */
2527           ip_addr_copy(lpcb->local_ip, *new_addr);
2528         }
2529       }
2530     }
2531   }
2532 }
2533 
2534 const char *
2535 tcp_debug_state_str(enum tcp_state s)
2536 {
2537   return tcp_state_str[s];
2538 }
2539 
2540 err_t
2541 tcp_tcp_get_tcp_addrinfo(struct tcp_pcb *pcb, int local, ip_addr_t *addr, u16_t *port)
2542 {
2543   if (pcb) {
2544     if (local) {
2545       if (addr) {
2546         *addr = pcb->local_ip;
2547       }
2548       if (port) {
2549         *port = pcb->local_port;
2550       }
2551     } else {
2552       if (addr) {
2553         *addr = pcb->remote_ip;
2554       }
2555       if (port) {
2556         *port = pcb->remote_port;
2557       }
2558     }
2559     return ERR_OK;
2560   }
2561   return ERR_VAL;
2562 }
2563 
2564 #if TCP_QUEUE_OOSEQ
2565 /* Free all ooseq pbufs (and possibly reset SACK state) */
2566 void
2567 tcp_free_ooseq(struct tcp_pcb *pcb)
2568 {
2569   if (pcb->ooseq) {
2570     tcp_segs_free(pcb->ooseq);
2571     pcb->ooseq = NULL;
2572 #if LWIP_TCP_SACK_OUT
2573     memset(pcb->rcv_sacks, 0, sizeof(pcb->rcv_sacks));
2574 #endif /* LWIP_TCP_SACK_OUT */
2575   }
2576 }
2577 #endif /* TCP_QUEUE_OOSEQ */
2578 
2579 #if TCP_DEBUG || TCP_INPUT_DEBUG || TCP_OUTPUT_DEBUG
2580 /**
2581  * Print a tcp header for debugging purposes.
2582  *
2583  * @param tcphdr pointer to a struct tcp_hdr
2584  */
2585 void
2586 tcp_debug_print(struct tcp_hdr *tcphdr)
2587 {
2588   LWIP_DEBUGF(TCP_DEBUG, ("TCP header:\n"));
2589   LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
2590   LWIP_DEBUGF(TCP_DEBUG, ("|    %5"U16_F"      |    %5"U16_F"      | (src port, dest port)\n",
2591                           lwip_ntohs(tcphdr->src), lwip_ntohs(tcphdr->dest)));
2592   LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
2593   LWIP_DEBUGF(TCP_DEBUG, ("|           %010"U32_F"          | (seq no)\n",
2594                           lwip_ntohl(tcphdr->seqno)));
2595   LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
2596   LWIP_DEBUGF(TCP_DEBUG, ("|           %010"U32_F"          | (ack no)\n",
2597                           lwip_ntohl(tcphdr->ackno)));
2598   LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
2599   LWIP_DEBUGF(TCP_DEBUG, ("| %2"U16_F" |   |%"U16_F"%"U16_F"%"U16_F"%"U16_F"%"U16_F"%"U16_F"|     %5"U16_F"     | (hdrlen, flags (",
2600                           TCPH_HDRLEN(tcphdr),
2601                           (u16_t)(TCPH_FLAGS(tcphdr) >> 5 & 1),
2602                           (u16_t)(TCPH_FLAGS(tcphdr) >> 4 & 1),
2603                           (u16_t)(TCPH_FLAGS(tcphdr) >> 3 & 1),
2604                           (u16_t)(TCPH_FLAGS(tcphdr) >> 2 & 1),
2605                           (u16_t)(TCPH_FLAGS(tcphdr) >> 1 & 1),
2606                           (u16_t)(TCPH_FLAGS(tcphdr)      & 1),
2607                           lwip_ntohs(tcphdr->wnd)));
2608   tcp_debug_print_flags(TCPH_FLAGS(tcphdr));
2609   LWIP_DEBUGF(TCP_DEBUG, ("), win)\n"));
2610   LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
2611   LWIP_DEBUGF(TCP_DEBUG, ("|    0x%04"X16_F"     |     %5"U16_F"     | (chksum, urgp)\n",
2612                           lwip_ntohs(tcphdr->chksum), lwip_ntohs(tcphdr->urgp)));
2613   LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
2614 }
2615 
2616 /**
2617  * Print a tcp state for debugging purposes.
2618  *
2619  * @param s enum tcp_state to print
2620  */
2621 void
2622 tcp_debug_print_state(enum tcp_state s)
2623 {
2624   LWIP_DEBUGF(TCP_DEBUG, ("State: %s\n", tcp_state_str[s]));
2625 }
2626 
2627 /**
2628  * Print tcp flags for debugging purposes.
2629  *
2630  * @param flags tcp flags, all active flags are printed
2631  */
2632 void
2633 tcp_debug_print_flags(u8_t flags)
2634 {
2635   if (flags & TCP_FIN) {
2636     LWIP_DEBUGF(TCP_DEBUG, ("FIN "));
2637   }
2638   if (flags & TCP_SYN) {
2639     LWIP_DEBUGF(TCP_DEBUG, ("SYN "));
2640   }
2641   if (flags & TCP_RST) {
2642     LWIP_DEBUGF(TCP_DEBUG, ("RST "));
2643   }
2644   if (flags & TCP_PSH) {
2645     LWIP_DEBUGF(TCP_DEBUG, ("PSH "));
2646   }
2647   if (flags & TCP_ACK) {
2648     LWIP_DEBUGF(TCP_DEBUG, ("ACK "));
2649   }
2650   if (flags & TCP_URG) {
2651     LWIP_DEBUGF(TCP_DEBUG, ("URG "));
2652   }
2653   if (flags & TCP_ECE) {
2654     LWIP_DEBUGF(TCP_DEBUG, ("ECE "));
2655   }
2656   if (flags & TCP_CWR) {
2657     LWIP_DEBUGF(TCP_DEBUG, ("CWR "));
2658   }
2659   LWIP_DEBUGF(TCP_DEBUG, ("\n"));
2660 }
2661 
2662 /**
2663  * Print all tcp_pcbs in every list for debugging purposes.
2664  */
2665 void
2666 tcp_debug_print_pcbs(void)
2667 {
2668   struct tcp_pcb *pcb;
2669   struct tcp_pcb_listen *pcbl;
2670 
2671   LWIP_DEBUGF(TCP_DEBUG, ("Active PCB states:\n"));
2672   for (pcb = tcp_active_pcbs; pcb != NULL; pcb = pcb->next) {
2673     LWIP_DEBUGF(TCP_DEBUG, ("Local port %"U16_F", foreign port %"U16_F" snd_nxt %"U32_F" rcv_nxt %"U32_F" ",
2674                             pcb->local_port, pcb->remote_port,
2675                             pcb->snd_nxt, pcb->rcv_nxt));
2676     tcp_debug_print_state(pcb->state);
2677   }
2678 
2679   LWIP_DEBUGF(TCP_DEBUG, ("Listen PCB states:\n"));
2680   for (pcbl = tcp_listen_pcbs.listen_pcbs; pcbl != NULL; pcbl = pcbl->next) {
2681     LWIP_DEBUGF(TCP_DEBUG, ("Local port %"U16_F" ", pcbl->local_port));
2682     tcp_debug_print_state(pcbl->state);
2683   }
2684 
2685   LWIP_DEBUGF(TCP_DEBUG, ("TIME-WAIT PCB states:\n"));
2686   for (pcb = tcp_tw_pcbs; pcb != NULL; pcb = pcb->next) {
2687     LWIP_DEBUGF(TCP_DEBUG, ("Local port %"U16_F", foreign port %"U16_F" snd_nxt %"U32_F" rcv_nxt %"U32_F" ",
2688                             pcb->local_port, pcb->remote_port,
2689                             pcb->snd_nxt, pcb->rcv_nxt));
2690     tcp_debug_print_state(pcb->state);
2691   }
2692 }
2693 
2694 /**
2695  * Check state consistency of the tcp_pcb lists.
2696  */
2697 s16_t
2698 tcp_pcbs_sane(void)
2699 {
2700   struct tcp_pcb *pcb;
2701   for (pcb = tcp_active_pcbs; pcb != NULL; pcb = pcb->next) {
2702     LWIP_ASSERT("tcp_pcbs_sane: active pcb->state != CLOSED", pcb->state != CLOSED);
2703     LWIP_ASSERT("tcp_pcbs_sane: active pcb->state != LISTEN", pcb->state != LISTEN);
2704     LWIP_ASSERT("tcp_pcbs_sane: active pcb->state != TIME-WAIT", pcb->state != TIME_WAIT);
2705   }
2706   for (pcb = tcp_tw_pcbs; pcb != NULL; pcb = pcb->next) {
2707     LWIP_ASSERT("tcp_pcbs_sane: tw pcb->state == TIME-WAIT", pcb->state == TIME_WAIT);
2708   }
2709   return 1;
2710 }
2711 #endif /* TCP_DEBUG */
2712 
2713 #if LWIP_TCP_PCB_NUM_EXT_ARGS
2714 /**
2715  * @defgroup tcp_raw_extargs ext arguments
2716  * @ingroup tcp_raw
2717  * Additional data storage per tcp pcb\n
2718  * @see @ref tcp_raw
2719  *
2720  * When LWIP_TCP_PCB_NUM_EXT_ARGS is > 0, every tcp pcb (including listen pcb)
2721  * includes a number of additional argument entries in an array.
2722  *
2723  * To support memory management, in addition to a 'void *', callbacks can be
2724  * provided to manage transition from listening pcbs to connections and to
2725  * deallocate memory when a pcb is deallocated (see struct @ref tcp_ext_arg_callbacks).
2726  *
2727  * After allocating this index, use @ref tcp_ext_arg_set and @ref tcp_ext_arg_get
2728  * to store and load arguments from this index for a given pcb.
2729  */
2730 
2731 static u8_t tcp_ext_arg_id;
2732 
2733 /**
2734  * @ingroup tcp_raw_extargs
2735  * Allocate an index to store data in ext_args member of struct tcp_pcb.
2736  * Returned value is an index in mentioned array.
2737  * The index is *global* over all pcbs!
2738  *
2739  * When @ref LWIP_TCP_PCB_NUM_EXT_ARGS is > 0, every tcp pcb (including listen pcb)
2740  * includes a number of additional argument entries in an array.
2741  *
2742  * To support memory management, in addition to a 'void *', callbacks can be
2743  * provided to manage transition from listening pcbs to connections and to
2744  * deallocate memory when a pcb is deallocated (see struct @ref tcp_ext_arg_callbacks).
2745  *
2746  * After allocating this index, use @ref tcp_ext_arg_set and @ref tcp_ext_arg_get
2747  * to store and load arguments from this index for a given pcb.
2748  *
2749  * @return a unique index into struct tcp_pcb.ext_args
2750  */
2751 u8_t
2752 tcp_ext_arg_alloc_id(void)
2753 {
2754   u8_t result = tcp_ext_arg_id;
2755   tcp_ext_arg_id++;
2756 
2757   LWIP_ASSERT_CORE_LOCKED();
2758 
2759 #if LWIP_TCP_PCB_NUM_EXT_ARGS >= 255
2760 #error LWIP_TCP_PCB_NUM_EXT_ARGS
2761 #endif
2762   LWIP_ASSERT("Increase LWIP_TCP_PCB_NUM_EXT_ARGS in lwipopts.h", result < LWIP_TCP_PCB_NUM_EXT_ARGS);
2763   return result;
2764 }
2765 
2766 /**
2767  * @ingroup tcp_raw_extargs
2768  * Set callbacks for a given index of ext_args on the specified pcb.
2769  *
2770  * @param pcb tcp_pcb for which to set the callback
2771  * @param id ext_args index to set (allocated via @ref tcp_ext_arg_alloc_id)
2772  * @param callbacks callback table (const since it is referenced, not copied!)
2773  */
2774 void
2775 tcp_ext_arg_set_callbacks(struct tcp_pcb *pcb, uint8_t id, const struct tcp_ext_arg_callbacks * const callbacks)
2776 {
2777   LWIP_ASSERT("pcb != NULL", pcb != NULL);
2778   LWIP_ASSERT("id < LWIP_TCP_PCB_NUM_EXT_ARGS", id < LWIP_TCP_PCB_NUM_EXT_ARGS);
2779   LWIP_ASSERT("callbacks != NULL", callbacks != NULL);
2780 
2781   LWIP_ASSERT_CORE_LOCKED();
2782 
2783   pcb->ext_args[id].callbacks = callbacks;
2784 }
2785 
2786 /**
2787  * @ingroup tcp_raw_extargs
2788  * Set data for a given index of ext_args on the specified pcb.
2789  *
2790  * @param pcb tcp_pcb for which to set the data
2791  * @param id ext_args index to set (allocated via @ref tcp_ext_arg_alloc_id)
2792  * @param arg data pointer to set
2793  */
2794 void tcp_ext_arg_set(struct tcp_pcb *pcb, uint8_t id, void *arg)
2795 {
2796   LWIP_ASSERT("pcb != NULL", pcb != NULL);
2797   LWIP_ASSERT("id < LWIP_TCP_PCB_NUM_EXT_ARGS", id < LWIP_TCP_PCB_NUM_EXT_ARGS);
2798 
2799   LWIP_ASSERT_CORE_LOCKED();
2800 
2801   pcb->ext_args[id].data = arg;
2802 }
2803 
2804 /**
2805  * @ingroup tcp_raw_extargs
2806  * Set data for a given index of ext_args on the specified pcb.
2807  *
2808  * @param pcb tcp_pcb for which to set the data
2809  * @param id ext_args index to set (allocated via @ref tcp_ext_arg_alloc_id)
2810  * @return data pointer at the given index
2811  */
2812 void *tcp_ext_arg_get(const struct tcp_pcb *pcb, uint8_t id)
2813 {
2814   LWIP_ASSERT("pcb != NULL", pcb != NULL);
2815   LWIP_ASSERT("id < LWIP_TCP_PCB_NUM_EXT_ARGS", id < LWIP_TCP_PCB_NUM_EXT_ARGS);
2816 
2817   LWIP_ASSERT_CORE_LOCKED();
2818 
2819   return pcb->ext_args[id].data;
2820 }
2821 
2822 /** This function calls the "destroy" callback for all ext_args once a pcb is
2823  * freed.
2824  */
2825 static void
2826 tcp_ext_arg_invoke_callbacks_destroyed(struct tcp_pcb_ext_args *ext_args)
2827 {
2828   int i;
2829   LWIP_ASSERT("ext_args != NULL", ext_args != NULL);
2830 
2831   for (i = 0; i < LWIP_TCP_PCB_NUM_EXT_ARGS; i++) {
2832     if (ext_args[i].callbacks != NULL) {
2833       if (ext_args[i].callbacks->destroy != NULL) {
2834         ext_args[i].callbacks->destroy((u8_t)i, ext_args[i].data);
2835       }
2836     }
2837   }
2838 }
2839 
2840 /** This function calls the "passive_open" callback for all ext_args if a connection
2841  * is in the process of being accepted. This is called just after the SYN is
2842  * received and before a SYN/ACK is sent, to allow to modify the very first
2843  * segment sent even on passive open. Naturally, the "accepted" callback of the
2844  * pcb has not been called yet!
2845  */
2846 err_t
2847 tcp_ext_arg_invoke_callbacks_passive_open(struct tcp_pcb_listen *lpcb, struct tcp_pcb *cpcb)
2848 {
2849   int i;
2850   LWIP_ASSERT("lpcb != NULL", lpcb != NULL);
2851   LWIP_ASSERT("cpcb != NULL", cpcb != NULL);
2852 
2853   for (i = 0; i < LWIP_TCP_PCB_NUM_EXT_ARGS; i++) {
2854     if (lpcb->ext_args[i].callbacks != NULL) {
2855       if (lpcb->ext_args[i].callbacks->passive_open != NULL) {
2856         err_t err = lpcb->ext_args[i].callbacks->passive_open((u8_t)i, lpcb, cpcb);
2857         if (err != ERR_OK) {
2858           return err;
2859         }
2860       }
2861     }
2862   }
2863   return ERR_OK;
2864 }
2865 #endif /* LWIP_TCP_PCB_NUM_EXT_ARGS */
2866 
2867 #endif /* LWIP_TCP */
2868