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