• 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<br>
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.<br>
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 succeeds
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_eq(&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_eq(&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_VLAN_PCP
1062   lpcb->netif_hints.tci = pcb->netif_hints.tci;
1063 #endif /* LWIP_VLAN_PCP */
1064 #if LWIP_IPV4 && LWIP_IPV6
1065   IP_SET_TYPE_VAL(lpcb->remote_ip, pcb->local_ip.type);
1066 #endif /* LWIP_IPV4 && LWIP_IPV6 */
1067   ip_addr_copy(lpcb->local_ip, pcb->local_ip);
1068   if (pcb->local_port != 0) {
1069     TCP_RMV(&tcp_bound_pcbs, pcb);
1070   }
1071 #if LWIP_TCP_PCB_NUM_EXT_ARGS
1072   /* copy over ext_args to listening pcb  */
1073   memcpy(&lpcb->ext_args, &pcb->ext_args, sizeof(pcb->ext_args));
1074 #endif
1075   tcp_free(pcb);
1076 #if LWIP_CALLBACK_API
1077   lpcb->accept = tcp_accept_null;
1078 #endif /* LWIP_CALLBACK_API */
1079 #if TCP_LISTEN_BACKLOG
1080   lpcb->accepts_pending = 0;
1081   tcp_backlog_set(lpcb, backlog);
1082 #endif /* TCP_LISTEN_BACKLOG */
1083   TCP_REG(&tcp_listen_pcbs.pcbs, (struct tcp_pcb *)lpcb);
1084   res = ERR_OK;
1085 done:
1086   if (err != NULL) {
1087     *err = res;
1088   }
1089   return (struct tcp_pcb *)lpcb;
1090 }
1091 
1092 /**
1093  * Update the state that tracks the available window space to advertise.
1094  *
1095  * Returns how much extra window would be advertised if we sent an
1096  * update now.
1097  */
1098 u32_t
1099 tcp_update_rcv_ann_wnd(struct tcp_pcb *pcb)
1100 {
1101   u32_t new_right_edge;
1102 
1103   LWIP_ASSERT("tcp_update_rcv_ann_wnd: invalid pcb", pcb != NULL);
1104   new_right_edge = pcb->rcv_nxt + pcb->rcv_wnd;
1105 
1106   if (TCP_SEQ_GEQ(new_right_edge, pcb->rcv_ann_right_edge + LWIP_MIN((TCP_WND / 2), pcb->mss))) {
1107     /* we can advertise more window */
1108     pcb->rcv_ann_wnd = pcb->rcv_wnd;
1109     return new_right_edge - pcb->rcv_ann_right_edge;
1110   } else {
1111     if (TCP_SEQ_GT(pcb->rcv_nxt, pcb->rcv_ann_right_edge)) {
1112       /* Can happen due to other end sending out of advertised window,
1113        * but within actual available (but not yet advertised) window */
1114       pcb->rcv_ann_wnd = 0;
1115     } else {
1116       /* keep the right edge of window constant */
1117       u32_t new_rcv_ann_wnd = pcb->rcv_ann_right_edge - pcb->rcv_nxt;
1118 #if !LWIP_WND_SCALE
1119       LWIP_ASSERT("new_rcv_ann_wnd <= 0xffff", new_rcv_ann_wnd <= 0xffff);
1120 #endif
1121       pcb->rcv_ann_wnd = (tcpwnd_size_t)new_rcv_ann_wnd;
1122     }
1123     return 0;
1124   }
1125 }
1126 
1127 /**
1128  * @ingroup tcp_raw
1129  * This function should be called by the application when it has
1130  * processed the data. The purpose is to advertise a larger window
1131  * when the data has been processed.
1132  *
1133  * @param pcb the tcp_pcb for which data is read
1134  * @param len the amount of bytes that have been read by the application
1135  */
1136 void
1137 tcp_recved(struct tcp_pcb *pcb, u16_t len)
1138 {
1139   u32_t wnd_inflation;
1140   tcpwnd_size_t rcv_wnd;
1141 
1142   LWIP_ASSERT_CORE_LOCKED();
1143 
1144   LWIP_ERROR("tcp_recved: invalid pcb", pcb != NULL, return);
1145 
1146   /* pcb->state LISTEN not allowed here */
1147   LWIP_ASSERT("don't call tcp_recved for listen-pcbs",
1148               pcb->state != LISTEN);
1149 
1150   rcv_wnd = (tcpwnd_size_t)(pcb->rcv_wnd + len);
1151   if ((rcv_wnd > TCP_WND_MAX(pcb)) || (rcv_wnd < pcb->rcv_wnd)) {
1152     /* window got too big or tcpwnd_size_t overflow */
1153     LWIP_DEBUGF(TCP_DEBUG, ("tcp_recved: window got too big or tcpwnd_size_t overflow\n"));
1154     pcb->rcv_wnd = TCP_WND_MAX(pcb);
1155   } else  {
1156     pcb->rcv_wnd = rcv_wnd;
1157   }
1158 
1159   wnd_inflation = tcp_update_rcv_ann_wnd(pcb);
1160 
1161   /* If the change in the right edge of window is significant (default
1162    * watermark is TCP_WND/4), then send an explicit update now.
1163    * Otherwise wait for a packet to be sent in the normal course of
1164    * events (or more window to be available later) */
1165   if (wnd_inflation >= TCP_WND_UPDATE_THRESHOLD) {
1166     tcp_ack_now(pcb);
1167     tcp_output(pcb);
1168   }
1169 
1170   LWIP_DEBUGF(TCP_DEBUG, ("tcp_recved: received %"U16_F" bytes, wnd %"TCPWNDSIZE_F" (%"TCPWNDSIZE_F").\n",
1171                           len, pcb->rcv_wnd, (u16_t)(TCP_WND_MAX(pcb) - pcb->rcv_wnd)));
1172 }
1173 
1174 /**
1175  * Allocate a new local TCP port.
1176  *
1177  * @return a new (free) local TCP port number
1178  */
1179 static u16_t
1180 tcp_new_port(void)
1181 {
1182   u8_t i;
1183   u16_t n = 0;
1184   struct tcp_pcb *pcb;
1185 
1186 again:
1187   tcp_port++;
1188   if (tcp_port == TCP_LOCAL_PORT_RANGE_END) {
1189     tcp_port = TCP_LOCAL_PORT_RANGE_START;
1190   }
1191   /* Check all PCB lists. */
1192   for (i = 0; i < NUM_TCP_PCB_LISTS; i++) {
1193     for (pcb = *tcp_pcb_lists[i]; pcb != NULL; pcb = pcb->next) {
1194       if (pcb->local_port == tcp_port) {
1195         n++;
1196         if (n > (TCP_LOCAL_PORT_RANGE_END - TCP_LOCAL_PORT_RANGE_START)) {
1197           return 0;
1198         }
1199         goto again;
1200       }
1201     }
1202   }
1203   return tcp_port;
1204 }
1205 
1206 /**
1207  * @ingroup tcp_raw
1208  * Connects to another host. The function given as the "connected"
1209  * argument will be called when the connection has been established.
1210  *  Sets up the pcb to connect to the remote host and sends the
1211  * initial SYN segment which opens the connection.
1212  *
1213  * The tcp_connect() function returns immediately; it does not wait for
1214  * the connection to be properly setup. Instead, it will call the
1215  * function specified as the fourth argument (the "connected" argument)
1216  * when the connection is established. If the connection could not be
1217  * properly established, either because the other host refused the
1218  * connection or because the other host didn't answer, the "err"
1219  * callback function of this pcb (registered with tcp_err, see below)
1220  * will be called.
1221  *
1222  * The tcp_connect() function can return ERR_MEM if no memory is
1223  * available for enqueueing the SYN segment. If the SYN indeed was
1224  * enqueued successfully, the tcp_connect() function returns ERR_OK.
1225  *
1226  * @param pcb the tcp_pcb used to establish the connection
1227  * @param ipaddr the remote ip address to connect to
1228  * @param port the remote tcp port to connect to
1229  * @param connected callback function to call when connected (on error,
1230                     the err callback will be called)
1231  * @return ERR_VAL if invalid arguments are given
1232  *         ERR_OK if connect request has been sent
1233  *         other err_t values if connect request couldn't be sent
1234  */
1235 err_t
1236 tcp_connect(struct tcp_pcb *pcb, const ip_addr_t *ipaddr, u16_t port,
1237             tcp_connected_fn connected)
1238 {
1239   struct netif *netif = NULL;
1240   err_t ret;
1241   u32_t iss;
1242   u16_t old_local_port;
1243 
1244   LWIP_ASSERT_CORE_LOCKED();
1245 
1246   LWIP_ERROR("tcp_connect: invalid pcb", pcb != NULL, return ERR_ARG);
1247   LWIP_ERROR("tcp_connect: invalid ipaddr", ipaddr != NULL, return ERR_ARG);
1248 
1249   LWIP_ERROR("tcp_connect: can only connect from state CLOSED", pcb->state == CLOSED, return ERR_ISCONN);
1250 
1251 #ifdef LOSCFG_NET_CONTAINER
1252   struct net_group *group = get_net_group_from_tcp_pcb(pcb);
1253   LWIP_ERROR("tcp_connect: invalid net group", group != NULL, return ERR_RTE);
1254 #endif
1255   LWIP_DEBUGF(TCP_DEBUG, ("tcp_connect to port %"U16_F"\n", port));
1256   ip_addr_set(&pcb->remote_ip, ipaddr);
1257   pcb->remote_port = port;
1258 
1259   if (pcb->netif_idx != NETIF_NO_INDEX) {
1260 #ifdef LOSCFG_NET_CONTAINER
1261     netif = netif_get_by_index(pcb->netif_idx, group);
1262 #else
1263     netif = netif_get_by_index(pcb->netif_idx);
1264 #endif
1265   } else {
1266     /* check if we have a route to the remote host */
1267 #ifdef LOSCFG_NET_CONTAINER
1268     netif = ip_route(&pcb->local_ip, &pcb->remote_ip, group);
1269 #else
1270     netif = ip_route(&pcb->local_ip, &pcb->remote_ip);
1271 #endif
1272   }
1273   if (netif == NULL) {
1274     /* Don't even try to send a SYN packet if we have no route since that will fail. */
1275     return ERR_RTE;
1276   }
1277 
1278   /* check if local IP has been assigned to pcb, if not, get one */
1279   if (ip_addr_isany(&pcb->local_ip)) {
1280     const ip_addr_t *local_ip = ip_netif_get_local_ip(netif, ipaddr);
1281     if (local_ip == NULL) {
1282       return ERR_RTE;
1283     }
1284     ip_addr_copy(pcb->local_ip, *local_ip);
1285   }
1286 
1287 #if LWIP_IPV6 && LWIP_IPV6_SCOPES
1288   /* If the given IP address should have a zone but doesn't, assign one now.
1289    * Given that we already have the target netif, this is easy and cheap. */
1290   if (IP_IS_V6(&pcb->remote_ip) &&
1291       ip6_addr_lacks_zone(ip_2_ip6(&pcb->remote_ip), IP6_UNICAST)) {
1292     ip6_addr_assign_zone(ip_2_ip6(&pcb->remote_ip), IP6_UNICAST, netif);
1293   }
1294 #endif /* LWIP_IPV6 && LWIP_IPV6_SCOPES */
1295 
1296   old_local_port = pcb->local_port;
1297   if (pcb->local_port == 0) {
1298     pcb->local_port = tcp_new_port();
1299     if (pcb->local_port == 0) {
1300       return ERR_BUF;
1301     }
1302   } else {
1303 #if SO_REUSE
1304     if (ip_get_option(pcb, SOF_REUSEADDR)) {
1305       /* Since SOF_REUSEADDR allows reusing a local address, we have to make sure
1306          now that the 5-tuple is unique. */
1307       struct tcp_pcb *cpcb;
1308       int i;
1309       /* Don't check listen- and bound-PCBs, check active- and TIME-WAIT PCBs. */
1310       for (i = 2; i < NUM_TCP_PCB_LISTS; i++) {
1311         for (cpcb = *tcp_pcb_lists[i]; cpcb != NULL; cpcb = cpcb->next) {
1312           if ((cpcb->local_port == pcb->local_port) &&
1313               (cpcb->remote_port == port) &&
1314               ip_addr_eq(&cpcb->local_ip, &pcb->local_ip) &&
1315               ip_addr_eq(&cpcb->remote_ip, ipaddr)) {
1316             /* linux returns EISCONN here, but ERR_USE should be OK for us */
1317             return ERR_USE;
1318           }
1319         }
1320       }
1321     }
1322 #endif /* SO_REUSE */
1323   }
1324 
1325   iss = tcp_next_iss(pcb);
1326   pcb->rcv_nxt = 0;
1327   pcb->snd_nxt = iss;
1328   pcb->lastack = iss - 1;
1329   pcb->snd_wl2 = iss - 1;
1330   pcb->snd_lbb = iss - 1;
1331   /* Start with a window that does not need scaling. When window scaling is
1332      enabled and used, the window is enlarged when both sides agree on scaling. */
1333   pcb->rcv_wnd = pcb->rcv_ann_wnd = TCPWND_MIN16(TCP_WND);
1334   pcb->rcv_ann_right_edge = pcb->rcv_nxt;
1335   pcb->snd_wnd = TCP_WND;
1336   /* As initial send MSS, we use TCP_MSS but limit it to 536.
1337      The send MSS is updated when an MSS option is received. */
1338   pcb->mss = INITIAL_MSS;
1339 #if TCP_CALCULATE_EFF_SEND_MSS
1340   pcb->mss = tcp_eff_send_mss_netif(pcb->mss, netif, &pcb->remote_ip);
1341 #endif /* TCP_CALCULATE_EFF_SEND_MSS */
1342   pcb->cwnd = 1;
1343 #if LWIP_CALLBACK_API
1344   pcb->connected = connected;
1345 #else /* LWIP_CALLBACK_API */
1346   LWIP_UNUSED_ARG(connected);
1347 #endif /* LWIP_CALLBACK_API */
1348 
1349   /* Send a SYN together with the MSS option. */
1350   ret = tcp_enqueue_flags(pcb, TCP_SYN);
1351   if (ret == ERR_OK) {
1352     /* SYN segment was enqueued, changed the pcbs state now */
1353     pcb->state = SYN_SENT;
1354     if (old_local_port != 0) {
1355       TCP_RMV(&tcp_bound_pcbs, pcb);
1356     }
1357     TCP_REG_ACTIVE(pcb);
1358     MIB2_STATS_INC(mib2.tcpactiveopens);
1359 
1360     tcp_output(pcb);
1361   }
1362   return ret;
1363 }
1364 
1365 /**
1366  * Called every 500 ms and implements the retransmission timer and the timer that
1367  * removes PCBs that have been in TIME-WAIT for enough time. It also increments
1368  * various timers such as the inactivity timer in each PCB.
1369  *
1370  * Automatically called from tcp_tmr().
1371  */
1372 void
1373 tcp_slowtmr(void)
1374 {
1375   struct tcp_pcb *pcb, *prev;
1376   tcpwnd_size_t eff_wnd;
1377   u8_t pcb_remove;      /* flag if a PCB should be removed */
1378   u8_t pcb_reset;       /* flag if a RST should be sent when removing */
1379   err_t err;
1380 
1381   err = ERR_OK;
1382 
1383   ++tcp_ticks;
1384   ++tcp_timer_ctr;
1385 
1386 tcp_slowtmr_start:
1387   /* Steps through all of the active PCBs. */
1388   prev = NULL;
1389   pcb = tcp_active_pcbs;
1390   if (pcb == NULL) {
1391     LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: no active pcbs\n"));
1392   }
1393   while (pcb != NULL) {
1394     LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: processing active pcb\n"));
1395     LWIP_ASSERT("tcp_slowtmr: active pcb->state != CLOSED", pcb->state != CLOSED);
1396     LWIP_ASSERT("tcp_slowtmr: active pcb->state != LISTEN", pcb->state != LISTEN);
1397     LWIP_ASSERT("tcp_slowtmr: active pcb->state != TIME-WAIT", pcb->state != TIME_WAIT);
1398     if (pcb->last_timer == tcp_timer_ctr) {
1399       /* skip this pcb, we have already processed it */
1400       prev = pcb;
1401       pcb = pcb->next;
1402       continue;
1403     }
1404     pcb->last_timer = tcp_timer_ctr;
1405 
1406     pcb_remove = 0;
1407     pcb_reset = 0;
1408 
1409     if (pcb->state == SYN_SENT && pcb->nrtx >= TCP_SYNMAXRTX) {
1410       ++pcb_remove;
1411       LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: max SYN retries reached\n"));
1412     } else if (pcb->nrtx >= TCP_MAXRTX) {
1413       ++pcb_remove;
1414       LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: max DATA retries reached\n"));
1415     } else {
1416       if (pcb->persist_backoff > 0) {
1417         LWIP_ASSERT("tcp_slowtimr: persist ticking with in-flight data", pcb->unacked == NULL);
1418         LWIP_ASSERT("tcp_slowtimr: persist ticking with empty send buffer", pcb->unsent != NULL);
1419         if (pcb->persist_probe >= TCP_MAXRTX) {
1420           ++pcb_remove; /* max probes reached */
1421         } else {
1422           u8_t backoff_cnt = tcp_persist_backoff[pcb->persist_backoff - 1];
1423           if (pcb->persist_cnt < backoff_cnt) {
1424             pcb->persist_cnt++;
1425           }
1426           if (pcb->persist_cnt >= backoff_cnt) {
1427             int next_slot = 1; /* increment timer to next slot */
1428             /* If snd_wnd is zero, send 1 byte probes */
1429             if (pcb->snd_wnd == 0) {
1430               if (tcp_zero_window_probe(pcb) != ERR_OK) {
1431                 next_slot = 0; /* try probe again with current slot */
1432               }
1433               /* snd_wnd not fully closed, split unsent head and fill window */
1434             } else {
1435               if (tcp_split_unsent_seg(pcb, (u16_t)pcb->snd_wnd) == ERR_OK) {
1436                 if (tcp_output(pcb) == ERR_OK) {
1437                   /* sending will cancel persist timer, else retry with current slot */
1438                   next_slot = 0;
1439                 }
1440               }
1441             }
1442             if (next_slot) {
1443               pcb->persist_cnt = 0;
1444               if (pcb->persist_backoff < sizeof(tcp_persist_backoff)) {
1445                 pcb->persist_backoff++;
1446               }
1447             }
1448           }
1449         }
1450       } else {
1451         /* Increase the retransmission timer if it is running */
1452         if ((pcb->rtime >= 0) && (pcb->rtime < 0x7FFF)) {
1453           ++pcb->rtime;
1454         }
1455 
1456         if (pcb->rtime >= pcb->rto) {
1457           /* Time for a retransmission. */
1458           LWIP_DEBUGF(TCP_RTO_DEBUG, ("tcp_slowtmr: rtime %"S16_F
1459                                       " pcb->rto %"S16_F"\n",
1460                                       pcb->rtime, pcb->rto));
1461           /* If prepare phase fails but we have unsent data but no unacked data,
1462              still execute the backoff calculations below, as this means we somehow
1463              failed to send segment. */
1464           if ((tcp_rexmit_rto_prepare(pcb) == ERR_OK) || ((pcb->unacked == NULL) && (pcb->unsent != NULL))) {
1465             /* Double retransmission time-out unless we are trying to
1466              * connect to somebody (i.e., we are in SYN_SENT). */
1467             if (pcb->state != SYN_SENT) {
1468               u8_t backoff_idx = LWIP_MIN(pcb->nrtx, sizeof(tcp_backoff) - 1);
1469               int calc_rto = ((pcb->sa >> 3) + pcb->sv) << tcp_backoff[backoff_idx];
1470               pcb->rto = (s16_t)LWIP_MIN(calc_rto, 0x7FFF);
1471             }
1472 
1473             /* Reset the retransmission timer. */
1474             pcb->rtime = 0;
1475 
1476             /* Reduce congestion window and ssthresh. */
1477             eff_wnd = LWIP_MIN(pcb->cwnd, pcb->snd_wnd);
1478             pcb->ssthresh = eff_wnd >> 1;
1479             if (pcb->ssthresh < (tcpwnd_size_t)(pcb->mss << 1)) {
1480               pcb->ssthresh = (tcpwnd_size_t)(pcb->mss << 1);
1481             }
1482             pcb->cwnd = pcb->mss;
1483             LWIP_DEBUGF(TCP_CWND_DEBUG, ("tcp_slowtmr: cwnd %"TCPWNDSIZE_F
1484                                          " ssthresh %"TCPWNDSIZE_F"\n",
1485                                          pcb->cwnd, pcb->ssthresh));
1486             pcb->bytes_acked = 0;
1487 
1488             /* The following needs to be called AFTER cwnd is set to one
1489                mss - STJ */
1490             tcp_rexmit_rto_commit(pcb);
1491           }
1492         }
1493       }
1494     }
1495     /* Check if this PCB has stayed too long in FIN-WAIT-2 */
1496     if (pcb->state == FIN_WAIT_2) {
1497       /* If this PCB is in FIN_WAIT_2 because of SHUT_WR don't let it time out. */
1498       if (pcb->flags & TF_RXCLOSED) {
1499         /* PCB was fully closed (either through close() or SHUT_RDWR):
1500            normal FIN-WAIT timeout handling. */
1501         if ((u32_t)(tcp_ticks - pcb->tmr) >
1502             TCP_FIN_WAIT_TIMEOUT / TCP_SLOW_INTERVAL) {
1503           ++pcb_remove;
1504           LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: removing pcb stuck in FIN-WAIT-2\n"));
1505         }
1506       }
1507     }
1508 
1509     /* Check if KEEPALIVE should be sent */
1510     if (ip_get_option(pcb, SOF_KEEPALIVE) &&
1511         ((pcb->state == ESTABLISHED) ||
1512          (pcb->state == CLOSE_WAIT))) {
1513       if ((u32_t)(tcp_ticks - pcb->tmr) >
1514           (pcb->keep_idle + TCP_KEEP_DUR(pcb)) / TCP_SLOW_INTERVAL) {
1515         LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: KEEPALIVE timeout. Aborting connection to "));
1516         ip_addr_debug_print_val(TCP_DEBUG, pcb->remote_ip);
1517         LWIP_DEBUGF(TCP_DEBUG, ("\n"));
1518 
1519         ++pcb_remove;
1520         ++pcb_reset;
1521       } else if ((u32_t)(tcp_ticks - pcb->tmr) >
1522                  (pcb->keep_idle + pcb->keep_cnt_sent * TCP_KEEP_INTVL(pcb))
1523                  / TCP_SLOW_INTERVAL) {
1524         err = tcp_keepalive(pcb);
1525         if (err == ERR_OK) {
1526           pcb->keep_cnt_sent++;
1527         }
1528       }
1529     }
1530 
1531     /* If this PCB has queued out of sequence data, but has been
1532        inactive for too long, will drop the data (it will eventually
1533        be retransmitted). */
1534 #if TCP_QUEUE_OOSEQ
1535     if (pcb->ooseq != NULL &&
1536         (tcp_ticks - pcb->tmr >= (u32_t)pcb->rto * TCP_OOSEQ_TIMEOUT)) {
1537       LWIP_DEBUGF(TCP_CWND_DEBUG, ("tcp_slowtmr: dropping OOSEQ queued data\n"));
1538       tcp_free_ooseq(pcb);
1539     }
1540 #endif /* TCP_QUEUE_OOSEQ */
1541 
1542     /* Check if this PCB has stayed too long in SYN-RCVD */
1543     if (pcb->state == SYN_RCVD) {
1544       if ((u32_t)(tcp_ticks - pcb->tmr) >
1545           TCP_SYN_RCVD_TIMEOUT / TCP_SLOW_INTERVAL) {
1546         ++pcb_remove;
1547         LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: removing pcb stuck in SYN-RCVD\n"));
1548       }
1549     }
1550 
1551     /* Check if this PCB has stayed too long in LAST-ACK */
1552     if (pcb->state == LAST_ACK) {
1553       if ((u32_t)(tcp_ticks - pcb->tmr) > 2 * TCP_MSL / TCP_SLOW_INTERVAL) {
1554         ++pcb_remove;
1555         LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: removing pcb stuck in LAST-ACK\n"));
1556       }
1557     }
1558 
1559     /* If the PCB should be removed, do it. */
1560     if (pcb_remove) {
1561       struct tcp_pcb *pcb2;
1562 #if LWIP_CALLBACK_API
1563       tcp_err_fn err_fn = pcb->errf;
1564 #endif /* LWIP_CALLBACK_API */
1565       void *err_arg;
1566       enum tcp_state last_state;
1567       tcp_pcb_purge(pcb);
1568       /* Remove PCB from tcp_active_pcbs list. */
1569       if (prev != NULL) {
1570         LWIP_ASSERT("tcp_slowtmr: middle tcp != tcp_active_pcbs", pcb != tcp_active_pcbs);
1571         prev->next = pcb->next;
1572       } else {
1573         /* This PCB was the first. */
1574         LWIP_ASSERT("tcp_slowtmr: first pcb == tcp_active_pcbs", tcp_active_pcbs == pcb);
1575         tcp_active_pcbs = pcb->next;
1576       }
1577 
1578       if (pcb_reset) {
1579         tcp_rst(pcb, pcb->snd_nxt, pcb->rcv_nxt, &pcb->local_ip, &pcb->remote_ip,
1580                 pcb->local_port, pcb->remote_port);
1581       }
1582 
1583       err_arg = pcb->callback_arg;
1584       last_state = pcb->state;
1585       pcb2 = pcb;
1586       pcb = pcb->next;
1587       tcp_free(pcb2);
1588 
1589       tcp_active_pcbs_changed = 0;
1590       TCP_EVENT_ERR(last_state, err_fn, err_arg, ERR_ABRT);
1591       if (tcp_active_pcbs_changed) {
1592         goto tcp_slowtmr_start;
1593       }
1594     } else {
1595       /* get the 'next' element now and work with 'prev' below (in case of abort) */
1596       prev = pcb;
1597       pcb = pcb->next;
1598 
1599       /* We check if we should poll the connection. */
1600       ++prev->polltmr;
1601       if (prev->polltmr >= prev->pollinterval) {
1602         prev->polltmr = 0;
1603         LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: polling application\n"));
1604         tcp_active_pcbs_changed = 0;
1605         TCP_EVENT_POLL(prev, err);
1606         if (tcp_active_pcbs_changed) {
1607           goto tcp_slowtmr_start;
1608         }
1609         /* if err == ERR_ABRT, 'prev' is already deallocated */
1610         if (err == ERR_OK) {
1611           tcp_output(prev);
1612         }
1613       }
1614     }
1615   }
1616 
1617 
1618   /* Steps through all of the TIME-WAIT PCBs. */
1619   prev = NULL;
1620   pcb = tcp_tw_pcbs;
1621   while (pcb != NULL) {
1622     LWIP_ASSERT("tcp_slowtmr: TIME-WAIT pcb->state == TIME-WAIT", pcb->state == TIME_WAIT);
1623     pcb_remove = 0;
1624 
1625     /* Check if this PCB has stayed long enough in TIME-WAIT */
1626     if ((u32_t)(tcp_ticks - pcb->tmr) > 2 * TCP_MSL / TCP_SLOW_INTERVAL) {
1627       ++pcb_remove;
1628     }
1629 
1630     /* If the PCB should be removed, do it. */
1631     if (pcb_remove) {
1632       struct tcp_pcb *pcb2;
1633       tcp_pcb_purge(pcb);
1634       /* Remove PCB from tcp_tw_pcbs list. */
1635       if (prev != NULL) {
1636         LWIP_ASSERT("tcp_slowtmr: middle tcp != tcp_tw_pcbs", pcb != tcp_tw_pcbs);
1637         prev->next = pcb->next;
1638       } else {
1639         /* This PCB was the first. */
1640         LWIP_ASSERT("tcp_slowtmr: first pcb == tcp_tw_pcbs", tcp_tw_pcbs == pcb);
1641         tcp_tw_pcbs = pcb->next;
1642       }
1643       pcb2 = pcb;
1644       pcb = pcb->next;
1645       tcp_free(pcb2);
1646     } else {
1647       prev = pcb;
1648       pcb = pcb->next;
1649     }
1650   }
1651 }
1652 
1653 /**
1654  * Is called every TCP_FAST_INTERVAL (250 ms) and process data previously
1655  * "refused" by upper layer (application) and sends delayed ACKs or pending FINs.
1656  *
1657  * Automatically called from tcp_tmr().
1658  */
1659 void
1660 tcp_fasttmr(void)
1661 {
1662   struct tcp_pcb *pcb;
1663 
1664   ++tcp_timer_ctr;
1665 
1666 tcp_fasttmr_start:
1667   pcb = tcp_active_pcbs;
1668 
1669   while (pcb != NULL) {
1670     if (pcb->last_timer != tcp_timer_ctr) {
1671       struct tcp_pcb *next;
1672       pcb->last_timer = tcp_timer_ctr;
1673       /* send delayed ACKs */
1674       if (pcb->flags & TF_ACK_DELAY) {
1675         LWIP_DEBUGF(TCP_DEBUG, ("tcp_fasttmr: delayed ACK\n"));
1676         tcp_ack_now(pcb);
1677         tcp_output(pcb);
1678         tcp_clear_flags(pcb, TF_ACK_DELAY | TF_ACK_NOW);
1679       }
1680       /* send pending FIN */
1681       if (pcb->flags & TF_CLOSEPEND) {
1682         LWIP_DEBUGF(TCP_DEBUG, ("tcp_fasttmr: pending FIN\n"));
1683         tcp_clear_flags(pcb, TF_CLOSEPEND);
1684         tcp_close_shutdown_fin(pcb);
1685       }
1686 
1687       next = pcb->next;
1688 
1689       /* If there is data which was previously "refused" by upper layer */
1690       if (pcb->refused_data != NULL) {
1691         tcp_active_pcbs_changed = 0;
1692         tcp_process_refused_data(pcb);
1693         if (tcp_active_pcbs_changed) {
1694           /* application callback has changed the pcb list: restart the loop */
1695           goto tcp_fasttmr_start;
1696         }
1697       }
1698       pcb = next;
1699     } else {
1700       pcb = pcb->next;
1701     }
1702   }
1703 }
1704 
1705 /** Call tcp_output for all active pcbs that have TF_NAGLEMEMERR set */
1706 void
1707 tcp_txnow(void)
1708 {
1709   struct tcp_pcb *pcb;
1710 
1711   for (pcb = tcp_active_pcbs; pcb != NULL; pcb = pcb->next) {
1712     if (pcb->flags & TF_NAGLEMEMERR) {
1713       tcp_output(pcb);
1714     }
1715   }
1716 }
1717 
1718 /** Pass pcb->refused_data to the recv callback */
1719 err_t
1720 tcp_process_refused_data(struct tcp_pcb *pcb)
1721 {
1722 #if TCP_QUEUE_OOSEQ && LWIP_WND_SCALE
1723   struct pbuf *rest;
1724 #endif /* TCP_QUEUE_OOSEQ && LWIP_WND_SCALE */
1725 
1726   LWIP_ERROR("tcp_process_refused_data: invalid pcb", pcb != NULL, return ERR_ARG);
1727 
1728 #if TCP_QUEUE_OOSEQ && LWIP_WND_SCALE
1729   while (pcb->refused_data != NULL)
1730 #endif /* TCP_QUEUE_OOSEQ && LWIP_WND_SCALE */
1731   {
1732     err_t err;
1733     u8_t refused_flags = pcb->refused_data->flags;
1734     /* set pcb->refused_data to NULL in case the callback frees it and then
1735        closes the pcb */
1736     struct pbuf *refused_data = pcb->refused_data;
1737 #if TCP_QUEUE_OOSEQ && LWIP_WND_SCALE
1738     pbuf_split_64k(refused_data, &rest);
1739     pcb->refused_data = rest;
1740 #else /* TCP_QUEUE_OOSEQ && LWIP_WND_SCALE */
1741     pcb->refused_data = NULL;
1742 #endif /* TCP_QUEUE_OOSEQ && LWIP_WND_SCALE */
1743     /* Notify again application with data previously received. */
1744     LWIP_DEBUGF(TCP_INPUT_DEBUG, ("tcp_input: notify kept packet\n"));
1745     TCP_EVENT_RECV(pcb, refused_data, ERR_OK, err);
1746     if (err == ERR_OK) {
1747       /* did refused_data include a FIN? */
1748       if ((refused_flags & PBUF_FLAG_TCP_FIN)
1749 #if TCP_QUEUE_OOSEQ && LWIP_WND_SCALE
1750           && (rest == NULL)
1751 #endif /* TCP_QUEUE_OOSEQ && LWIP_WND_SCALE */
1752          ) {
1753         /* correct rcv_wnd as the application won't call tcp_recved()
1754            for the FIN's seqno */
1755         if (pcb->rcv_wnd != TCP_WND_MAX(pcb)) {
1756           pcb->rcv_wnd++;
1757         }
1758         TCP_EVENT_CLOSED(pcb, err);
1759         if (err == ERR_ABRT) {
1760           return ERR_ABRT;
1761         }
1762       }
1763     } else if (err == ERR_ABRT) {
1764       /* if err == ERR_ABRT, 'pcb' is already deallocated */
1765       /* Drop incoming packets because pcb is "full" (only if the incoming
1766          segment contains data). */
1767       LWIP_DEBUGF(TCP_INPUT_DEBUG, ("tcp_input: drop incoming packets, because pcb is \"full\"\n"));
1768       return ERR_ABRT;
1769     } else {
1770       /* data is still refused, pbuf is still valid (go on for ACK-only packets) */
1771 #if TCP_QUEUE_OOSEQ && LWIP_WND_SCALE
1772       if (rest != NULL) {
1773         pbuf_cat(refused_data, rest);
1774       }
1775 #endif /* TCP_QUEUE_OOSEQ && LWIP_WND_SCALE */
1776       pcb->refused_data = refused_data;
1777       return ERR_INPROGRESS;
1778     }
1779   }
1780   return ERR_OK;
1781 }
1782 
1783 /**
1784  * Deallocates a list of TCP segments (tcp_seg structures).
1785  *
1786  * @param seg tcp_seg list of TCP segments to free
1787  */
1788 void
1789 tcp_segs_free(struct tcp_seg *seg)
1790 {
1791   while (seg != NULL) {
1792     struct tcp_seg *next = seg->next;
1793     tcp_seg_free(seg);
1794     seg = next;
1795   }
1796 }
1797 
1798 /**
1799  * Frees a TCP segment (tcp_seg structure).
1800  *
1801  * @param seg single tcp_seg to free
1802  */
1803 void
1804 tcp_seg_free(struct tcp_seg *seg)
1805 {
1806   if (seg != NULL) {
1807     if (seg->p != NULL) {
1808       pbuf_free(seg->p);
1809 #if TCP_DEBUG
1810       seg->p = NULL;
1811 #endif /* TCP_DEBUG */
1812     }
1813     memp_free(MEMP_TCP_SEG, seg);
1814   }
1815 }
1816 
1817 /**
1818  * @ingroup tcp
1819  * Sets the priority of a connection.
1820  *
1821  * @param pcb the tcp_pcb to manipulate
1822  * @param prio new priority
1823  */
1824 void
1825 tcp_setprio(struct tcp_pcb *pcb, u8_t prio)
1826 {
1827   LWIP_ASSERT_CORE_LOCKED();
1828 
1829   LWIP_ERROR("tcp_setprio: invalid pcb", pcb != NULL, return);
1830 
1831   pcb->prio = prio;
1832 }
1833 
1834 #if TCP_QUEUE_OOSEQ
1835 /**
1836  * Returns a copy of the given TCP segment.
1837  * The pbuf and data are not copied, only the pointers
1838  *
1839  * @param seg the old tcp_seg
1840  * @return a copy of seg
1841  */
1842 struct tcp_seg *
1843 tcp_seg_copy(struct tcp_seg *seg)
1844 {
1845   struct tcp_seg *cseg;
1846 
1847   LWIP_ASSERT("tcp_seg_copy: invalid seg", seg != NULL);
1848 
1849   cseg = (struct tcp_seg *)memp_malloc(MEMP_TCP_SEG);
1850   if (cseg == NULL) {
1851     return NULL;
1852   }
1853   SMEMCPY((u8_t *)cseg, (const u8_t *)seg, sizeof(struct tcp_seg));
1854   pbuf_ref(cseg->p);
1855   return cseg;
1856 }
1857 #endif /* TCP_QUEUE_OOSEQ */
1858 
1859 #if LWIP_CALLBACK_API
1860 /**
1861  * Default receive callback that is called if the user didn't register
1862  * a recv callback for the pcb.
1863  */
1864 err_t
1865 tcp_recv_null(void *arg, struct tcp_pcb *pcb, struct pbuf *p, err_t err)
1866 {
1867   LWIP_UNUSED_ARG(arg);
1868 
1869   LWIP_ERROR("tcp_recv_null: invalid pcb", pcb != NULL, return ERR_ARG);
1870 
1871   if (p != NULL) {
1872     tcp_recved(pcb, p->tot_len);
1873     pbuf_free(p);
1874   } else if (err == ERR_OK) {
1875     return tcp_close(pcb);
1876   }
1877   return ERR_OK;
1878 }
1879 #endif /* LWIP_CALLBACK_API */
1880 
1881 /**
1882  * Kills the oldest active connection that has a lower priority than 'prio'.
1883  *
1884  * @param prio minimum priority
1885  */
1886 static void
1887 tcp_kill_prio(u8_t prio)
1888 {
1889   struct tcp_pcb *pcb, *inactive;
1890   u32_t inactivity;
1891   u8_t mprio;
1892 
1893   mprio = LWIP_MIN(TCP_PRIO_MAX, prio);
1894 
1895   /* We want to kill connections with a lower prio, so bail out if
1896    * supplied prio is 0 - there can never be a lower prio
1897    */
1898   if (mprio == 0) {
1899     return;
1900   }
1901 
1902   /* We only want kill connections with a lower prio, so decrement prio by one
1903    * and start searching for oldest connection with same or lower priority than mprio.
1904    * We want to find the connections with the lowest possible prio, and among
1905    * these the one with the longest inactivity time.
1906    */
1907   mprio--;
1908 
1909   inactivity = 0;
1910   inactive = NULL;
1911   for (pcb = tcp_active_pcbs; pcb != NULL; pcb = pcb->next) {
1912         /* lower prio is always a kill candidate */
1913     if ((pcb->prio < mprio) ||
1914         /* longer inactivity is also a kill candidate */
1915         ((pcb->prio == mprio) && ((u32_t)(tcp_ticks - pcb->tmr) >= inactivity))) {
1916       inactivity = tcp_ticks - pcb->tmr;
1917       inactive   = pcb;
1918       mprio      = pcb->prio;
1919     }
1920   }
1921   if (inactive != NULL) {
1922     LWIP_DEBUGF(TCP_DEBUG, ("tcp_kill_prio: killing oldest PCB %p (%"S32_F")\n",
1923                             (void *)inactive, inactivity));
1924     tcp_abort(inactive);
1925   }
1926 }
1927 
1928 /**
1929  * Kills the oldest connection that is in specific state.
1930  * Called from tcp_alloc() for LAST_ACK and CLOSING if no more connections are available.
1931  */
1932 static void
1933 tcp_kill_state(enum tcp_state state)
1934 {
1935   struct tcp_pcb *pcb, *inactive;
1936   u32_t inactivity;
1937 
1938   LWIP_ASSERT("invalid state", (state == CLOSING) || (state == LAST_ACK));
1939 
1940   inactivity = 0;
1941   inactive = NULL;
1942   /* Go through the list of active pcbs and get the oldest pcb that is in state
1943      CLOSING/LAST_ACK. */
1944   for (pcb = tcp_active_pcbs; pcb != NULL; pcb = pcb->next) {
1945     if (pcb->state == state) {
1946       if ((u32_t)(tcp_ticks - pcb->tmr) >= inactivity) {
1947         inactivity = tcp_ticks - pcb->tmr;
1948         inactive = pcb;
1949       }
1950     }
1951   }
1952   if (inactive != NULL) {
1953     LWIP_DEBUGF(TCP_DEBUG, ("tcp_kill_closing: killing oldest %s PCB %p (%"S32_F")\n",
1954                             tcp_state_str[state], (void *)inactive, inactivity));
1955     /* Don't send a RST, since no data is lost. */
1956     tcp_abandon(inactive, 0);
1957   }
1958 }
1959 
1960 /**
1961  * Kills the oldest connection that is in TIME_WAIT state.
1962  * Called from tcp_alloc() if no more connections are available.
1963  */
1964 static void
1965 tcp_kill_timewait(void)
1966 {
1967   struct tcp_pcb *pcb, *inactive;
1968   u32_t inactivity;
1969 
1970   inactivity = 0;
1971   inactive = NULL;
1972   /* Go through the list of TIME_WAIT pcbs and get the oldest pcb. */
1973   for (pcb = tcp_tw_pcbs; pcb != NULL; pcb = pcb->next) {
1974     if ((u32_t)(tcp_ticks - pcb->tmr) >= inactivity) {
1975       inactivity = tcp_ticks - pcb->tmr;
1976       inactive = pcb;
1977     }
1978   }
1979   if (inactive != NULL) {
1980     LWIP_DEBUGF(TCP_DEBUG, ("tcp_kill_timewait: killing oldest TIME-WAIT PCB %p (%"S32_F")\n",
1981                             (void *)inactive, inactivity));
1982     tcp_abort(inactive);
1983   }
1984 }
1985 
1986 /* Called when allocating a pcb fails.
1987  * In this case, we want to handle all pcbs that want to close first: if we can
1988  * now send the FIN (which failed before), the pcb might be in a state that is
1989  * OK for us to now free it.
1990  */
1991 static void
1992 tcp_handle_closepend(void)
1993 {
1994   struct tcp_pcb *pcb = tcp_active_pcbs;
1995 
1996   while (pcb != NULL) {
1997     struct tcp_pcb *next = pcb->next;
1998     /* send pending FIN */
1999     if (pcb->flags & TF_CLOSEPEND) {
2000       LWIP_DEBUGF(TCP_DEBUG, ("tcp_handle_closepend: pending FIN\n"));
2001       tcp_clear_flags(pcb, TF_CLOSEPEND);
2002       tcp_close_shutdown_fin(pcb);
2003     }
2004     pcb = next;
2005   }
2006 }
2007 
2008 /**
2009  * Allocate a new tcp_pcb structure.
2010  *
2011  * @param prio priority for the new pcb
2012  * @return a new tcp_pcb that initially is in state CLOSED
2013  */
2014 struct tcp_pcb *
2015 tcp_alloc(u8_t prio)
2016 {
2017   struct tcp_pcb *pcb;
2018 
2019   LWIP_ASSERT_CORE_LOCKED();
2020 
2021   pcb = (struct tcp_pcb *)memp_malloc(MEMP_TCP_PCB);
2022   if (pcb == NULL) {
2023     /* Try to send FIN for all pcbs stuck in TF_CLOSEPEND first */
2024     tcp_handle_closepend();
2025 
2026     /* Try killing oldest connection in TIME-WAIT. */
2027     LWIP_DEBUGF(TCP_DEBUG, ("tcp_alloc: killing off oldest TIME-WAIT connection\n"));
2028     tcp_kill_timewait();
2029     /* Try to allocate a tcp_pcb again. */
2030     pcb = (struct tcp_pcb *)memp_malloc(MEMP_TCP_PCB);
2031     if (pcb == NULL) {
2032       /* Try killing oldest connection in LAST-ACK (these wouldn't go to TIME-WAIT). */
2033       LWIP_DEBUGF(TCP_DEBUG, ("tcp_alloc: killing off oldest LAST-ACK connection\n"));
2034       tcp_kill_state(LAST_ACK);
2035       /* Try to allocate a tcp_pcb again. */
2036       pcb = (struct tcp_pcb *)memp_malloc(MEMP_TCP_PCB);
2037       if (pcb == NULL) {
2038         /* Try killing oldest connection in CLOSING. */
2039         LWIP_DEBUGF(TCP_DEBUG, ("tcp_alloc: killing off oldest CLOSING connection\n"));
2040         tcp_kill_state(CLOSING);
2041         /* Try to allocate a tcp_pcb again. */
2042         pcb = (struct tcp_pcb *)memp_malloc(MEMP_TCP_PCB);
2043         if (pcb == NULL) {
2044           /* Try killing oldest active connection with lower priority than the new one. */
2045           LWIP_DEBUGF(TCP_DEBUG, ("tcp_alloc: killing oldest connection with prio lower than %d\n", prio));
2046           tcp_kill_prio(prio);
2047           /* Try to allocate a tcp_pcb again. */
2048           pcb = (struct tcp_pcb *)memp_malloc(MEMP_TCP_PCB);
2049           if (pcb != NULL) {
2050             /* adjust err stats: memp_malloc failed multiple times before */
2051             MEMP_STATS_DEC(err, MEMP_TCP_PCB);
2052           }
2053         }
2054         if (pcb != NULL) {
2055           /* adjust err stats: memp_malloc failed multiple times before */
2056           MEMP_STATS_DEC(err, MEMP_TCP_PCB);
2057         }
2058       }
2059       if (pcb != NULL) {
2060         /* adjust err stats: memp_malloc failed multiple times before */
2061         MEMP_STATS_DEC(err, MEMP_TCP_PCB);
2062       }
2063     }
2064     if (pcb != NULL) {
2065       /* adjust err stats: memp_malloc failed above */
2066       MEMP_STATS_DEC(err, MEMP_TCP_PCB);
2067     }
2068   }
2069   if (pcb != NULL) {
2070     /* zero out the whole pcb, so there is no need to initialize members to zero */
2071     memset(pcb, 0, sizeof(struct tcp_pcb));
2072     pcb->prio = prio;
2073     pcb->snd_buf = TCP_SND_BUF;
2074     /* Start with a window that does not need scaling. When window scaling is
2075        enabled and used, the window is enlarged when both sides agree on scaling. */
2076     pcb->rcv_wnd = pcb->rcv_ann_wnd = TCPWND_MIN16(TCP_WND);
2077     pcb->ttl = TCP_TTL;
2078     /* As initial send MSS, we use TCP_MSS but limit it to 536.
2079        The send MSS is updated when an MSS option is received. */
2080     pcb->mss = INITIAL_MSS;
2081     /* Set initial TCP's retransmission timeout to 3000 ms by default.
2082        This value could be configured in lwipopts */
2083     pcb->rto = LWIP_TCP_RTO_TIME / TCP_SLOW_INTERVAL;
2084     pcb->sv = LWIP_TCP_RTO_TIME / TCP_SLOW_INTERVAL;
2085     pcb->rtime = -1;
2086     pcb->cwnd = 1;
2087     pcb->tmr = tcp_ticks;
2088     pcb->last_timer = tcp_timer_ctr;
2089 
2090     /* RFC 5681 recommends setting ssthresh arbitrarily high and gives an example
2091     of using the largest advertised receive window.  We've seen complications with
2092     receiving TCPs that use window scaling and/or window auto-tuning where the
2093     initial advertised window is very small and then grows rapidly once the
2094     connection is established. To avoid these complications, we set ssthresh to the
2095     largest effective cwnd (amount of in-flight data) that the sender can have. */
2096     pcb->ssthresh = TCP_SND_BUF;
2097 
2098 #if LWIP_CALLBACK_API
2099     pcb->recv = tcp_recv_null;
2100 #endif /* LWIP_CALLBACK_API */
2101 
2102     /* Init KEEPALIVE timer */
2103     pcb->keep_idle  = TCP_KEEPIDLE_DEFAULT;
2104 
2105 #if LWIP_TCP_KEEPALIVE
2106     pcb->keep_intvl = TCP_KEEPINTVL_DEFAULT;
2107     pcb->keep_cnt   = TCP_KEEPCNT_DEFAULT;
2108 #endif /* LWIP_TCP_KEEPALIVE */
2109     pcb_tci_init(pcb);
2110   }
2111   return pcb;
2112 }
2113 
2114 /**
2115  * @ingroup tcp_raw
2116  * Creates a new TCP protocol control block but doesn't place it on
2117  * any of the TCP PCB lists.
2118  * The pcb is not put on any list until binding using tcp_bind().
2119  * If memory is not available for creating the new pcb, NULL is returned.
2120  * @see MEMP_NUM_TCP_PCB_LISTEN and MEMP_NUM_TCP_PCB
2121  *
2122  * @internal: Maybe there should be a idle TCP PCB list where these
2123  * PCBs are put on. Port reservation using tcp_bind() is implemented but
2124  * allocated pcbs that are not bound can't be killed automatically if wanting
2125  * to allocate a pcb with higher prio (@see tcp_kill_prio())
2126  *
2127  * @return a new tcp_pcb that initially is in state CLOSED
2128  */
2129 struct tcp_pcb *
2130 tcp_new(void)
2131 {
2132   return tcp_alloc(TCP_PRIO_NORMAL);
2133 }
2134 
2135 /**
2136  * @ingroup tcp_raw
2137  * Creates a new TCP protocol control block but doesn't
2138  * place it on any of the TCP PCB lists.
2139  * The pcb is not put on any list until binding using tcp_bind().
2140  * @see MEMP_NUM_TCP_PCB_LISTEN and MEMP_NUM_TCP_PCB
2141  *
2142  * @param type IP address type, see @ref lwip_ip_addr_type definitions.
2143  * If you want to listen to IPv4 and IPv6 (dual-stack) connections,
2144  * supply @ref IPADDR_TYPE_ANY as argument and bind to @ref IP_ANY_TYPE.
2145  * @return a new tcp_pcb that initially is in state CLOSED
2146  */
2147 struct tcp_pcb *
2148 tcp_new_ip_type(u8_t type)
2149 {
2150   struct tcp_pcb *pcb;
2151   pcb = tcp_alloc(TCP_PRIO_NORMAL);
2152 #if LWIP_IPV4 && LWIP_IPV6
2153   if (pcb != NULL) {
2154     IP_SET_TYPE_VAL(pcb->local_ip, type);
2155     IP_SET_TYPE_VAL(pcb->remote_ip, type);
2156   }
2157 #else
2158   LWIP_UNUSED_ARG(type);
2159 #endif /* LWIP_IPV4 && LWIP_IPV6 */
2160   return pcb;
2161 }
2162 
2163 /**
2164  * @ingroup tcp_raw
2165  * Specifies the program specific state that should be passed to all
2166  * other callback functions. The "pcb" argument is the current TCP
2167  * connection control block, and the "arg" argument is the argument
2168  * that will be passed to the callbacks.
2169  *
2170  * @param pcb tcp_pcb to set the callback argument
2171  * @param arg void pointer argument to pass to callback functions
2172  */
2173 void
2174 tcp_arg(struct tcp_pcb *pcb, void *arg)
2175 {
2176   LWIP_ASSERT_CORE_LOCKED();
2177   /* This function is allowed to be called for both listen pcbs and
2178      connection pcbs. */
2179   if (pcb != NULL) {
2180     pcb->callback_arg = arg;
2181   }
2182 }
2183 #if LWIP_CALLBACK_API
2184 
2185 /**
2186  * @ingroup tcp_raw
2187  * Sets the callback function that will be called when new data
2188  * arrives. The callback function will be passed a NULL pbuf to
2189  * indicate that the remote host has closed the connection. If the
2190  * callback function returns ERR_OK or ERR_ABRT it must have
2191  * freed the pbuf, otherwise it must not have freed it.
2192  *
2193  * @param pcb tcp_pcb to set the recv callback
2194  * @param recv callback function to call for this pcb when data is received
2195  */
2196 void
2197 tcp_recv(struct tcp_pcb *pcb, tcp_recv_fn recv)
2198 {
2199   LWIP_ASSERT_CORE_LOCKED();
2200   if (pcb != NULL) {
2201     LWIP_ASSERT("invalid socket state for recv callback", pcb->state != LISTEN);
2202     pcb->recv = recv;
2203   }
2204 }
2205 
2206 /**
2207  * @ingroup tcp_raw
2208  * Specifies the callback function that should be called when data has
2209  * successfully been received (i.e., acknowledged) by the remote
2210  * host. The len argument passed to the callback function gives the
2211  * amount bytes that was acknowledged by the last acknowledgment.
2212  *
2213  * @param pcb tcp_pcb to set the sent callback
2214  * @param sent callback function to call for this pcb when data is successfully sent
2215  */
2216 void
2217 tcp_sent(struct tcp_pcb *pcb, tcp_sent_fn sent)
2218 {
2219   LWIP_ASSERT_CORE_LOCKED();
2220   if (pcb != NULL) {
2221     LWIP_ASSERT("invalid socket state for sent callback", pcb->state != LISTEN);
2222     pcb->sent = sent;
2223   }
2224 }
2225 
2226 /**
2227  * @ingroup tcp_raw
2228  * Used to specify the function that should be called when a fatal error
2229  * has occurred on the connection.
2230  *
2231  * If a connection is aborted because of an error, the application is
2232  * alerted of this event by the err callback. Errors that might abort a
2233  * connection are when there is a shortage of memory. The callback
2234  * function to be called is set using the tcp_err() function.
2235  *
2236  * @note The corresponding pcb is already freed when this callback is called!
2237  *
2238  * @param pcb tcp_pcb to set the err callback
2239  * @param err callback function to call for this pcb when a fatal error
2240  *        has occurred on the connection
2241  */
2242 void
2243 tcp_err(struct tcp_pcb *pcb, tcp_err_fn err)
2244 {
2245   LWIP_ASSERT_CORE_LOCKED();
2246   if (pcb != NULL) {
2247     LWIP_ASSERT("invalid socket state for err callback", pcb->state != LISTEN);
2248     pcb->errf = err;
2249   }
2250 }
2251 
2252 /**
2253  * @ingroup tcp_raw
2254  * Used for specifying the function that should be called when a
2255  * LISTENing connection has been connected to another host.
2256  * @see MEMP_NUM_TCP_PCB_LISTEN and MEMP_NUM_TCP_PCB
2257  *
2258  * @param pcb tcp_pcb to set the accept callback
2259  * @param accept callback function to call for this pcb when LISTENing
2260  *        connection has been connected to another host
2261  */
2262 void
2263 tcp_accept(struct tcp_pcb *pcb, tcp_accept_fn accept)
2264 {
2265   LWIP_ASSERT_CORE_LOCKED();
2266   if ((pcb != NULL) && (pcb->state == LISTEN)) {
2267     struct tcp_pcb_listen *lpcb = (struct tcp_pcb_listen *)pcb;
2268     lpcb->accept = accept;
2269   }
2270 }
2271 #endif /* LWIP_CALLBACK_API */
2272 
2273 
2274 /**
2275  * @ingroup tcp_raw
2276  * Specifies the polling interval and the callback function that should
2277  * be called to poll the application. The interval is specified in
2278  * number of TCP coarse grained timer shots, which typically occurs
2279  * twice a second. An interval of 10 means that the application would
2280  * be polled every 5 seconds.
2281  *
2282  * When a connection is idle (i.e., no data is either transmitted or
2283  * received), lwIP will repeatedly poll the application by calling a
2284  * specified callback function. This can be used either as a watchdog
2285  * timer for killing connections that have stayed idle for too long, or
2286  * as a method of waiting for memory to become available. For instance,
2287  * if a call to tcp_write() has failed because memory wasn't available,
2288  * the application may use the polling functionality to call tcp_write()
2289  * again when the connection has been idle for a while.
2290  */
2291 void
2292 tcp_poll(struct tcp_pcb *pcb, tcp_poll_fn poll, u8_t interval)
2293 {
2294   LWIP_ASSERT_CORE_LOCKED();
2295 
2296   LWIP_ERROR("tcp_poll: invalid pcb", pcb != NULL, return);
2297   LWIP_ASSERT("invalid socket state for poll", pcb->state != LISTEN);
2298 
2299 #if LWIP_CALLBACK_API
2300   pcb->poll = poll;
2301 #else /* LWIP_CALLBACK_API */
2302   LWIP_UNUSED_ARG(poll);
2303 #endif /* LWIP_CALLBACK_API */
2304   pcb->pollinterval = interval;
2305 }
2306 
2307 /**
2308  * Purges a TCP PCB. Removes any buffered data and frees the buffer memory
2309  * (pcb->ooseq, pcb->unsent and pcb->unacked are freed).
2310  *
2311  * @param pcb tcp_pcb to purge. The pcb itself is not deallocated!
2312  */
2313 void
2314 tcp_pcb_purge(struct tcp_pcb *pcb)
2315 {
2316   LWIP_ERROR("tcp_pcb_purge: invalid pcb", pcb != NULL, return);
2317 
2318   if (pcb->state != CLOSED &&
2319       pcb->state != TIME_WAIT &&
2320       pcb->state != LISTEN) {
2321 
2322     LWIP_DEBUGF(TCP_DEBUG, ("tcp_pcb_purge\n"));
2323 
2324     tcp_backlog_accepted(pcb);
2325 
2326     if (pcb->refused_data != NULL) {
2327       LWIP_DEBUGF(TCP_DEBUG, ("tcp_pcb_purge: data left on ->refused_data\n"));
2328       pbuf_free(pcb->refused_data);
2329       pcb->refused_data = NULL;
2330     }
2331     if (pcb->unsent != NULL) {
2332       LWIP_DEBUGF(TCP_DEBUG, ("tcp_pcb_purge: not all data sent\n"));
2333     }
2334     if (pcb->unacked != NULL) {
2335       LWIP_DEBUGF(TCP_DEBUG, ("tcp_pcb_purge: data left on ->unacked\n"));
2336     }
2337 #if TCP_QUEUE_OOSEQ
2338     if (pcb->ooseq != NULL) {
2339       LWIP_DEBUGF(TCP_DEBUG, ("tcp_pcb_purge: data left on ->ooseq\n"));
2340       tcp_free_ooseq(pcb);
2341     }
2342 #endif /* TCP_QUEUE_OOSEQ */
2343 
2344     /* Stop the retransmission timer as it will expect data on unacked
2345        queue if it fires */
2346     pcb->rtime = -1;
2347 
2348     tcp_segs_free(pcb->unsent);
2349     tcp_segs_free(pcb->unacked);
2350     pcb->unacked = pcb->unsent = NULL;
2351 #if TCP_OVERSIZE
2352     pcb->unsent_oversize = 0;
2353 #endif /* TCP_OVERSIZE */
2354   }
2355 }
2356 
2357 /**
2358  * Purges the PCB and removes it from a PCB list. Any delayed ACKs are sent first.
2359  *
2360  * @param pcblist PCB list to purge.
2361  * @param pcb tcp_pcb to purge. The pcb itself is NOT deallocated!
2362  */
2363 void
2364 tcp_pcb_remove(struct tcp_pcb **pcblist, struct tcp_pcb *pcb)
2365 {
2366   LWIP_ASSERT("tcp_pcb_remove: invalid pcb", pcb != NULL);
2367   LWIP_ASSERT("tcp_pcb_remove: invalid pcblist", pcblist != NULL);
2368 
2369   TCP_RMV(pcblist, pcb);
2370 
2371   tcp_pcb_purge(pcb);
2372 
2373   /* if there is an outstanding delayed ACKs, send it */
2374   if ((pcb->state != TIME_WAIT) &&
2375       (pcb->state != LISTEN) &&
2376       (pcb->flags & TF_ACK_DELAY)) {
2377     tcp_ack_now(pcb);
2378     tcp_output(pcb);
2379   }
2380 
2381   if (pcb->state != LISTEN) {
2382     LWIP_ASSERT("unsent segments leaking", pcb->unsent == NULL);
2383     LWIP_ASSERT("unacked segments leaking", pcb->unacked == NULL);
2384 #if TCP_QUEUE_OOSEQ
2385     LWIP_ASSERT("ooseq segments leaking", pcb->ooseq == NULL);
2386 #endif /* TCP_QUEUE_OOSEQ */
2387   }
2388 
2389   pcb->state = CLOSED;
2390   /* reset the local port to prevent the pcb from being 'bound' */
2391   pcb->local_port = 0;
2392 
2393   LWIP_ASSERT("tcp_pcb_remove: tcp_pcbs_sane()", tcp_pcbs_sane());
2394 }
2395 
2396 /**
2397  * Calculates a new initial sequence number for new connections.
2398  *
2399  * @return u32_t pseudo random sequence number
2400  */
2401 u32_t
2402 tcp_next_iss(struct tcp_pcb *pcb)
2403 {
2404 #ifdef LWIP_HOOK_TCP_ISN
2405   LWIP_ASSERT("tcp_next_iss: invalid pcb", pcb != NULL);
2406   return LWIP_HOOK_TCP_ISN(&pcb->local_ip, pcb->local_port, &pcb->remote_ip, pcb->remote_port);
2407 #else /* LWIP_HOOK_TCP_ISN */
2408   static u32_t iss = 6510;
2409 
2410   LWIP_ASSERT("tcp_next_iss: invalid pcb", pcb != NULL);
2411   LWIP_UNUSED_ARG(pcb);
2412 
2413   iss += tcp_ticks;       /* XXX */
2414   return iss;
2415 #endif /* LWIP_HOOK_TCP_ISN */
2416 }
2417 
2418 #if TCP_CALCULATE_EFF_SEND_MSS
2419 /**
2420  * Calculates the effective send mss that can be used for a specific IP address
2421  * by calculating the minimum of TCP_MSS and the mtu (if set) of the target
2422  * netif (if not NULL).
2423  */
2424 u16_t
2425 tcp_eff_send_mss_netif(u16_t sendmss, struct netif *outif, const ip_addr_t *dest)
2426 {
2427   u16_t mss_s;
2428   u16_t mtu;
2429 
2430   LWIP_UNUSED_ARG(dest); /* in case IPv6 is disabled */
2431 
2432   LWIP_ASSERT("tcp_eff_send_mss_netif: invalid dst_ip", dest != NULL);
2433 
2434 #if LWIP_IPV6
2435 #if LWIP_IPV4
2436   if (IP_IS_V6(dest))
2437 #endif /* LWIP_IPV4 */
2438   {
2439     /* First look in destination cache, to see if there is a Path MTU. */
2440     mtu = nd6_get_destination_mtu(ip_2_ip6(dest), outif);
2441   }
2442 #if LWIP_IPV4
2443   else
2444 #endif /* LWIP_IPV4 */
2445 #endif /* LWIP_IPV6 */
2446 #if LWIP_IPV4
2447   {
2448     if (outif == NULL) {
2449       return sendmss;
2450     }
2451     mtu = outif->mtu;
2452   }
2453 #endif /* LWIP_IPV4 */
2454 
2455   if (mtu != 0) {
2456     u16_t offset;
2457 #if LWIP_IPV6
2458 #if LWIP_IPV4
2459     if (IP_IS_V6(dest))
2460 #endif /* LWIP_IPV4 */
2461     {
2462       offset = IP6_HLEN + TCP_HLEN;
2463     }
2464 #if LWIP_IPV4
2465     else
2466 #endif /* LWIP_IPV4 */
2467 #endif /* LWIP_IPV6 */
2468 #if LWIP_IPV4
2469     {
2470       offset = IP_HLEN + TCP_HLEN;
2471     }
2472 #endif /* LWIP_IPV4 */
2473     mss_s = (mtu > offset) ? (u16_t)(mtu - offset) : 0;
2474     /* RFC 1122, chap 4.2.2.6:
2475      * Eff.snd.MSS = min(SendMSS+20, MMS_S) - TCPhdrsize - IPoptionsize
2476      * We correct for TCP options in tcp_write(), and don't support IP options.
2477      */
2478     sendmss = LWIP_MIN(sendmss, mss_s);
2479   }
2480   return sendmss;
2481 }
2482 #endif /* TCP_CALCULATE_EFF_SEND_MSS */
2483 
2484 /** Helper function for tcp_netif_ip_addr_changed() that iterates a pcb list */
2485 static void
2486 tcp_netif_ip_addr_changed_pcblist(const ip_addr_t *old_addr, struct tcp_pcb *pcb_list)
2487 {
2488   struct tcp_pcb *pcb;
2489   pcb = pcb_list;
2490 
2491   LWIP_ASSERT("tcp_netif_ip_addr_changed_pcblist: invalid old_addr", old_addr != NULL);
2492 
2493   while (pcb != NULL) {
2494     /* PCB bound to current local interface address? */
2495     if (ip_addr_eq(&pcb->local_ip, old_addr)
2496 #if LWIP_AUTOIP
2497         /* connections to link-local addresses must persist (RFC3927 ch. 1.9) */
2498         && (!IP_IS_V4_VAL(pcb->local_ip) || !ip4_addr_islinklocal(ip_2_ip4(&pcb->local_ip)))
2499 #endif /* LWIP_AUTOIP */
2500        ) {
2501       /* this connection must be aborted */
2502       struct tcp_pcb *next = pcb->next;
2503       LWIP_DEBUGF(NETIF_DEBUG | LWIP_DBG_STATE, ("netif_set_ipaddr: aborting TCP pcb %p\n", (void *)pcb));
2504       tcp_abort(pcb);
2505       pcb = next;
2506     } else {
2507       pcb = pcb->next;
2508     }
2509   }
2510 }
2511 
2512 /** This function is called from netif.c when address is changed or netif is removed
2513  *
2514  * @param old_addr IP address of the netif before change
2515  * @param new_addr IP address of the netif after change or NULL if netif has been removed
2516  */
2517 void
2518 tcp_netif_ip_addr_changed(const ip_addr_t *old_addr, const ip_addr_t *new_addr)
2519 {
2520   struct tcp_pcb_listen *lpcb;
2521 
2522   if (!ip_addr_isany(old_addr)) {
2523     tcp_netif_ip_addr_changed_pcblist(old_addr, tcp_active_pcbs);
2524     tcp_netif_ip_addr_changed_pcblist(old_addr, tcp_bound_pcbs);
2525 
2526     if (!ip_addr_isany(new_addr)) {
2527       /* PCB bound to current local interface address? */
2528       for (lpcb = tcp_listen_pcbs.listen_pcbs; lpcb != NULL; lpcb = lpcb->next) {
2529         /* PCB bound to current local interface address? */
2530         if (ip_addr_eq(&lpcb->local_ip, old_addr)) {
2531           /* The PCB is listening to the old ipaddr and
2532             * is set to listen to the new one instead */
2533           ip_addr_copy(lpcb->local_ip, *new_addr);
2534         }
2535       }
2536     }
2537   }
2538 }
2539 
2540 const char *
2541 tcp_debug_state_str(enum tcp_state s)
2542 {
2543   return tcp_state_str[s];
2544 }
2545 
2546 err_t
2547 tcp_tcp_get_tcp_addrinfo(struct tcp_pcb *pcb, int local, ip_addr_t *addr, u16_t *port)
2548 {
2549   if (pcb) {
2550     if (local) {
2551       if (addr) {
2552         *addr = pcb->local_ip;
2553       }
2554       if (port) {
2555         *port = pcb->local_port;
2556       }
2557     } else {
2558       if (addr) {
2559         *addr = pcb->remote_ip;
2560       }
2561       if (port) {
2562         *port = pcb->remote_port;
2563       }
2564     }
2565     return ERR_OK;
2566   }
2567   return ERR_VAL;
2568 }
2569 
2570 #if TCP_QUEUE_OOSEQ
2571 /* Free all ooseq pbufs (and possibly reset SACK state) */
2572 void
2573 tcp_free_ooseq(struct tcp_pcb *pcb)
2574 {
2575   if (pcb->ooseq) {
2576     tcp_segs_free(pcb->ooseq);
2577     pcb->ooseq = NULL;
2578 #if LWIP_TCP_SACK_OUT
2579     memset(pcb->rcv_sacks, 0, sizeof(pcb->rcv_sacks));
2580 #endif /* LWIP_TCP_SACK_OUT */
2581   }
2582 }
2583 #endif /* TCP_QUEUE_OOSEQ */
2584 
2585 #if TCP_DEBUG || TCP_INPUT_DEBUG || TCP_OUTPUT_DEBUG
2586 /**
2587  * Print a tcp header for debugging purposes.
2588  *
2589  * @param tcphdr pointer to a struct tcp_hdr
2590  */
2591 void
2592 tcp_debug_print(struct tcp_hdr *tcphdr)
2593 {
2594   LWIP_DEBUGF(TCP_DEBUG, ("TCP header:\n"));
2595   LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
2596   LWIP_DEBUGF(TCP_DEBUG, ("|    %5"U16_F"      |    %5"U16_F"      | (src port, dest port)\n",
2597                           lwip_ntohs(tcphdr->src), lwip_ntohs(tcphdr->dest)));
2598   LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
2599   LWIP_DEBUGF(TCP_DEBUG, ("|           %010"U32_F"          | (seq no)\n",
2600                           lwip_ntohl(tcphdr->seqno)));
2601   LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
2602   LWIP_DEBUGF(TCP_DEBUG, ("|           %010"U32_F"          | (ack no)\n",
2603                           lwip_ntohl(tcphdr->ackno)));
2604   LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
2605   LWIP_DEBUGF(TCP_DEBUG, ("| %2"U16_F" |   |%"U16_F"%"U16_F"%"U16_F"%"U16_F"%"U16_F"%"U16_F"|     %5"U16_F"     | (hdrlen, flags (",
2606                           TCPH_HDRLEN(tcphdr),
2607                           (u16_t)(TCPH_FLAGS(tcphdr) >> 5 & 1),
2608                           (u16_t)(TCPH_FLAGS(tcphdr) >> 4 & 1),
2609                           (u16_t)(TCPH_FLAGS(tcphdr) >> 3 & 1),
2610                           (u16_t)(TCPH_FLAGS(tcphdr) >> 2 & 1),
2611                           (u16_t)(TCPH_FLAGS(tcphdr) >> 1 & 1),
2612                           (u16_t)(TCPH_FLAGS(tcphdr)      & 1),
2613                           lwip_ntohs(tcphdr->wnd)));
2614   tcp_debug_print_flags(TCPH_FLAGS(tcphdr));
2615   LWIP_DEBUGF(TCP_DEBUG, ("), win)\n"));
2616   LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
2617   LWIP_DEBUGF(TCP_DEBUG, ("|    0x%04"X16_F"     |     %5"U16_F"     | (chksum, urgp)\n",
2618                           lwip_ntohs(tcphdr->chksum), lwip_ntohs(tcphdr->urgp)));
2619   LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
2620 }
2621 
2622 /**
2623  * Print a tcp state for debugging purposes.
2624  *
2625  * @param s enum tcp_state to print
2626  */
2627 void
2628 tcp_debug_print_state(enum tcp_state s)
2629 {
2630   LWIP_DEBUGF(TCP_DEBUG, ("State: %s\n", tcp_state_str[s]));
2631 }
2632 
2633 /**
2634  * Print tcp flags for debugging purposes.
2635  *
2636  * @param flags tcp flags, all active flags are printed
2637  */
2638 void
2639 tcp_debug_print_flags(u8_t flags)
2640 {
2641   if (flags & TCP_FIN) {
2642     LWIP_DEBUGF(TCP_DEBUG, ("FIN "));
2643   }
2644   if (flags & TCP_SYN) {
2645     LWIP_DEBUGF(TCP_DEBUG, ("SYN "));
2646   }
2647   if (flags & TCP_RST) {
2648     LWIP_DEBUGF(TCP_DEBUG, ("RST "));
2649   }
2650   if (flags & TCP_PSH) {
2651     LWIP_DEBUGF(TCP_DEBUG, ("PSH "));
2652   }
2653   if (flags & TCP_ACK) {
2654     LWIP_DEBUGF(TCP_DEBUG, ("ACK "));
2655   }
2656   if (flags & TCP_URG) {
2657     LWIP_DEBUGF(TCP_DEBUG, ("URG "));
2658   }
2659   if (flags & TCP_ECE) {
2660     LWIP_DEBUGF(TCP_DEBUG, ("ECE "));
2661   }
2662   if (flags & TCP_CWR) {
2663     LWIP_DEBUGF(TCP_DEBUG, ("CWR "));
2664   }
2665   LWIP_DEBUGF(TCP_DEBUG, ("\n"));
2666 }
2667 
2668 /**
2669  * Print all tcp_pcbs in every list for debugging purposes.
2670  */
2671 void
2672 tcp_debug_print_pcbs(void)
2673 {
2674   struct tcp_pcb *pcb;
2675   struct tcp_pcb_listen *pcbl;
2676 
2677   LWIP_DEBUGF(TCP_DEBUG, ("Active PCB states:\n"));
2678   for (pcb = tcp_active_pcbs; pcb != NULL; pcb = pcb->next) {
2679     LWIP_DEBUGF(TCP_DEBUG, ("Local port %"U16_F", foreign port %"U16_F" snd_nxt %"U32_F" rcv_nxt %"U32_F" ",
2680                             pcb->local_port, pcb->remote_port,
2681                             pcb->snd_nxt, pcb->rcv_nxt));
2682     tcp_debug_print_state(pcb->state);
2683   }
2684 
2685   LWIP_DEBUGF(TCP_DEBUG, ("Listen PCB states:\n"));
2686   for (pcbl = tcp_listen_pcbs.listen_pcbs; pcbl != NULL; pcbl = pcbl->next) {
2687     LWIP_DEBUGF(TCP_DEBUG, ("Local port %"U16_F" ", pcbl->local_port));
2688     tcp_debug_print_state(pcbl->state);
2689   }
2690 
2691   LWIP_DEBUGF(TCP_DEBUG, ("TIME-WAIT PCB states:\n"));
2692   for (pcb = tcp_tw_pcbs; pcb != NULL; pcb = pcb->next) {
2693     LWIP_DEBUGF(TCP_DEBUG, ("Local port %"U16_F", foreign port %"U16_F" snd_nxt %"U32_F" rcv_nxt %"U32_F" ",
2694                             pcb->local_port, pcb->remote_port,
2695                             pcb->snd_nxt, pcb->rcv_nxt));
2696     tcp_debug_print_state(pcb->state);
2697   }
2698 }
2699 
2700 /**
2701  * Check state consistency of the tcp_pcb lists.
2702  */
2703 s16_t
2704 tcp_pcbs_sane(void)
2705 {
2706   struct tcp_pcb *pcb;
2707   for (pcb = tcp_active_pcbs; pcb != NULL; pcb = pcb->next) {
2708     LWIP_ASSERT("tcp_pcbs_sane: active pcb->state != CLOSED", pcb->state != CLOSED);
2709     LWIP_ASSERT("tcp_pcbs_sane: active pcb->state != LISTEN", pcb->state != LISTEN);
2710     LWIP_ASSERT("tcp_pcbs_sane: active pcb->state != TIME-WAIT", pcb->state != TIME_WAIT);
2711   }
2712   for (pcb = tcp_tw_pcbs; pcb != NULL; pcb = pcb->next) {
2713     LWIP_ASSERT("tcp_pcbs_sane: tw pcb->state == TIME-WAIT", pcb->state == TIME_WAIT);
2714   }
2715   return 1;
2716 }
2717 #endif /* TCP_DEBUG */
2718 
2719 #if LWIP_TCP_PCB_NUM_EXT_ARGS
2720 /**
2721  * @defgroup tcp_raw_extargs ext arguments
2722  * @ingroup tcp_raw
2723  * Additional data storage per tcp pcb<br>
2724  * @see @ref tcp_raw
2725  *
2726  * When LWIP_TCP_PCB_NUM_EXT_ARGS is > 0, every tcp pcb (including listen pcb)
2727  * includes a number of additional argument entries in an array.
2728  *
2729  * To support memory management, in addition to a 'void *', callbacks can be
2730  * provided to manage transition from listening pcbs to connections and to
2731  * deallocate memory when a pcb is deallocated (see struct @ref tcp_ext_arg_callbacks).
2732  *
2733  * After allocating this index, use @ref tcp_ext_arg_set and @ref tcp_ext_arg_get
2734  * to store and load arguments from this index for a given pcb.
2735  */
2736 
2737 static u8_t tcp_ext_arg_id;
2738 
2739 /**
2740  * @ingroup tcp_raw_extargs
2741  * Allocate an index to store data in ext_args member of struct tcp_pcb.
2742  * Returned value is an index in mentioned array.
2743  * The index is *global* over all pcbs!
2744  *
2745  * When @ref LWIP_TCP_PCB_NUM_EXT_ARGS is > 0, every tcp pcb (including listen pcb)
2746  * includes a number of additional argument entries in an array.
2747  *
2748  * To support memory management, in addition to a 'void *', callbacks can be
2749  * provided to manage transition from listening pcbs to connections and to
2750  * deallocate memory when a pcb is deallocated (see struct @ref tcp_ext_arg_callbacks).
2751  *
2752  * After allocating this index, use @ref tcp_ext_arg_set and @ref tcp_ext_arg_get
2753  * to store and load arguments from this index for a given pcb.
2754  *
2755  * @return a unique index into struct tcp_pcb.ext_args
2756  */
2757 u8_t
2758 tcp_ext_arg_alloc_id(void)
2759 {
2760   u8_t result = tcp_ext_arg_id;
2761   tcp_ext_arg_id++;
2762 
2763   LWIP_ASSERT_CORE_LOCKED();
2764 
2765 #if LWIP_TCP_PCB_NUM_EXT_ARGS >= 255
2766 #error LWIP_TCP_PCB_NUM_EXT_ARGS
2767 #endif
2768   LWIP_ASSERT("Increase LWIP_TCP_PCB_NUM_EXT_ARGS in lwipopts.h", result < LWIP_TCP_PCB_NUM_EXT_ARGS);
2769   return result;
2770 }
2771 
2772 /**
2773  * @ingroup tcp_raw_extargs
2774  * Set callbacks for a given index of ext_args on the specified pcb.
2775  *
2776  * @param pcb tcp_pcb for which to set the callback
2777  * @param id ext_args index to set (allocated via @ref tcp_ext_arg_alloc_id)
2778  * @param callbacks callback table (const since it is referenced, not copied!)
2779  */
2780 void
2781 tcp_ext_arg_set_callbacks(struct tcp_pcb *pcb, u8_t id, const struct tcp_ext_arg_callbacks * const callbacks)
2782 {
2783   LWIP_ASSERT("pcb != NULL", pcb != NULL);
2784   LWIP_ASSERT("id < LWIP_TCP_PCB_NUM_EXT_ARGS", id < LWIP_TCP_PCB_NUM_EXT_ARGS);
2785   LWIP_ASSERT("callbacks != NULL", callbacks != NULL);
2786 
2787   LWIP_ASSERT_CORE_LOCKED();
2788 
2789   pcb->ext_args[id].callbacks = callbacks;
2790 }
2791 
2792 /**
2793  * @ingroup tcp_raw_extargs
2794  * Set data for a given index of ext_args on the specified pcb.
2795  *
2796  * @param pcb tcp_pcb for which to set the data
2797  * @param id ext_args index to set (allocated via @ref tcp_ext_arg_alloc_id)
2798  * @param arg data pointer to set
2799  */
2800 void tcp_ext_arg_set(struct tcp_pcb *pcb, u8_t id, void *arg)
2801 {
2802   LWIP_ASSERT("pcb != NULL", pcb != NULL);
2803   LWIP_ASSERT("id < LWIP_TCP_PCB_NUM_EXT_ARGS", id < LWIP_TCP_PCB_NUM_EXT_ARGS);
2804 
2805   LWIP_ASSERT_CORE_LOCKED();
2806 
2807   pcb->ext_args[id].data = arg;
2808 }
2809 
2810 /**
2811  * @ingroup tcp_raw_extargs
2812  * Set data for a given index of ext_args on the specified pcb.
2813  *
2814  * @param pcb tcp_pcb for which to set the data
2815  * @param id ext_args index to set (allocated via @ref tcp_ext_arg_alloc_id)
2816  * @return data pointer at the given index
2817  */
2818 void *tcp_ext_arg_get(const struct tcp_pcb *pcb, u8_t id)
2819 {
2820   LWIP_ASSERT("pcb != NULL", pcb != NULL);
2821   LWIP_ASSERT("id < LWIP_TCP_PCB_NUM_EXT_ARGS", id < LWIP_TCP_PCB_NUM_EXT_ARGS);
2822 
2823   LWIP_ASSERT_CORE_LOCKED();
2824 
2825   return pcb->ext_args[id].data;
2826 }
2827 
2828 /** This function calls the "destroy" callback for all ext_args once a pcb is
2829  * freed.
2830  */
2831 static void
2832 tcp_ext_arg_invoke_callbacks_destroyed(struct tcp_pcb_ext_args *ext_args)
2833 {
2834   int i;
2835   LWIP_ASSERT("ext_args != NULL", ext_args != NULL);
2836 
2837   for (i = 0; i < LWIP_TCP_PCB_NUM_EXT_ARGS; i++) {
2838     if (ext_args[i].callbacks != NULL) {
2839       if (ext_args[i].callbacks->destroy != NULL) {
2840         ext_args[i].callbacks->destroy((u8_t)i, ext_args[i].data);
2841       }
2842     }
2843   }
2844 }
2845 
2846 /** This function calls the "passive_open" callback for all ext_args if a connection
2847  * is in the process of being accepted. This is called just after the SYN is
2848  * received and before a SYN/ACK is sent, to allow to modify the very first
2849  * segment sent even on passive open. Naturally, the "accepted" callback of the
2850  * pcb has not been called yet!
2851  */
2852 err_t
2853 tcp_ext_arg_invoke_callbacks_passive_open(struct tcp_pcb_listen *lpcb, struct tcp_pcb *cpcb)
2854 {
2855   int i;
2856   LWIP_ASSERT("lpcb != NULL", lpcb != NULL);
2857   LWIP_ASSERT("cpcb != NULL", cpcb != NULL);
2858 
2859   for (i = 0; i < LWIP_TCP_PCB_NUM_EXT_ARGS; i++) {
2860     if (lpcb->ext_args[i].callbacks != NULL) {
2861       if (lpcb->ext_args[i].callbacks->passive_open != NULL) {
2862         err_t err = lpcb->ext_args[i].callbacks->passive_open((u8_t)i, lpcb, cpcb);
2863         if (err != ERR_OK) {
2864           return err;
2865         }
2866       }
2867     }
2868   }
2869   return ERR_OK;
2870 }
2871 #endif /* LWIP_TCP_PCB_NUM_EXT_ARGS */
2872 
2873 #endif /* LWIP_TCP */
2874