1/*
2 * Copyright (c) 2001-2004 Swedish Institute of Computer Science.
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without modification,
6 * are permitted provided that the following conditions are met:
7 *
8 * 1. Redistributions of source code must retain the above copyright notice,
9 *    this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright notice,
11 *    this list of conditions and the following disclaimer in the documentation
12 *    and/or other materials provided with the distribution.
13 * 3. The name of the author may not be used to endorse or promote products
14 *    derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
17 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
18 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
19 * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
20 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
21 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
24 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
25 * OF SUCH DAMAGE.
26 *
27 * This file is part of the lwIP TCP/IP stack.
28 *
29 * Author: Adam Dunkels <adam@sics.se>
30 *
31 */
32#ifndef __LWIP_TCP_H__
33#define __LWIP_TCP_H__
34
35#include "lwip/opt.h"
36
37#if LWIP_TCP                    /* don't build if not configured for use in lwipopts.h */
38
39#include "lwip/sys.h"
40#include "lwip/mem.h"
41#include "lwip/pbuf.h"
42#include "lwip/ip.h"
43#include "lwip/icmp.h"
44#include "lwip/err.h"
45
46#ifdef __cplusplus
47extern "C" {
48#endif
49
50    struct tcp_pcb;
51
52/* Functions for interfacing with TCP: */
53
54/* Lower layer interface to TCP: */
55#define tcp_init()              /* Compatibility define, not init needed. */
56    void tcp_tmr(void);         /* Must be called every
57                                   TCP_TMR_INTERVAL
58                                   ms. (Typically 250 ms). */
59/* Application program's interface: */
60    struct tcp_pcb *tcp_new(void);
61    struct tcp_pcb *tcp_alloc(u8_t prio);
62
63    void tcp_arg(struct tcp_pcb *pcb, void *arg);
64    void tcp_accept(struct tcp_pcb *pcb,
65                    err_t(*accept) (void *arg, struct tcp_pcb * newpcb,
66                                    err_t err));
67    void tcp_recv(struct tcp_pcb *pcb,
68                  err_t(*recv) (void *arg, struct tcp_pcb * tpcb,
69                                struct pbuf * p, err_t err));
70    void tcp_sent(struct tcp_pcb *pcb,
71                  err_t(*sent) (void *arg, struct tcp_pcb * tpcb, u16_t len));
72    void tcp_poll(struct tcp_pcb *pcb,
73                  err_t(*poll) (void *arg, struct tcp_pcb * tpcb),
74                  u8_t interval);
75    void tcp_err(struct tcp_pcb *pcb, void (*err) (void *arg, err_t err));
76
77#define          tcp_mss(pcb)      ((pcb)->mss)
78#define          tcp_sndbuf(pcb)   ((pcb)->snd_buf)
79
80#if TCP_LISTEN_BACKLOG
81#define          tcp_accepted(pcb) (((struct tcp_pcb_listen *)(pcb))->accepts_pending--)
82#else                           /* TCP_LISTEN_BACKLOG */
83#define          tcp_accepted(pcb)
84#endif                          /* TCP_LISTEN_BACKLOG */
85
86    void tcp_recved(struct tcp_pcb *pcb, u16_t len);
87    err_t tcp_bind(struct tcp_pcb *pcb, struct ip_addr *ipaddr, u16_t port);
88    err_t tcp_redirect(struct tcp_pcb *pcb,
89                       struct ip_addr *local_ip,
90                       u16_t local_port,
91                       struct ip_addr *remote_ip, u16_t remote_port);
92     err_t
93      tcp_pause(struct tcp_pcb *pcb, struct ip_addr *local_ip, u16_t local_port,
94                struct ip_addr *remote_ip, u16_t remote_port);
95    err_t tcp_connect(struct tcp_pcb *pcb, struct ip_addr *ipaddr,
96                      u16_t port, err_t(*connected) (void *arg,
97                                                     struct tcp_pcb * tpcb,
98                                                     err_t err));
99
100    struct tcp_pcb *tcp_listen_with_backlog(struct tcp_pcb *pcb, u8_t backlog);
101#define          tcp_listen(pcb) tcp_listen_with_backlog(pcb, TCP_DEFAULT_LISTEN_BACKLOG)
102
103    void tcp_abandon(struct tcp_pcb *pcb, int reset);
104#define          tcp_abort(pcb) tcp_abandon((pcb), 1)
105    err_t tcp_close(struct tcp_pcb *pcb);
106
107/* Flags for "apiflags" parameter in tcp_write and tcp_enqueue */
108#define TCP_WRITE_FLAG_COPY 0x01
109#define TCP_WRITE_FLAG_MORE 0x02
110
111    err_t tcp_write(struct tcp_pcb *pcb, const void *dataptr, u16_t len,
112                    u8_t apiflags);
113
114    void tcp_setprio(struct tcp_pcb *pcb, u8_t prio);
115
116#define TCP_PRIO_MIN    1
117#define TCP_PRIO_NORMAL 64
118#define TCP_PRIO_MAX    127
119
120/* It is also possible to call these two functions at the right
121   intervals (instead of calling tcp_tmr()). */
122    void tcp_slowtmr(void);
123    void tcp_fasttmr(void);
124
125
126/* Only used by IP to pass a TCP segment to TCP: */
127    void tcp_input(struct pbuf *p, struct netif *inp);
128/* Used within the TCP code only: */
129    err_t tcp_output(struct tcp_pcb *pcb);
130    void tcp_rexmit(struct tcp_pcb *pcb);
131    void tcp_rexmit_rto(struct tcp_pcb *pcb);
132    u32_t tcp_update_rcv_ann_wnd(struct tcp_pcb *pcb);
133
134/**
135 * This is the Nagle algorithm: try to combine user data to send as few TCP
136 * segments as possible. Only send if
137 * - no previously transmitted data on the connection remains unacknowledged or
138 * - the TF_NODELAY flag is set (nagle algorithm turned off for this pcb) or
139 * - the only unsent segment is at least pcb->mss bytes long (or there is more
140 *   than one unsent segment - with lwIP, this can happen although unsent->len < mss)
141 */
142#define tcp_do_output_nagle(tpcb) ((((tpcb)->unacked == NULL) || \
143                            ((tpcb)->flags & TF_NODELAY) || \
144                            (((tpcb)->unsent != NULL) && (((tpcb)->unsent->next != NULL) || \
145                              ((tpcb)->unsent->len >= (tpcb)->mss))) \
146                            ) ? 1 : 0)
147#define tcp_output_nagle(tpcb) (tcp_do_output_nagle(tpcb) ? tcp_output(tpcb) : ERR_OK)
148
149
150#define TCP_SEQ_LT(a,b)     ((s32_t)((a)-(b)) < 0)
151#define TCP_SEQ_LEQ(a,b)    ((s32_t)((a)-(b)) <= 0)
152#define TCP_SEQ_GT(a,b)     ((s32_t)((a)-(b)) > 0)
153#define TCP_SEQ_GEQ(a,b)    ((s32_t)((a)-(b)) >= 0)
154/* is b<=a<=c? */
155#if 0                           /* see bug #10548 */
156#define TCP_SEQ_BETWEEN(a,b,c) ((c)-(b) >= (a)-(b))
157#endif
158#define TCP_SEQ_BETWEEN(a,b,c) (TCP_SEQ_GEQ(a,b) && TCP_SEQ_LEQ(a,c))
159#define TCP_FIN 0x01U
160#define TCP_SYN 0x02U
161#define TCP_RST 0x04U
162#define TCP_PSH 0x08U
163#define TCP_ACK 0x10U
164#define TCP_URG 0x20U
165#define TCP_ECE 0x40U
166#define TCP_CWR 0x80U
167
168#define TCP_FLAGS 0x3fU
169
170/* Length of the TCP header, excluding options. */
171#define TCP_HLEN 20
172
173#ifndef TCP_TMR_INTERVAL
174#define TCP_TMR_INTERVAL       250      /* The TCP timer interval in milliseconds. */
175#endif                          /* TCP_TMR_INTERVAL */
176
177#ifndef TCP_FAST_INTERVAL
178#define TCP_FAST_INTERVAL      TCP_TMR_INTERVAL /* the fine grained timeout in milliseconds */
179#endif                          /* TCP_FAST_INTERVAL */
180
181#ifndef TCP_SLOW_INTERVAL
182#define TCP_SLOW_INTERVAL      (2*TCP_TMR_INTERVAL)     /* the coarse grained timeout in milliseconds */
183#endif                          /* TCP_SLOW_INTERVAL */
184
185#define TCP_FIN_WAIT_TIMEOUT 20000      /* milliseconds */
186#define TCP_SYN_RCVD_TIMEOUT 20000      /* milliseconds */
187
188#define TCP_OOSEQ_TIMEOUT        6U     /* x RTO */
189
190#ifndef TCP_MSL
191#define TCP_MSL 60000UL         /* The maximum segment lifetime in milliseconds */
192#endif
193
194/* Keepalive values, compliant with RFC 1122. Don't change this unless you know what you're doing */
195#ifndef  TCP_KEEPIDLE_DEFAULT
196#define  TCP_KEEPIDLE_DEFAULT     7200000UL     /* Default KEEPALIVE timer in milliseconds */
197#endif
198
199#ifndef  TCP_KEEPINTVL_DEFAULT
200#define  TCP_KEEPINTVL_DEFAULT    75000UL       /* Default Time between KEEPALIVE probes in milliseconds */
201#endif
202
203#ifndef  TCP_KEEPCNT_DEFAULT
204#define  TCP_KEEPCNT_DEFAULT      9U    /* Default Counter for KEEPALIVE probes */
205#endif
206
207#define  TCP_MAXIDLE              TCP_KEEPCNT_DEFAULT * TCP_KEEPINTVL_DEFAULT   /* Maximum KEEPALIVE probe time */
208
209/* Fields are (of course) in network byte order.
210 * Some fields are converted to host byte order in tcp_input().
211 */
212#ifdef PACK_STRUCT_USE_INCLUDES
213#include "arch/bpstruct.h"
214#endif
215     PACK_STRUCT_BEGIN struct tcp_hdr {
216        PACK_STRUCT_FIELD(u16_t src);
217        PACK_STRUCT_FIELD(u16_t dest);
218        PACK_STRUCT_FIELD(u32_t seqno);
219        PACK_STRUCT_FIELD(u32_t ackno);
220        PACK_STRUCT_FIELD(u16_t _hdrlen_rsvd_flags);
221        PACK_STRUCT_FIELD(u16_t wnd);
222        PACK_STRUCT_FIELD(u16_t chksum);
223        PACK_STRUCT_FIELD(u16_t urgp);
224    } PACK_STRUCT_STRUCT;
225     PACK_STRUCT_END
226#ifdef PACK_STRUCT_USE_INCLUDES
227#include "arch/epstruct.h"
228#endif
229#define TCPH_OFFSET(phdr) (ntohs((phdr)->_hdrlen_rsvd_flags) >> 8)
230#define TCPH_HDRLEN(phdr) (ntohs((phdr)->_hdrlen_rsvd_flags) >> 12)
231#define TCPH_FLAGS(phdr)  (ntohs((phdr)->_hdrlen_rsvd_flags) & TCP_FLAGS)
232#define TCPH_OFFSET_SET(phdr, offset) (phdr)->_hdrlen_rsvd_flags = htons(((offset) << 8) | TCPH_FLAGS(phdr))
233#define TCPH_HDRLEN_SET(phdr, len) (phdr)->_hdrlen_rsvd_flags = htons(((len) << 12) | TCPH_FLAGS(phdr))
234#define TCPH_FLAGS_SET(phdr, flags) (phdr)->_hdrlen_rsvd_flags = htons((ntohs((phdr)->_hdrlen_rsvd_flags) & ~TCP_FLAGS) | (flags))
235#define TCPH_SET_FLAG(phdr, flags ) (phdr)->_hdrlen_rsvd_flags = htons(ntohs((phdr)->_hdrlen_rsvd_flags) | (flags))
236#define TCPH_UNSET_FLAG(phdr, flags) (phdr)->_hdrlen_rsvd_flags = htons(ntohs((phdr)->_hdrlen_rsvd_flags) | (TCPH_FLAGS(phdr) & ~(flags)) )
237#define TCP_TCPLEN(seg) ((seg)->len + ((TCPH_FLAGS((seg)->tcphdr) & TCP_FIN || \
238          TCPH_FLAGS((seg)->tcphdr) & TCP_SYN)? 1: 0))
239      enum tcp_state {
240        CLOSED = 0,
241        LISTEN = 1,
242        SYN_SENT = 2,
243        SYN_RCVD = 3,
244        ESTABLISHED = 4,
245        FIN_WAIT_1 = 5,
246        FIN_WAIT_2 = 6,
247        CLOSE_WAIT = 7,
248        CLOSING = 8,
249        LAST_ACK = 9,
250        TIME_WAIT = 10
251    };
252
253/** Flags used on input processing, not on pcb->flags
254*/
255#define TF_RESET     (u8_t)0x08U        /* Connection was reset. */
256#define TF_CLOSED    (u8_t)0x10U        /* Connection was sucessfully closed. */
257#define TF_GOT_FIN   (u8_t)0x20U        /* Connection was closed by the remote end. */
258
259
260#if LWIP_CALLBACK_API
261    /* Function to call when a listener has been connected.
262     * @param arg user-supplied argument (tcp_pcb.callback_arg)
263     * @param pcb a new tcp_pcb that now is connected
264     * @param err an error argument (TODO: that is current always ERR_OK?)
265     * @return ERR_OK: accept the new connection,
266     *                 any other err_t abortsthe new connection
267     */
268#define DEF_ACCEPT_CALLBACK  err_t (* accept)(void *arg, struct tcp_pcb *newpcb, err_t err)
269#else                           /* LWIP_CALLBACK_API */
270#define DEF_ACCEPT_CALLBACK
271#endif                          /* LWIP_CALLBACK_API */
272
273/**
274 * members common to struct tcp_pcb and struct tcp_listen_pcb
275 */
276#define TCP_PCB_COMMON(type) \
277  type *next; /* for the linked list */ \
278  enum tcp_state state; /* TCP state */ \
279  u8_t prio; \
280  void *callback_arg; \
281  /* ports are in host byte order */ \
282  u16_t local_port; \
283  /* the accept callback for listen- and normal pcbs, if LWIP_CALLBACK_API */ \
284  DEF_ACCEPT_CALLBACK
285
286
287/* the TCP protocol control block */
288    struct tcp_pcb {
289/** common PCB members */
290        IP_PCB;
291/** protocol specific PCB members */
292        TCP_PCB_COMMON(struct tcp_pcb);
293
294        /* ports are in host byte order */
295        u16_t remote_port;
296
297        u8_t flags;
298#define TF_ACK_DELAY   ((u8_t)0x01U)    /* Delayed ACK. */
299#define TF_ACK_NOW     ((u8_t)0x02U)    /* Immediate ACK. */
300#define TF_INFR        ((u8_t)0x04U)    /* In fast recovery. */
301#define TF_TIMESTAMP   ((u8_t)0x08U)    /* Timestamp option enabled */
302#define TF_FIN         ((u8_t)0x20U)    /* Connection was closed locally (FIN segment enqueued). */
303#define TF_NODELAY     ((u8_t)0x40U)    /* Disable Nagle algorithm */
304#define TF_NAGLEMEMERR ((u8_t)0x80U)    /* nagle enabled, memerr, try to output to prevent delayed ACK to happen */
305
306        /* the rest of the fields are in host byte order
307           as we have to do some math with them */
308        /* receiver variables */
309        u32_t rcv_nxt;          /* next seqno expected */
310        u16_t rcv_wnd;          /* receiver window available */
311        u16_t rcv_ann_wnd;      /* receiver window to announce */
312        u32_t rcv_ann_right_edge;       /* announced right edge of window */
313
314        /* Timers */
315        u32_t tmr;
316        u8_t polltmr, pollinterval;
317
318        /* Retransmission timer. */
319        s16_t rtime;
320
321        u16_t mss;              /* maximum segment size */
322
323        /* RTT (round trip time) estimation variables */
324        u32_t rttest;           /* RTT estimate in 500ms ticks */
325        u32_t rtseq;            /* sequence number being timed */
326        s16_t sa, sv;           /* @todo document this */
327
328        s16_t rto;              /* retransmission time-out */
329        u8_t nrtx;              /* number of retransmissions */
330
331        /* fast retransmit/recovery */
332        u32_t lastack;          /* Highest acknowledged seqno. */
333        u8_t dupacks;
334
335        /* congestion avoidance/control variables */
336        u16_t cwnd;
337        u16_t ssthresh;
338
339        /* sender variables */
340        u32_t snd_nxt;          /* next new seqno to be sent */
341        u16_t snd_wnd;          /* sender window */
342        u32_t snd_wl1, snd_wl2; /* Sequence and acknowledgement numbers of last
343                                   window update. */
344        u32_t snd_lbb;          /* Sequence number of next byte to be buffered. */
345
346        u16_t acked;
347
348        u16_t snd_buf;          /* Available buffer space for sending (in bytes). */
349#define TCP_SNDQUEUELEN_OVERFLOW (0xffff-3)
350        u16_t snd_queuelen;     /* Available buffer space for sending (in tcp_segs). */
351
352
353        /* These are ordered by sequence number: */
354        struct tcp_seg *unsent; /* Unsent (queued) segments. */
355        struct tcp_seg *unacked;        /* Sent but unacknowledged segments. */
356#if TCP_QUEUE_OOSEQ
357        struct tcp_seg *ooseq;  /* Received out of sequence segments. */
358#endif                          /* TCP_QUEUE_OOSEQ */
359
360        struct pbuf *refused_data;      /* Data previously received but not yet taken by upper layer */
361
362#if LWIP_CALLBACK_API
363        /* Function to be called when more send buffer space is available.
364         * @param arg user-supplied argument (tcp_pcb.callback_arg)
365         * @param pcb the tcp_pcb which has send buffer space available
366         * @param space the amount of bytes available
367         * @return ERR_OK: try to send some data by calling tcp_output
368         */
369         err_t(*sent) (void *arg, struct tcp_pcb * pcb, u16_t space);
370
371        /* Function to be called when (in-sequence) data has arrived.
372         * @param arg user-supplied argument (tcp_pcb.callback_arg)
373         * @param pcb the tcp_pcb for which data has arrived
374         * @param p the packet buffer which arrived
375         * @param err an error argument (TODO: that is current always ERR_OK?)
376         * @return ERR_OK: try to send some data by calling tcp_output
377         */
378         err_t(*recv) (void *arg, struct tcp_pcb * pcb, struct pbuf * p,
379                       err_t err);
380
381        /* Function to be called when a connection has been set up.
382         * @param arg user-supplied argument (tcp_pcb.callback_arg)
383         * @param pcb the tcp_pcb that now is connected
384         * @param err an error argument (TODO: that is current always ERR_OK?)
385         * @return value is currently ignored
386         */
387         err_t(*connected) (void *arg, struct tcp_pcb * pcb, err_t err);
388
389        /* Function which is called periodically.
390         * The period can be adjusted in multiples of the TCP slow timer interval
391         * by changing tcp_pcb.polltmr.
392         * @param arg user-supplied argument (tcp_pcb.callback_arg)
393         * @param pcb the tcp_pcb to poll for
394         * @return ERR_OK: try to send some data by calling tcp_output
395         */
396         err_t(*poll) (void *arg, struct tcp_pcb * pcb);
397
398        /* Function to be called whenever a fatal error occurs.
399         * There is no pcb parameter since most of the times, the pcb is
400         * already deallocated (or there is no pcb) when this function is called.
401         * @param arg user-supplied argument (tcp_pcb.callback_arg)
402         * @param err an indication why the error callback is called:
403         *            ERR_ABRT: aborted through tcp_abort or by a TCP timer
404         *            ERR_RST: the connection was reset by the remote host
405         */
406        void (*errf) (void *arg, err_t err);
407#endif                          /* LWIP_CALLBACK_API */
408
409#if LWIP_TCP_TIMESTAMPS
410        u32_t ts_lastacksent;
411        u32_t ts_recent;
412#endif                          /* LWIP_TCP_TIMESTAMPS */
413
414        /* idle time before KEEPALIVE is sent */
415        u32_t keep_idle;
416#if LWIP_TCP_KEEPALIVE
417        u32_t keep_intvl;
418        u32_t keep_cnt;
419#endif                          /* LWIP_TCP_KEEPALIVE */
420
421        /* Persist timer counter */
422        u32_t persist_cnt;
423        /* Persist timer back-off */
424        u8_t persist_backoff;
425
426        /* KEEPALIVE counter */
427        u8_t keep_cnt_sent;
428    };
429
430    struct tcp_pcb_listen {
431/* Common members of all PCB types */
432        IP_PCB;
433/* Protocol specific PCB members */
434        TCP_PCB_COMMON(struct tcp_pcb_listen);
435
436#if TCP_LISTEN_BACKLOG
437        u8_t backlog;
438        u8_t accepts_pending;
439#endif                          /* TCP_LISTEN_BACKLOG */
440    };
441
442#if LWIP_EVENT_API
443
444    enum lwip_event {
445        LWIP_EVENT_ACCEPT,
446        LWIP_EVENT_SENT,
447        LWIP_EVENT_RECV,
448        LWIP_EVENT_CONNECTED,
449        LWIP_EVENT_POLL,
450        LWIP_EVENT_ERR
451    };
452
453    err_t lwip_tcp_event(void *arg, struct tcp_pcb *pcb,
454                         enum lwip_event,
455                         struct pbuf *p, u16_t size, err_t err);
456
457#define TCP_EVENT_ACCEPT(pcb,err,ret)    ret = lwip_tcp_event((pcb)->callback_arg, (pcb),\
458                LWIP_EVENT_ACCEPT, NULL, 0, err)
459#define TCP_EVENT_SENT(pcb,space,ret) ret = lwip_tcp_event((pcb)->callback_arg, (pcb),\
460                   LWIP_EVENT_SENT, NULL, space, ERR_OK)
461#define TCP_EVENT_RECV(pcb,p,err,ret) ret = lwip_tcp_event((pcb)->callback_arg, (pcb),\
462                LWIP_EVENT_RECV, (p), 0, (err))
463#define TCP_EVENT_CONNECTED(pcb,err,ret) ret = lwip_tcp_event((pcb)->callback_arg, (pcb),\
464                LWIP_EVENT_CONNECTED, NULL, 0, (err))
465#define TCP_EVENT_POLL(pcb,ret)       ret = lwip_tcp_event((pcb)->callback_arg, (pcb),\
466                LWIP_EVENT_POLL, NULL, 0, ERR_OK)
467#define TCP_EVENT_ERR(errf,arg,err)  lwip_tcp_event((arg), NULL, \
468                LWIP_EVENT_ERR, NULL, 0, (err))
469#else                           /* LWIP_EVENT_API */
470
471#define TCP_EVENT_ACCEPT(pcb,err,ret)                          \
472  do {                                                         \
473    if((pcb)->accept != NULL)                                  \
474      (ret) = (pcb)->accept((pcb)->callback_arg,(pcb),(err));  \
475    else (ret) = ERR_OK;                                       \
476  } while (0)
477
478#define TCP_EVENT_SENT(pcb,space,ret)                          \
479  do {                                                         \
480    if((pcb)->sent != NULL)                                    \
481      (ret) = (pcb)->sent((pcb)->callback_arg,(pcb),(space));  \
482    else (ret) = ERR_OK;                                       \
483  } while (0)
484
485#define TCP_EVENT_RECV(pcb,p,err,ret)                           \
486  do {                                                          \
487    if((pcb)->recv != NULL) {                                   \
488      (ret) = (pcb)->recv((pcb)->callback_arg,(pcb),(p),(err)); \
489    } else {                                                    \
490      (ret) = ERR_OK;                                           \
491      if (p != NULL)                                            \
492        pbuf_free(p);                                           \
493    }                                                           \
494  } while (0)
495
496#define TCP_EVENT_CONNECTED(pcb,err,ret)                         \
497  do {                                                           \
498    if((pcb)->connected != NULL)                                 \
499      (ret) = (pcb)->connected((pcb)->callback_arg,(pcb),(err)); \
500    else (ret) = ERR_OK;                                         \
501  } while (0)
502
503#define TCP_EVENT_POLL(pcb,ret)                                \
504  do {                                                         \
505    if((pcb)->poll != NULL)                                    \
506      (ret) = (pcb)->poll((pcb)->callback_arg,(pcb));          \
507    else (ret) = ERR_OK;                                       \
508  } while (0)
509
510#define TCP_EVENT_ERR(errf,arg,err)                            \
511  do {                                                         \
512    if((errf) != NULL)                                         \
513      (errf)((arg),(err));                                     \
514  } while (0)
515
516#endif                          /* LWIP_EVENT_API */
517
518/* This structure represents a TCP segment on the unsent and unacked queues */
519    struct tcp_seg {
520        struct tcp_seg *next;   /* used when putting segements on a queue */
521        struct pbuf *p;         /* buffer containing data + TCP header */
522        void *dataptr;          /* pointer to the TCP data in the pbuf */
523        u16_t len;              /* the TCP length of this segment */
524        u8_t flags;
525#define TF_SEG_OPTS_MSS   (u8_t)0x01U   /* Include MSS option. */
526#define TF_SEG_OPTS_TS    (u8_t)0x02U   /* Include timestamp option. */
527        struct tcp_hdr *tcphdr; /* the TCP header */
528    };
529
530#define LWIP_TCP_OPT_LENGTH(flags)              \
531  (flags & TF_SEG_OPTS_MSS ? 4  : 0) +          \
532  (flags & TF_SEG_OPTS_TS  ? 12 : 0)
533
534/** This returns a TCP header option for MSS in an u32_t */
535#define TCP_BUILD_MSS_OPTION(x) (x) = htonl(((u32_t)2 << 24) |          \
536                                            ((u32_t)4 << 16) |          \
537                                            (((u32_t)TCP_MSS / 256) << 8) | \
538                                            (TCP_MSS & 255))
539
540/* Internal functions and global variables: */
541    struct tcp_pcb *tcp_pcb_copy(struct tcp_pcb *pcb);
542    void tcp_pcb_purge(struct tcp_pcb *pcb);
543    void tcp_pcb_remove(struct tcp_pcb **pcblist, struct tcp_pcb *pcb);
544
545    u8_t tcp_segs_free(struct tcp_seg *seg);
546    u8_t tcp_seg_free(struct tcp_seg *seg);
547    struct tcp_seg *tcp_seg_copy(struct tcp_seg *seg);
548
549#define tcp_ack(pcb)                               \
550  do {                                             \
551    if((pcb)->flags & TF_ACK_DELAY) {              \
552      (pcb)->flags &= ~TF_ACK_DELAY;               \
553      (pcb)->flags |= TF_ACK_NOW;                  \
554      tcp_output(pcb);                             \
555    }                                              \
556    else {                                         \
557      (pcb)->flags |= TF_ACK_DELAY;                \
558    }                                              \
559  } while (0)
560
561#define tcp_ack_now(pcb)                           \
562  do {                                             \
563    (pcb)->flags |= TF_ACK_NOW;                    \
564    tcp_output(pcb);                               \
565  } while (0)
566
567    err_t tcp_send_ctrl(struct tcp_pcb *pcb, u8_t flags);
568    err_t tcp_enqueue(struct tcp_pcb *pcb, void *dataptr, u16_t len,
569                      u8_t flags, u8_t apiflags, u8_t optflags);
570
571    void tcp_rexmit_seg(struct tcp_pcb *pcb, struct tcp_seg *seg);
572
573    void tcp_rst(u32_t seqno, u32_t ackno,
574                 struct ip_addr *local_ip, struct ip_addr *remote_ip,
575                 u16_t local_port, u16_t remote_port);
576
577    u32_t tcp_next_iss(void);
578
579    void tcp_keepalive(struct tcp_pcb *pcb);
580    void tcp_zero_window_probe(struct tcp_pcb *pcb);
581
582#if TCP_CALCULATE_EFF_SEND_MSS
583    u16_t tcp_eff_send_mss(u16_t sendmss, struct ip_addr *addr);
584#endif                          /* TCP_CALCULATE_EFF_SEND_MSS */
585
586    extern struct tcp_pcb *tcp_input_pcb;
587    extern u32_t tcp_ticks;
588
589#if TCP_DEBUG || TCP_INPUT_DEBUG || TCP_OUTPUT_DEBUG
590    void tcp_debug_print(struct tcp_hdr *tcphdr);
591    void tcp_debug_print_flags(u8_t flags);
592    void tcp_debug_print_state(enum tcp_state s);
593    void tcp_debug_print_pcbs(void);
594    s16_t tcp_pcbs_sane(void);
595#else
596#define tcp_debug_print(tcphdr)
597#define tcp_debug_print_flags(flags)
598#define tcp_debug_print_state(s)
599#define tcp_debug_print_pcbs()
600#define tcp_pcbs_sane() 1
601#endif                          /* TCP_DEBUG */
602
603#if NO_SYS
604#define tcp_timer_needed()
605#else
606    void tcp_timer_needed(void);
607#endif
608
609/* The TCP PCB lists. */
610    union tcp_listen_pcbs_t {   /* List of all TCP PCBs in LISTEN state. */
611        struct tcp_pcb_listen *listen_pcbs;
612        struct tcp_pcb *pcbs;
613    };
614    extern union tcp_listen_pcbs_t tcp_listen_pcbs;
615    extern struct tcp_pcb *tcp_active_pcbs;     /* List of all TCP PCBs that are in a
616                                                   state in which they accept or send
617                                                   data. */
618    extern struct tcp_pcb *tcp_tw_pcbs; /* List of all TCP PCBs in TIME-WAIT. */
619
620    extern struct tcp_pcb *tcp_tmp_pcb; /* Only used for temporary storage. */
621
622/* Axioms about the above lists:
623   1) Every TCP PCB that is not CLOSED is in one of the lists.
624   2) A PCB is only in one of the lists.
625   3) All PCBs in the tcp_listen_pcbs list is in LISTEN state.
626   4) All PCBs in the tcp_tw_pcbs list is in TIME-WAIT state.
627*/
628
629/* Define two macros, TCP_REG and TCP_RMV that registers a TCP PCB
630   with a PCB list or removes a PCB from a list, respectively. */
631#if 0
632#define TCP_REG(pcbs, npcb) do {\
633                            LWIP_DEBUGF(TCP_DEBUG, ("TCP_REG %p local port %d\n", npcb, npcb->local_port)); \
634                            for(tcp_tmp_pcb = *pcbs; \
635          tcp_tmp_pcb != NULL; \
636        tcp_tmp_pcb = tcp_tmp_pcb->next) { \
637                                LWIP_ASSERT("TCP_REG: already registered\n", tcp_tmp_pcb != npcb); \
638                            } \
639                            LWIP_ASSERT("TCP_REG: pcb->state != CLOSED", npcb->state != CLOSED); \
640                            npcb->next = *pcbs; \
641                            LWIP_ASSERT("TCP_REG: npcb->next != npcb", npcb->next != npcb); \
642                            *(pcbs) = npcb; \
643                            LWIP_ASSERT("TCP_RMV: tcp_pcbs sane", tcp_pcbs_sane()); \
644              tcp_timer_needed(); \
645                            } while(0)
646#define TCP_RMV(pcbs, npcb) do { \
647                            LWIP_ASSERT("TCP_RMV: pcbs != NULL", *pcbs != NULL); \
648                            LWIP_DEBUGF(TCP_DEBUG, ("TCP_RMV: removing %p from %p\n", npcb, *pcbs)); \
649                            if(*pcbs == npcb) { \
650                               *pcbs = (*pcbs)->next; \
651                            } else for(tcp_tmp_pcb = *pcbs; tcp_tmp_pcb != NULL; tcp_tmp_pcb = tcp_tmp_pcb->next) { \
652                               if(tcp_tmp_pcb->next != NULL && tcp_tmp_pcb->next == npcb) { \
653                                  tcp_tmp_pcb->next = npcb->next; \
654                                  break; \
655                               } \
656                            } \
657                            npcb->next = NULL; \
658                            LWIP_ASSERT("TCP_RMV: tcp_pcbs sane", tcp_pcbs_sane()); \
659                            LWIP_DEBUGF(TCP_DEBUG, ("TCP_RMV: removed %p from %p\n", npcb, *pcbs)); \
660                            } while(0)
661
662#else                           /* LWIP_DEBUG */
663
664#define TCP_REG(pcbs, npcb)                        \
665  do {                                             \
666    npcb->next = *pcbs;                            \
667    *(pcbs) = npcb;                                \
668    tcp_timer_needed();                            \
669  } while (0)
670
671#define TCP_RMV(pcbs, npcb)                        \
672  do {                                             \
673    if(*(pcbs) == npcb) {                          \
674      (*(pcbs)) = (*pcbs)->next;                   \
675    }                                              \
676    else {                                         \
677      for(tcp_tmp_pcb = *pcbs;                                         \
678          tcp_tmp_pcb != NULL;                                         \
679          tcp_tmp_pcb = tcp_tmp_pcb->next) {                           \
680        if(tcp_tmp_pcb->next != NULL && tcp_tmp_pcb->next == npcb) {   \
681          tcp_tmp_pcb->next = npcb->next;          \
682          break;                                   \
683        }                                          \
684      }                                            \
685    }                                              \
686    npcb->next = NULL;                             \
687  } while(0)
688
689#endif                          /* LWIP_DEBUG */
690
691#ifdef __cplusplus
692}
693#endif
694#endif                          /* LWIP_TCP */
695#endif                          /* __LWIP_TCP_H__ */
696