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