1 /**
2 * @file
3 * Transmission Control Protocol for IP
4 * See also @ref tcp_raw
5 *
6 * @defgroup tcp_raw TCP
7 * @ingroup callbackstyle_api
8 * Transmission Control Protocol for IP\n
9 * @see @ref api
10 *
11 * Common functions for the TCP implementation, such as functions
12 * for manipulating the data structures and the TCP timer functions. TCP functions
13 * related to input and output is found in tcp_in.c and tcp_out.c respectively.\n
14 *
15 * TCP connection setup
16 * --------------------
17 * The functions used for setting up connections is similar to that of
18 * the sequential API and of the BSD socket API. A new TCP connection
19 * identifier (i.e., a protocol control block - PCB) is created with the
20 * tcp_new() function. This PCB can then be either set to listen for new
21 * incoming connections or be explicitly connected to another host.
22 * - tcp_new()
23 * - tcp_bind()
24 * - tcp_listen() and tcp_listen_with_backlog()
25 * - tcp_accept()
26 * - tcp_connect()
27 *
28 * Sending TCP data
29 * ----------------
30 * TCP data is sent by enqueueing the data with a call to tcp_write() and
31 * triggering to send by calling tcp_output(). When the data is successfully
32 * transmitted to the remote host, the application will be notified with a
33 * call to a specified callback function.
34 * - tcp_write()
35 * - tcp_output()
36 * - tcp_sent()
37 *
38 * Receiving TCP data
39 * ------------------
40 * TCP data reception is callback based - an application specified
41 * callback function is called when new data arrives. When the
42 * application has taken the data, it has to call the tcp_recved()
43 * function to indicate that TCP can advertise increase the receive
44 * window.
45 * - tcp_recv()
46 * - tcp_recved()
47 *
48 * Application polling
49 * -------------------
50 * When a connection is idle (i.e., no data is either transmitted or
51 * received), lwIP will repeatedly poll the application by calling a
52 * specified callback function. This can be used either as a watchdog
53 * timer for killing connections that have stayed idle for too long, or
54 * as a method of waiting for memory to become available. For instance,
55 * if a call to tcp_write() has failed because memory wasn't available,
56 * the application may use the polling functionality to call tcp_write()
57 * again when the connection has been idle for a while.
58 * - tcp_poll()
59 *
60 * Closing and aborting connections
61 * --------------------------------
62 * - tcp_close()
63 * - tcp_abort()
64 * - tcp_err()
65 *
66 */
67
68 /*
69 * Copyright (c) 2001-2004 Swedish Institute of Computer Science.
70 * All rights reserved.
71 *
72 * Redistribution and use in source and binary forms, with or without modification,
73 * are permitted provided that the following conditions are met:
74 *
75 * 1. Redistributions of source code must retain the above copyright notice,
76 * this list of conditions and the following disclaimer.
77 * 2. Redistributions in binary form must reproduce the above copyright notice,
78 * this list of conditions and the following disclaimer in the documentation
79 * and/or other materials provided with the distribution.
80 * 3. The name of the author may not be used to endorse or promote products
81 * derived from this software without specific prior written permission.
82 *
83 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
84 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
85 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
86 * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
87 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
88 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
89 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
90 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
91 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
92 * OF SUCH DAMAGE.
93 *
94 * This file is part of the lwIP TCP/IP stack.
95 *
96 * Author: Adam Dunkels <[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 enum tcp_state last_state;
587 seqno = pcb->snd_nxt;
588 ackno = pcb->rcv_nxt;
589 #if LWIP_CALLBACK_API
590 errf = pcb->errf;
591 #endif /* LWIP_CALLBACK_API */
592 errf_arg = pcb->callback_arg;
593 if (pcb->state == CLOSED) {
594 if (pcb->local_port != 0) {
595 /* bound, not yet opened */
596 TCP_RMV(&tcp_bound_pcbs, pcb);
597 }
598 } else {
599 send_rst = reset;
600 TCP_PCB_REMOVE_ACTIVE(pcb);
601 }
602 if (pcb->unacked != NULL) {
603 tcp_segs_free(pcb->unacked);
604 }
605 if (pcb->unsent != NULL) {
606 tcp_segs_free(pcb->unsent);
607 }
608 #if TCP_QUEUE_OOSEQ
609 if (pcb->ooseq != NULL) {
610 tcp_segs_free(pcb->ooseq);
611 }
612 #endif /* TCP_QUEUE_OOSEQ */
613 tcp_backlog_accepted(pcb);
614 if (send_rst) {
615 LWIP_DEBUGF(TCP_RST_DEBUG, ("tcp_abandon: sending RST\n"));
616 tcp_rst(pcb, seqno, ackno, &pcb->local_ip, &pcb->remote_ip, pcb->local_port, pcb->remote_port);
617 }
618 last_state = pcb->state;
619 tcp_free(pcb);
620 TCP_EVENT_ERR(last_state, errf, errf_arg, ERR_ABRT);
621 }
622 }
623
624 /**
625 * @ingroup tcp_raw
626 * Aborts the connection by sending a RST (reset) segment to the remote
627 * host. The pcb is deallocated. This function never fails.
628 *
629 * ATTENTION: When calling this from one of the TCP callbacks, make
630 * sure you always return ERR_ABRT (and never return ERR_ABRT otherwise
631 * or you will risk accessing deallocated memory or memory leaks!
632 *
633 * @param pcb the tcp pcb to abort
634 */
635 void
tcp_abort(struct tcp_pcb * pcb)636 tcp_abort(struct tcp_pcb *pcb)
637 {
638 tcp_abandon(pcb, 1);
639 }
640
641 /**
642 * @ingroup tcp_raw
643 * Binds the connection to a local port number and IP address. If the
644 * IP address is not given (i.e., ipaddr == IP_ANY_TYPE), the connection is
645 * bound to all local IP addresses.
646 * If another connection is bound to the same port, the function will
647 * return ERR_USE, otherwise ERR_OK is returned.
648 *
649 * @param pcb the tcp_pcb to bind (no check is done whether this pcb is
650 * already bound!)
651 * @param ipaddr the local ip address to bind to (use IPx_ADDR_ANY to bind
652 * to any local address
653 * @param port the local port to bind to
654 * @return ERR_USE if the port is already in use
655 * ERR_VAL if bind failed because the PCB is not in a valid state
656 * ERR_OK if bound
657 */
658 err_t
tcp_bind(struct tcp_pcb * pcb,const ip_addr_t * ipaddr,u16_t port)659 tcp_bind(struct tcp_pcb *pcb, const ip_addr_t *ipaddr, u16_t port)
660 {
661 int i;
662 int max_pcb_list = NUM_TCP_PCB_LISTS;
663 struct tcp_pcb *cpcb;
664 #if LWIP_IPV6 && LWIP_IPV6_SCOPES
665 ip_addr_t zoned_ipaddr;
666 #endif /* LWIP_IPV6 && LWIP_IPV6_SCOPES */
667
668 LWIP_ASSERT_CORE_LOCKED();
669
670 #if LWIP_IPV4
671 /* Don't propagate NULL pointer (IPv4 ANY) to subsequent functions */
672 if (ipaddr == NULL) {
673 ipaddr = IP4_ADDR_ANY;
674 }
675 #else /* LWIP_IPV4 */
676 LWIP_ERROR("tcp_bind: invalid ipaddr", ipaddr != NULL, return ERR_ARG);
677 #endif /* LWIP_IPV4 */
678
679 LWIP_ERROR("tcp_bind: invalid pcb", pcb != NULL, return ERR_ARG);
680
681 LWIP_ERROR("tcp_bind: can only bind in state CLOSED", pcb->state == CLOSED, return ERR_VAL);
682
683 #if SO_REUSE
684 /* Unless the REUSEADDR flag is set,
685 we have to check the pcbs in TIME-WAIT state, also.
686 We do not dump TIME_WAIT pcb's; they can still be matched by incoming
687 packets using both local and remote IP addresses and ports to distinguish.
688 */
689 if (ip_get_option(pcb, SOF_REUSEADDR)) {
690 max_pcb_list = NUM_TCP_PCB_LISTS_NO_TIME_WAIT;
691 }
692 #endif /* SO_REUSE */
693
694 #if LWIP_IPV6 && LWIP_IPV6_SCOPES
695 /* If the given IP address should have a zone but doesn't, assign one now.
696 * This is legacy support: scope-aware callers should always provide properly
697 * zoned source addresses. Do the zone selection before the address-in-use
698 * check below; as such we have to make a temporary copy of the address. */
699 if (IP_IS_V6(ipaddr) && ip6_addr_lacks_zone(ip_2_ip6(ipaddr), IP6_UNICAST)) {
700 ip_addr_copy(zoned_ipaddr, *ipaddr);
701 ip6_addr_select_zone(ip_2_ip6(&zoned_ipaddr), ip_2_ip6(&zoned_ipaddr));
702 ipaddr = &zoned_ipaddr;
703 }
704 #endif /* LWIP_IPV6 && LWIP_IPV6_SCOPES */
705
706 if (port == 0) {
707 port = tcp_new_port();
708 if (port == 0) {
709 return ERR_BUF;
710 }
711 } else {
712 /* Check if the address already is in use (on all lists) */
713 for (i = 0; i < max_pcb_list; i++) {
714 for (cpcb = *tcp_pcb_lists[i]; cpcb != NULL; cpcb = cpcb->next) {
715 if (cpcb->local_port == port) {
716 #if SO_REUSE
717 /* Omit checking for the same port if both pcbs have REUSEADDR set.
718 For SO_REUSEADDR, the duplicate-check for a 5-tuple is done in
719 tcp_connect. */
720 if (!ip_get_option(pcb, SOF_REUSEADDR) ||
721 !ip_get_option(cpcb, SOF_REUSEADDR))
722 #endif /* SO_REUSE */
723 {
724 /* @todo: check accept_any_ip_version */
725 if ((IP_IS_V6(ipaddr) == IP_IS_V6_VAL(cpcb->local_ip)) &&
726 (ip_addr_isany(&cpcb->local_ip) ||
727 ip_addr_isany(ipaddr) ||
728 ip_addr_cmp(&cpcb->local_ip, ipaddr))) {
729 return ERR_USE;
730 }
731 }
732 }
733 }
734 }
735 }
736
737 if (!ip_addr_isany(ipaddr)
738 #if LWIP_IPV4 && LWIP_IPV6
739 || (IP_GET_TYPE(ipaddr) != IP_GET_TYPE(&pcb->local_ip))
740 #endif /* LWIP_IPV4 && LWIP_IPV6 */
741 ) {
742 ip_addr_set(&pcb->local_ip, ipaddr);
743 }
744 pcb->local_port = port;
745 TCP_REG(&tcp_bound_pcbs, pcb);
746 LWIP_DEBUGF(TCP_DEBUG, ("tcp_bind: bind to port %"U16_F"\n", port));
747 return ERR_OK;
748 }
749
750 /**
751 * @ingroup tcp_raw
752 * Binds the connection to a netif and IP address.
753 * After calling this function, all packets received via this PCB
754 * are guaranteed to have come in via the specified netif, and all
755 * outgoing packets will go out via the specified netif.
756 *
757 * @param pcb the tcp_pcb to bind.
758 * @param netif the netif to bind to. Can be NULL.
759 */
760 void
tcp_bind_netif(struct tcp_pcb * pcb,const struct netif * netif)761 tcp_bind_netif(struct tcp_pcb *pcb, const struct netif *netif)
762 {
763 LWIP_ASSERT_CORE_LOCKED();
764 if (netif != NULL) {
765 pcb->netif_idx = netif_get_index(netif);
766 } else {
767 pcb->netif_idx = NETIF_NO_INDEX;
768 }
769 }
770
771 #if LWIP_CALLBACK_API
772 /**
773 * Default accept callback if no accept callback is specified by the user.
774 */
775 static err_t
tcp_accept_null(void * arg,struct tcp_pcb * pcb,err_t err)776 tcp_accept_null(void *arg, struct tcp_pcb *pcb, err_t err)
777 {
778 LWIP_UNUSED_ARG(arg);
779 LWIP_UNUSED_ARG(err);
780
781 LWIP_ASSERT("tcp_accept_null: invalid pcb", pcb != NULL);
782
783 tcp_abort(pcb);
784
785 return ERR_ABRT;
786 }
787 #endif /* LWIP_CALLBACK_API */
788
789 /**
790 * @ingroup tcp_raw
791 * Set the state of the connection to be LISTEN, which means that it
792 * is able to accept incoming connections. The protocol control block
793 * is reallocated in order to consume less memory. Setting the
794 * connection to LISTEN is an irreversible process.
795 * When an incoming connection is accepted, the function specified with
796 * the tcp_accept() function will be called. The pcb has to be bound
797 * to a local port with the tcp_bind() function.
798 *
799 * The tcp_listen() function returns a new connection identifier, and
800 * the one passed as an argument to the function will be
801 * deallocated. The reason for this behavior is that less memory is
802 * needed for a connection that is listening, so tcp_listen() will
803 * reclaim the memory needed for the original connection and allocate a
804 * new smaller memory block for the listening connection.
805 *
806 * tcp_listen() may return NULL if no memory was available for the
807 * listening connection. If so, the memory associated with the pcb
808 * passed as an argument to tcp_listen() will not be deallocated.
809 *
810 * The backlog limits the number of outstanding connections
811 * in the listen queue to the value specified by the backlog argument.
812 * To use it, your need to set TCP_LISTEN_BACKLOG=1 in your lwipopts.h.
813 *
814 * @param pcb the original tcp_pcb
815 * @param backlog the incoming connections queue limit
816 * @return tcp_pcb used for listening, consumes less memory.
817 *
818 * @note The original tcp_pcb is freed. This function therefore has to be
819 * called like this:
820 * tpcb = tcp_listen_with_backlog(tpcb, backlog);
821 */
822 struct tcp_pcb *
tcp_listen_with_backlog(struct tcp_pcb * pcb,u8_t backlog)823 tcp_listen_with_backlog(struct tcp_pcb *pcb, u8_t backlog)
824 {
825 LWIP_ASSERT_CORE_LOCKED();
826 return tcp_listen_with_backlog_and_err(pcb, backlog, NULL);
827 }
828
829 /**
830 * @ingroup tcp_raw
831 * Set the state of the connection to be LISTEN, which means that it
832 * is able to accept incoming connections. The protocol control block
833 * is reallocated in order to consume less memory. Setting the
834 * connection to LISTEN is an irreversible process.
835 *
836 * @param pcb the original tcp_pcb
837 * @param backlog the incoming connections queue limit
838 * @param err when NULL is returned, this contains the error reason
839 * @return tcp_pcb used for listening, consumes less memory.
840 *
841 * @note The original tcp_pcb is freed. This function therefore has to be
842 * called like this:
843 * tpcb = tcp_listen_with_backlog_and_err(tpcb, backlog, &err);
844 */
845 struct tcp_pcb *
tcp_listen_with_backlog_and_err(struct tcp_pcb * pcb,u8_t backlog,err_t * err)846 tcp_listen_with_backlog_and_err(struct tcp_pcb *pcb, u8_t backlog, err_t *err)
847 {
848 struct tcp_pcb_listen *lpcb = NULL;
849 err_t res;
850
851 LWIP_UNUSED_ARG(backlog);
852
853 LWIP_ASSERT_CORE_LOCKED();
854
855 LWIP_ERROR("tcp_listen_with_backlog_and_err: invalid pcb", pcb != NULL, res = ERR_ARG; goto done);
856 LWIP_ERROR("tcp_listen_with_backlog_and_err: pcb already connected", pcb->state == CLOSED, res = ERR_CLSD; goto done);
857
858 /* already listening? */
859 if (pcb->state == LISTEN) {
860 lpcb = (struct tcp_pcb_listen *)pcb;
861 res = ERR_ALREADY;
862 goto done;
863 }
864 #if SO_REUSE
865 if (ip_get_option(pcb, SOF_REUSEADDR)) {
866 /* Since SOF_REUSEADDR allows reusing a local address before the pcb's usage
867 is declared (listen-/connection-pcb), we have to make sure now that
868 this port is only used once for every local IP. */
869 for (lpcb = tcp_listen_pcbs.listen_pcbs; lpcb != NULL; lpcb = lpcb->next) {
870 if ((lpcb->local_port == pcb->local_port) &&
871 ip_addr_cmp(&lpcb->local_ip, &pcb->local_ip)) {
872 /* this address/port is already used */
873 lpcb = NULL;
874 res = ERR_USE;
875 goto done;
876 }
877 }
878 }
879 #endif /* SO_REUSE */
880 lpcb = (struct tcp_pcb_listen *)memp_malloc(MEMP_TCP_PCB_LISTEN);
881 if (lpcb == NULL) {
882 res = ERR_MEM;
883 goto done;
884 }
885 lpcb->callback_arg = pcb->callback_arg;
886 lpcb->local_port = pcb->local_port;
887 lpcb->state = LISTEN;
888 lpcb->prio = pcb->prio;
889 lpcb->so_options = pcb->so_options;
890 lpcb->netif_idx = NETIF_NO_INDEX;
891 lpcb->ttl = pcb->ttl;
892 lpcb->tos = pcb->tos;
893 #if LWIP_IPV4 && LWIP_IPV6
894 IP_SET_TYPE_VAL(lpcb->remote_ip, pcb->local_ip.type);
895 #endif /* LWIP_IPV4 && LWIP_IPV6 */
896 ip_addr_copy(lpcb->local_ip, pcb->local_ip);
897 if (pcb->local_port != 0) {
898 TCP_RMV(&tcp_bound_pcbs, pcb);
899 }
900 #if LWIP_TCP_PCB_NUM_EXT_ARGS
901 /* copy over ext_args to listening pcb */
902 memcpy(&lpcb->ext_args, &pcb->ext_args, sizeof(pcb->ext_args));
903 #endif
904 tcp_free(pcb);
905 #if LWIP_CALLBACK_API
906 lpcb->accept = tcp_accept_null;
907 #endif /* LWIP_CALLBACK_API */
908 #if TCP_LISTEN_BACKLOG
909 lpcb->accepts_pending = 0;
910 tcp_backlog_set(lpcb, backlog);
911 #endif /* TCP_LISTEN_BACKLOG */
912 TCP_REG(&tcp_listen_pcbs.pcbs, (struct tcp_pcb *)lpcb);
913 res = ERR_OK;
914 done:
915 if (err != NULL) {
916 *err = res;
917 }
918 return (struct tcp_pcb *)lpcb;
919 }
920
921 /**
922 * Update the state that tracks the available window space to advertise.
923 *
924 * Returns how much extra window would be advertised if we sent an
925 * update now.
926 */
927 u32_t
tcp_update_rcv_ann_wnd(struct tcp_pcb * pcb)928 tcp_update_rcv_ann_wnd(struct tcp_pcb *pcb)
929 {
930 u32_t new_right_edge;
931
932 LWIP_ASSERT("tcp_update_rcv_ann_wnd: invalid pcb", pcb != NULL);
933 new_right_edge = pcb->rcv_nxt + pcb->rcv_wnd;
934
935 if (TCP_SEQ_GEQ(new_right_edge, pcb->rcv_ann_right_edge + LWIP_MIN((TCP_WND / 2), pcb->mss))) {
936 /* we can advertise more window */
937 pcb->rcv_ann_wnd = pcb->rcv_wnd;
938 return new_right_edge - pcb->rcv_ann_right_edge;
939 } else {
940 if (TCP_SEQ_GT(pcb->rcv_nxt, pcb->rcv_ann_right_edge)) {
941 /* Can happen due to other end sending out of advertised window,
942 * but within actual available (but not yet advertised) window */
943 pcb->rcv_ann_wnd = 0;
944 } else {
945 /* keep the right edge of window constant */
946 u32_t new_rcv_ann_wnd = pcb->rcv_ann_right_edge - pcb->rcv_nxt;
947 #if !LWIP_WND_SCALE
948 LWIP_ASSERT("new_rcv_ann_wnd <= 0xffff", new_rcv_ann_wnd <= 0xffff);
949 #endif
950 pcb->rcv_ann_wnd = (tcpwnd_size_t)new_rcv_ann_wnd;
951 }
952 return 0;
953 }
954 }
955
956 /**
957 * @ingroup tcp_raw
958 * This function should be called by the application when it has
959 * processed the data. The purpose is to advertise a larger window
960 * when the data has been processed.
961 *
962 * @param pcb the tcp_pcb for which data is read
963 * @param len the amount of bytes that have been read by the application
964 */
965 void
tcp_recved(struct tcp_pcb * pcb,u16_t len)966 tcp_recved(struct tcp_pcb *pcb, u16_t len)
967 {
968 u32_t wnd_inflation;
969
970 LWIP_ASSERT_CORE_LOCKED();
971
972 LWIP_ERROR("tcp_recved: invalid pcb", pcb != NULL, return);
973
974 /* pcb->state LISTEN not allowed here */
975 LWIP_ASSERT("don't call tcp_recved for listen-pcbs",
976 pcb->state != LISTEN);
977
978 pcb->rcv_wnd = (tcpwnd_size_t)(pcb->rcv_wnd + len);
979 if (pcb->rcv_wnd > TCP_WND_MAX(pcb)) {
980 pcb->rcv_wnd = TCP_WND_MAX(pcb);
981 } else if (pcb->rcv_wnd == 0) {
982 /* rcv_wnd overflowed */
983 if (TCP_STATE_IS_CLOSING(pcb->state)) {
984 /* In passive close, we allow this, since the FIN bit is added to rcv_wnd
985 by the stack itself, since it is not mandatory for an application
986 to call tcp_recved() for the FIN bit, but e.g. the netconn API does so. */
987 pcb->rcv_wnd = TCP_WND_MAX(pcb);
988 } else {
989 LWIP_ASSERT("tcp_recved: len wrapped rcv_wnd\n", 0);
990 }
991 }
992
993 wnd_inflation = tcp_update_rcv_ann_wnd(pcb);
994
995 /* If the change in the right edge of window is significant (default
996 * watermark is TCP_WND/4), then send an explicit update now.
997 * Otherwise wait for a packet to be sent in the normal course of
998 * events (or more window to be available later) */
999 if (wnd_inflation >= TCP_WND_UPDATE_THRESHOLD) {
1000 tcp_ack_now(pcb);
1001 tcp_output(pcb);
1002 }
1003
1004 LWIP_DEBUGF(TCP_DEBUG, ("tcp_recved: received %"U16_F" bytes, wnd %"TCPWNDSIZE_F" (%"TCPWNDSIZE_F").\n",
1005 len, pcb->rcv_wnd, (u16_t)(TCP_WND_MAX(pcb) - pcb->rcv_wnd)));
1006 }
1007
1008 /**
1009 * Allocate a new local TCP port.
1010 *
1011 * @return a new (free) local TCP port number
1012 */
1013 static u16_t
tcp_new_port(void)1014 tcp_new_port(void)
1015 {
1016 u8_t i;
1017 u16_t n = 0;
1018 struct tcp_pcb *pcb;
1019
1020 again:
1021 tcp_port++;
1022 if (tcp_port == TCP_LOCAL_PORT_RANGE_END) {
1023 tcp_port = TCP_LOCAL_PORT_RANGE_START;
1024 }
1025 /* Check all PCB lists. */
1026 for (i = 0; i < NUM_TCP_PCB_LISTS; i++) {
1027 for (pcb = *tcp_pcb_lists[i]; pcb != NULL; pcb = pcb->next) {
1028 if (pcb->local_port == tcp_port) {
1029 n++;
1030 if (n > (TCP_LOCAL_PORT_RANGE_END - TCP_LOCAL_PORT_RANGE_START)) {
1031 return 0;
1032 }
1033 goto again;
1034 }
1035 }
1036 }
1037 return tcp_port;
1038 }
1039
1040 /**
1041 * @ingroup tcp_raw
1042 * Connects to another host. The function given as the "connected"
1043 * argument will be called when the connection has been established.
1044 * Sets up the pcb to connect to the remote host and sends the
1045 * initial SYN segment which opens the connection.
1046 *
1047 * The tcp_connect() function returns immediately; it does not wait for
1048 * the connection to be properly setup. Instead, it will call the
1049 * function specified as the fourth argument (the "connected" argument)
1050 * when the connection is established. If the connection could not be
1051 * properly established, either because the other host refused the
1052 * connection or because the other host didn't answer, the "err"
1053 * callback function of this pcb (registered with tcp_err, see below)
1054 * will be called.
1055 *
1056 * The tcp_connect() function can return ERR_MEM if no memory is
1057 * available for enqueueing the SYN segment. If the SYN indeed was
1058 * enqueued successfully, the tcp_connect() function returns ERR_OK.
1059 *
1060 * @param pcb the tcp_pcb used to establish the connection
1061 * @param ipaddr the remote ip address to connect to
1062 * @param port the remote tcp port to connect to
1063 * @param connected callback function to call when connected (on error,
1064 the err calback will be called)
1065 * @return ERR_VAL if invalid arguments are given
1066 * ERR_OK if connect request has been sent
1067 * other err_t values if connect request couldn't be sent
1068 */
1069 err_t
tcp_connect(struct tcp_pcb * pcb,const ip_addr_t * ipaddr,u16_t port,tcp_connected_fn connected)1070 tcp_connect(struct tcp_pcb *pcb, const ip_addr_t *ipaddr, u16_t port,
1071 tcp_connected_fn connected)
1072 {
1073 struct netif *netif = NULL;
1074 err_t ret;
1075 u32_t iss;
1076 u16_t old_local_port;
1077
1078 LWIP_ASSERT_CORE_LOCKED();
1079
1080 LWIP_ERROR("tcp_connect: invalid pcb", pcb != NULL, return ERR_ARG);
1081 LWIP_ERROR("tcp_connect: invalid ipaddr", ipaddr != NULL, return ERR_ARG);
1082
1083 LWIP_ERROR("tcp_connect: can only connect from state CLOSED", pcb->state == CLOSED, return ERR_ISCONN);
1084
1085 LWIP_DEBUGF(TCP_DEBUG, ("tcp_connect to port %"U16_F"\n", port));
1086 ip_addr_set(&pcb->remote_ip, ipaddr);
1087 pcb->remote_port = port;
1088
1089 if (pcb->netif_idx != NETIF_NO_INDEX) {
1090 netif = netif_get_by_index(pcb->netif_idx);
1091 } else {
1092 /* check if we have a route to the remote host */
1093 netif = ip_route(&pcb->local_ip, &pcb->remote_ip);
1094 }
1095 if (netif == NULL) {
1096 /* Don't even try to send a SYN packet if we have no route since that will fail. */
1097 return ERR_RTE;
1098 }
1099
1100 /* check if local IP has been assigned to pcb, if not, get one */
1101 if (ip_addr_isany(&pcb->local_ip)) {
1102 const ip_addr_t *local_ip = ip_netif_get_local_ip(netif, ipaddr);
1103 if (local_ip == NULL) {
1104 return ERR_RTE;
1105 }
1106 ip_addr_copy(pcb->local_ip, *local_ip);
1107 }
1108
1109 #if LWIP_IPV6 && LWIP_IPV6_SCOPES
1110 /* If the given IP address should have a zone but doesn't, assign one now.
1111 * Given that we already have the target netif, this is easy and cheap. */
1112 if (IP_IS_V6(&pcb->remote_ip) &&
1113 ip6_addr_lacks_zone(ip_2_ip6(&pcb->remote_ip), IP6_UNICAST)) {
1114 ip6_addr_assign_zone(ip_2_ip6(&pcb->remote_ip), IP6_UNICAST, netif);
1115 }
1116 #endif /* LWIP_IPV6 && LWIP_IPV6_SCOPES */
1117
1118 old_local_port = pcb->local_port;
1119 if (pcb->local_port == 0) {
1120 pcb->local_port = tcp_new_port();
1121 if (pcb->local_port == 0) {
1122 return ERR_BUF;
1123 }
1124 } else {
1125 #if SO_REUSE
1126 if (ip_get_option(pcb, SOF_REUSEADDR)) {
1127 /* Since SOF_REUSEADDR allows reusing a local address, we have to make sure
1128 now that the 5-tuple is unique. */
1129 struct tcp_pcb *cpcb;
1130 int i;
1131 /* Don't check listen- and bound-PCBs, check active- and TIME-WAIT PCBs. */
1132 for (i = 2; i < NUM_TCP_PCB_LISTS; i++) {
1133 for (cpcb = *tcp_pcb_lists[i]; cpcb != NULL; cpcb = cpcb->next) {
1134 if ((cpcb->local_port == pcb->local_port) &&
1135 (cpcb->remote_port == port) &&
1136 ip_addr_cmp(&cpcb->local_ip, &pcb->local_ip) &&
1137 ip_addr_cmp(&cpcb->remote_ip, ipaddr)) {
1138 /* linux returns EISCONN here, but ERR_USE should be OK for us */
1139 return ERR_USE;
1140 }
1141 }
1142 }
1143 }
1144 #endif /* SO_REUSE */
1145 }
1146
1147 iss = tcp_next_iss(pcb);
1148 pcb->rcv_nxt = 0;
1149 pcb->snd_nxt = iss;
1150 pcb->lastack = iss - 1;
1151 pcb->snd_wl2 = iss - 1;
1152 pcb->snd_lbb = iss - 1;
1153 /* Start with a window that does not need scaling. When window scaling is
1154 enabled and used, the window is enlarged when both sides agree on scaling. */
1155 pcb->rcv_wnd = pcb->rcv_ann_wnd = TCPWND_MIN16(TCP_WND);
1156 pcb->rcv_ann_right_edge = pcb->rcv_nxt;
1157 pcb->snd_wnd = TCP_WND;
1158 /* As initial send MSS, we use TCP_MSS but limit it to 536.
1159 The send MSS is updated when an MSS option is received. */
1160 pcb->mss = INITIAL_MSS;
1161 #if TCP_CALCULATE_EFF_SEND_MSS
1162 pcb->mss = tcp_eff_send_mss_netif(pcb->mss, netif, &pcb->remote_ip);
1163 #endif /* TCP_CALCULATE_EFF_SEND_MSS */
1164 pcb->cwnd = 1;
1165 #if LWIP_CALLBACK_API
1166 pcb->connected = connected;
1167 #else /* LWIP_CALLBACK_API */
1168 LWIP_UNUSED_ARG(connected);
1169 #endif /* LWIP_CALLBACK_API */
1170
1171 /* Send a SYN together with the MSS option. */
1172 ret = tcp_enqueue_flags(pcb, TCP_SYN);
1173 if (ret == ERR_OK) {
1174 /* SYN segment was enqueued, changed the pcbs state now */
1175 pcb->state = SYN_SENT;
1176 if (old_local_port != 0) {
1177 TCP_RMV(&tcp_bound_pcbs, pcb);
1178 }
1179 TCP_REG_ACTIVE(pcb);
1180 MIB2_STATS_INC(mib2.tcpactiveopens);
1181
1182 tcp_output(pcb);
1183 }
1184 return ret;
1185 }
1186
1187 /**
1188 * Called every 500 ms and implements the retransmission timer and the timer that
1189 * removes PCBs that have been in TIME-WAIT for enough time. It also increments
1190 * various timers such as the inactivity timer in each PCB.
1191 *
1192 * Automatically called from tcp_tmr().
1193 */
1194 void
tcp_slowtmr(void)1195 tcp_slowtmr(void)
1196 {
1197 struct tcp_pcb *pcb, *prev;
1198 tcpwnd_size_t eff_wnd;
1199 u8_t pcb_remove; /* flag if a PCB should be removed */
1200 u8_t pcb_reset; /* flag if a RST should be sent when removing */
1201 err_t err;
1202
1203 err = ERR_OK;
1204
1205 ++tcp_ticks;
1206 ++tcp_timer_ctr;
1207
1208 tcp_slowtmr_start:
1209 /* Steps through all of the active PCBs. */
1210 prev = NULL;
1211 pcb = tcp_active_pcbs;
1212 if (pcb == NULL) {
1213 LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: no active pcbs\n"));
1214 }
1215 while (pcb != NULL) {
1216 LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: processing active pcb\n"));
1217 LWIP_ASSERT("tcp_slowtmr: active pcb->state != CLOSED\n", pcb->state != CLOSED);
1218 LWIP_ASSERT("tcp_slowtmr: active pcb->state != LISTEN\n", pcb->state != LISTEN);
1219 LWIP_ASSERT("tcp_slowtmr: active pcb->state != TIME-WAIT\n", pcb->state != TIME_WAIT);
1220 if (pcb->last_timer == tcp_timer_ctr) {
1221 /* skip this pcb, we have already processed it */
1222 pcb = pcb->next;
1223 continue;
1224 }
1225 pcb->last_timer = tcp_timer_ctr;
1226
1227 pcb_remove = 0;
1228 pcb_reset = 0;
1229
1230 if (pcb->state == SYN_SENT && pcb->nrtx >= TCP_SYNMAXRTX) {
1231 ++pcb_remove;
1232 LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: max SYN retries reached\n"));
1233 } else if (pcb->nrtx >= TCP_MAXRTX) {
1234 ++pcb_remove;
1235 LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: max DATA retries reached\n"));
1236 } else {
1237 if (pcb->persist_backoff > 0) {
1238 LWIP_ASSERT("tcp_slowtimr: persist ticking with in-flight data", pcb->unacked == NULL);
1239 LWIP_ASSERT("tcp_slowtimr: persist ticking with empty send buffer", pcb->unsent != NULL);
1240 if (pcb->persist_probe >= TCP_MAXRTX) {
1241 ++pcb_remove; /* max probes reached */
1242 } else {
1243 u8_t backoff_cnt = tcp_persist_backoff[pcb->persist_backoff - 1];
1244 if (pcb->persist_cnt < backoff_cnt) {
1245 pcb->persist_cnt++;
1246 }
1247 if (pcb->persist_cnt >= backoff_cnt) {
1248 int next_slot = 1; /* increment timer to next slot */
1249 /* If snd_wnd is zero, send 1 byte probes */
1250 if (pcb->snd_wnd == 0) {
1251 if (tcp_zero_window_probe(pcb) != ERR_OK) {
1252 next_slot = 0; /* try probe again with current slot */
1253 }
1254 /* snd_wnd not fully closed, split unsent head and fill window */
1255 } else {
1256 if (tcp_split_unsent_seg(pcb, (u16_t)pcb->snd_wnd) == ERR_OK) {
1257 if (tcp_output(pcb) == ERR_OK) {
1258 /* sending will cancel persist timer, else retry with current slot */
1259 next_slot = 0;
1260 }
1261 }
1262 }
1263 if (next_slot) {
1264 pcb->persist_cnt = 0;
1265 if (pcb->persist_backoff < sizeof(tcp_persist_backoff)) {
1266 pcb->persist_backoff++;
1267 }
1268 }
1269 }
1270 }
1271 } else {
1272 /* Increase the retransmission timer if it is running */
1273 if ((pcb->rtime >= 0) && (pcb->rtime < 0x7FFF)) {
1274 ++pcb->rtime;
1275 }
1276
1277 if (pcb->rtime >= pcb->rto) {
1278 /* Time for a retransmission. */
1279 LWIP_DEBUGF(TCP_RTO_DEBUG, ("tcp_slowtmr: rtime %"S16_F
1280 " pcb->rto %"S16_F"\n",
1281 pcb->rtime, pcb->rto));
1282 /* If prepare phase fails but we have unsent data but no unacked data,
1283 still execute the backoff calculations below, as this means we somehow
1284 failed to send segment. */
1285 if ((tcp_rexmit_rto_prepare(pcb) == ERR_OK) || ((pcb->unacked == NULL) && (pcb->unsent != NULL))) {
1286 /* Double retransmission time-out unless we are trying to
1287 * connect to somebody (i.e., we are in SYN_SENT). */
1288 if (pcb->state != SYN_SENT) {
1289 u8_t backoff_idx = LWIP_MIN(pcb->nrtx, sizeof(tcp_backoff) - 1);
1290 int calc_rto = ((pcb->sa >> 3) + pcb->sv) << tcp_backoff[backoff_idx];
1291 pcb->rto = (s16_t)LWIP_MIN(calc_rto, 0x7FFF);
1292 }
1293
1294 /* Reset the retransmission timer. */
1295 pcb->rtime = 0;
1296
1297 /* Reduce congestion window and ssthresh. */
1298 eff_wnd = LWIP_MIN(pcb->cwnd, pcb->snd_wnd);
1299 pcb->ssthresh = eff_wnd >> 1;
1300 if (pcb->ssthresh < (tcpwnd_size_t)(pcb->mss << 1)) {
1301 pcb->ssthresh = (tcpwnd_size_t)(pcb->mss << 1);
1302 }
1303 pcb->cwnd = pcb->mss;
1304 LWIP_DEBUGF(TCP_CWND_DEBUG, ("tcp_slowtmr: cwnd %"TCPWNDSIZE_F
1305 " ssthresh %"TCPWNDSIZE_F"\n",
1306 pcb->cwnd, pcb->ssthresh));
1307 pcb->bytes_acked = 0;
1308
1309 /* The following needs to be called AFTER cwnd is set to one
1310 mss - STJ */
1311 tcp_rexmit_rto_commit(pcb);
1312 }
1313 }
1314 }
1315 }
1316 /* Check if this PCB has stayed too long in FIN-WAIT-2 */
1317 if (pcb->state == FIN_WAIT_2) {
1318 /* If this PCB is in FIN_WAIT_2 because of SHUT_WR don't let it time out. */
1319 if (pcb->flags & TF_RXCLOSED) {
1320 /* PCB was fully closed (either through close() or SHUT_RDWR):
1321 normal FIN-WAIT timeout handling. */
1322 if ((u32_t)(tcp_ticks - pcb->tmr) >
1323 TCP_FIN_WAIT_TIMEOUT / TCP_SLOW_INTERVAL) {
1324 ++pcb_remove;
1325 LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: removing pcb stuck in FIN-WAIT-2\n"));
1326 }
1327 }
1328 }
1329
1330 /* Check if KEEPALIVE should be sent */
1331 if (ip_get_option(pcb, SOF_KEEPALIVE) &&
1332 ((pcb->state == ESTABLISHED) ||
1333 (pcb->state == CLOSE_WAIT))) {
1334 if ((u32_t)(tcp_ticks - pcb->tmr) >
1335 (pcb->keep_idle + TCP_KEEP_DUR(pcb)) / TCP_SLOW_INTERVAL) {
1336 LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: KEEPALIVE timeout. Aborting connection to "));
1337 ip_addr_debug_print_val(TCP_DEBUG, pcb->remote_ip);
1338 LWIP_DEBUGF(TCP_DEBUG, ("\n"));
1339
1340 ++pcb_remove;
1341 ++pcb_reset;
1342 } else if ((u32_t)(tcp_ticks - pcb->tmr) >
1343 (pcb->keep_idle + pcb->keep_cnt_sent * TCP_KEEP_INTVL(pcb))
1344 / TCP_SLOW_INTERVAL) {
1345 err = tcp_keepalive(pcb);
1346 if (err == ERR_OK) {
1347 pcb->keep_cnt_sent++;
1348 }
1349 }
1350 }
1351
1352 /* If this PCB has queued out of sequence data, but has been
1353 inactive for too long, will drop the data (it will eventually
1354 be retransmitted). */
1355 #if TCP_QUEUE_OOSEQ
1356 if (pcb->ooseq != NULL &&
1357 (tcp_ticks - pcb->tmr >= (u32_t)pcb->rto * TCP_OOSEQ_TIMEOUT)) {
1358 LWIP_DEBUGF(TCP_CWND_DEBUG, ("tcp_slowtmr: dropping OOSEQ queued data\n"));
1359 tcp_free_ooseq(pcb);
1360 }
1361 #endif /* TCP_QUEUE_OOSEQ */
1362
1363 /* Check if this PCB has stayed too long in SYN-RCVD */
1364 if (pcb->state == SYN_RCVD) {
1365 if ((u32_t)(tcp_ticks - pcb->tmr) >
1366 TCP_SYN_RCVD_TIMEOUT / TCP_SLOW_INTERVAL) {
1367 ++pcb_remove;
1368 LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: removing pcb stuck in SYN-RCVD\n"));
1369 }
1370 }
1371
1372 /* Check if this PCB has stayed too long in LAST-ACK */
1373 if (pcb->state == LAST_ACK) {
1374 if ((u32_t)(tcp_ticks - pcb->tmr) > 2 * TCP_MSL / TCP_SLOW_INTERVAL) {
1375 ++pcb_remove;
1376 LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: removing pcb stuck in LAST-ACK\n"));
1377 }
1378 }
1379
1380 /* If the PCB should be removed, do it. */
1381 if (pcb_remove) {
1382 struct tcp_pcb *pcb2;
1383 #if LWIP_CALLBACK_API
1384 tcp_err_fn err_fn = pcb->errf;
1385 #endif /* LWIP_CALLBACK_API */
1386 void *err_arg;
1387 enum tcp_state last_state;
1388 tcp_pcb_purge(pcb);
1389 /* Remove PCB from tcp_active_pcbs list. */
1390 if (prev != NULL) {
1391 LWIP_ASSERT("tcp_slowtmr: middle tcp != tcp_active_pcbs", pcb != tcp_active_pcbs);
1392 prev->next = pcb->next;
1393 } else {
1394 /* This PCB was the first. */
1395 LWIP_ASSERT("tcp_slowtmr: first pcb == tcp_active_pcbs", tcp_active_pcbs == pcb);
1396 tcp_active_pcbs = pcb->next;
1397 }
1398
1399 if (pcb_reset) {
1400 tcp_rst(pcb, pcb->snd_nxt, pcb->rcv_nxt, &pcb->local_ip, &pcb->remote_ip,
1401 pcb->local_port, pcb->remote_port);
1402 }
1403
1404 err_arg = pcb->callback_arg;
1405 last_state = pcb->state;
1406 pcb2 = pcb;
1407 pcb = pcb->next;
1408 tcp_free(pcb2);
1409
1410 tcp_active_pcbs_changed = 0;
1411 TCP_EVENT_ERR(last_state, err_fn, err_arg, ERR_ABRT);
1412 if (tcp_active_pcbs_changed) {
1413 goto tcp_slowtmr_start;
1414 }
1415 } else {
1416 /* get the 'next' element now and work with 'prev' below (in case of abort) */
1417 prev = pcb;
1418 pcb = pcb->next;
1419
1420 /* We check if we should poll the connection. */
1421 ++prev->polltmr;
1422 if (prev->polltmr >= prev->pollinterval) {
1423 prev->polltmr = 0;
1424 LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: polling application\n"));
1425 tcp_active_pcbs_changed = 0;
1426 TCP_EVENT_POLL(prev, err);
1427 if (tcp_active_pcbs_changed) {
1428 goto tcp_slowtmr_start;
1429 }
1430 /* if err == ERR_ABRT, 'prev' is already deallocated */
1431 if (err == ERR_OK) {
1432 tcp_output(prev);
1433 }
1434 }
1435 }
1436 }
1437
1438
1439 /* Steps through all of the TIME-WAIT PCBs. */
1440 prev = NULL;
1441 pcb = tcp_tw_pcbs;
1442 while (pcb != NULL) {
1443 LWIP_ASSERT("tcp_slowtmr: TIME-WAIT pcb->state == TIME-WAIT", pcb->state == TIME_WAIT);
1444 pcb_remove = 0;
1445
1446 /* Check if this PCB has stayed long enough in TIME-WAIT */
1447 if ((u32_t)(tcp_ticks - pcb->tmr) > 2 * TCP_MSL / TCP_SLOW_INTERVAL) {
1448 ++pcb_remove;
1449 }
1450
1451 /* If the PCB should be removed, do it. */
1452 if (pcb_remove) {
1453 struct tcp_pcb *pcb2;
1454 tcp_pcb_purge(pcb);
1455 /* Remove PCB from tcp_tw_pcbs list. */
1456 if (prev != NULL) {
1457 LWIP_ASSERT("tcp_slowtmr: middle tcp != tcp_tw_pcbs", pcb != tcp_tw_pcbs);
1458 prev->next = pcb->next;
1459 } else {
1460 /* This PCB was the first. */
1461 LWIP_ASSERT("tcp_slowtmr: first pcb == tcp_tw_pcbs", tcp_tw_pcbs == pcb);
1462 tcp_tw_pcbs = pcb->next;
1463 }
1464 pcb2 = pcb;
1465 pcb = pcb->next;
1466 tcp_free(pcb2);
1467 } else {
1468 prev = pcb;
1469 pcb = pcb->next;
1470 }
1471 }
1472 }
1473
1474 /**
1475 * Is called every TCP_FAST_INTERVAL (250 ms) and process data previously
1476 * "refused" by upper layer (application) and sends delayed ACKs or pending FINs.
1477 *
1478 * Automatically called from tcp_tmr().
1479 */
1480 void
tcp_fasttmr(void)1481 tcp_fasttmr(void)
1482 {
1483 struct tcp_pcb *pcb;
1484
1485 ++tcp_timer_ctr;
1486
1487 tcp_fasttmr_start:
1488 pcb = tcp_active_pcbs;
1489
1490 while (pcb != NULL) {
1491 if (pcb->last_timer != tcp_timer_ctr) {
1492 struct tcp_pcb *next;
1493 pcb->last_timer = tcp_timer_ctr;
1494 /* send delayed ACKs */
1495 if (pcb->flags & TF_ACK_DELAY) {
1496 LWIP_DEBUGF(TCP_DEBUG, ("tcp_fasttmr: delayed ACK\n"));
1497 tcp_ack_now(pcb);
1498 tcp_output(pcb);
1499 tcp_clear_flags(pcb, TF_ACK_DELAY | TF_ACK_NOW);
1500 }
1501 /* send pending FIN */
1502 if (pcb->flags & TF_CLOSEPEND) {
1503 LWIP_DEBUGF(TCP_DEBUG, ("tcp_fasttmr: pending FIN\n"));
1504 tcp_clear_flags(pcb, TF_CLOSEPEND);
1505 tcp_close_shutdown_fin(pcb);
1506 }
1507
1508 next = pcb->next;
1509
1510 /* If there is data which was previously "refused" by upper layer */
1511 if (pcb->refused_data != NULL) {
1512 tcp_active_pcbs_changed = 0;
1513 tcp_process_refused_data(pcb);
1514 if (tcp_active_pcbs_changed) {
1515 /* application callback has changed the pcb list: restart the loop */
1516 goto tcp_fasttmr_start;
1517 }
1518 }
1519 pcb = next;
1520 } else {
1521 pcb = pcb->next;
1522 }
1523 }
1524 }
1525
1526 /** Call tcp_output for all active pcbs that have TF_NAGLEMEMERR set */
1527 void
tcp_txnow(void)1528 tcp_txnow(void)
1529 {
1530 struct tcp_pcb *pcb;
1531
1532 for (pcb = tcp_active_pcbs; pcb != NULL; pcb = pcb->next) {
1533 if (pcb->flags & TF_NAGLEMEMERR) {
1534 tcp_output(pcb);
1535 }
1536 }
1537 }
1538
1539 /** Pass pcb->refused_data to the recv callback */
1540 err_t
tcp_process_refused_data(struct tcp_pcb * pcb)1541 tcp_process_refused_data(struct tcp_pcb *pcb)
1542 {
1543 #if TCP_QUEUE_OOSEQ && LWIP_WND_SCALE
1544 struct pbuf *rest;
1545 #endif /* TCP_QUEUE_OOSEQ && LWIP_WND_SCALE */
1546
1547 LWIP_ERROR("tcp_process_refused_data: invalid pcb", pcb != NULL, return ERR_ARG);
1548
1549 #if TCP_QUEUE_OOSEQ && LWIP_WND_SCALE
1550 while (pcb->refused_data != NULL)
1551 #endif /* TCP_QUEUE_OOSEQ && LWIP_WND_SCALE */
1552 {
1553 err_t err;
1554 u8_t refused_flags = pcb->refused_data->flags;
1555 /* set pcb->refused_data to NULL in case the callback frees it and then
1556 closes the pcb */
1557 struct pbuf *refused_data = pcb->refused_data;
1558 #if TCP_QUEUE_OOSEQ && LWIP_WND_SCALE
1559 pbuf_split_64k(refused_data, &rest);
1560 pcb->refused_data = rest;
1561 #else /* TCP_QUEUE_OOSEQ && LWIP_WND_SCALE */
1562 pcb->refused_data = NULL;
1563 #endif /* TCP_QUEUE_OOSEQ && LWIP_WND_SCALE */
1564 /* Notify again application with data previously received. */
1565 LWIP_DEBUGF(TCP_INPUT_DEBUG, ("tcp_input: notify kept packet\n"));
1566 TCP_EVENT_RECV(pcb, refused_data, ERR_OK, err);
1567 if (err == ERR_OK) {
1568 /* did refused_data include a FIN? */
1569 if ((refused_flags & PBUF_FLAG_TCP_FIN)
1570 #if TCP_QUEUE_OOSEQ && LWIP_WND_SCALE
1571 && (rest == NULL)
1572 #endif /* TCP_QUEUE_OOSEQ && LWIP_WND_SCALE */
1573 ) {
1574 /* correct rcv_wnd as the application won't call tcp_recved()
1575 for the FIN's seqno */
1576 if (pcb->rcv_wnd != TCP_WND_MAX(pcb)) {
1577 pcb->rcv_wnd++;
1578 }
1579 TCP_EVENT_CLOSED(pcb, err);
1580 if (err == ERR_ABRT) {
1581 return ERR_ABRT;
1582 }
1583 }
1584 } else if (err == ERR_ABRT) {
1585 /* if err == ERR_ABRT, 'pcb' is already deallocated */
1586 /* Drop incoming packets because pcb is "full" (only if the incoming
1587 segment contains data). */
1588 LWIP_DEBUGF(TCP_INPUT_DEBUG, ("tcp_input: drop incoming packets, because pcb is \"full\"\n"));
1589 return ERR_ABRT;
1590 } else {
1591 /* data is still refused, pbuf is still valid (go on for ACK-only packets) */
1592 #if TCP_QUEUE_OOSEQ && LWIP_WND_SCALE
1593 if (rest != NULL) {
1594 pbuf_cat(refused_data, rest);
1595 }
1596 #endif /* TCP_QUEUE_OOSEQ && LWIP_WND_SCALE */
1597 pcb->refused_data = refused_data;
1598 return ERR_INPROGRESS;
1599 }
1600 }
1601 return ERR_OK;
1602 }
1603
1604 /**
1605 * Deallocates a list of TCP segments (tcp_seg structures).
1606 *
1607 * @param seg tcp_seg list of TCP segments to free
1608 */
1609 void
tcp_segs_free(struct tcp_seg * seg)1610 tcp_segs_free(struct tcp_seg *seg)
1611 {
1612 while (seg != NULL) {
1613 struct tcp_seg *next = seg->next;
1614 tcp_seg_free(seg);
1615 seg = next;
1616 }
1617 }
1618
1619 /**
1620 * Frees a TCP segment (tcp_seg structure).
1621 *
1622 * @param seg single tcp_seg to free
1623 */
1624 void
tcp_seg_free(struct tcp_seg * seg)1625 tcp_seg_free(struct tcp_seg *seg)
1626 {
1627 if (seg != NULL) {
1628 if (seg->p != NULL) {
1629 pbuf_free(seg->p);
1630 #if TCP_DEBUG
1631 seg->p = NULL;
1632 #endif /* TCP_DEBUG */
1633 }
1634 memp_free(MEMP_TCP_SEG, seg);
1635 }
1636 }
1637
1638 /**
1639 * @ingroup tcp
1640 * Sets the priority of a connection.
1641 *
1642 * @param pcb the tcp_pcb to manipulate
1643 * @param prio new priority
1644 */
1645 void
tcp_setprio(struct tcp_pcb * pcb,u8_t prio)1646 tcp_setprio(struct tcp_pcb *pcb, u8_t prio)
1647 {
1648 LWIP_ASSERT_CORE_LOCKED();
1649
1650 LWIP_ERROR("tcp_setprio: invalid pcb", pcb != NULL, return);
1651
1652 pcb->prio = prio;
1653 }
1654
1655 #if TCP_QUEUE_OOSEQ
1656 /**
1657 * Returns a copy of the given TCP segment.
1658 * The pbuf and data are not copied, only the pointers
1659 *
1660 * @param seg the old tcp_seg
1661 * @return a copy of seg
1662 */
1663 struct tcp_seg *
tcp_seg_copy(struct tcp_seg * seg)1664 tcp_seg_copy(struct tcp_seg *seg)
1665 {
1666 struct tcp_seg *cseg;
1667
1668 LWIP_ASSERT("tcp_seg_copy: invalid seg", seg != NULL);
1669
1670 cseg = (struct tcp_seg *)memp_malloc(MEMP_TCP_SEG);
1671 if (cseg == NULL) {
1672 return NULL;
1673 }
1674 SMEMCPY((u8_t *)cseg, (const u8_t *)seg, sizeof(struct tcp_seg));
1675 pbuf_ref(cseg->p);
1676 return cseg;
1677 }
1678 #endif /* TCP_QUEUE_OOSEQ */
1679
1680 #if LWIP_CALLBACK_API
1681 /**
1682 * Default receive callback that is called if the user didn't register
1683 * a recv callback for the pcb.
1684 */
1685 err_t
tcp_recv_null(void * arg,struct tcp_pcb * pcb,struct pbuf * p,err_t err)1686 tcp_recv_null(void *arg, struct tcp_pcb *pcb, struct pbuf *p, err_t err)
1687 {
1688 LWIP_UNUSED_ARG(arg);
1689
1690 LWIP_ERROR("tcp_recv_null: invalid pcb", pcb != NULL, return ERR_ARG);
1691
1692 if (p != NULL) {
1693 tcp_recved(pcb, p->tot_len);
1694 pbuf_free(p);
1695 } else if (err == ERR_OK) {
1696 return tcp_close(pcb);
1697 }
1698 return ERR_OK;
1699 }
1700 #endif /* LWIP_CALLBACK_API */
1701
1702 /**
1703 * Kills the oldest active connection that has a lower priority than 'prio'.
1704 *
1705 * @param prio minimum priority
1706 */
1707 static void
tcp_kill_prio(u8_t prio)1708 tcp_kill_prio(u8_t prio)
1709 {
1710 struct tcp_pcb *pcb, *inactive;
1711 u32_t inactivity;
1712 u8_t mprio;
1713
1714 mprio = LWIP_MIN(TCP_PRIO_MAX, prio);
1715
1716 /* We want to kill connections with a lower prio, so bail out if
1717 * supplied prio is 0 - there can never be a lower prio
1718 */
1719 if (mprio == 0) {
1720 return;
1721 }
1722
1723 /* We only want kill connections with a lower prio, so decrement prio by one
1724 * and start searching for oldest connection with same or lower priority than mprio.
1725 * We want to find the connections with the lowest possible prio, and among
1726 * these the one with the longest inactivity time.
1727 */
1728 mprio--;
1729
1730 inactivity = 0;
1731 inactive = NULL;
1732 for (pcb = tcp_active_pcbs; pcb != NULL; pcb = pcb->next) {
1733 /* lower prio is always a kill candidate */
1734 if ((pcb->prio < mprio) ||
1735 /* longer inactivity is also a kill candidate */
1736 ((pcb->prio == mprio) && ((u32_t)(tcp_ticks - pcb->tmr) >= inactivity))) {
1737 inactivity = tcp_ticks - pcb->tmr;
1738 inactive = pcb;
1739 mprio = pcb->prio;
1740 }
1741 }
1742 if (inactive != NULL) {
1743 LWIP_DEBUGF(TCP_DEBUG, ("tcp_kill_prio: killing oldest PCB %p (%"S32_F")\n",
1744 (void *)inactive, inactivity));
1745 tcp_abort(inactive);
1746 }
1747 }
1748
1749 /**
1750 * Kills the oldest connection that is in specific state.
1751 * Called from tcp_alloc() for LAST_ACK and CLOSING if no more connections are available.
1752 */
1753 static void
tcp_kill_state(enum tcp_state state)1754 tcp_kill_state(enum tcp_state state)
1755 {
1756 struct tcp_pcb *pcb, *inactive;
1757 u32_t inactivity;
1758
1759 LWIP_ASSERT("invalid state", (state == CLOSING) || (state == LAST_ACK));
1760
1761 inactivity = 0;
1762 inactive = NULL;
1763 /* Go through the list of active pcbs and get the oldest pcb that is in state
1764 CLOSING/LAST_ACK. */
1765 for (pcb = tcp_active_pcbs; pcb != NULL; pcb = pcb->next) {
1766 if (pcb->state == state) {
1767 if ((u32_t)(tcp_ticks - pcb->tmr) >= inactivity) {
1768 inactivity = tcp_ticks - pcb->tmr;
1769 inactive = pcb;
1770 }
1771 }
1772 }
1773 if (inactive != NULL) {
1774 LWIP_DEBUGF(TCP_DEBUG, ("tcp_kill_closing: killing oldest %s PCB %p (%"S32_F")\n",
1775 tcp_state_str[state], (void *)inactive, inactivity));
1776 /* Don't send a RST, since no data is lost. */
1777 tcp_abandon(inactive, 0);
1778 }
1779 }
1780
1781 /**
1782 * Kills the oldest connection that is in TIME_WAIT state.
1783 * Called from tcp_alloc() if no more connections are available.
1784 */
1785 static void
tcp_kill_timewait(void)1786 tcp_kill_timewait(void)
1787 {
1788 struct tcp_pcb *pcb, *inactive;
1789 u32_t inactivity;
1790
1791 inactivity = 0;
1792 inactive = NULL;
1793 /* Go through the list of TIME_WAIT pcbs and get the oldest pcb. */
1794 for (pcb = tcp_tw_pcbs; pcb != NULL; pcb = pcb->next) {
1795 if ((u32_t)(tcp_ticks - pcb->tmr) >= inactivity) {
1796 inactivity = tcp_ticks - pcb->tmr;
1797 inactive = pcb;
1798 }
1799 }
1800 if (inactive != NULL) {
1801 LWIP_DEBUGF(TCP_DEBUG, ("tcp_kill_timewait: killing oldest TIME-WAIT PCB %p (%"S32_F")\n",
1802 (void *)inactive, inactivity));
1803 tcp_abort(inactive);
1804 }
1805 }
1806
1807 /* Called when allocating a pcb fails.
1808 * In this case, we want to handle all pcbs that want to close first: if we can
1809 * now send the FIN (which failed before), the pcb might be in a state that is
1810 * OK for us to now free it.
1811 */
1812 static void
tcp_handle_closepend(void)1813 tcp_handle_closepend(void)
1814 {
1815 struct tcp_pcb *pcb = tcp_active_pcbs;
1816
1817 while (pcb != NULL) {
1818 struct tcp_pcb *next = pcb->next;
1819 /* send pending FIN */
1820 if (pcb->flags & TF_CLOSEPEND) {
1821 LWIP_DEBUGF(TCP_DEBUG, ("tcp_handle_closepend: pending FIN\n"));
1822 tcp_clear_flags(pcb, TF_CLOSEPEND);
1823 tcp_close_shutdown_fin(pcb);
1824 }
1825 pcb = next;
1826 }
1827 }
1828
1829 /**
1830 * Allocate a new tcp_pcb structure.
1831 *
1832 * @param prio priority for the new pcb
1833 * @return a new tcp_pcb that initially is in state CLOSED
1834 */
1835 struct tcp_pcb *
tcp_alloc(u8_t prio)1836 tcp_alloc(u8_t prio)
1837 {
1838 struct tcp_pcb *pcb;
1839
1840 LWIP_ASSERT_CORE_LOCKED();
1841
1842 pcb = (struct tcp_pcb *)memp_malloc(MEMP_TCP_PCB);
1843 if (pcb == NULL) {
1844 /* Try to send FIN for all pcbs stuck in TF_CLOSEPEND first */
1845 tcp_handle_closepend();
1846
1847 /* Try killing oldest connection in TIME-WAIT. */
1848 LWIP_DEBUGF(TCP_DEBUG, ("tcp_alloc: killing off oldest TIME-WAIT connection\n"));
1849 tcp_kill_timewait();
1850 /* Try to allocate a tcp_pcb again. */
1851 pcb = (struct tcp_pcb *)memp_malloc(MEMP_TCP_PCB);
1852 if (pcb == NULL) {
1853 /* Try killing oldest connection in LAST-ACK (these wouldn't go to TIME-WAIT). */
1854 LWIP_DEBUGF(TCP_DEBUG, ("tcp_alloc: killing off oldest LAST-ACK connection\n"));
1855 tcp_kill_state(LAST_ACK);
1856 /* Try to allocate a tcp_pcb again. */
1857 pcb = (struct tcp_pcb *)memp_malloc(MEMP_TCP_PCB);
1858 if (pcb == NULL) {
1859 /* Try killing oldest connection in CLOSING. */
1860 LWIP_DEBUGF(TCP_DEBUG, ("tcp_alloc: killing off oldest CLOSING connection\n"));
1861 tcp_kill_state(CLOSING);
1862 /* Try to allocate a tcp_pcb again. */
1863 pcb = (struct tcp_pcb *)memp_malloc(MEMP_TCP_PCB);
1864 if (pcb == NULL) {
1865 /* Try killing oldest active connection with lower priority than the new one. */
1866 LWIP_DEBUGF(TCP_DEBUG, ("tcp_alloc: killing oldest connection with prio lower than %d\n", prio));
1867 tcp_kill_prio(prio);
1868 /* Try to allocate a tcp_pcb again. */
1869 pcb = (struct tcp_pcb *)memp_malloc(MEMP_TCP_PCB);
1870 if (pcb != NULL) {
1871 /* adjust err stats: memp_malloc failed multiple times before */
1872 MEMP_STATS_DEC(err, MEMP_TCP_PCB);
1873 }
1874 }
1875 if (pcb != NULL) {
1876 /* adjust err stats: memp_malloc failed multiple times before */
1877 MEMP_STATS_DEC(err, MEMP_TCP_PCB);
1878 }
1879 }
1880 if (pcb != NULL) {
1881 /* adjust err stats: memp_malloc failed multiple times before */
1882 MEMP_STATS_DEC(err, MEMP_TCP_PCB);
1883 }
1884 }
1885 if (pcb != NULL) {
1886 /* adjust err stats: memp_malloc failed above */
1887 MEMP_STATS_DEC(err, MEMP_TCP_PCB);
1888 }
1889 }
1890 if (pcb != NULL) {
1891 /* zero out the whole pcb, so there is no need to initialize members to zero */
1892 memset(pcb, 0, sizeof(struct tcp_pcb));
1893 pcb->prio = prio;
1894 pcb->snd_buf = TCP_SND_BUF;
1895 /* Start with a window that does not need scaling. When window scaling is
1896 enabled and used, the window is enlarged when both sides agree on scaling. */
1897 pcb->rcv_wnd = pcb->rcv_ann_wnd = TCPWND_MIN16(TCP_WND);
1898 pcb->ttl = TCP_TTL;
1899 /* As initial send MSS, we use TCP_MSS but limit it to 536.
1900 The send MSS is updated when an MSS option is received. */
1901 pcb->mss = INITIAL_MSS;
1902 pcb->rto = 3000 / TCP_SLOW_INTERVAL;
1903 pcb->sv = 3000 / TCP_SLOW_INTERVAL;
1904 pcb->rtime = -1;
1905 pcb->cwnd = 1;
1906 pcb->tmr = tcp_ticks;
1907 pcb->last_timer = tcp_timer_ctr;
1908
1909 /* RFC 5681 recommends setting ssthresh abritrarily high and gives an example
1910 of using the largest advertised receive window. We've seen complications with
1911 receiving TCPs that use window scaling and/or window auto-tuning where the
1912 initial advertised window is very small and then grows rapidly once the
1913 connection is established. To avoid these complications, we set ssthresh to the
1914 largest effective cwnd (amount of in-flight data) that the sender can have. */
1915 pcb->ssthresh = TCP_SND_BUF;
1916
1917 #if LWIP_CALLBACK_API
1918 pcb->recv = tcp_recv_null;
1919 #endif /* LWIP_CALLBACK_API */
1920
1921 /* Init KEEPALIVE timer */
1922 pcb->keep_idle = TCP_KEEPIDLE_DEFAULT;
1923
1924 #if LWIP_TCP_KEEPALIVE
1925 pcb->keep_intvl = TCP_KEEPINTVL_DEFAULT;
1926 pcb->keep_cnt = TCP_KEEPCNT_DEFAULT;
1927 #endif /* LWIP_TCP_KEEPALIVE */
1928 }
1929 return pcb;
1930 }
1931
1932 /**
1933 * @ingroup tcp_raw
1934 * Creates a new TCP protocol control block but doesn't place it on
1935 * any of the TCP PCB lists.
1936 * The pcb is not put on any list until binding using tcp_bind().
1937 * If memory is not available for creating the new pcb, NULL is returned.
1938 *
1939 * @internal: Maybe there should be a idle TCP PCB list where these
1940 * PCBs are put on. Port reservation using tcp_bind() is implemented but
1941 * allocated pcbs that are not bound can't be killed automatically if wanting
1942 * to allocate a pcb with higher prio (@see tcp_kill_prio())
1943 *
1944 * @return a new tcp_pcb that initially is in state CLOSED
1945 */
1946 struct tcp_pcb *
tcp_new(void)1947 tcp_new(void)
1948 {
1949 return tcp_alloc(TCP_PRIO_NORMAL);
1950 }
1951
1952 /**
1953 * @ingroup tcp_raw
1954 * Creates a new TCP protocol control block but doesn't
1955 * place it on any of the TCP PCB lists.
1956 * The pcb is not put on any list until binding using tcp_bind().
1957 *
1958 * @param type IP address type, see @ref lwip_ip_addr_type definitions.
1959 * If you want to listen to IPv4 and IPv6 (dual-stack) connections,
1960 * supply @ref IPADDR_TYPE_ANY as argument and bind to @ref IP_ANY_TYPE.
1961 * @return a new tcp_pcb that initially is in state CLOSED
1962 */
1963 struct tcp_pcb *
tcp_new_ip_type(u8_t type)1964 tcp_new_ip_type(u8_t type)
1965 {
1966 struct tcp_pcb *pcb;
1967 pcb = tcp_alloc(TCP_PRIO_NORMAL);
1968 #if LWIP_IPV4 && LWIP_IPV6
1969 if (pcb != NULL) {
1970 IP_SET_TYPE_VAL(pcb->local_ip, type);
1971 IP_SET_TYPE_VAL(pcb->remote_ip, type);
1972 }
1973 #else
1974 LWIP_UNUSED_ARG(type);
1975 #endif /* LWIP_IPV4 && LWIP_IPV6 */
1976 return pcb;
1977 }
1978
1979 /**
1980 * @ingroup tcp_raw
1981 * Specifies the program specific state that should be passed to all
1982 * other callback functions. The "pcb" argument is the current TCP
1983 * connection control block, and the "arg" argument is the argument
1984 * that will be passed to the callbacks.
1985 *
1986 * @param pcb tcp_pcb to set the callback argument
1987 * @param arg void pointer argument to pass to callback functions
1988 */
1989 void
tcp_arg(struct tcp_pcb * pcb,void * arg)1990 tcp_arg(struct tcp_pcb *pcb, void *arg)
1991 {
1992 LWIP_ASSERT_CORE_LOCKED();
1993 /* This function is allowed to be called for both listen pcbs and
1994 connection pcbs. */
1995 if (pcb != NULL) {
1996 pcb->callback_arg = arg;
1997 }
1998 }
1999 #if LWIP_CALLBACK_API
2000
2001 /**
2002 * @ingroup tcp_raw
2003 * Sets the callback function that will be called when new data
2004 * arrives. The callback function will be passed a NULL pbuf to
2005 * indicate that the remote host has closed the connection. If the
2006 * callback function returns ERR_OK or ERR_ABRT it must have
2007 * freed the pbuf, otherwise it must not have freed it.
2008 *
2009 * @param pcb tcp_pcb to set the recv callback
2010 * @param recv callback function to call for this pcb when data is received
2011 */
2012 void
tcp_recv(struct tcp_pcb * pcb,tcp_recv_fn recv)2013 tcp_recv(struct tcp_pcb *pcb, tcp_recv_fn recv)
2014 {
2015 LWIP_ASSERT_CORE_LOCKED();
2016 if (pcb != NULL) {
2017 LWIP_ASSERT("invalid socket state for recv callback", pcb->state != LISTEN);
2018 pcb->recv = recv;
2019 }
2020 }
2021
2022 /**
2023 * @ingroup tcp_raw
2024 * Specifies the callback function that should be called when data has
2025 * successfully been received (i.e., acknowledged) by the remote
2026 * host. The len argument passed to the callback function gives the
2027 * amount bytes that was acknowledged by the last acknowledgment.
2028 *
2029 * @param pcb tcp_pcb to set the sent callback
2030 * @param sent callback function to call for this pcb when data is successfully sent
2031 */
2032 void
tcp_sent(struct tcp_pcb * pcb,tcp_sent_fn sent)2033 tcp_sent(struct tcp_pcb *pcb, tcp_sent_fn sent)
2034 {
2035 LWIP_ASSERT_CORE_LOCKED();
2036 if (pcb != NULL) {
2037 LWIP_ASSERT("invalid socket state for sent callback", pcb->state != LISTEN);
2038 pcb->sent = sent;
2039 }
2040 }
2041
2042 /**
2043 * @ingroup tcp_raw
2044 * Used to specify the function that should be called when a fatal error
2045 * has occurred on the connection.
2046 *
2047 * If a connection is aborted because of an error, the application is
2048 * alerted of this event by the err callback. Errors that might abort a
2049 * connection are when there is a shortage of memory. The callback
2050 * function to be called is set using the tcp_err() function.
2051 *
2052 * @note The corresponding pcb is already freed when this callback is called!
2053 *
2054 * @param pcb tcp_pcb to set the err callback
2055 * @param err callback function to call for this pcb when a fatal error
2056 * has occurred on the connection
2057 */
2058 void
tcp_err(struct tcp_pcb * pcb,tcp_err_fn err)2059 tcp_err(struct tcp_pcb *pcb, tcp_err_fn err)
2060 {
2061 LWIP_ASSERT_CORE_LOCKED();
2062 if (pcb != NULL) {
2063 LWIP_ASSERT("invalid socket state for err callback", pcb->state != LISTEN);
2064 pcb->errf = err;
2065 }
2066 }
2067
2068 /**
2069 * @ingroup tcp_raw
2070 * Used for specifying the function that should be called when a
2071 * LISTENing connection has been connected to another host.
2072 *
2073 * @param pcb tcp_pcb to set the accept callback
2074 * @param accept callback function to call for this pcb when LISTENing
2075 * connection has been connected to another host
2076 */
2077 void
tcp_accept(struct tcp_pcb * pcb,tcp_accept_fn accept)2078 tcp_accept(struct tcp_pcb *pcb, tcp_accept_fn accept)
2079 {
2080 LWIP_ASSERT_CORE_LOCKED();
2081 if ((pcb != NULL) && (pcb->state == LISTEN)) {
2082 struct tcp_pcb_listen *lpcb = (struct tcp_pcb_listen *)pcb;
2083 lpcb->accept = accept;
2084 }
2085 }
2086 #endif /* LWIP_CALLBACK_API */
2087
2088
2089 /**
2090 * @ingroup tcp_raw
2091 * Specifies the polling interval and the callback function that should
2092 * be called to poll the application. The interval is specified in
2093 * number of TCP coarse grained timer shots, which typically occurs
2094 * twice a second. An interval of 10 means that the application would
2095 * be polled every 5 seconds.
2096 *
2097 * When a connection is idle (i.e., no data is either transmitted or
2098 * received), lwIP will repeatedly poll the application by calling a
2099 * specified callback function. This can be used either as a watchdog
2100 * timer for killing connections that have stayed idle for too long, or
2101 * as a method of waiting for memory to become available. For instance,
2102 * if a call to tcp_write() has failed because memory wasn't available,
2103 * the application may use the polling functionality to call tcp_write()
2104 * again when the connection has been idle for a while.
2105 */
2106 void
tcp_poll(struct tcp_pcb * pcb,tcp_poll_fn poll,u8_t interval)2107 tcp_poll(struct tcp_pcb *pcb, tcp_poll_fn poll, u8_t interval)
2108 {
2109 LWIP_ASSERT_CORE_LOCKED();
2110
2111 LWIP_ERROR("tcp_poll: invalid pcb", pcb != NULL, return);
2112 LWIP_ASSERT("invalid socket state for poll", pcb->state != LISTEN);
2113
2114 #if LWIP_CALLBACK_API
2115 pcb->poll = poll;
2116 #else /* LWIP_CALLBACK_API */
2117 LWIP_UNUSED_ARG(poll);
2118 #endif /* LWIP_CALLBACK_API */
2119 pcb->pollinterval = interval;
2120 }
2121
2122 /**
2123 * Purges a TCP PCB. Removes any buffered data and frees the buffer memory
2124 * (pcb->ooseq, pcb->unsent and pcb->unacked are freed).
2125 *
2126 * @param pcb tcp_pcb to purge. The pcb itself is not deallocated!
2127 */
2128 void
tcp_pcb_purge(struct tcp_pcb * pcb)2129 tcp_pcb_purge(struct tcp_pcb *pcb)
2130 {
2131 LWIP_ERROR("tcp_pcb_purge: invalid pcb", pcb != NULL, return);
2132
2133 if (pcb->state != CLOSED &&
2134 pcb->state != TIME_WAIT &&
2135 pcb->state != LISTEN) {
2136
2137 LWIP_DEBUGF(TCP_DEBUG, ("tcp_pcb_purge\n"));
2138
2139 tcp_backlog_accepted(pcb);
2140
2141 if (pcb->refused_data != NULL) {
2142 LWIP_DEBUGF(TCP_DEBUG, ("tcp_pcb_purge: data left on ->refused_data\n"));
2143 pbuf_free(pcb->refused_data);
2144 pcb->refused_data = NULL;
2145 }
2146 if (pcb->unsent != NULL) {
2147 LWIP_DEBUGF(TCP_DEBUG, ("tcp_pcb_purge: not all data sent\n"));
2148 }
2149 if (pcb->unacked != NULL) {
2150 LWIP_DEBUGF(TCP_DEBUG, ("tcp_pcb_purge: data left on ->unacked\n"));
2151 }
2152 #if TCP_QUEUE_OOSEQ
2153 if (pcb->ooseq != NULL) {
2154 LWIP_DEBUGF(TCP_DEBUG, ("tcp_pcb_purge: data left on ->ooseq\n"));
2155 tcp_free_ooseq(pcb);
2156 }
2157 #endif /* TCP_QUEUE_OOSEQ */
2158
2159 /* Stop the retransmission timer as it will expect data on unacked
2160 queue if it fires */
2161 pcb->rtime = -1;
2162
2163 tcp_segs_free(pcb->unsent);
2164 tcp_segs_free(pcb->unacked);
2165 pcb->unacked = pcb->unsent = NULL;
2166 #if TCP_OVERSIZE
2167 pcb->unsent_oversize = 0;
2168 #endif /* TCP_OVERSIZE */
2169 }
2170 }
2171
2172 /**
2173 * Purges the PCB and removes it from a PCB list. Any delayed ACKs are sent first.
2174 *
2175 * @param pcblist PCB list to purge.
2176 * @param pcb tcp_pcb to purge. The pcb itself is NOT deallocated!
2177 */
2178 void
tcp_pcb_remove(struct tcp_pcb ** pcblist,struct tcp_pcb * pcb)2179 tcp_pcb_remove(struct tcp_pcb **pcblist, struct tcp_pcb *pcb)
2180 {
2181 LWIP_ASSERT("tcp_pcb_remove: invalid pcb", pcb != NULL);
2182 LWIP_ASSERT("tcp_pcb_remove: invalid pcblist", pcblist != NULL);
2183
2184 TCP_RMV(pcblist, pcb);
2185
2186 tcp_pcb_purge(pcb);
2187
2188 /* if there is an outstanding delayed ACKs, send it */
2189 if ((pcb->state != TIME_WAIT) &&
2190 (pcb->state != LISTEN) &&
2191 (pcb->flags & TF_ACK_DELAY)) {
2192 tcp_ack_now(pcb);
2193 tcp_output(pcb);
2194 }
2195
2196 if (pcb->state != LISTEN) {
2197 LWIP_ASSERT("unsent segments leaking", pcb->unsent == NULL);
2198 LWIP_ASSERT("unacked segments leaking", pcb->unacked == NULL);
2199 #if TCP_QUEUE_OOSEQ
2200 LWIP_ASSERT("ooseq segments leaking", pcb->ooseq == NULL);
2201 #endif /* TCP_QUEUE_OOSEQ */
2202 }
2203
2204 pcb->state = CLOSED;
2205 /* reset the local port to prevent the pcb from being 'bound' */
2206 pcb->local_port = 0;
2207
2208 LWIP_ASSERT("tcp_pcb_remove: tcp_pcbs_sane()", tcp_pcbs_sane());
2209 }
2210
2211 /**
2212 * Calculates a new initial sequence number for new connections.
2213 *
2214 * @return u32_t pseudo random sequence number
2215 */
2216 u32_t
tcp_next_iss(struct tcp_pcb * pcb)2217 tcp_next_iss(struct tcp_pcb *pcb)
2218 {
2219 #ifdef LWIP_HOOK_TCP_ISN
2220 LWIP_ASSERT("tcp_next_iss: invalid pcb", pcb != NULL);
2221 return LWIP_HOOK_TCP_ISN(&pcb->local_ip, pcb->local_port, &pcb->remote_ip, pcb->remote_port);
2222 #else /* LWIP_HOOK_TCP_ISN */
2223 static u32_t iss = 6510;
2224
2225 LWIP_ASSERT("tcp_next_iss: invalid pcb", pcb != NULL);
2226 LWIP_UNUSED_ARG(pcb);
2227
2228 iss += tcp_ticks; /* XXX */
2229 return iss;
2230 #endif /* LWIP_HOOK_TCP_ISN */
2231 }
2232
2233 #if TCP_CALCULATE_EFF_SEND_MSS
2234 /**
2235 * Calculates the effective send mss that can be used for a specific IP address
2236 * by calculating the minimum of TCP_MSS and the mtu (if set) of the target
2237 * netif (if not NULL).
2238 */
2239 u16_t
tcp_eff_send_mss_netif(u16_t sendmss,struct netif * outif,const ip_addr_t * dest)2240 tcp_eff_send_mss_netif(u16_t sendmss, struct netif *outif, const ip_addr_t *dest)
2241 {
2242 u16_t mss_s;
2243 u16_t mtu;
2244
2245 LWIP_UNUSED_ARG(dest); /* in case IPv6 is disabled */
2246
2247 LWIP_ASSERT("tcp_eff_send_mss_netif: invalid dst_ip", dest != NULL);
2248
2249 #if LWIP_IPV6
2250 #if LWIP_IPV4
2251 if (IP_IS_V6(dest))
2252 #endif /* LWIP_IPV4 */
2253 {
2254 /* First look in destination cache, to see if there is a Path MTU. */
2255 mtu = nd6_get_destination_mtu(ip_2_ip6(dest), outif);
2256 }
2257 #if LWIP_IPV4
2258 else
2259 #endif /* LWIP_IPV4 */
2260 #endif /* LWIP_IPV6 */
2261 #if LWIP_IPV4
2262 {
2263 if (outif == NULL) {
2264 return sendmss;
2265 }
2266 mtu = outif->mtu;
2267 }
2268 #endif /* LWIP_IPV4 */
2269
2270 if (mtu != 0) {
2271 u16_t offset;
2272 #if LWIP_IPV6
2273 #if LWIP_IPV4
2274 if (IP_IS_V6(dest))
2275 #endif /* LWIP_IPV4 */
2276 {
2277 offset = IP6_HLEN + TCP_HLEN;
2278 }
2279 #if LWIP_IPV4
2280 else
2281 #endif /* LWIP_IPV4 */
2282 #endif /* LWIP_IPV6 */
2283 #if LWIP_IPV4
2284 {
2285 offset = IP_HLEN + TCP_HLEN;
2286 }
2287 #endif /* LWIP_IPV4 */
2288 mss_s = (mtu > offset) ? (u16_t)(mtu - offset) : 0;
2289 /* RFC 1122, chap 4.2.2.6:
2290 * Eff.snd.MSS = min(SendMSS+20, MMS_S) - TCPhdrsize - IPoptionsize
2291 * We correct for TCP options in tcp_write(), and don't support IP options.
2292 */
2293 sendmss = LWIP_MIN(sendmss, mss_s);
2294 }
2295 return sendmss;
2296 }
2297 #endif /* TCP_CALCULATE_EFF_SEND_MSS */
2298
2299 /** Helper function for tcp_netif_ip_addr_changed() that iterates a pcb list */
2300 static void
tcp_netif_ip_addr_changed_pcblist(const ip_addr_t * old_addr,struct tcp_pcb * pcb_list)2301 tcp_netif_ip_addr_changed_pcblist(const ip_addr_t *old_addr, struct tcp_pcb *pcb_list)
2302 {
2303 struct tcp_pcb *pcb;
2304 pcb = pcb_list;
2305
2306 LWIP_ASSERT("tcp_netif_ip_addr_changed_pcblist: invalid old_addr", old_addr != NULL);
2307
2308 while (pcb != NULL) {
2309 /* PCB bound to current local interface address? */
2310 if (ip_addr_cmp(&pcb->local_ip, old_addr)
2311 #if LWIP_AUTOIP
2312 /* connections to link-local addresses must persist (RFC3927 ch. 1.9) */
2313 && (!IP_IS_V4_VAL(pcb->local_ip) || !ip4_addr_islinklocal(ip_2_ip4(&pcb->local_ip)))
2314 #endif /* LWIP_AUTOIP */
2315 ) {
2316 /* this connection must be aborted */
2317 struct tcp_pcb *next = pcb->next;
2318 LWIP_DEBUGF(NETIF_DEBUG | LWIP_DBG_STATE, ("netif_set_ipaddr: aborting TCP pcb %p\n", (void *)pcb));
2319 tcp_abort(pcb);
2320 pcb = next;
2321 } else {
2322 pcb = pcb->next;
2323 }
2324 }
2325 }
2326
2327 /** This function is called from netif.c when address is changed or netif is removed
2328 *
2329 * @param old_addr IP address of the netif before change
2330 * @param new_addr IP address of the netif after change or NULL if netif has been removed
2331 */
2332 void
tcp_netif_ip_addr_changed(const ip_addr_t * old_addr,const ip_addr_t * new_addr)2333 tcp_netif_ip_addr_changed(const ip_addr_t *old_addr, const ip_addr_t *new_addr)
2334 {
2335 struct tcp_pcb_listen *lpcb;
2336
2337 if (!ip_addr_isany(old_addr)) {
2338 tcp_netif_ip_addr_changed_pcblist(old_addr, tcp_active_pcbs);
2339 tcp_netif_ip_addr_changed_pcblist(old_addr, tcp_bound_pcbs);
2340
2341 if (!ip_addr_isany(new_addr)) {
2342 /* PCB bound to current local interface address? */
2343 for (lpcb = tcp_listen_pcbs.listen_pcbs; lpcb != NULL; lpcb = lpcb->next) {
2344 /* PCB bound to current local interface address? */
2345 if (ip_addr_cmp(&lpcb->local_ip, old_addr)) {
2346 /* The PCB is listening to the old ipaddr and
2347 * is set to listen to the new one instead */
2348 ip_addr_copy(lpcb->local_ip, *new_addr);
2349 }
2350 }
2351 }
2352 }
2353 }
2354
2355 const char *
tcp_debug_state_str(enum tcp_state s)2356 tcp_debug_state_str(enum tcp_state s)
2357 {
2358 return tcp_state_str[s];
2359 }
2360
2361 err_t
tcp_tcp_get_tcp_addrinfo(struct tcp_pcb * pcb,int local,ip_addr_t * addr,u16_t * port)2362 tcp_tcp_get_tcp_addrinfo(struct tcp_pcb *pcb, int local, ip_addr_t *addr, u16_t *port)
2363 {
2364 if (pcb) {
2365 if (local) {
2366 if (addr) {
2367 *addr = pcb->local_ip;
2368 }
2369 if (port) {
2370 *port = pcb->local_port;
2371 }
2372 } else {
2373 if (addr) {
2374 *addr = pcb->remote_ip;
2375 }
2376 if (port) {
2377 *port = pcb->remote_port;
2378 }
2379 }
2380 return ERR_OK;
2381 }
2382 return ERR_VAL;
2383 }
2384
2385 #if TCP_QUEUE_OOSEQ
2386 /* Free all ooseq pbufs (and possibly reset SACK state) */
2387 void
tcp_free_ooseq(struct tcp_pcb * pcb)2388 tcp_free_ooseq(struct tcp_pcb *pcb)
2389 {
2390 if (pcb->ooseq) {
2391 tcp_segs_free(pcb->ooseq);
2392 pcb->ooseq = NULL;
2393 #if LWIP_TCP_SACK_OUT
2394 memset(pcb->rcv_sacks, 0, sizeof(pcb->rcv_sacks));
2395 #endif /* LWIP_TCP_SACK_OUT */
2396 }
2397 }
2398 #endif /* TCP_QUEUE_OOSEQ */
2399
2400 #if TCP_DEBUG || TCP_INPUT_DEBUG || TCP_OUTPUT_DEBUG
2401 /**
2402 * Print a tcp header for debugging purposes.
2403 *
2404 * @param tcphdr pointer to a struct tcp_hdr
2405 */
2406 void
tcp_debug_print(struct tcp_hdr * tcphdr)2407 tcp_debug_print(struct tcp_hdr *tcphdr)
2408 {
2409 LWIP_DEBUGF(TCP_DEBUG, ("TCP header:\n"));
2410 LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
2411 LWIP_DEBUGF(TCP_DEBUG, ("| %5"U16_F" | %5"U16_F" | (src port, dest port)\n",
2412 lwip_ntohs(tcphdr->src), lwip_ntohs(tcphdr->dest)));
2413 LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
2414 LWIP_DEBUGF(TCP_DEBUG, ("| %010"U32_F" | (seq no)\n",
2415 lwip_ntohl(tcphdr->seqno)));
2416 LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
2417 LWIP_DEBUGF(TCP_DEBUG, ("| %010"U32_F" | (ack no)\n",
2418 lwip_ntohl(tcphdr->ackno)));
2419 LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
2420 LWIP_DEBUGF(TCP_DEBUG, ("| %2"U16_F" | |%"U16_F"%"U16_F"%"U16_F"%"U16_F"%"U16_F"%"U16_F"| %5"U16_F" | (hdrlen, flags (",
2421 TCPH_HDRLEN(tcphdr),
2422 (u16_t)(TCPH_FLAGS(tcphdr) >> 5 & 1),
2423 (u16_t)(TCPH_FLAGS(tcphdr) >> 4 & 1),
2424 (u16_t)(TCPH_FLAGS(tcphdr) >> 3 & 1),
2425 (u16_t)(TCPH_FLAGS(tcphdr) >> 2 & 1),
2426 (u16_t)(TCPH_FLAGS(tcphdr) >> 1 & 1),
2427 (u16_t)(TCPH_FLAGS(tcphdr) & 1),
2428 lwip_ntohs(tcphdr->wnd)));
2429 tcp_debug_print_flags(TCPH_FLAGS(tcphdr));
2430 LWIP_DEBUGF(TCP_DEBUG, ("), win)\n"));
2431 LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
2432 LWIP_DEBUGF(TCP_DEBUG, ("| 0x%04"X16_F" | %5"U16_F" | (chksum, urgp)\n",
2433 lwip_ntohs(tcphdr->chksum), lwip_ntohs(tcphdr->urgp)));
2434 LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
2435 }
2436
2437 /**
2438 * Print a tcp state for debugging purposes.
2439 *
2440 * @param s enum tcp_state to print
2441 */
2442 void
tcp_debug_print_state(enum tcp_state s)2443 tcp_debug_print_state(enum tcp_state s)
2444 {
2445 LWIP_DEBUGF(TCP_DEBUG, ("State: %s\n", tcp_state_str[s]));
2446 }
2447
2448 /**
2449 * Print tcp flags for debugging purposes.
2450 *
2451 * @param flags tcp flags, all active flags are printed
2452 */
2453 void
tcp_debug_print_flags(u8_t flags)2454 tcp_debug_print_flags(u8_t flags)
2455 {
2456 if (flags & TCP_FIN) {
2457 LWIP_DEBUGF(TCP_DEBUG, ("FIN "));
2458 }
2459 if (flags & TCP_SYN) {
2460 LWIP_DEBUGF(TCP_DEBUG, ("SYN "));
2461 }
2462 if (flags & TCP_RST) {
2463 LWIP_DEBUGF(TCP_DEBUG, ("RST "));
2464 }
2465 if (flags & TCP_PSH) {
2466 LWIP_DEBUGF(TCP_DEBUG, ("PSH "));
2467 }
2468 if (flags & TCP_ACK) {
2469 LWIP_DEBUGF(TCP_DEBUG, ("ACK "));
2470 }
2471 if (flags & TCP_URG) {
2472 LWIP_DEBUGF(TCP_DEBUG, ("URG "));
2473 }
2474 if (flags & TCP_ECE) {
2475 LWIP_DEBUGF(TCP_DEBUG, ("ECE "));
2476 }
2477 if (flags & TCP_CWR) {
2478 LWIP_DEBUGF(TCP_DEBUG, ("CWR "));
2479 }
2480 LWIP_DEBUGF(TCP_DEBUG, ("\n"));
2481 }
2482
2483 /**
2484 * Print all tcp_pcbs in every list for debugging purposes.
2485 */
2486 void
tcp_debug_print_pcbs(void)2487 tcp_debug_print_pcbs(void)
2488 {
2489 struct tcp_pcb *pcb;
2490 struct tcp_pcb_listen *pcbl;
2491
2492 LWIP_DEBUGF(TCP_DEBUG, ("Active PCB states:\n"));
2493 for (pcb = tcp_active_pcbs; pcb != NULL; pcb = pcb->next) {
2494 LWIP_DEBUGF(TCP_DEBUG, ("Local port %"U16_F", foreign port %"U16_F" snd_nxt %"U32_F" rcv_nxt %"U32_F" ",
2495 pcb->local_port, pcb->remote_port,
2496 pcb->snd_nxt, pcb->rcv_nxt));
2497 tcp_debug_print_state(pcb->state);
2498 }
2499
2500 LWIP_DEBUGF(TCP_DEBUG, ("Listen PCB states:\n"));
2501 for (pcbl = tcp_listen_pcbs.listen_pcbs; pcbl != NULL; pcbl = pcbl->next) {
2502 LWIP_DEBUGF(TCP_DEBUG, ("Local port %"U16_F" ", pcbl->local_port));
2503 tcp_debug_print_state(pcbl->state);
2504 }
2505
2506 LWIP_DEBUGF(TCP_DEBUG, ("TIME-WAIT PCB states:\n"));
2507 for (pcb = tcp_tw_pcbs; pcb != NULL; pcb = pcb->next) {
2508 LWIP_DEBUGF(TCP_DEBUG, ("Local port %"U16_F", foreign port %"U16_F" snd_nxt %"U32_F" rcv_nxt %"U32_F" ",
2509 pcb->local_port, pcb->remote_port,
2510 pcb->snd_nxt, pcb->rcv_nxt));
2511 tcp_debug_print_state(pcb->state);
2512 }
2513 }
2514
2515 /**
2516 * Check state consistency of the tcp_pcb lists.
2517 */
2518 s16_t
tcp_pcbs_sane(void)2519 tcp_pcbs_sane(void)
2520 {
2521 struct tcp_pcb *pcb;
2522 for (pcb = tcp_active_pcbs; pcb != NULL; pcb = pcb->next) {
2523 LWIP_ASSERT("tcp_pcbs_sane: active pcb->state != CLOSED", pcb->state != CLOSED);
2524 LWIP_ASSERT("tcp_pcbs_sane: active pcb->state != LISTEN", pcb->state != LISTEN);
2525 LWIP_ASSERT("tcp_pcbs_sane: active pcb->state != TIME-WAIT", pcb->state != TIME_WAIT);
2526 }
2527 for (pcb = tcp_tw_pcbs; pcb != NULL; pcb = pcb->next) {
2528 LWIP_ASSERT("tcp_pcbs_sane: tw pcb->state == TIME-WAIT", pcb->state == TIME_WAIT);
2529 }
2530 return 1;
2531 }
2532 #endif /* TCP_DEBUG */
2533
2534 #if LWIP_TCP_PCB_NUM_EXT_ARGS
2535 /**
2536 * @defgroup tcp_raw_extargs ext arguments
2537 * @ingroup tcp_raw
2538 * Additional data storage per tcp pcb\n
2539 * @see @ref tcp_raw
2540 *
2541 * When LWIP_TCP_PCB_NUM_EXT_ARGS is > 0, every tcp pcb (including listen pcb)
2542 * includes a number of additional argument entries in an array.
2543 *
2544 * To support memory management, in addition to a 'void *', callbacks can be
2545 * provided to manage transition from listening pcbs to connections and to
2546 * deallocate memory when a pcb is deallocated (see struct @ref tcp_ext_arg_callbacks).
2547 *
2548 * After allocating this index, use @ref tcp_ext_arg_set and @ref tcp_ext_arg_get
2549 * to store and load arguments from this index for a given pcb.
2550 */
2551
2552 static u8_t tcp_ext_arg_id;
2553
2554 /**
2555 * @ingroup tcp_raw_extargs
2556 * Allocate an index to store data in ext_args member of struct tcp_pcb.
2557 * Returned value is an index in mentioned array.
2558 * The index is *global* over all pcbs!
2559 *
2560 * When @ref LWIP_TCP_PCB_NUM_EXT_ARGS is > 0, every tcp pcb (including listen pcb)
2561 * includes a number of additional argument entries in an array.
2562 *
2563 * To support memory management, in addition to a 'void *', callbacks can be
2564 * provided to manage transition from listening pcbs to connections and to
2565 * deallocate memory when a pcb is deallocated (see struct @ref tcp_ext_arg_callbacks).
2566 *
2567 * After allocating this index, use @ref tcp_ext_arg_set and @ref tcp_ext_arg_get
2568 * to store and load arguments from this index for a given pcb.
2569 *
2570 * @return a unique index into struct tcp_pcb.ext_args
2571 */
2572 u8_t
tcp_ext_arg_alloc_id(void)2573 tcp_ext_arg_alloc_id(void)
2574 {
2575 u8_t result = tcp_ext_arg_id;
2576 tcp_ext_arg_id++;
2577
2578 LWIP_ASSERT_CORE_LOCKED();
2579
2580 #if LWIP_TCP_PCB_NUM_EXT_ARGS >= 255
2581 #error LWIP_TCP_PCB_NUM_EXT_ARGS
2582 #endif
2583 LWIP_ASSERT("Increase LWIP_TCP_PCB_NUM_EXT_ARGS in lwipopts.h", result < LWIP_TCP_PCB_NUM_EXT_ARGS);
2584 return result;
2585 }
2586
2587 /**
2588 * @ingroup tcp_raw_extargs
2589 * Set callbacks for a given index of ext_args on the specified pcb.
2590 *
2591 * @param pcb tcp_pcb for which to set the callback
2592 * @param id ext_args index to set (allocated via @ref tcp_ext_arg_alloc_id)
2593 * @param callbacks callback table (const since it is referenced, not copied!)
2594 */
2595 void
tcp_ext_arg_set_callbacks(struct tcp_pcb * pcb,uint8_t id,const struct tcp_ext_arg_callbacks * const callbacks)2596 tcp_ext_arg_set_callbacks(struct tcp_pcb *pcb, uint8_t id, const struct tcp_ext_arg_callbacks * const callbacks)
2597 {
2598 LWIP_ASSERT("pcb != NULL", pcb != NULL);
2599 LWIP_ASSERT("id < LWIP_TCP_PCB_NUM_EXT_ARGS", id < LWIP_TCP_PCB_NUM_EXT_ARGS);
2600 LWIP_ASSERT("callbacks != NULL", callbacks != NULL);
2601
2602 LWIP_ASSERT_CORE_LOCKED();
2603
2604 pcb->ext_args[id].callbacks = callbacks;
2605 }
2606
2607 /**
2608 * @ingroup tcp_raw_extargs
2609 * Set data for a given index of ext_args on the specified pcb.
2610 *
2611 * @param pcb tcp_pcb for which to set the data
2612 * @param id ext_args index to set (allocated via @ref tcp_ext_arg_alloc_id)
2613 * @param arg data pointer to set
2614 */
tcp_ext_arg_set(struct tcp_pcb * pcb,uint8_t id,void * arg)2615 void tcp_ext_arg_set(struct tcp_pcb *pcb, uint8_t id, void *arg)
2616 {
2617 LWIP_ASSERT("pcb != NULL", pcb != NULL);
2618 LWIP_ASSERT("id < LWIP_TCP_PCB_NUM_EXT_ARGS", id < LWIP_TCP_PCB_NUM_EXT_ARGS);
2619
2620 LWIP_ASSERT_CORE_LOCKED();
2621
2622 pcb->ext_args[id].data = arg;
2623 }
2624
2625 /**
2626 * @ingroup tcp_raw_extargs
2627 * Set data for a given index of ext_args on the specified pcb.
2628 *
2629 * @param pcb tcp_pcb for which to set the data
2630 * @param id ext_args index to set (allocated via @ref tcp_ext_arg_alloc_id)
2631 * @return data pointer at the given index
2632 */
tcp_ext_arg_get(const struct tcp_pcb * pcb,uint8_t id)2633 void *tcp_ext_arg_get(const struct tcp_pcb *pcb, uint8_t id)
2634 {
2635 LWIP_ASSERT("pcb != NULL", pcb != NULL);
2636 LWIP_ASSERT("id < LWIP_TCP_PCB_NUM_EXT_ARGS", id < LWIP_TCP_PCB_NUM_EXT_ARGS);
2637
2638 LWIP_ASSERT_CORE_LOCKED();
2639
2640 return pcb->ext_args[id].data;
2641 }
2642
2643 /** This function calls the "destroy" callback for all ext_args once a pcb is
2644 * freed.
2645 */
2646 static void
tcp_ext_arg_invoke_callbacks_destroyed(struct tcp_pcb_ext_args * ext_args)2647 tcp_ext_arg_invoke_callbacks_destroyed(struct tcp_pcb_ext_args *ext_args)
2648 {
2649 int i;
2650 LWIP_ASSERT("ext_args != NULL", ext_args != NULL);
2651
2652 for (i = 0; i < LWIP_TCP_PCB_NUM_EXT_ARGS; i++) {
2653 if (ext_args[i].callbacks != NULL) {
2654 if (ext_args[i].callbacks->destroy != NULL) {
2655 ext_args[i].callbacks->destroy((u8_t)i, ext_args[i].data);
2656 }
2657 }
2658 }
2659 }
2660
2661 /** This function calls the "passive_open" callback for all ext_args if a connection
2662 * is in the process of being accepted. This is called just after the SYN is
2663 * received and before a SYN/ACK is sent, to allow to modify the very first
2664 * segment sent even on passive open. Naturally, the "accepted" callback of the
2665 * pcb has not been called yet!
2666 */
2667 err_t
tcp_ext_arg_invoke_callbacks_passive_open(struct tcp_pcb_listen * lpcb,struct tcp_pcb * cpcb)2668 tcp_ext_arg_invoke_callbacks_passive_open(struct tcp_pcb_listen *lpcb, struct tcp_pcb *cpcb)
2669 {
2670 int i;
2671 LWIP_ASSERT("lpcb != NULL", lpcb != NULL);
2672 LWIP_ASSERT("cpcb != NULL", cpcb != NULL);
2673
2674 for (i = 0; i < LWIP_TCP_PCB_NUM_EXT_ARGS; i++) {
2675 if (lpcb->ext_args[i].callbacks != NULL) {
2676 if (lpcb->ext_args[i].callbacks->passive_open != NULL) {
2677 err_t err = lpcb->ext_args[i].callbacks->passive_open((u8_t)i, lpcb, cpcb);
2678 if (err != ERR_OK) {
2679 return err;
2680 }
2681 }
2682 }
2683 }
2684 return ERR_OK;
2685 }
2686 #endif /* LWIP_TCP_PCB_NUM_EXT_ARGS */
2687
2688 #endif /* LWIP_TCP */
2689