]> git.donarmstrong.com Git - qmk_firmware.git/blob - tool/mbed/mbed-sdk/libraries/net/lwip/lwip/core/tcp.c
Squashed 'tmk_core/' changes from 7967731..b9e0ea0
[qmk_firmware.git] / tool / mbed / mbed-sdk / libraries / net / lwip / lwip / core / tcp.c
1 /**
2  * @file
3  * Transmission Control Protocol for IP
4  *
5  * This file contains common functions for the TCP implementation, such as functinos
6  * for manipulating the data structures and the TCP timer functions. TCP functions
7  * related to input and output is found in tcp_in.c and tcp_out.c respectively.
8  *
9  */
10
11 /*
12  * Copyright (c) 2001-2004 Swedish Institute of Computer Science.
13  * All rights reserved. 
14  * 
15  * Redistribution and use in source and binary forms, with or without modification, 
16  * are permitted provided that the following conditions are met:
17  *
18  * 1. Redistributions of source code must retain the above copyright notice,
19  *    this list of conditions and the following disclaimer.
20  * 2. Redistributions in binary form must reproduce the above copyright notice,
21  *    this list of conditions and the following disclaimer in the documentation
22  *    and/or other materials provided with the distribution.
23  * 3. The name of the author may not be used to endorse or promote products
24  *    derived from this software without specific prior written permission. 
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED 
27  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
28  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT 
29  * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 
30  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT 
31  * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
32  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
33  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING 
34  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY 
35  * OF SUCH DAMAGE.
36  *
37  * This file is part of the lwIP TCP/IP stack.
38  * 
39  * Author: Adam Dunkels <adam@sics.se>
40  *
41  */
42
43 #include "lwip/opt.h"
44
45 #if LWIP_TCP /* don't build if not configured for use in lwipopts.h */
46
47 #include "lwip/def.h"
48 #include "lwip/mem.h"
49 #include "lwip/memp.h"
50 #include "lwip/snmp.h"
51 #include "lwip/tcp.h"
52 #include "lwip/tcp_impl.h"
53 #include "lwip/debug.h"
54 #include "lwip/stats.h"
55
56 #include <string.h>
57
58 const char * const tcp_state_str[] = {
59   "CLOSED",      
60   "LISTEN",      
61   "SYN_SENT",    
62   "SYN_RCVD",    
63   "ESTABLISHED", 
64   "FIN_WAIT_1",  
65   "FIN_WAIT_2",  
66   "CLOSE_WAIT",  
67   "CLOSING",     
68   "LAST_ACK",    
69   "TIME_WAIT"   
70 };
71
72 /* Incremented every coarse grained timer shot (typically every 500 ms). */
73 u32_t tcp_ticks;
74 const u8_t tcp_backoff[13] =
75     { 1, 2, 3, 4, 5, 6, 7, 7, 7, 7, 7, 7, 7};
76  /* Times per slowtmr hits */
77 const u8_t tcp_persist_backoff[7] = { 3, 6, 12, 24, 48, 96, 120 };
78
79 /* The TCP PCB lists. */
80
81 /** List of all TCP PCBs bound but not yet (connected || listening) */
82 struct tcp_pcb *tcp_bound_pcbs;
83 /** List of all TCP PCBs in LISTEN state */
84 union tcp_listen_pcbs_t tcp_listen_pcbs;
85 /** List of all TCP PCBs that are in a state in which
86  * they accept or send data. */
87 struct tcp_pcb *tcp_active_pcbs;
88 /** List of all TCP PCBs in TIME-WAIT state */
89 struct tcp_pcb *tcp_tw_pcbs;
90
91 #define NUM_TCP_PCB_LISTS               4
92 #define NUM_TCP_PCB_LISTS_NO_TIME_WAIT  3
93 /** An array with all (non-temporary) PCB lists, mainly used for smaller code size */
94 struct tcp_pcb ** const tcp_pcb_lists[] = {&tcp_listen_pcbs.pcbs, &tcp_bound_pcbs,
95   &tcp_active_pcbs, &tcp_tw_pcbs};
96
97 /** Only used for temporary storage. */
98 struct tcp_pcb *tcp_tmp_pcb;
99
100 /** Timer counter to handle calling slow-timer from tcp_tmr() */ 
101 static u8_t tcp_timer;
102 static u16_t tcp_new_port(void);
103
104 /**
105  * Called periodically to dispatch TCP timers.
106  *
107  */
108 void
109 tcp_tmr(void)
110 {
111   /* Call tcp_fasttmr() every 250 ms */
112   tcp_fasttmr();
113
114   if (++tcp_timer & 1) {
115     /* Call tcp_tmr() every 500 ms, i.e., every other timer
116        tcp_tmr() is called. */
117     tcp_slowtmr();
118   }
119 }
120
121 /**
122  * Closes the TX side of a connection held by the PCB.
123  * For tcp_close(), a RST is sent if the application didn't receive all data
124  * (tcp_recved() not called for all data passed to recv callback).
125  *
126  * Listening pcbs are freed and may not be referenced any more.
127  * Connection pcbs are freed if not yet connected and may not be referenced
128  * any more. If a connection is established (at least SYN received or in
129  * a closing state), the connection is closed, and put in a closing state.
130  * The pcb is then automatically freed in tcp_slowtmr(). It is therefore
131  * unsafe to reference it.
132  *
133  * @param pcb the tcp_pcb to close
134  * @return ERR_OK if connection has been closed
135  *         another err_t if closing failed and pcb is not freed
136  */
137 static err_t
138 tcp_close_shutdown(struct tcp_pcb *pcb, u8_t rst_on_unacked_data)
139 {
140   err_t err;
141
142   if (rst_on_unacked_data && (pcb->state != LISTEN)) {
143     if ((pcb->refused_data != NULL) || (pcb->rcv_wnd != TCP_WND)) {
144       /* Not all data received by application, send RST to tell the remote
145          side about this. */
146       LWIP_ASSERT("pcb->flags & TF_RXCLOSED", pcb->flags & TF_RXCLOSED);
147
148       /* don't call tcp_abort here: we must not deallocate the pcb since
149          that might not be expected when calling tcp_close */
150       tcp_rst(pcb->snd_nxt, pcb->rcv_nxt, &pcb->local_ip, &pcb->remote_ip,
151         pcb->local_port, pcb->remote_port);
152
153       tcp_pcb_purge(pcb);
154
155       /* TODO: to which state do we move now? */
156
157       /* move to TIME_WAIT since we close actively */
158       TCP_RMV(&tcp_active_pcbs, pcb);
159       pcb->state = TIME_WAIT;
160       TCP_REG(&tcp_tw_pcbs, pcb);
161
162       return ERR_OK;
163     }
164   }
165
166   switch (pcb->state) {
167   case CLOSED:
168     /* Closing a pcb in the CLOSED state might seem erroneous,
169      * however, it is in this state once allocated and as yet unused
170      * and the user needs some way to free it should the need arise.
171      * Calling tcp_close() with a pcb that has already been closed, (i.e. twice)
172      * or for a pcb that has been used and then entered the CLOSED state 
173      * is erroneous, but this should never happen as the pcb has in those cases
174      * been freed, and so any remaining handles are bogus. */
175     err = ERR_OK;
176     if (pcb->local_port != 0) {
177       TCP_RMV(&tcp_bound_pcbs, pcb);
178     }
179     memp_free(MEMP_TCP_PCB, pcb);
180     pcb = NULL;
181     break;
182   case LISTEN:
183     err = ERR_OK;
184     tcp_pcb_remove(&tcp_listen_pcbs.pcbs, pcb);
185     memp_free(MEMP_TCP_PCB_LISTEN, pcb);
186     pcb = NULL;
187     break;
188   case SYN_SENT:
189     err = ERR_OK;
190     tcp_pcb_remove(&tcp_active_pcbs, pcb);
191     memp_free(MEMP_TCP_PCB, pcb);
192     pcb = NULL;
193     snmp_inc_tcpattemptfails();
194     break;
195   case SYN_RCVD:
196     err = tcp_send_fin(pcb);
197     if (err == ERR_OK) {
198       snmp_inc_tcpattemptfails();
199       pcb->state = FIN_WAIT_1;
200     }
201     break;
202   case ESTABLISHED:
203     err = tcp_send_fin(pcb);
204     if (err == ERR_OK) {
205       snmp_inc_tcpestabresets();
206       pcb->state = FIN_WAIT_1;
207     }
208     break;
209   case CLOSE_WAIT:
210     err = tcp_send_fin(pcb);
211     if (err == ERR_OK) {
212       snmp_inc_tcpestabresets();
213       pcb->state = LAST_ACK;
214     }
215     break;
216   default:
217     /* Has already been closed, do nothing. */
218     err = ERR_OK;
219     pcb = NULL;
220     break;
221   }
222
223   if (pcb != NULL && err == ERR_OK) {
224     /* To ensure all data has been sent when tcp_close returns, we have
225        to make sure tcp_output doesn't fail.
226        Since we don't really have to ensure all data has been sent when tcp_close
227        returns (unsent data is sent from tcp timer functions, also), we don't care
228        for the return value of tcp_output for now. */
229     /* @todo: When implementing SO_LINGER, this must be changed somehow:
230        If SOF_LINGER is set, the data should be sent and acked before close returns.
231        This can only be valid for sequential APIs, not for the raw API. */
232     tcp_output(pcb);
233   }
234   return err;
235 }
236
237 /**
238  * Closes the connection held by the PCB.
239  *
240  * Listening pcbs are freed and may not be referenced any more.
241  * Connection pcbs are freed if not yet connected and may not be referenced
242  * any more. If a connection is established (at least SYN received or in
243  * a closing state), the connection is closed, and put in a closing state.
244  * The pcb is then automatically freed in tcp_slowtmr(). It is therefore
245  * unsafe to reference it (unless an error is returned).
246  *
247  * @param pcb the tcp_pcb to close
248  * @return ERR_OK if connection has been closed
249  *         another err_t if closing failed and pcb is not freed
250  */
251 err_t
252 tcp_close(struct tcp_pcb *pcb)
253 {
254 #if TCP_DEBUG
255   LWIP_DEBUGF(TCP_DEBUG, ("tcp_close: closing in "));
256   tcp_debug_print_state(pcb->state);
257 #endif /* TCP_DEBUG */
258
259   if (pcb->state != LISTEN) {
260     /* Set a flag not to receive any more data... */
261     pcb->flags |= TF_RXCLOSED;
262   }
263   /* ... and close */
264   return tcp_close_shutdown(pcb, 1);
265 }
266
267 /**
268  * Causes all or part of a full-duplex connection of this PCB to be shut down.
269  * This doesn't deallocate the PCB!
270  *
271  * @param pcb PCB to shutdown
272  * @param shut_rx shut down receive side if this is != 0
273  * @param shut_tx shut down send side if this is != 0
274  * @return ERR_OK if shutdown succeeded (or the PCB has already been shut down)
275  *         another err_t on error.
276  */
277 err_t
278 tcp_shutdown(struct tcp_pcb *pcb, int shut_rx, int shut_tx)
279 {
280   if (pcb->state == LISTEN) {
281     return ERR_CONN;
282   }
283   if (shut_rx) {
284     /* shut down the receive side: free buffered data... */
285     if (pcb->refused_data != NULL) {
286       pbuf_free(pcb->refused_data);
287       pcb->refused_data = NULL;
288     }
289     /* ... and set a flag not to receive any more data */
290     pcb->flags |= TF_RXCLOSED;
291   }
292   if (shut_tx) {
293     /* This can't happen twice since if it succeeds, the pcb's state is changed.
294        Only close in these states as the others directly deallocate the PCB */
295     switch (pcb->state) {
296   case SYN_RCVD:
297   case ESTABLISHED:
298   case CLOSE_WAIT:
299     return tcp_close_shutdown(pcb, 0);
300   default:
301     /* don't shut down other states */
302     break;
303     }
304   }
305   /* @todo: return another err_t if not in correct state or already shut? */
306   return ERR_OK;
307 }
308
309 /**
310  * Abandons a connection and optionally sends a RST to the remote
311  * host.  Deletes the local protocol control block. This is done when
312  * a connection is killed because of shortage of memory.
313  *
314  * @param pcb the tcp_pcb to abort
315  * @param reset boolean to indicate whether a reset should be sent
316  */
317 void
318 tcp_abandon(struct tcp_pcb *pcb, int reset)
319 {
320   u32_t seqno, ackno;
321   u16_t remote_port, local_port;
322   ip_addr_t remote_ip, local_ip;
323 #if LWIP_CALLBACK_API  
324   tcp_err_fn errf;
325 #endif /* LWIP_CALLBACK_API */
326   void *errf_arg;
327
328   /* pcb->state LISTEN not allowed here */
329   LWIP_ASSERT("don't call tcp_abort/tcp_abandon for listen-pcbs",
330     pcb->state != LISTEN);
331   /* Figure out on which TCP PCB list we are, and remove us. If we
332      are in an active state, call the receive function associated with
333      the PCB with a NULL argument, and send an RST to the remote end. */
334   if (pcb->state == TIME_WAIT) {
335     tcp_pcb_remove(&tcp_tw_pcbs, pcb);
336     memp_free(MEMP_TCP_PCB, pcb);
337   } else {
338     seqno = pcb->snd_nxt;
339     ackno = pcb->rcv_nxt;
340     ip_addr_copy(local_ip, pcb->local_ip);
341     ip_addr_copy(remote_ip, pcb->remote_ip);
342     local_port = pcb->local_port;
343     remote_port = pcb->remote_port;
344 #if LWIP_CALLBACK_API
345     errf = pcb->errf;
346 #endif /* LWIP_CALLBACK_API */
347     errf_arg = pcb->callback_arg;
348     tcp_pcb_remove(&tcp_active_pcbs, pcb);
349     if (pcb->unacked != NULL) {
350       tcp_segs_free(pcb->unacked);
351     }
352     if (pcb->unsent != NULL) {
353       tcp_segs_free(pcb->unsent);
354     }
355 #if TCP_QUEUE_OOSEQ    
356     if (pcb->ooseq != NULL) {
357       tcp_segs_free(pcb->ooseq);
358     }
359 #endif /* TCP_QUEUE_OOSEQ */
360     memp_free(MEMP_TCP_PCB, pcb);
361     TCP_EVENT_ERR(errf, errf_arg, ERR_ABRT);
362     if (reset) {
363       LWIP_DEBUGF(TCP_RST_DEBUG, ("tcp_abandon: sending RST\n"));
364       tcp_rst(seqno, ackno, &local_ip, &remote_ip, local_port, remote_port);
365     }
366   }
367 }
368
369 /**
370  * Aborts the connection by sending a RST (reset) segment to the remote
371  * host. The pcb is deallocated. This function never fails.
372  *
373  * ATTENTION: When calling this from one of the TCP callbacks, make
374  * sure you always return ERR_ABRT (and never return ERR_ABRT otherwise
375  * or you will risk accessing deallocated memory or memory leaks!
376  *
377  * @param pcb the tcp pcb to abort
378  */
379 void
380 tcp_abort(struct tcp_pcb *pcb)
381 {
382   tcp_abandon(pcb, 1);
383 }
384
385 /**
386  * Binds the connection to a local portnumber and IP address. If the
387  * IP address is not given (i.e., ipaddr == NULL), the IP address of
388  * the outgoing network interface is used instead.
389  *
390  * @param pcb the tcp_pcb to bind (no check is done whether this pcb is
391  *        already bound!)
392  * @param ipaddr the local ip address to bind to (use IP_ADDR_ANY to bind
393  *        to any local address
394  * @param port the local port to bind to
395  * @return ERR_USE if the port is already in use
396  *         ERR_VAL if bind failed because the PCB is not in a valid state
397  *         ERR_OK if bound
398  */
399 err_t
400 tcp_bind(struct tcp_pcb *pcb, ip_addr_t *ipaddr, u16_t port)
401 {
402   int i;
403   int max_pcb_list = NUM_TCP_PCB_LISTS;
404   struct tcp_pcb *cpcb;
405
406   LWIP_ERROR("tcp_bind: can only bind in state CLOSED", pcb->state == CLOSED, return ERR_VAL);
407
408 #if SO_REUSE
409   /* Unless the REUSEADDR flag is set,
410      we have to check the pcbs in TIME-WAIT state, also.
411      We do not dump TIME_WAIT pcb's; they can still be matched by incoming
412      packets using both local and remote IP addresses and ports to distinguish.
413    */
414   if ((pcb->so_options & SOF_REUSEADDR) != 0) {
415     max_pcb_list = NUM_TCP_PCB_LISTS_NO_TIME_WAIT;
416   }
417 #endif /* SO_REUSE */
418
419   if (port == 0) {
420     port = tcp_new_port();
421   }
422
423   /* Check if the address already is in use (on all lists) */
424   for (i = 0; i < max_pcb_list; i++) {
425     for(cpcb = *tcp_pcb_lists[i]; cpcb != NULL; cpcb = cpcb->next) {
426       if (cpcb->local_port == port) {
427 #if SO_REUSE
428         /* Omit checking for the same port if both pcbs have REUSEADDR set.
429            For SO_REUSEADDR, the duplicate-check for a 5-tuple is done in
430            tcp_connect. */
431         if (((pcb->so_options & SOF_REUSEADDR) == 0) ||
432           ((cpcb->so_options & SOF_REUSEADDR) == 0))
433 #endif /* SO_REUSE */
434         {
435           if (ip_addr_isany(&(cpcb->local_ip)) ||
436               ip_addr_isany(ipaddr) ||
437               ip_addr_cmp(&(cpcb->local_ip), ipaddr)) {
438             return ERR_USE;
439           }
440         }
441       }
442     }
443   }
444
445   if (!ip_addr_isany(ipaddr)) {
446     pcb->local_ip = *ipaddr;
447   }
448   pcb->local_port = port;
449   TCP_REG(&tcp_bound_pcbs, pcb);
450   LWIP_DEBUGF(TCP_DEBUG, ("tcp_bind: bind to port %"U16_F"\n", port));
451   return ERR_OK;
452 }
453 #if LWIP_CALLBACK_API
454 /**
455  * Default accept callback if no accept callback is specified by the user.
456  */
457 static err_t
458 tcp_accept_null(void *arg, struct tcp_pcb *pcb, err_t err)
459 {
460   LWIP_UNUSED_ARG(arg);
461   LWIP_UNUSED_ARG(pcb);
462   LWIP_UNUSED_ARG(err);
463
464   return ERR_ABRT;
465 }
466 #endif /* LWIP_CALLBACK_API */
467
468 /**
469  * Set the state of the connection to be LISTEN, which means that it
470  * is able to accept incoming connections. The protocol control block
471  * is reallocated in order to consume less memory. Setting the
472  * connection to LISTEN is an irreversible process.
473  *
474  * @param pcb the original tcp_pcb
475  * @param backlog the incoming connections queue limit
476  * @return tcp_pcb used for listening, consumes less memory.
477  *
478  * @note The original tcp_pcb is freed. This function therefore has to be
479  *       called like this:
480  *             tpcb = tcp_listen(tpcb);
481  */
482 struct tcp_pcb *
483 tcp_listen_with_backlog(struct tcp_pcb *pcb, u8_t backlog)
484 {
485   struct tcp_pcb_listen *lpcb;
486
487   LWIP_UNUSED_ARG(backlog);
488   LWIP_ERROR("tcp_listen: pcb already connected", pcb->state == CLOSED, return NULL);
489
490   /* already listening? */
491   if (pcb->state == LISTEN) {
492     return pcb;
493   }
494 #if SO_REUSE
495   if ((pcb->so_options & SOF_REUSEADDR) != 0) {
496     /* Since SOF_REUSEADDR allows reusing a local address before the pcb's usage
497        is declared (listen-/connection-pcb), we have to make sure now that
498        this port is only used once for every local IP. */
499     for(lpcb = tcp_listen_pcbs.listen_pcbs; lpcb != NULL; lpcb = lpcb->next) {
500       if (lpcb->local_port == pcb->local_port) {
501         if (ip_addr_cmp(&lpcb->local_ip, &pcb->local_ip)) {
502           /* this address/port is already used */
503           return NULL;
504         }
505       }
506     }
507   }
508 #endif /* SO_REUSE */
509   lpcb = (struct tcp_pcb_listen *)memp_malloc(MEMP_TCP_PCB_LISTEN);
510   if (lpcb == NULL) {
511     return NULL;
512   }
513   lpcb->callback_arg = pcb->callback_arg;
514   lpcb->local_port = pcb->local_port;
515   lpcb->state = LISTEN;
516   lpcb->prio = pcb->prio;
517   lpcb->so_options = pcb->so_options;
518   lpcb->so_options |= SOF_ACCEPTCONN;
519   lpcb->ttl = pcb->ttl;
520   lpcb->tos = pcb->tos;
521   ip_addr_copy(lpcb->local_ip, pcb->local_ip);
522   if (pcb->local_port != 0) {
523     TCP_RMV(&tcp_bound_pcbs, pcb);
524   }
525   memp_free(MEMP_TCP_PCB, pcb);
526 #if LWIP_CALLBACK_API
527   lpcb->accept = tcp_accept_null;
528 #endif /* LWIP_CALLBACK_API */
529 #if TCP_LISTEN_BACKLOG
530   lpcb->accepts_pending = 0;
531   lpcb->backlog = (backlog ? backlog : 1);
532 #endif /* TCP_LISTEN_BACKLOG */
533   TCP_REG(&tcp_listen_pcbs.pcbs, (struct tcp_pcb *)lpcb);
534   return (struct tcp_pcb *)lpcb;
535 }
536
537 /** 
538  * Update the state that tracks the available window space to advertise.
539  *
540  * Returns how much extra window would be advertised if we sent an
541  * update now.
542  */
543 u32_t tcp_update_rcv_ann_wnd(struct tcp_pcb *pcb)
544 {
545   u32_t new_right_edge = pcb->rcv_nxt + pcb->rcv_wnd;
546
547   if (TCP_SEQ_GEQ(new_right_edge, pcb->rcv_ann_right_edge + LWIP_MIN((TCP_WND / 2), pcb->mss))) {
548     /* we can advertise more window */
549     pcb->rcv_ann_wnd = pcb->rcv_wnd;
550     return new_right_edge - pcb->rcv_ann_right_edge;
551   } else {
552     if (TCP_SEQ_GT(pcb->rcv_nxt, pcb->rcv_ann_right_edge)) {
553       /* Can happen due to other end sending out of advertised window,
554        * but within actual available (but not yet advertised) window */
555       pcb->rcv_ann_wnd = 0;
556     } else {
557       /* keep the right edge of window constant */
558       u32_t new_rcv_ann_wnd = pcb->rcv_ann_right_edge - pcb->rcv_nxt;
559       LWIP_ASSERT("new_rcv_ann_wnd <= 0xffff", new_rcv_ann_wnd <= 0xffff);
560       pcb->rcv_ann_wnd = (u16_t)new_rcv_ann_wnd;
561     }
562     return 0;
563   }
564 }
565
566 /**
567  * This function should be called by the application when it has
568  * processed the data. The purpose is to advertise a larger window
569  * when the data has been processed.
570  *
571  * @param pcb the tcp_pcb for which data is read
572  * @param len the amount of bytes that have been read by the application
573  */
574 void
575 tcp_recved(struct tcp_pcb *pcb, u16_t len)
576 {
577   int wnd_inflation;
578
579   LWIP_ASSERT("tcp_recved: len would wrap rcv_wnd\n",
580               len <= 0xffff - pcb->rcv_wnd );
581
582   pcb->rcv_wnd += len;
583   if (pcb->rcv_wnd > TCP_WND) {
584     pcb->rcv_wnd = TCP_WND;
585   }
586
587   wnd_inflation = tcp_update_rcv_ann_wnd(pcb);
588
589   /* If the change in the right edge of window is significant (default
590    * watermark is TCP_WND/4), then send an explicit update now.
591    * Otherwise wait for a packet to be sent in the normal course of
592    * events (or more window to be available later) */
593   if (wnd_inflation >= TCP_WND_UPDATE_THRESHOLD) {
594     tcp_ack_now(pcb);
595     tcp_output(pcb);
596   }
597
598   LWIP_DEBUGF(TCP_DEBUG, ("tcp_recved: recveived %"U16_F" bytes, wnd %"U16_F" (%"U16_F").\n",
599          len, pcb->rcv_wnd, TCP_WND - pcb->rcv_wnd));
600 }
601
602 /**
603  * A nastly hack featuring 'goto' statements that allocates a
604  * new TCP local port.
605  *
606  * @return a new (free) local TCP port number
607  */
608 static u16_t
609 tcp_new_port(void)
610 {
611   int i;
612   struct tcp_pcb *pcb;
613 #ifndef TCP_LOCAL_PORT_RANGE_START
614 /* From http://www.iana.org/assignments/port-numbers:
615    "The Dynamic and/or Private Ports are those from 49152 through 65535" */
616 #define TCP_LOCAL_PORT_RANGE_START  0xc000
617 #define TCP_LOCAL_PORT_RANGE_END    0xffff
618 #endif
619   static u16_t port = TCP_LOCAL_PORT_RANGE_START;
620   
621  again:
622   if (port++ >= TCP_LOCAL_PORT_RANGE_END) {
623     port = TCP_LOCAL_PORT_RANGE_START;
624   }
625   /* Check all PCB lists. */
626   for (i = 0; i < NUM_TCP_PCB_LISTS; i++) {
627     for(pcb = *tcp_pcb_lists[i]; pcb != NULL; pcb = pcb->next) {
628       if (pcb->local_port == port) {
629         goto again;
630       }
631     }
632   }
633   return port;
634 }
635
636 /**
637  * Connects to another host. The function given as the "connected"
638  * argument will be called when the connection has been established.
639  *
640  * @param pcb the tcp_pcb used to establish the connection
641  * @param ipaddr the remote ip address to connect to
642  * @param port the remote tcp port to connect to
643  * @param connected callback function to call when connected (or on error)
644  * @return ERR_VAL if invalid arguments are given
645  *         ERR_OK if connect request has been sent
646  *         other err_t values if connect request couldn't be sent
647  */
648 err_t
649 tcp_connect(struct tcp_pcb *pcb, ip_addr_t *ipaddr, u16_t port,
650       tcp_connected_fn connected)
651 {
652   err_t ret;
653   u32_t iss;
654   u16_t old_local_port;
655
656   LWIP_ERROR("tcp_connect: can only connect from state CLOSED", pcb->state == CLOSED, return ERR_ISCONN);
657
658   LWIP_DEBUGF(TCP_DEBUG, ("tcp_connect to port %"U16_F"\n", port));
659   if (ipaddr != NULL) {
660     pcb->remote_ip = *ipaddr;
661   } else {
662     return ERR_VAL;
663   }
664   pcb->remote_port = port;
665
666   /* check if we have a route to the remote host */
667   if (ip_addr_isany(&(pcb->local_ip))) {
668     /* no local IP address set, yet. */
669     struct netif *netif = ip_route(&(pcb->remote_ip));
670     if (netif == NULL) {
671       /* Don't even try to send a SYN packet if we have no route
672          since that will fail. */
673       return ERR_RTE;
674     }
675     /* Use the netif's IP address as local address. */
676     ip_addr_copy(pcb->local_ip, netif->ip_addr);
677   }
678
679   old_local_port = pcb->local_port;
680   if (pcb->local_port == 0) {
681     pcb->local_port = tcp_new_port();
682   }
683 #if SO_REUSE
684   if ((pcb->so_options & SOF_REUSEADDR) != 0) {
685     /* Since SOF_REUSEADDR allows reusing a local address, we have to make sure
686        now that the 5-tuple is unique. */
687     struct tcp_pcb *cpcb;
688     int i;
689     /* Don't check listen- and bound-PCBs, check active- and TIME-WAIT PCBs. */
690     for (i = 2; i < NUM_TCP_PCB_LISTS; i++) {
691       for(cpcb = *tcp_pcb_lists[i]; cpcb != NULL; cpcb = cpcb->next) {
692         if ((cpcb->local_port == pcb->local_port) &&
693             (cpcb->remote_port == port) &&
694             ip_addr_cmp(&cpcb->local_ip, &pcb->local_ip) &&
695             ip_addr_cmp(&cpcb->remote_ip, ipaddr)) {
696           /* linux returns EISCONN here, but ERR_USE should be OK for us */
697           return ERR_USE;
698         }
699       }
700     }
701   }
702 #endif /* SO_REUSE */
703   iss = tcp_next_iss();
704   pcb->rcv_nxt = 0;
705   pcb->snd_nxt = iss;
706   pcb->lastack = iss - 1;
707   pcb->snd_lbb = iss - 1;
708   pcb->rcv_wnd = TCP_WND;
709   pcb->rcv_ann_wnd = TCP_WND;
710   pcb->rcv_ann_right_edge = pcb->rcv_nxt;
711   pcb->snd_wnd = TCP_WND;
712   /* As initial send MSS, we use TCP_MSS but limit it to 536.
713      The send MSS is updated when an MSS option is received. */
714   pcb->mss = (TCP_MSS > 536) ? 536 : TCP_MSS;
715 #if TCP_CALCULATE_EFF_SEND_MSS
716   pcb->mss = tcp_eff_send_mss(pcb->mss, ipaddr);
717 #endif /* TCP_CALCULATE_EFF_SEND_MSS */
718   pcb->cwnd = 1;
719   pcb->ssthresh = pcb->mss * 10;
720 #if LWIP_CALLBACK_API
721   pcb->connected = connected;
722 #else /* LWIP_CALLBACK_API */  
723   LWIP_UNUSED_ARG(connected);
724 #endif /* LWIP_CALLBACK_API */
725
726   /* Send a SYN together with the MSS option. */
727   ret = tcp_enqueue_flags(pcb, TCP_SYN);
728   if (ret == ERR_OK) {
729     /* SYN segment was enqueued, changed the pcbs state now */
730     pcb->state = SYN_SENT;
731     if (old_local_port != 0) {
732       TCP_RMV(&tcp_bound_pcbs, pcb);
733     }
734     TCP_REG(&tcp_active_pcbs, pcb);
735     snmp_inc_tcpactiveopens();
736
737     tcp_output(pcb);
738   }
739   return ret;
740 }
741
742 /**
743  * Called every 500 ms and implements the retransmission timer and the timer that
744  * removes PCBs that have been in TIME-WAIT for enough time. It also increments
745  * various timers such as the inactivity timer in each PCB.
746  *
747  * Automatically called from tcp_tmr().
748  */
749 void
750 tcp_slowtmr(void)
751 {
752   struct tcp_pcb *pcb, *prev;
753   u16_t eff_wnd;
754   u8_t pcb_remove;      /* flag if a PCB should be removed */
755   u8_t pcb_reset;       /* flag if a RST should be sent when removing */
756   err_t err;
757
758   err = ERR_OK;
759
760   ++tcp_ticks;
761
762   /* Steps through all of the active PCBs. */
763   prev = NULL;
764   pcb = tcp_active_pcbs;
765   if (pcb == NULL) {
766     LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: no active pcbs\n"));
767   }
768   while (pcb != NULL) {
769     LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: processing active pcb\n"));
770     LWIP_ASSERT("tcp_slowtmr: active pcb->state != CLOSED\n", pcb->state != CLOSED);
771     LWIP_ASSERT("tcp_slowtmr: active pcb->state != LISTEN\n", pcb->state != LISTEN);
772     LWIP_ASSERT("tcp_slowtmr: active pcb->state != TIME-WAIT\n", pcb->state != TIME_WAIT);
773
774     pcb_remove = 0;
775     pcb_reset = 0;
776
777     if (pcb->state == SYN_SENT && pcb->nrtx == TCP_SYNMAXRTX) {
778       ++pcb_remove;
779       LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: max SYN retries reached\n"));
780     }
781     else if (pcb->nrtx == TCP_MAXRTX) {
782       ++pcb_remove;
783       LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: max DATA retries reached\n"));
784     } else {
785       if (pcb->persist_backoff > 0) {
786         /* If snd_wnd is zero, use persist timer to send 1 byte probes
787          * instead of using the standard retransmission mechanism. */
788         pcb->persist_cnt++;
789         if (pcb->persist_cnt >= tcp_persist_backoff[pcb->persist_backoff-1]) {
790           pcb->persist_cnt = 0;
791           if (pcb->persist_backoff < sizeof(tcp_persist_backoff)) {
792             pcb->persist_backoff++;
793           }
794           tcp_zero_window_probe(pcb);
795         }
796       } else {
797         /* Increase the retransmission timer if it is running */
798         if(pcb->rtime >= 0)
799           ++pcb->rtime;
800
801         if (pcb->unacked != NULL && pcb->rtime >= pcb->rto) {
802           /* Time for a retransmission. */
803           LWIP_DEBUGF(TCP_RTO_DEBUG, ("tcp_slowtmr: rtime %"S16_F
804                                       " pcb->rto %"S16_F"\n",
805                                       pcb->rtime, pcb->rto));
806
807           /* Double retransmission time-out unless we are trying to
808            * connect to somebody (i.e., we are in SYN_SENT). */
809           if (pcb->state != SYN_SENT) {
810             pcb->rto = ((pcb->sa >> 3) + pcb->sv) << tcp_backoff[pcb->nrtx];
811           }
812
813           /* Reset the retransmission timer. */
814           pcb->rtime = 0;
815
816           /* Reduce congestion window and ssthresh. */
817           eff_wnd = LWIP_MIN(pcb->cwnd, pcb->snd_wnd);
818           pcb->ssthresh = eff_wnd >> 1;
819           if (pcb->ssthresh < (pcb->mss << 1)) {
820             pcb->ssthresh = (pcb->mss << 1);
821           }
822           pcb->cwnd = pcb->mss;
823           LWIP_DEBUGF(TCP_CWND_DEBUG, ("tcp_slowtmr: cwnd %"U16_F
824                                        " ssthresh %"U16_F"\n",
825                                        pcb->cwnd, pcb->ssthresh));
826  
827           /* The following needs to be called AFTER cwnd is set to one
828              mss - STJ */
829           tcp_rexmit_rto(pcb);
830         }
831       }
832     }
833     /* Check if this PCB has stayed too long in FIN-WAIT-2 */
834     if (pcb->state == FIN_WAIT_2) {
835       if ((u32_t)(tcp_ticks - pcb->tmr) >
836           TCP_FIN_WAIT_TIMEOUT / TCP_SLOW_INTERVAL) {
837         ++pcb_remove;
838         LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: removing pcb stuck in FIN-WAIT-2\n"));
839       }
840     }
841
842     /* Check if KEEPALIVE should be sent */
843     if((pcb->so_options & SOF_KEEPALIVE) &&
844        ((pcb->state == ESTABLISHED) ||
845         (pcb->state == CLOSE_WAIT))) {
846 #if LWIP_TCP_KEEPALIVE
847       if((u32_t)(tcp_ticks - pcb->tmr) >
848          (pcb->keep_idle + (pcb->keep_cnt*pcb->keep_intvl))
849          / TCP_SLOW_INTERVAL)
850 #else      
851       if((u32_t)(tcp_ticks - pcb->tmr) >
852          (pcb->keep_idle + TCP_MAXIDLE) / TCP_SLOW_INTERVAL)
853 #endif /* LWIP_TCP_KEEPALIVE */
854       {
855         LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: KEEPALIVE timeout. Aborting connection to %"U16_F".%"U16_F".%"U16_F".%"U16_F".\n",
856                                 ip4_addr1_16(&pcb->remote_ip), ip4_addr2_16(&pcb->remote_ip),
857                                 ip4_addr3_16(&pcb->remote_ip), ip4_addr4_16(&pcb->remote_ip)));
858         
859         ++pcb_remove;
860         ++pcb_reset;
861       }
862 #if LWIP_TCP_KEEPALIVE
863       else if((u32_t)(tcp_ticks - pcb->tmr) > 
864               (pcb->keep_idle + pcb->keep_cnt_sent * pcb->keep_intvl)
865               / TCP_SLOW_INTERVAL)
866 #else
867       else if((u32_t)(tcp_ticks - pcb->tmr) > 
868               (pcb->keep_idle + pcb->keep_cnt_sent * TCP_KEEPINTVL_DEFAULT) 
869               / TCP_SLOW_INTERVAL)
870 #endif /* LWIP_TCP_KEEPALIVE */
871       {
872         tcp_keepalive(pcb);
873         pcb->keep_cnt_sent++;
874       }
875     }
876
877     /* If this PCB has queued out of sequence data, but has been
878        inactive for too long, will drop the data (it will eventually
879        be retransmitted). */
880 #if TCP_QUEUE_OOSEQ
881     if (pcb->ooseq != NULL &&
882         (u32_t)tcp_ticks - pcb->tmr >= pcb->rto * TCP_OOSEQ_TIMEOUT) {
883       tcp_segs_free(pcb->ooseq);
884       pcb->ooseq = NULL;
885       LWIP_DEBUGF(TCP_CWND_DEBUG, ("tcp_slowtmr: dropping OOSEQ queued data\n"));
886     }
887 #endif /* TCP_QUEUE_OOSEQ */
888
889     /* Check if this PCB has stayed too long in SYN-RCVD */
890     if (pcb->state == SYN_RCVD) {
891       if ((u32_t)(tcp_ticks - pcb->tmr) >
892           TCP_SYN_RCVD_TIMEOUT / TCP_SLOW_INTERVAL) {
893         ++pcb_remove;
894         LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: removing pcb stuck in SYN-RCVD\n"));
895       }
896     }
897
898     /* Check if this PCB has stayed too long in LAST-ACK */
899     if (pcb->state == LAST_ACK) {
900       if ((u32_t)(tcp_ticks - pcb->tmr) > 2 * TCP_MSL / TCP_SLOW_INTERVAL) {
901         ++pcb_remove;
902         LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: removing pcb stuck in LAST-ACK\n"));
903       }
904     }
905
906     /* If the PCB should be removed, do it. */
907     if (pcb_remove) {
908       struct tcp_pcb *pcb2;
909       tcp_pcb_purge(pcb);
910       /* Remove PCB from tcp_active_pcbs list. */
911       if (prev != NULL) {
912         LWIP_ASSERT("tcp_slowtmr: middle tcp != tcp_active_pcbs", pcb != tcp_active_pcbs);
913         prev->next = pcb->next;
914       } else {
915         /* This PCB was the first. */
916         LWIP_ASSERT("tcp_slowtmr: first pcb == tcp_active_pcbs", tcp_active_pcbs == pcb);
917         tcp_active_pcbs = pcb->next;
918       }
919
920       TCP_EVENT_ERR(pcb->errf, pcb->callback_arg, ERR_ABRT);
921       if (pcb_reset) {
922         tcp_rst(pcb->snd_nxt, pcb->rcv_nxt, &pcb->local_ip, &pcb->remote_ip,
923           pcb->local_port, pcb->remote_port);
924       }
925
926       pcb2 = pcb;
927       pcb = pcb->next;
928       memp_free(MEMP_TCP_PCB, pcb2);
929     } else {
930       /* get the 'next' element now and work with 'prev' below (in case of abort) */
931       prev = pcb;
932       pcb = pcb->next;
933
934       /* We check if we should poll the connection. */
935       ++prev->polltmr;
936       if (prev->polltmr >= prev->pollinterval) {
937         prev->polltmr = 0;
938         LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: polling application\n"));
939         TCP_EVENT_POLL(prev, err);
940         /* if err == ERR_ABRT, 'prev' is already deallocated */
941         if (err == ERR_OK) {
942           tcp_output(prev);
943         }
944       }
945     }
946   }
947
948   
949   /* Steps through all of the TIME-WAIT PCBs. */
950   prev = NULL;
951   pcb = tcp_tw_pcbs;
952   while (pcb != NULL) {
953     LWIP_ASSERT("tcp_slowtmr: TIME-WAIT pcb->state == TIME-WAIT", pcb->state == TIME_WAIT);
954     pcb_remove = 0;
955
956     /* Check if this PCB has stayed long enough in TIME-WAIT */
957     if ((u32_t)(tcp_ticks - pcb->tmr) > 2 * TCP_MSL / TCP_SLOW_INTERVAL) {
958       ++pcb_remove;
959     }
960     
961
962
963     /* If the PCB should be removed, do it. */
964     if (pcb_remove) {
965       struct tcp_pcb *pcb2;
966       tcp_pcb_purge(pcb);
967       /* Remove PCB from tcp_tw_pcbs list. */
968       if (prev != NULL) {
969         LWIP_ASSERT("tcp_slowtmr: middle tcp != tcp_tw_pcbs", pcb != tcp_tw_pcbs);
970         prev->next = pcb->next;
971       } else {
972         /* This PCB was the first. */
973         LWIP_ASSERT("tcp_slowtmr: first pcb == tcp_tw_pcbs", tcp_tw_pcbs == pcb);
974         tcp_tw_pcbs = pcb->next;
975       }
976       pcb2 = pcb;
977       pcb = pcb->next;
978       memp_free(MEMP_TCP_PCB, pcb2);
979     } else {
980       prev = pcb;
981       pcb = pcb->next;
982     }
983   }
984 }
985
986 /**
987  * Is called every TCP_FAST_INTERVAL (250 ms) and process data previously
988  * "refused" by upper layer (application) and sends delayed ACKs.
989  *
990  * Automatically called from tcp_tmr().
991  */
992 void
993 tcp_fasttmr(void)
994 {
995   struct tcp_pcb *pcb = tcp_active_pcbs;
996
997   while(pcb != NULL) {
998     struct tcp_pcb *next = pcb->next;
999     /* If there is data which was previously "refused" by upper layer */
1000     if (pcb->refused_data != NULL) {
1001       /* Notify again application with data previously received. */
1002       err_t err;
1003       LWIP_DEBUGF(TCP_INPUT_DEBUG, ("tcp_fasttmr: notify kept packet\n"));
1004       TCP_EVENT_RECV(pcb, pcb->refused_data, ERR_OK, err);
1005       if (err == ERR_OK) {
1006         pcb->refused_data = NULL;
1007       } else if (err == ERR_ABRT) {
1008         /* if err == ERR_ABRT, 'pcb' is already deallocated */
1009         pcb = NULL;
1010       }
1011     }
1012
1013     /* send delayed ACKs */
1014     if (pcb && (pcb->flags & TF_ACK_DELAY)) {
1015       LWIP_DEBUGF(TCP_DEBUG, ("tcp_fasttmr: delayed ACK\n"));
1016       tcp_ack_now(pcb);
1017       tcp_output(pcb);
1018       pcb->flags &= ~(TF_ACK_DELAY | TF_ACK_NOW);
1019     }
1020
1021     pcb = next;
1022   }
1023 }
1024
1025 /**
1026  * Deallocates a list of TCP segments (tcp_seg structures).
1027  *
1028  * @param seg tcp_seg list of TCP segments to free
1029  */
1030 void
1031 tcp_segs_free(struct tcp_seg *seg)
1032 {
1033   while (seg != NULL) {
1034     struct tcp_seg *next = seg->next;
1035     tcp_seg_free(seg);
1036     seg = next;
1037   }
1038 }
1039
1040 /**
1041  * Frees a TCP segment (tcp_seg structure).
1042  *
1043  * @param seg single tcp_seg to free
1044  */
1045 void
1046 tcp_seg_free(struct tcp_seg *seg)
1047 {
1048   if (seg != NULL) {
1049     if (seg->p != NULL) {
1050       pbuf_free(seg->p);
1051 #if TCP_DEBUG
1052       seg->p = NULL;
1053 #endif /* TCP_DEBUG */
1054     }
1055     memp_free(MEMP_TCP_SEG, seg);
1056   }
1057 }
1058
1059 /**
1060  * Sets the priority of a connection.
1061  *
1062  * @param pcb the tcp_pcb to manipulate
1063  * @param prio new priority
1064  */
1065 void
1066 tcp_setprio(struct tcp_pcb *pcb, u8_t prio)
1067 {
1068   pcb->prio = prio;
1069 }
1070
1071 #if TCP_QUEUE_OOSEQ
1072 /**
1073  * Returns a copy of the given TCP segment.
1074  * The pbuf and data are not copied, only the pointers
1075  *
1076  * @param seg the old tcp_seg
1077  * @return a copy of seg
1078  */ 
1079 struct tcp_seg *
1080 tcp_seg_copy(struct tcp_seg *seg)
1081 {
1082   struct tcp_seg *cseg;
1083
1084   cseg = (struct tcp_seg *)memp_malloc(MEMP_TCP_SEG);
1085   if (cseg == NULL) {
1086     return NULL;
1087   }
1088   SMEMCPY((u8_t *)cseg, (const u8_t *)seg, sizeof(struct tcp_seg)); 
1089   pbuf_ref(cseg->p);
1090   return cseg;
1091 }
1092 #endif /* TCP_QUEUE_OOSEQ */
1093
1094 #if LWIP_CALLBACK_API
1095 /**
1096  * Default receive callback that is called if the user didn't register
1097  * a recv callback for the pcb.
1098  */
1099 err_t
1100 tcp_recv_null(void *arg, struct tcp_pcb *pcb, struct pbuf *p, err_t err)
1101 {
1102   LWIP_UNUSED_ARG(arg);
1103   if (p != NULL) {
1104     tcp_recved(pcb, p->tot_len);
1105     pbuf_free(p);
1106   } else if (err == ERR_OK) {
1107     return tcp_close(pcb);
1108   }
1109   return ERR_OK;
1110 }
1111 #endif /* LWIP_CALLBACK_API */
1112
1113 /**
1114  * Kills the oldest active connection that has lower priority than prio.
1115  *
1116  * @param prio minimum priority
1117  */
1118 static void
1119 tcp_kill_prio(u8_t prio)
1120 {
1121   struct tcp_pcb *pcb, *inactive;
1122   u32_t inactivity;
1123   u8_t mprio;
1124
1125
1126   mprio = TCP_PRIO_MAX;
1127   
1128   /* We kill the oldest active connection that has lower priority than prio. */
1129   inactivity = 0;
1130   inactive = NULL;
1131   for(pcb = tcp_active_pcbs; pcb != NULL; pcb = pcb->next) {
1132     if (pcb->prio <= prio &&
1133        pcb->prio <= mprio &&
1134        (u32_t)(tcp_ticks - pcb->tmr) >= inactivity) {
1135       inactivity = tcp_ticks - pcb->tmr;
1136       inactive = pcb;
1137       mprio = pcb->prio;
1138     }
1139   }
1140   if (inactive != NULL) {
1141     LWIP_DEBUGF(TCP_DEBUG, ("tcp_kill_prio: killing oldest PCB %p (%"S32_F")\n",
1142            (void *)inactive, inactivity));
1143     tcp_abort(inactive);
1144   }
1145 }
1146
1147 /**
1148  * Kills the oldest connection that is in TIME_WAIT state.
1149  * Called from tcp_alloc() if no more connections are available.
1150  */
1151 static void
1152 tcp_kill_timewait(void)
1153 {
1154   struct tcp_pcb *pcb, *inactive;
1155   u32_t inactivity;
1156
1157   inactivity = 0;
1158   inactive = NULL;
1159   /* Go through the list of TIME_WAIT pcbs and get the oldest pcb. */
1160   for(pcb = tcp_tw_pcbs; pcb != NULL; pcb = pcb->next) {
1161     if ((u32_t)(tcp_ticks - pcb->tmr) >= inactivity) {
1162       inactivity = tcp_ticks - pcb->tmr;
1163       inactive = pcb;
1164     }
1165   }
1166   if (inactive != NULL) {
1167     LWIP_DEBUGF(TCP_DEBUG, ("tcp_kill_timewait: killing oldest TIME-WAIT PCB %p (%"S32_F")\n",
1168            (void *)inactive, inactivity));
1169     tcp_abort(inactive);
1170   }
1171 }
1172
1173 /**
1174  * Allocate a new tcp_pcb structure.
1175  *
1176  * @param prio priority for the new pcb
1177  * @return a new tcp_pcb that initially is in state CLOSED
1178  */
1179 struct tcp_pcb *
1180 tcp_alloc(u8_t prio)
1181 {
1182   struct tcp_pcb *pcb;
1183   u32_t iss;
1184   
1185   pcb = (struct tcp_pcb *)memp_malloc(MEMP_TCP_PCB);
1186   if (pcb == NULL) {
1187     /* Try killing oldest connection in TIME-WAIT. */
1188     LWIP_DEBUGF(TCP_DEBUG, ("tcp_alloc: killing off oldest TIME-WAIT connection\n"));
1189     tcp_kill_timewait();
1190     /* Try to allocate a tcp_pcb again. */
1191     pcb = (struct tcp_pcb *)memp_malloc(MEMP_TCP_PCB);
1192     if (pcb == NULL) {
1193       /* Try killing active connections with lower priority than the new one. */
1194       LWIP_DEBUGF(TCP_DEBUG, ("tcp_alloc: killing connection with prio lower than %d\n", prio));
1195       tcp_kill_prio(prio);
1196       /* Try to allocate a tcp_pcb again. */
1197       pcb = (struct tcp_pcb *)memp_malloc(MEMP_TCP_PCB);
1198       if (pcb != NULL) {
1199         /* adjust err stats: memp_malloc failed twice before */
1200         MEMP_STATS_DEC(err, MEMP_TCP_PCB);
1201       }
1202     }
1203     if (pcb != NULL) {
1204       /* adjust err stats: timewait PCB was freed above */
1205       MEMP_STATS_DEC(err, MEMP_TCP_PCB);
1206     }
1207   }
1208   if (pcb != NULL) {
1209     memset(pcb, 0, sizeof(struct tcp_pcb));
1210     pcb->prio = prio;
1211     pcb->snd_buf = TCP_SND_BUF;
1212     pcb->snd_queuelen = 0;
1213     pcb->rcv_wnd = TCP_WND;
1214     pcb->rcv_ann_wnd = TCP_WND;
1215     pcb->tos = 0;
1216     pcb->ttl = TCP_TTL;
1217     /* As initial send MSS, we use TCP_MSS but limit it to 536.
1218        The send MSS is updated when an MSS option is received. */
1219     pcb->mss = (TCP_MSS > 536) ? 536 : TCP_MSS;
1220     pcb->rto = 3000 / TCP_SLOW_INTERVAL;
1221     pcb->sa = 0;
1222     pcb->sv = 3000 / TCP_SLOW_INTERVAL;
1223     pcb->rtime = -1;
1224     pcb->cwnd = 1;
1225     iss = tcp_next_iss();
1226     pcb->snd_wl2 = iss;
1227     pcb->snd_nxt = iss;
1228     pcb->lastack = iss;
1229     pcb->snd_lbb = iss;   
1230     pcb->tmr = tcp_ticks;
1231
1232     pcb->polltmr = 0;
1233
1234 #if LWIP_CALLBACK_API
1235     pcb->recv = tcp_recv_null;
1236 #endif /* LWIP_CALLBACK_API */  
1237     
1238     /* Init KEEPALIVE timer */
1239     pcb->keep_idle  = TCP_KEEPIDLE_DEFAULT;
1240     
1241 #if LWIP_TCP_KEEPALIVE
1242     pcb->keep_intvl = TCP_KEEPINTVL_DEFAULT;
1243     pcb->keep_cnt   = TCP_KEEPCNT_DEFAULT;
1244 #endif /* LWIP_TCP_KEEPALIVE */
1245
1246     pcb->keep_cnt_sent = 0;
1247   }
1248   return pcb;
1249 }
1250
1251 /**
1252  * Creates a new TCP protocol control block but doesn't place it on
1253  * any of the TCP PCB lists.
1254  * The pcb is not put on any list until binding using tcp_bind().
1255  *
1256  * @internal: Maybe there should be a idle TCP PCB list where these
1257  * PCBs are put on. Port reservation using tcp_bind() is implemented but
1258  * allocated pcbs that are not bound can't be killed automatically if wanting
1259  * to allocate a pcb with higher prio (@see tcp_kill_prio())
1260  *
1261  * @return a new tcp_pcb that initially is in state CLOSED
1262  */
1263 struct tcp_pcb *
1264 tcp_new(void)
1265 {
1266   return tcp_alloc(TCP_PRIO_NORMAL);
1267 }
1268
1269 /**
1270  * Used to specify the argument that should be passed callback
1271  * functions.
1272  *
1273  * @param pcb tcp_pcb to set the callback argument
1274  * @param arg void pointer argument to pass to callback functions
1275  */ 
1276 void
1277 tcp_arg(struct tcp_pcb *pcb, void *arg)
1278 {  
1279   pcb->callback_arg = arg;
1280 }
1281 #if LWIP_CALLBACK_API
1282
1283 /**
1284  * Used to specify the function that should be called when a TCP
1285  * connection receives data.
1286  *
1287  * @param pcb tcp_pcb to set the recv callback
1288  * @param recv callback function to call for this pcb when data is received
1289  */ 
1290 void
1291 tcp_recv(struct tcp_pcb *pcb, tcp_recv_fn recv)
1292 {
1293   pcb->recv = recv;
1294 }
1295
1296 /**
1297  * Used to specify the function that should be called when TCP data
1298  * has been successfully delivered to the remote host.
1299  *
1300  * @param pcb tcp_pcb to set the sent callback
1301  * @param sent callback function to call for this pcb when data is successfully sent
1302  */ 
1303 void
1304 tcp_sent(struct tcp_pcb *pcb, tcp_sent_fn sent)
1305 {
1306   pcb->sent = sent;
1307 }
1308
1309 /**
1310  * Used to specify the function that should be called when a fatal error
1311  * has occured on the connection.
1312  *
1313  * @param pcb tcp_pcb to set the err callback
1314  * @param err callback function to call for this pcb when a fatal error
1315  *        has occured on the connection
1316  */ 
1317 void
1318 tcp_err(struct tcp_pcb *pcb, tcp_err_fn err)
1319 {
1320   pcb->errf = err;
1321 }
1322
1323 /**
1324  * Used for specifying the function that should be called when a
1325  * LISTENing connection has been connected to another host.
1326  *
1327  * @param pcb tcp_pcb to set the accept callback
1328  * @param accept callback function to call for this pcb when LISTENing
1329  *        connection has been connected to another host
1330  */ 
1331 void
1332 tcp_accept(struct tcp_pcb *pcb, tcp_accept_fn accept)
1333 {
1334   pcb->accept = accept;
1335 }
1336 #endif /* LWIP_CALLBACK_API */
1337
1338
1339 /**
1340  * Used to specify the function that should be called periodically
1341  * from TCP. The interval is specified in terms of the TCP coarse
1342  * timer interval, which is called twice a second.
1343  *
1344  */ 
1345 void
1346 tcp_poll(struct tcp_pcb *pcb, tcp_poll_fn poll, u8_t interval)
1347 {
1348 #if LWIP_CALLBACK_API
1349   pcb->poll = poll;
1350 #else /* LWIP_CALLBACK_API */  
1351   LWIP_UNUSED_ARG(poll);
1352 #endif /* LWIP_CALLBACK_API */  
1353   pcb->pollinterval = interval;
1354 }
1355
1356 /**
1357  * Purges a TCP PCB. Removes any buffered data and frees the buffer memory
1358  * (pcb->ooseq, pcb->unsent and pcb->unacked are freed).
1359  *
1360  * @param pcb tcp_pcb to purge. The pcb itself is not deallocated!
1361  */
1362 void
1363 tcp_pcb_purge(struct tcp_pcb *pcb)
1364 {
1365   if (pcb->state != CLOSED &&
1366      pcb->state != TIME_WAIT &&
1367      pcb->state != LISTEN) {
1368
1369     LWIP_DEBUGF(TCP_DEBUG, ("tcp_pcb_purge\n"));
1370
1371 #if TCP_LISTEN_BACKLOG
1372     if (pcb->state == SYN_RCVD) {
1373       /* Need to find the corresponding listen_pcb and decrease its accepts_pending */
1374       struct tcp_pcb_listen *lpcb;
1375       LWIP_ASSERT("tcp_pcb_purge: pcb->state == SYN_RCVD but tcp_listen_pcbs is NULL",
1376         tcp_listen_pcbs.listen_pcbs != NULL);
1377       for (lpcb = tcp_listen_pcbs.listen_pcbs; lpcb != NULL; lpcb = lpcb->next) {
1378         if ((lpcb->local_port == pcb->local_port) &&
1379             (ip_addr_isany(&lpcb->local_ip) ||
1380              ip_addr_cmp(&pcb->local_ip, &lpcb->local_ip))) {
1381             /* port and address of the listen pcb match the timed-out pcb */
1382             LWIP_ASSERT("tcp_pcb_purge: listen pcb does not have accepts pending",
1383               lpcb->accepts_pending > 0);
1384             lpcb->accepts_pending--;
1385             break;
1386           }
1387       }
1388     }
1389 #endif /* TCP_LISTEN_BACKLOG */
1390
1391
1392     if (pcb->refused_data != NULL) {
1393       LWIP_DEBUGF(TCP_DEBUG, ("tcp_pcb_purge: data left on ->refused_data\n"));
1394       pbuf_free(pcb->refused_data);
1395       pcb->refused_data = NULL;
1396     }
1397     if (pcb->unsent != NULL) {
1398       LWIP_DEBUGF(TCP_DEBUG, ("tcp_pcb_purge: not all data sent\n"));
1399     }
1400     if (pcb->unacked != NULL) {
1401       LWIP_DEBUGF(TCP_DEBUG, ("tcp_pcb_purge: data left on ->unacked\n"));
1402     }
1403 #if TCP_QUEUE_OOSEQ
1404     if (pcb->ooseq != NULL) {
1405       LWIP_DEBUGF(TCP_DEBUG, ("tcp_pcb_purge: data left on ->ooseq\n"));
1406     }
1407     tcp_segs_free(pcb->ooseq);
1408     pcb->ooseq = NULL;
1409 #endif /* TCP_QUEUE_OOSEQ */
1410
1411     /* Stop the retransmission timer as it will expect data on unacked
1412        queue if it fires */
1413     pcb->rtime = -1;
1414
1415     tcp_segs_free(pcb->unsent);
1416     tcp_segs_free(pcb->unacked);
1417     pcb->unacked = pcb->unsent = NULL;
1418 #if TCP_OVERSIZE
1419     pcb->unsent_oversize = 0;
1420 #endif /* TCP_OVERSIZE */
1421   }
1422 }
1423
1424 /**
1425  * Purges the PCB and removes it from a PCB list. Any delayed ACKs are sent first.
1426  *
1427  * @param pcblist PCB list to purge.
1428  * @param pcb tcp_pcb to purge. The pcb itself is NOT deallocated!
1429  */
1430 void
1431 tcp_pcb_remove(struct tcp_pcb **pcblist, struct tcp_pcb *pcb)
1432 {
1433   TCP_RMV(pcblist, pcb);
1434
1435   tcp_pcb_purge(pcb);
1436   
1437   /* if there is an outstanding delayed ACKs, send it */
1438   if (pcb->state != TIME_WAIT &&
1439      pcb->state != LISTEN &&
1440      pcb->flags & TF_ACK_DELAY) {
1441     pcb->flags |= TF_ACK_NOW;
1442     tcp_output(pcb);
1443   }
1444
1445   if (pcb->state != LISTEN) {
1446     LWIP_ASSERT("unsent segments leaking", pcb->unsent == NULL);
1447     LWIP_ASSERT("unacked segments leaking", pcb->unacked == NULL);
1448 #if TCP_QUEUE_OOSEQ
1449     LWIP_ASSERT("ooseq segments leaking", pcb->ooseq == NULL);
1450 #endif /* TCP_QUEUE_OOSEQ */
1451   }
1452
1453   pcb->state = CLOSED;
1454
1455   LWIP_ASSERT("tcp_pcb_remove: tcp_pcbs_sane()", tcp_pcbs_sane());
1456 }
1457
1458 /**
1459  * Calculates a new initial sequence number for new connections.
1460  *
1461  * @return u32_t pseudo random sequence number
1462  */
1463 u32_t
1464 tcp_next_iss(void)
1465 {
1466   static u32_t iss = 6510;
1467   
1468   iss += tcp_ticks;       /* XXX */
1469   return iss;
1470 }
1471
1472 #if TCP_CALCULATE_EFF_SEND_MSS
1473 /**
1474  * Calcluates the effective send mss that can be used for a specific IP address
1475  * by using ip_route to determin the netif used to send to the address and
1476  * calculating the minimum of TCP_MSS and that netif's mtu (if set).
1477  */
1478 u16_t
1479 tcp_eff_send_mss(u16_t sendmss, ip_addr_t *addr)
1480 {
1481   u16_t mss_s;
1482   struct netif *outif;
1483
1484   outif = ip_route(addr);
1485   if ((outif != NULL) && (outif->mtu != 0)) {
1486     mss_s = outif->mtu - IP_HLEN - TCP_HLEN;
1487     /* RFC 1122, chap 4.2.2.6:
1488      * Eff.snd.MSS = min(SendMSS+20, MMS_S) - TCPhdrsize - IPoptionsize
1489      * We correct for TCP options in tcp_write(), and don't support IP options.
1490      */
1491     sendmss = LWIP_MIN(sendmss, mss_s);
1492   }
1493   return sendmss;
1494 }
1495 #endif /* TCP_CALCULATE_EFF_SEND_MSS */
1496
1497 const char*
1498 tcp_debug_state_str(enum tcp_state s)
1499 {
1500   return tcp_state_str[s];
1501 }
1502
1503 #if TCP_DEBUG || TCP_INPUT_DEBUG || TCP_OUTPUT_DEBUG
1504 /**
1505  * Print a tcp header for debugging purposes.
1506  *
1507  * @param tcphdr pointer to a struct tcp_hdr
1508  */
1509 void
1510 tcp_debug_print(struct tcp_hdr *tcphdr)
1511 {
1512   LWIP_DEBUGF(TCP_DEBUG, ("TCP header:\n"));
1513   LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
1514   LWIP_DEBUGF(TCP_DEBUG, ("|    %5"U16_F"      |    %5"U16_F"      | (src port, dest port)\n",
1515          ntohs(tcphdr->src), ntohs(tcphdr->dest)));
1516   LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
1517   LWIP_DEBUGF(TCP_DEBUG, ("|           %010"U32_F"          | (seq no)\n",
1518           ntohl(tcphdr->seqno)));
1519   LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
1520   LWIP_DEBUGF(TCP_DEBUG, ("|           %010"U32_F"          | (ack no)\n",
1521          ntohl(tcphdr->ackno)));
1522   LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
1523   LWIP_DEBUGF(TCP_DEBUG, ("| %2"U16_F" |   |%"U16_F"%"U16_F"%"U16_F"%"U16_F"%"U16_F"%"U16_F"|     %5"U16_F"     | (hdrlen, flags (",
1524        TCPH_HDRLEN(tcphdr),
1525          TCPH_FLAGS(tcphdr) >> 5 & 1,
1526          TCPH_FLAGS(tcphdr) >> 4 & 1,
1527          TCPH_FLAGS(tcphdr) >> 3 & 1,
1528          TCPH_FLAGS(tcphdr) >> 2 & 1,
1529          TCPH_FLAGS(tcphdr) >> 1 & 1,
1530          TCPH_FLAGS(tcphdr) & 1,
1531          ntohs(tcphdr->wnd)));
1532   tcp_debug_print_flags(TCPH_FLAGS(tcphdr));
1533   LWIP_DEBUGF(TCP_DEBUG, ("), win)\n"));
1534   LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
1535   LWIP_DEBUGF(TCP_DEBUG, ("|    0x%04"X16_F"     |     %5"U16_F"     | (chksum, urgp)\n",
1536          ntohs(tcphdr->chksum), ntohs(tcphdr->urgp)));
1537   LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n"));
1538 }
1539
1540 /**
1541  * Print a tcp state for debugging purposes.
1542  *
1543  * @param s enum tcp_state to print
1544  */
1545 void
1546 tcp_debug_print_state(enum tcp_state s)
1547 {
1548   LWIP_DEBUGF(TCP_DEBUG, ("State: %s\n", tcp_state_str[s]));
1549 }
1550
1551 /**
1552  * Print tcp flags for debugging purposes.
1553  *
1554  * @param flags tcp flags, all active flags are printed
1555  */
1556 void
1557 tcp_debug_print_flags(u8_t flags)
1558 {
1559   if (flags & TCP_FIN) {
1560     LWIP_DEBUGF(TCP_DEBUG, ("FIN "));
1561   }
1562   if (flags & TCP_SYN) {
1563     LWIP_DEBUGF(TCP_DEBUG, ("SYN "));
1564   }
1565   if (flags & TCP_RST) {
1566     LWIP_DEBUGF(TCP_DEBUG, ("RST "));
1567   }
1568   if (flags & TCP_PSH) {
1569     LWIP_DEBUGF(TCP_DEBUG, ("PSH "));
1570   }
1571   if (flags & TCP_ACK) {
1572     LWIP_DEBUGF(TCP_DEBUG, ("ACK "));
1573   }
1574   if (flags & TCP_URG) {
1575     LWIP_DEBUGF(TCP_DEBUG, ("URG "));
1576   }
1577   if (flags & TCP_ECE) {
1578     LWIP_DEBUGF(TCP_DEBUG, ("ECE "));
1579   }
1580   if (flags & TCP_CWR) {
1581     LWIP_DEBUGF(TCP_DEBUG, ("CWR "));
1582   }
1583   LWIP_DEBUGF(TCP_DEBUG, ("\n"));
1584 }
1585
1586 /**
1587  * Print all tcp_pcbs in every list for debugging purposes.
1588  */
1589 void
1590 tcp_debug_print_pcbs(void)
1591 {
1592   struct tcp_pcb *pcb;
1593   LWIP_DEBUGF(TCP_DEBUG, ("Active PCB states:\n"));
1594   for(pcb = tcp_active_pcbs; pcb != NULL; pcb = pcb->next) {
1595     LWIP_DEBUGF(TCP_DEBUG, ("Local port %"U16_F", foreign port %"U16_F" snd_nxt %"U32_F" rcv_nxt %"U32_F" ",
1596                        pcb->local_port, pcb->remote_port,
1597                        pcb->snd_nxt, pcb->rcv_nxt));
1598     tcp_debug_print_state(pcb->state);
1599   }    
1600   LWIP_DEBUGF(TCP_DEBUG, ("Listen PCB states:\n"));
1601   for(pcb = (struct tcp_pcb *)tcp_listen_pcbs.pcbs; pcb != NULL; pcb = pcb->next) {
1602     LWIP_DEBUGF(TCP_DEBUG, ("Local port %"U16_F", foreign port %"U16_F" snd_nxt %"U32_F" rcv_nxt %"U32_F" ",
1603                        pcb->local_port, pcb->remote_port,
1604                        pcb->snd_nxt, pcb->rcv_nxt));
1605     tcp_debug_print_state(pcb->state);
1606   }    
1607   LWIP_DEBUGF(TCP_DEBUG, ("TIME-WAIT PCB states:\n"));
1608   for(pcb = tcp_tw_pcbs; pcb != NULL; pcb = pcb->next) {
1609     LWIP_DEBUGF(TCP_DEBUG, ("Local port %"U16_F", foreign port %"U16_F" snd_nxt %"U32_F" rcv_nxt %"U32_F" ",
1610                        pcb->local_port, pcb->remote_port,
1611                        pcb->snd_nxt, pcb->rcv_nxt));
1612     tcp_debug_print_state(pcb->state);
1613   }    
1614 }
1615
1616 /**
1617  * Check state consistency of the tcp_pcb lists.
1618  */
1619 s16_t
1620 tcp_pcbs_sane(void)
1621 {
1622   struct tcp_pcb *pcb;
1623   for(pcb = tcp_active_pcbs; pcb != NULL; pcb = pcb->next) {
1624     LWIP_ASSERT("tcp_pcbs_sane: active pcb->state != CLOSED", pcb->state != CLOSED);
1625     LWIP_ASSERT("tcp_pcbs_sane: active pcb->state != LISTEN", pcb->state != LISTEN);
1626     LWIP_ASSERT("tcp_pcbs_sane: active pcb->state != TIME-WAIT", pcb->state != TIME_WAIT);
1627   }
1628   for(pcb = tcp_tw_pcbs; pcb != NULL; pcb = pcb->next) {
1629     LWIP_ASSERT("tcp_pcbs_sane: tw pcb->state == TIME-WAIT", pcb->state == TIME_WAIT);
1630   }
1631   return 1;
1632 }
1633 #endif /* TCP_DEBUG */
1634
1635 #endif /* LWIP_TCP */