• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

tabascoeye / lwip / 14 / 1

Source File

47.51
/src/core/tcp_in.c
1
/**
2
 * @file
3
 * Transmission Control Protocol, incoming traffic
4
 *
5
 * The input processing functions of the TCP layer.
6
 *
7
 * These functions are generally called in the order (ip_input() ->)
8
 * tcp_input() -> * tcp_process() -> tcp_receive() (-> application).
9
 * 
10
 */
11

12
/*
13
 * Copyright (c) 2001-2004 Swedish Institute of Computer Science.
14
 * All rights reserved.
15
 *
16
 * Redistribution and use in source and binary forms, with or without modification,
17
 * are permitted provided that the following conditions are met:
18
 *
19
 * 1. Redistributions of source code must retain the above copyright notice,
20
 *    this list of conditions and the following disclaimer.
21
 * 2. Redistributions in binary form must reproduce the above copyright notice,
22
 *    this list of conditions and the following disclaimer in the documentation
23
 *    and/or other materials provided with the distribution.
24
 * 3. The name of the author may not be used to endorse or promote products
25
 *    derived from this software without specific prior written permission.
26
 *
27
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
28
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
29
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
30
 * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
31
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
32
 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
33
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
34
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
35
 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
36
 * OF SUCH DAMAGE.
37
 *
38
 * This file is part of the lwIP TCP/IP stack.
39
 *
40
 * Author: Adam Dunkels <adam@sics.se>
41
 *
42
 */
43

44
#include "lwip/opt.h"
45

46
#if LWIP_TCP /* don't build if not configured for use in lwipopts.h */
47

48
#include "lwip/tcp_impl.h"
49
#include "lwip/def.h"
50
#include "lwip/ip_addr.h"
51
#include "lwip/netif.h"
52
#include "lwip/mem.h"
53
#include "lwip/memp.h"
54
#include "lwip/inet_chksum.h"
55
#include "lwip/stats.h"
56
#include "lwip/snmp.h"
57
#include "arch/perf.h"
58
#include "lwip/ip6.h"
59
#include "lwip/ip6_addr.h"
60
#include "lwip/inet_chksum.h"
61
#if LWIP_ND6_TCP_REACHABILITY_HINTS
62
#include "lwip/nd6.h"
63
#endif /* LWIP_ND6_TCP_REACHABILITY_HINTS */
64

65
/* These variables are global to all functions involved in the input
66
   processing of TCP segments. They are set by the tcp_input()
67
   function. */
68
static struct tcp_seg inseg;
69
static struct tcp_hdr *tcphdr;
70
static u16_t tcphdr_opt1len;
71
static u8_t* tcphdr_opt2;
72
static u16_t tcp_optidx;
73
static u32_t seqno, ackno;
74
static u8_t flags;
75
static u16_t tcplen;
76

77
static u8_t recv_flags;
78
static struct pbuf *recv_data;
79

80
struct tcp_pcb *tcp_input_pcb;
81

82
/* Forward declarations. */
83
static err_t tcp_process(struct tcp_pcb *pcb);
84
static void tcp_receive(struct tcp_pcb *pcb);
85
static void tcp_parseopt(struct tcp_pcb *pcb);
86

87
static err_t tcp_listen_input(struct tcp_pcb_listen *pcb);
88
static err_t tcp_timewait_input(struct tcp_pcb *pcb);
89

90
/**
91
 * The initial input processing of TCP. It verifies the TCP header, demultiplexes
92
 * the segment between the PCBs and passes it on to tcp_process(), which implements
93
 * the TCP finite state machine. This function is called by the IP layer (in
94
 * ip_input()).
95
 *
96
 * @param p received TCP segment to process (p->payload pointing to the TCP header)
97
 * @param inp network interface on which this segment was received
98
 */
99
void
100
tcp_input(struct pbuf *p, struct netif *inp)
102✔
101
{
102
  struct tcp_pcb *pcb, *prev;
103
  struct tcp_pcb_listen *lpcb;
104
#if SO_REUSE
105
  struct tcp_pcb *lpcb_prev = NULL;
106
  struct tcp_pcb_listen *lpcb_any = NULL;
107
#endif /* SO_REUSE */
108
  u8_t hdrlen;
109
  err_t err;
110
#if CHECKSUM_CHECK_TCP
111
  u16_t chksum;
112
#endif /* CHECKSUM_CHECK_TCP */
113

114
  PERF_START;
115

116
  TCP_STATS_INC(tcp.recv);
102✔
117
  snmp_inc_tcpinsegs();
102✔
118

119
  tcphdr = (struct tcp_hdr *)p->payload;
102✔
120

121
#if TCP_INPUT_DEBUG
122
  tcp_debug_print(tcphdr);
123
#endif
124

125
  /* Check that TCP header fits in payload */
126
  if (p->len < sizeof(struct tcp_hdr)) {
102✔
127
    /* drop short packets */
128
    LWIP_DEBUGF(TCP_INPUT_DEBUG, ("tcp_input: short packet (%"U16_F" bytes) discarded\n", p->tot_len));
129
    TCP_STATS_INC(tcp.lenerr);
×
130
    goto dropped;
×
131
  }
132

133
  /* Don't even process incoming broadcasts/multicasts. */
134
  if ((!ip_current_is_v6() && ip_addr_isbroadcast(ip_current_dest_addr(), inp)) ||
204✔
135
       ipX_addr_ismulticast(ip_current_is_v6(), ipX_current_dest_addr())) {
102✔
136
    TCP_STATS_INC(tcp.proterr);
×
137
    goto dropped;
×
138
  }
139

140
#if CHECKSUM_CHECK_TCP
141
  /* Verify TCP checksum. */
142
  chksum = ipX_chksum_pseudo(ip_current_is_v6(), p, IP_PROTO_TCP, p->tot_len,
102✔
143
                             ipX_current_src_addr(), ipX_current_dest_addr());
144
  if (chksum != 0) {
102✔
145
      LWIP_DEBUGF(TCP_INPUT_DEBUG, ("tcp_input: packet discarded due to failing checksum 0x%04"X16_F"\n",
146
        chksum));
147
    tcp_debug_print(tcphdr);
148
    TCP_STATS_INC(tcp.chkerr);
×
149
    goto dropped;
×
150
  }
151
#endif /* CHECKSUM_CHECK_TCP */
152

153
  /* Move the payload pointer in the pbuf so that it points to the
154
     TCP data instead of the TCP header. */
155
  hdrlen = TCPH_HDRLEN(tcphdr);
102✔
156
  tcphdr_opt1len = (hdrlen * 4) - TCP_HLEN;
102✔
157
  tcphdr_opt2 = NULL;
102✔
158
  if (p->len < hdrlen * 4) {
102✔
159
    if (p->len >= TCP_HLEN) {
×
160
      /* TCP header fits into first pbuf, options don't - data is in the next pbuf */
161
      u16_t optlen = tcphdr_opt1len;
×
162
      pbuf_header(p, -TCP_HLEN); /* cannot fail */
×
163
      LWIP_ASSERT("tcphdr_opt1len >= p->len", tcphdr_opt1len >= p->len);
×
164
      LWIP_ASSERT("p->next != NULL", p->next != NULL);
×
165
      tcphdr_opt1len = p->len;
×
166
      if (optlen > tcphdr_opt1len) {
×
167
        s16_t opt2len;
168
        /* options continue in the next pbuf: set p to zero length and hide the
169
           options in the next pbuf (adjusting p->tot_len) */
170
        u8_t phret = pbuf_header(p, -(s16_t)tcphdr_opt1len);
×
171
        LWIP_ASSERT("phret == 0", phret == 0);
172
        tcphdr_opt2 = (u8_t*)p->next->payload;
×
173
        opt2len = optlen - tcphdr_opt1len;
×
174
        phret = pbuf_header(p->next, -opt2len);
×
175
        LWIP_ASSERT("phret == 0", phret == 0);
176
        /* p->next->payload now points to the TCP data */
177
        /* manually adjust p->tot_len to changed p->next->tot_len change */
178
        p->tot_len -= opt2len;
×
179
      }
180
      LWIP_ASSERT("p->len == 0", p->len == 0);
×
181
    } else {
182
      /* drop short packets */
183
      LWIP_DEBUGF(TCP_INPUT_DEBUG, ("tcp_input: short packet\n"));
184
      TCP_STATS_INC(tcp.lenerr);
×
185
      goto dropped;
×
186
    }
187
  } else {
188
    pbuf_header(p, -(hdrlen * 4)); /* cannot fail */
102✔
189
  }
190

191
  /* Convert fields in TCP header to host byte order. */
192
  tcphdr->src = ntohs(tcphdr->src);
102✔
193
  tcphdr->dest = ntohs(tcphdr->dest);
102✔
194
  seqno = tcphdr->seqno = ntohl(tcphdr->seqno);
102✔
195
  ackno = tcphdr->ackno = ntohl(tcphdr->ackno);
102✔
196
  tcphdr->wnd = ntohs(tcphdr->wnd);
102✔
197

198
  flags = TCPH_FLAGS(tcphdr);
102✔
199
  tcplen = p->tot_len + ((flags & (TCP_FIN | TCP_SYN)) ? 1 : 0);
102✔
200

201
  /* Demultiplex an incoming segment. First, we check if it is destined
202
     for an active connection. */
203
  prev = NULL;
102✔
204

205
  
206
  for(pcb = tcp_active_pcbs; pcb != NULL; pcb = pcb->next) {
102✔
207
    LWIP_ASSERT("tcp_input: active pcb->state != CLOSED", pcb->state != CLOSED);
102✔
208
    LWIP_ASSERT("tcp_input: active pcb->state != TIME-WAIT", pcb->state != TIME_WAIT);
102✔
209
    LWIP_ASSERT("tcp_input: active pcb->state != LISTEN", pcb->state != LISTEN);
102✔
210
    if (pcb->remote_port == tcphdr->src &&
102✔
211
        pcb->local_port == tcphdr->dest &&
102✔
212
        IP_PCB_IPVER_INPUT_MATCH(pcb) &&
102✔
213
        ipX_addr_cmp(ip_current_is_v6(), &pcb->remote_ip, ipX_current_src_addr()) &&
204✔
214
        ipX_addr_cmp(ip_current_is_v6(),&pcb->local_ip, ipX_current_dest_addr())) {
102✔
215
      /* Move this PCB to the front of the list so that subsequent
216
         lookups will be faster (we exploit locality in TCP segment
217
         arrivals). */
218
      LWIP_ASSERT("tcp_input: pcb->next != pcb (before cache)", pcb->next != pcb);
102✔
219
      if (prev != NULL) {
102✔
220
        prev->next = pcb->next;
×
221
        pcb->next = tcp_active_pcbs;
×
222
        tcp_active_pcbs = pcb;
×
223
      }
224
      LWIP_ASSERT("tcp_input: pcb->next != pcb (after cache)", pcb->next != pcb);
102✔
225
      break;
102✔
226
    }
227
    prev = pcb;
×
228
  }
229

230
  if (pcb == NULL) {
102✔
231
    /* If it did not go to an active connection, we check the connections
232
       in the TIME-WAIT state. */
233
    for(pcb = tcp_tw_pcbs; pcb != NULL; pcb = pcb->next) {
×
234
      LWIP_ASSERT("tcp_input: TIME-WAIT pcb->state == TIME-WAIT", pcb->state == TIME_WAIT);
×
235
      if (pcb->remote_port == tcphdr->src &&
×
236
          pcb->local_port == tcphdr->dest &&
×
237
          IP_PCB_IPVER_INPUT_MATCH(pcb) &&
×
238
          ipX_addr_cmp(ip_current_is_v6(), &pcb->remote_ip, ipX_current_src_addr()) &&
×
239
          ipX_addr_cmp(ip_current_is_v6(),&pcb->local_ip, ipX_current_dest_addr())) {
×
240
        /* We don't really care enough to move this PCB to the front
241
           of the list since we are not very likely to receive that
242
           many segments for connections in TIME-WAIT. */
243
        LWIP_DEBUGF(TCP_INPUT_DEBUG, ("tcp_input: packed for TIME_WAITing connection.\n"));
244
        tcp_timewait_input(pcb);
×
245
        pbuf_free(p);
×
246
        return;
×
247
      }
248
    }
249

250
    /* Finally, if we still did not get a match, we check all PCBs that
251
       are LISTENing for incoming connections. */
252
    prev = NULL;
×
253
    for(lpcb = tcp_listen_pcbs.listen_pcbs; lpcb != NULL; lpcb = lpcb->next) {
×
254
      if (lpcb->local_port == tcphdr->dest) {
×
255
#if LWIP_IPV6
256
        if (lpcb->accept_any_ip_version) {
257
          /* found an ANY-match */
258
#if SO_REUSE
259
          lpcb_any = lpcb;
260
          lpcb_prev = prev;
261
#else /* SO_REUSE */
262
          break;
263
#endif /* SO_REUSE */
264
        } else
265
#endif /* LWIP_IPV6 */
266
        if (IP_PCB_IPVER_INPUT_MATCH(lpcb)) {
267
          if (ipX_addr_cmp(ip_current_is_v6(), &lpcb->local_ip, ipX_current_dest_addr())) {
×
268
            /* found an exact match */
269
            break;
×
270
          } else if (ipX_addr_isany(ip_current_is_v6(), &lpcb->local_ip)) {
×
271
            /* found an ANY-match */
272
#if SO_REUSE
273
            lpcb_any = lpcb;
274
            lpcb_prev = prev;
275
#else /* SO_REUSE */
276
            break;
277
 #endif /* SO_REUSE */
278
          }
279
        }
280
      }
281
      prev = (struct tcp_pcb *)lpcb;
×
282
    }
283
#if SO_REUSE
284
    /* first try specific local IP */
285
    if (lpcb == NULL) {
286
      /* only pass to ANY if no specific local IP has been found */
287
      lpcb = lpcb_any;
288
      prev = lpcb_prev;
289
    }
290
#endif /* SO_REUSE */
291
    if (lpcb != NULL) {
×
292
      /* Move this PCB to the front of the list so that subsequent
293
         lookups will be faster (we exploit locality in TCP segment
294
         arrivals). */
295
      if (prev != NULL) {
×
296
        ((struct tcp_pcb_listen *)prev)->next = lpcb->next;
×
297
              /* our successor is the remainder of the listening list */
298
        lpcb->next = tcp_listen_pcbs.listen_pcbs;
×
299
              /* put this listening pcb at the head of the listening list */
300
        tcp_listen_pcbs.listen_pcbs = lpcb;
×
301
      }
302
    
303
      LWIP_DEBUGF(TCP_INPUT_DEBUG, ("tcp_input: packed for LISTENing connection.\n"));
304
      tcp_listen_input(lpcb);
×
305
      pbuf_free(p);
×
306
      return;
×
307
    }
308
  }
309

310
#if TCP_INPUT_DEBUG
311
  LWIP_DEBUGF(TCP_INPUT_DEBUG, ("+-+-+-+-+-+-+-+-+-+-+-+-+-+- tcp_input: flags "));
312
  tcp_debug_print_flags(TCPH_FLAGS(tcphdr));
313
  LWIP_DEBUGF(TCP_INPUT_DEBUG, ("-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n"));
314
#endif /* TCP_INPUT_DEBUG */
315

316

317
  if (pcb != NULL) {
102✔
318
    /* The incoming segment belongs to a connection. */
319
#if TCP_INPUT_DEBUG
320
#if TCP_DEBUG
321
    tcp_debug_print_state(pcb->state);
322
#endif /* TCP_DEBUG */
323
#endif /* TCP_INPUT_DEBUG */
324

325
    /* Set up a tcp_seg structure. */
326
    inseg.next = NULL;
102✔
327
    inseg.len = p->tot_len;
102✔
328
    inseg.p = p;
102✔
329
    inseg.tcphdr = tcphdr;
102✔
330

331
    recv_data = NULL;
102✔
332
    recv_flags = 0;
102✔
333

334
    if (flags & TCP_PSH) {
102✔
335
      p->flags |= PBUF_FLAG_PUSH;
×
336
    }
337

338
    /* If there is data which was previously "refused" by upper layer */
339
    if (pcb->refused_data != NULL) {
102✔
340
      if ((tcp_process_refused_data(pcb) == ERR_ABRT) ||
×
341
        ((pcb->refused_data != NULL) && (tcplen > 0))) {
×
342
        /* pcb has been aborted or refused data is still refused and the new
343
           segment contains data */
344
        TCP_STATS_INC(tcp.drop);
×
345
        snmp_inc_tcpinerrs();
×
346
        goto aborted;
×
347
      }
348
    }
349
    tcp_input_pcb = pcb;
102✔
350
    err = tcp_process(pcb);
102✔
351
    /* A return value of ERR_ABRT means that tcp_abort() was called
352
       and that the pcb has been freed. If so, we don't do anything. */
353
    if (err != ERR_ABRT) {
102✔
354
      if (recv_flags & TF_RESET) {
102✔
355
        /* TF_RESET means that the connection was reset by the other
356
           end. We then call the error callback to inform the
357
           application that the connection is dead before we
358
           deallocate the PCB. */
359
        TCP_EVENT_ERR(pcb->errf, pcb->callback_arg, ERR_RST);
×
360
        tcp_pcb_remove(&tcp_active_pcbs, pcb);
×
361
        memp_free(MEMP_TCP_PCB, pcb);
×
362
      } else if (recv_flags & TF_CLOSED) {
102✔
363
        /* The connection has been closed and we will deallocate the
364
           PCB. */
365
        if (!(pcb->flags & TF_RXCLOSED)) {
×
366
          /* Connection closed although the application has only shut down the
367
             tx side: call the PCB's err callback and indicate the closure to
368
             ensure the application doesn't continue using the PCB. */
369
          TCP_EVENT_ERR(pcb->errf, pcb->callback_arg, ERR_CLSD);
×
370
        }
371
        tcp_pcb_remove(&tcp_active_pcbs, pcb);
×
372
        memp_free(MEMP_TCP_PCB, pcb);
×
373
      } else {
374
        err = ERR_OK;
102✔
375
        /* If the application has registered a "sent" function to be
376
           called when new send buffer space is available, we call it
377
           now. */
378
        if (pcb->acked > 0) {
102✔
379
          u16_t acked;
380
#if LWIP_WND_SCALE
381
          /* pcb->acked is u32_t but the sent callback only takes a u16_t,
382
             so we might have to call it multiple times. */
383
          u32_t pcb_acked = pcb->acked;
4✔
384
          while(pcb_acked > 0) {
12✔
385
            acked = (u16_t)LWIP_MIN(pcb_acked, 0xffffu);
4✔
386
            pcb_acked -= acked;
4✔
387
#else
388
          {
389
            acked = pcb->acked;
390
#endif
391
            TCP_EVENT_SENT(pcb, (u16_t)acked, err);
4✔
392
            if (err == ERR_ABRT) {
4✔
393
              goto aborted;
×
394
            }
395
          }
396
        }
397

398
#if TCP_QUEUE_OOSEQ && LWIP_WND_SCALE
399
        while (recv_data != NULL) {
225✔
400
          struct pbuf *rest = NULL;
21✔
401
          pbuf_split_64k(recv_data, &rest);
21✔
402
#else /* TCP_QUEUE_OOSEQ && LWIP_WND_SCALE */
403
        if (recv_data != NULL) {
404
#endif /* TCP_QUEUE_OOSEQ && LWIP_WND_SCALE */
405

406
          LWIP_ASSERT("pcb->refused_data == NULL", pcb->refused_data == NULL);
21✔
407
          if (pcb->flags & TF_RXCLOSED) {
21✔
408
            /* received data although already closed -> abort (send RST) to
409
               notify the remote host that not all data has been processed */
410
            pbuf_free(recv_data);
×
411
#if TCP_QUEUE_OOSEQ && LWIP_WND_SCALE
412
            if (rest != NULL) {
×
413
              pbuf_free(rest);
×
414
            }
415
#endif /* TCP_QUEUE_OOSEQ && LWIP_WND_SCALE */
416
            tcp_abort(pcb);
×
417
            goto aborted;
×
418
          }
419

420
          /* Notify application that data has been received. */
421
          TCP_EVENT_RECV(pcb, recv_data, ERR_OK, err);
21✔
422
          if (err == ERR_ABRT) {
21✔
423
#if TCP_QUEUE_OOSEQ && LWIP_WND_SCALE
424
            if (rest != NULL) {
×
425
              pbuf_free(rest);
×
426
            }
427
#endif /* TCP_QUEUE_OOSEQ && LWIP_WND_SCALE */
428
            goto aborted;
×
429
          }
430

431
          /* If the upper layer can't receive this data, store it */
432
          if (err != ERR_OK) {
21✔
433
#if TCP_QUEUE_OOSEQ && LWIP_WND_SCALE
434
            if (rest != NULL) {
×
435
              pbuf_cat(recv_data, rest);
×
436
            }
437
#endif /* TCP_QUEUE_OOSEQ && LWIP_WND_SCALE */
438
            pcb->refused_data = recv_data;
×
439
            LWIP_DEBUGF(TCP_INPUT_DEBUG, ("tcp_input: keep incoming packet, because pcb is \"full\"\n"));
440
#if TCP_QUEUE_OOSEQ && LWIP_WND_SCALE
441
            break;
×
442
          } else {
443
            /* Upper layer received the data, go on with the rest if > 64K */
444
            recv_data = rest;
21✔
445
#endif /* TCP_QUEUE_OOSEQ && LWIP_WND_SCALE */
446
          }
447
        }
448

449
        /* If a FIN segment was received, we call the callback
450
           function with a NULL buffer to indicate EOF. */
451
        if (recv_flags & TF_GOT_FIN) {
102✔
452
          if (pcb->refused_data != NULL) {
18✔
453
            /* Delay this if we have refused data. */
454
            pcb->refused_data->flags |= PBUF_FLAG_TCP_FIN;
×
455
          } else {
456
            /* correct rcv_wnd as the application won't call tcp_recved()
457
               for the FIN's seqno */
458
            if (pcb->rcv_wnd != TCP_WND) {
18✔
459
              pcb->rcv_wnd++;
18✔
460
            }
461
            TCP_EVENT_CLOSED(pcb, err);
18✔
462
            if (err == ERR_ABRT) {
18✔
463
              goto aborted;
×
464
            }
465
          }
466
        }
467

468
        tcp_input_pcb = NULL;
102✔
469
        /* Try to send something out. */
470
        tcp_output(pcb);
102✔
471
#if TCP_INPUT_DEBUG
472
#if TCP_DEBUG
473
        tcp_debug_print_state(pcb->state);
474
#endif /* TCP_DEBUG */
475
#endif /* TCP_INPUT_DEBUG */
476
      }
477
    }
478
    /* Jump target if pcb has been aborted in a callback (by calling tcp_abort()).
479
       Below this line, 'pcb' may not be dereferenced! */
480
aborted:
481
    tcp_input_pcb = NULL;
102✔
482
    recv_data = NULL;
102✔
483

484
    /* give up our reference to inseg.p */
485
    if (inseg.p != NULL)
102✔
486
    {
487
      pbuf_free(inseg.p);
81✔
488
      inseg.p = NULL;
81✔
489
    }
490
  } else {
491

492
    /* If no matching PCB was found, send a TCP RST (reset) to the
493
       sender. */
494
    LWIP_DEBUGF(TCP_RST_DEBUG, ("tcp_input: no PCB match found, resetting.\n"));
495
    if (!(TCPH_FLAGS(tcphdr) & TCP_RST)) {
×
496
      TCP_STATS_INC(tcp.proterr);
×
497
      TCP_STATS_INC(tcp.drop);
×
498
      tcp_rst(ackno, seqno + tcplen, ipX_current_dest_addr(),
×
499
        ipX_current_src_addr(), tcphdr->dest, tcphdr->src, ip_current_is_v6());
500
    }
501
    pbuf_free(p);
×
502
  }
503

504
  LWIP_ASSERT("tcp_input: tcp_pcbs_sane()", tcp_pcbs_sane());
505
  PERF_STOP("tcp_input");
506
  return;
102✔
507
dropped:
508
  TCP_STATS_INC(tcp.drop);
×
509
  snmp_inc_tcpinerrs();
×
510
  pbuf_free(p);
×
511
}
512

513
/**
514
 * Called by tcp_input() when a segment arrives for a listening
515
 * connection (from tcp_input()).
516
 *
517
 * @param pcb the tcp_pcb_listen for which a segment arrived
518
 * @return ERR_OK if the segment was processed
519
 *         another err_t on error
520
 *
521
 * @note the return value is not (yet?) used in tcp_input()
522
 * @note the segment which arrived is saved in global variables, therefore only the pcb
523
 *       involved is passed as a parameter to this function
524
 */
525
static err_t
526
tcp_listen_input(struct tcp_pcb_listen *pcb)
×
527
{
528
  struct tcp_pcb *npcb;
529
  err_t rc;
530

531
  if (flags & TCP_RST) {
×
532
    /* An incoming RST should be ignored. Return. */
533
    return ERR_OK;
×
534
  }
535

536
  /* In the LISTEN state, we check for incoming SYN segments,
537
     creates a new PCB, and responds with a SYN|ACK. */
538
  if (flags & TCP_ACK) {
×
539
    /* For incoming segments with the ACK flag set, respond with a
540
       RST. */
541
    LWIP_DEBUGF(TCP_RST_DEBUG, ("tcp_listen_input: ACK in LISTEN, sending reset\n"));
542
    tcp_rst(ackno, seqno + tcplen, ipX_current_dest_addr(),
×
543
      ipX_current_src_addr(), tcphdr->dest, tcphdr->src, ip_current_is_v6());
544
  } else if (flags & TCP_SYN) {
×
545
    LWIP_DEBUGF(TCP_DEBUG, ("TCP connection request %"U16_F" -> %"U16_F".\n", tcphdr->src, tcphdr->dest));
546
#if TCP_LISTEN_BACKLOG
547
    if (pcb->accepts_pending >= pcb->backlog) {
548
      LWIP_DEBUGF(TCP_DEBUG, ("tcp_listen_input: listen backlog exceeded for port %"U16_F"\n", tcphdr->dest));
549
      return ERR_ABRT;
550
    }
551
#endif /* TCP_LISTEN_BACKLOG */
552
    npcb = tcp_alloc(pcb->prio);
×
553
    /* If a new PCB could not be created (probably due to lack of memory),
554
       we don't do anything, but rely on the sender will retransmit the
555
       SYN at a time when we have more memory available. */
556
    if (npcb == NULL) {
×
557
      LWIP_DEBUGF(TCP_DEBUG, ("tcp_listen_input: could not allocate PCB\n"));
558
      TCP_STATS_INC(tcp.memerr);
×
559
      return ERR_MEM;
×
560
    }
561
#if TCP_LISTEN_BACKLOG
562
    pcb->accepts_pending++;
563
#endif /* TCP_LISTEN_BACKLOG */
564
    /* Set up the new PCB. */
565
#if LWIP_IPV6
566
    PCB_ISIPV6(npcb) = ip_current_is_v6();
567
#endif /* LWIP_IPV6 */
568
    ipX_addr_copy(ip_current_is_v6(), npcb->local_ip, *ipX_current_dest_addr());
×
569
    ipX_addr_copy(ip_current_is_v6(), npcb->remote_ip, *ipX_current_src_addr());
×
570
    npcb->local_port = pcb->local_port;
×
571
    npcb->remote_port = tcphdr->src;
×
572
    npcb->state = SYN_RCVD;
×
573
    npcb->rcv_nxt = seqno + 1;
×
574
    npcb->rcv_ann_right_edge = npcb->rcv_nxt;
×
575
    npcb->snd_wl1 = seqno - 1;/* Initialize to seqno-1 to force window update */
×
576
    npcb->callback_arg = pcb->callback_arg;
×
577
#if LWIP_CALLBACK_API
578
    npcb->accept = pcb->accept;
×
579
#endif /* LWIP_CALLBACK_API */
580
    /* inherit socket options */
581
    npcb->so_options = pcb->so_options & SOF_INHERITED;
×
582
    /* Register the new PCB so that we can begin receiving segments
583
       for it. */
584
    TCP_REG_ACTIVE(npcb);
×
585

586
    /* Parse any options in the SYN. */
587
    tcp_parseopt(npcb);
×
588
    npcb->snd_wnd = SND_WND_SCALE(npcb, tcphdr->wnd);
×
589
    npcb->snd_wnd_max = npcb->snd_wnd;
×
590
    npcb->ssthresh = npcb->snd_wnd;
×
591

592
#if TCP_CALCULATE_EFF_SEND_MSS
593
    npcb->mss = tcp_eff_send_mss(npcb->mss, &npcb->local_ip,
×
594
      &npcb->remote_ip, PCB_ISIPV6(npcb));
595
#endif /* TCP_CALCULATE_EFF_SEND_MSS */
596

597
    snmp_inc_tcppassiveopens();
×
598

599
    /* Send a SYN|ACK together with the MSS option. */
600
    rc = tcp_enqueue_flags(npcb, TCP_SYN | TCP_ACK);
×
601
    if (rc != ERR_OK) {
×
602
      tcp_abandon(npcb, 0);
×
603
      return rc;
×
604
    }
605
    return tcp_output(npcb);
×
606
  }
607
  return ERR_OK;
×
608
}
609

610
/**
611
 * Called by tcp_input() when a segment arrives for a connection in
612
 * TIME_WAIT.
613
 *
614
 * @param pcb the tcp_pcb for which a segment arrived
615
 *
616
 * @note the segment which arrived is saved in global variables, therefore only the pcb
617
 *       involved is passed as a parameter to this function
618
 */
619
static err_t
620
tcp_timewait_input(struct tcp_pcb *pcb)
×
621
{
622
  /* RFC 1337: in TIME_WAIT, ignore RST and ACK FINs + any 'acceptable' segments */
623
  /* RFC 793 3.9 Event Processing - Segment Arrives:
624
   * - first check sequence number - we skip that one in TIME_WAIT (always
625
   *   acceptable since we only send ACKs)
626
   * - second check the RST bit (... return) */
627
  if (flags & TCP_RST)  {
×
628
    return ERR_OK;
×
629
  }
630
  /* - fourth, check the SYN bit, */
631
  if (flags & TCP_SYN) {
×
632
    /* If an incoming segment is not acceptable, an acknowledgment
633
       should be sent in reply */
634
    if (TCP_SEQ_BETWEEN(seqno, pcb->rcv_nxt, pcb->rcv_nxt+pcb->rcv_wnd)) {
×
635
      /* If the SYN is in the window it is an error, send a reset */
636
      tcp_rst(ackno, seqno + tcplen, ipX_current_dest_addr(),
×
637
        ipX_current_src_addr(), tcphdr->dest, tcphdr->src, ip_current_is_v6());
638
      return ERR_OK;
×
639
    }
640
  } else if (flags & TCP_FIN) {
×
641
    /* - eighth, check the FIN bit: Remain in the TIME-WAIT state.
642
         Restart the 2 MSL time-wait timeout.*/
643
    pcb->tmr = tcp_ticks;
×
644
  }
645

646
  if ((tcplen > 0))  {
×
647
    /* Acknowledge data, FIN or out-of-window SYN */
648
    pcb->flags |= TF_ACK_NOW;
×
649
    return tcp_output(pcb);
×
650
  }
651
  return ERR_OK;
×
652
}
653

654
/**
655
 * Implements the TCP state machine. Called by tcp_input. In some
656
 * states tcp_receive() is called to receive data. The tcp_seg
657
 * argument will be freed by the caller (tcp_input()) unless the
658
 * recv_data pointer in the pcb is set.
659
 *
660
 * @param pcb the tcp_pcb for which a segment arrived
661
 *
662
 * @note the segment which arrived is saved in global variables, therefore only the pcb
663
 *       involved is passed as a parameter to this function
664
 */
665
static err_t
666
tcp_process(struct tcp_pcb *pcb)
102✔
667
{
668
  struct tcp_seg *rseg;
669
  err_t err;
670

671
  err = ERR_OK;
102✔
672

673
  /* Process incoming RST segments. */
674
  if (flags & TCP_RST) {
102✔
675
    /* First, determine if the reset is acceptable. (in case of RST only if the sequence number matches) */
676
    if (ackno == pcb->snd_nxt) {
×
677
      LWIP_DEBUGF(TCP_INPUT_DEBUG, ("tcp_process: Connection RESET\n"));
678
      LWIP_ASSERT("tcp_input: pcb->state != CLOSED", pcb->state != CLOSED);
×
679
      recv_flags |= TF_RESET;
×
680
      pcb->flags &= ~TF_ACK_DELAY;
×
681
      return ERR_RST;
×
682
    } else {
683
      /* if the sequence number is inside the window, we only send an ACK 
684
      and wait for a re-send with matching sequence number.
685
      This is protection against CVE-2004-0230 (RST spoofing attack) */
686
      if (TCP_SEQ_BETWEEN(seqno, pcb->rcv_nxt,
×
687
                          pcb->rcv_nxt+pcb->rcv_wnd)) {
688
        tcp_ack_now(pcb);
×
689
      }
690
      LWIP_DEBUGF(TCP_INPUT_DEBUG, ("tcp_process: unacceptable reset seqno %"U32_F" rcv_nxt %"U32_F"\n",
691
       seqno, pcb->rcv_nxt));
692
      LWIP_DEBUGF(TCP_DEBUG, ("tcp_process: unacceptable reset seqno %"U32_F" rcv_nxt %"U32_F"\n",
693
       seqno, pcb->rcv_nxt));
694
      return ERR_OK;
×
695
    }
696
  }
697

698
  if ((flags & TCP_SYN) && (pcb->state != SYN_SENT && pcb->state != SYN_RCVD)) { 
102✔
699
    /* Cope with new connection attempt after remote end crashed */
700
    tcp_ack_now(pcb);
×
701
    return ERR_OK;
×
702
  }
703
  
704
  if ((pcb->flags & TF_RXCLOSED) == 0) {
102✔
705
    /* Update the PCB (in)activity timer unless rx is closed (see tcp_shutdown) */
706
    pcb->tmr = tcp_ticks;
102✔
707
  }
708
  pcb->keep_cnt_sent = 0;
102✔
709

710
  tcp_parseopt(pcb);
102✔
711

712
  /* Do different things depending on the TCP state. */
713
  switch (pcb->state) {
102✔
714
  case SYN_SENT:
715
    LWIP_DEBUGF(TCP_INPUT_DEBUG, ("SYN-SENT: ackno %"U32_F" pcb->snd_nxt %"U32_F" unacked %"U32_F"\n", ackno,
716
     pcb->snd_nxt, ntohl(pcb->unacked->tcphdr->seqno)));
717
    /* received SYN ACK with expected sequence number? */
718
    if ((flags & TCP_ACK) && (flags & TCP_SYN)
×
719
        && ackno == ntohl(pcb->unacked->tcphdr->seqno) + 1) {
×
720
      pcb->snd_buf++;
×
721
      pcb->rcv_nxt = seqno + 1;
×
722
      pcb->rcv_ann_right_edge = pcb->rcv_nxt;
×
723
      pcb->lastack = ackno;
×
724
      pcb->snd_wnd = SND_WND_SCALE(pcb, tcphdr->wnd);
×
725
      pcb->snd_wnd_max = pcb->snd_wnd;
×
726
      pcb->snd_wl1 = seqno - 1; /* Initialize to seqno - 1 to force window update */
×
727
      pcb->state = ESTABLISHED;
×
728

729
#if TCP_CALCULATE_EFF_SEND_MSS
730
      pcb->mss = tcp_eff_send_mss(pcb->mss, &pcb->local_ip, &pcb->remote_ip,
×
731
        PCB_ISIPV6(pcb));
732
#endif /* TCP_CALCULATE_EFF_SEND_MSS */
733

734
      /* Set ssthresh again after changing pcb->mss (already set in tcp_connect
735
       * but for the default value of pcb->mss) */
736
      pcb->ssthresh = pcb->mss * 10;
×
737

738
      pcb->cwnd = ((pcb->cwnd == 1) ? (pcb->mss * 2) : pcb->mss);
×
739
      LWIP_ASSERT("pcb->snd_queuelen > 0", (pcb->snd_queuelen > 0));
×
740
      --pcb->snd_queuelen;
×
741
      LWIP_DEBUGF(TCP_QLEN_DEBUG, ("tcp_process: SYN-SENT --queuelen %"TCPWNDSIZE_F"\n", (tcpwnd_size_t)pcb->snd_queuelen));
742
      rseg = pcb->unacked;
×
743
      pcb->unacked = rseg->next;
×
744
      tcp_seg_free(rseg);
×
745

746
      /* If there's nothing left to acknowledge, stop the retransmit
747
         timer, otherwise reset it to start again */
748
      if(pcb->unacked == NULL)
×
749
        pcb->rtime = -1;
×
750
      else {
751
        pcb->rtime = 0;
×
752
        pcb->nrtx = 0;
×
753
      }
754

755
      /* Call the user specified function to call when successfully
756
       * connected. */
757
      TCP_EVENT_CONNECTED(pcb, ERR_OK, err);
×
758
      if (err == ERR_ABRT) {
×
759
        return ERR_ABRT;
×
760
      }
761
      tcp_ack_now(pcb);
×
762
    }
763
    /* received ACK? possibly a half-open connection */
764
    else if (flags & TCP_ACK) {
×
765
      /* send a RST to bring the other side in a non-synchronized state. */
766
      tcp_rst(ackno, seqno + tcplen, ipX_current_dest_addr(),
×
767
        ipX_current_src_addr(), tcphdr->dest, tcphdr->src, ip_current_is_v6());
768
    }
769
    break;
×
770
  case SYN_RCVD:
771
    if (flags & TCP_ACK) {
×
772
      /* expected ACK number? */
773
      if (TCP_SEQ_BETWEEN(ackno, pcb->lastack+1, pcb->snd_nxt)) {
×
774
        tcpwnd_size_t old_cwnd;
775
        pcb->state = ESTABLISHED;
×
776
        LWIP_DEBUGF(TCP_DEBUG, ("TCP connection established %"U16_F" -> %"U16_F".\n", inseg.tcphdr->src, inseg.tcphdr->dest));
777
#if LWIP_CALLBACK_API
778
        LWIP_ASSERT("pcb->accept != NULL", pcb->accept != NULL);
×
779
#endif
780
        /* Call the accept function. */
781
        TCP_EVENT_ACCEPT(pcb, ERR_OK, err);
×
782
        if (err != ERR_OK) {
×
783
          /* If the accept function returns with an error, we abort
784
           * the connection. */
785
          /* Already aborted? */
786
          if (err != ERR_ABRT) {
×
787
            tcp_abort(pcb);
×
788
          }
789
          return ERR_ABRT;
×
790
        }
791
        old_cwnd = pcb->cwnd;
×
792
        /* If there was any data contained within this ACK,
793
         * we'd better pass it on to the application as well. */
794
        tcp_receive(pcb);
×
795

796
        /* Prevent ACK for SYN to generate a sent event */
797
        if (pcb->acked != 0) {
×
798
          pcb->acked--;
×
799
        }
800

801
        pcb->cwnd = ((old_cwnd == 1) ? (pcb->mss * 2) : pcb->mss);
×
802

803
        if (recv_flags & TF_GOT_FIN) {
×
804
          tcp_ack_now(pcb);
×
805
          pcb->state = CLOSE_WAIT;
×
806
        }
807
      } else {
808
        /* incorrect ACK number, send RST */
809
        tcp_rst(ackno, seqno + tcplen, ipX_current_dest_addr(),
×
810
          ipX_current_src_addr(), tcphdr->dest, tcphdr->src, ip_current_is_v6());
811
      }
812
    } else if ((flags & TCP_SYN) && (seqno == pcb->rcv_nxt - 1)) {
×
813
      /* Looks like another copy of the SYN - retransmit our SYN-ACK */
814
      tcp_rexmit(pcb);
×
815
    }
816
    break;
×
817
  case CLOSE_WAIT:
818
    /* FALLTHROUGH */
819
  case ESTABLISHED:
820
    tcp_receive(pcb);
102✔
821
    if (recv_flags & TF_GOT_FIN) { /* passive close */
102✔
822
      tcp_ack_now(pcb);
18✔
823
      pcb->state = CLOSE_WAIT;
18✔
824
    }
825
    break;
102✔
826
  case FIN_WAIT_1:
827
    tcp_receive(pcb);
×
828
    if (recv_flags & TF_GOT_FIN) {
×
829
      if ((flags & TCP_ACK) && (ackno == pcb->snd_nxt)) {
×
830
        LWIP_DEBUGF(TCP_DEBUG,
831
          ("TCP connection closed: FIN_WAIT_1 %"U16_F" -> %"U16_F".\n", inseg.tcphdr->src, inseg.tcphdr->dest));
832
        tcp_ack_now(pcb);
×
833
        tcp_pcb_purge(pcb);
×
834
        TCP_RMV_ACTIVE(pcb);
×
835
        pcb->state = TIME_WAIT;
×
836
        TCP_REG(&tcp_tw_pcbs, pcb);
×
837
      } else {
838
        tcp_ack_now(pcb);
×
839
        pcb->state = CLOSING;
×
840
      }
841
    } else if ((flags & TCP_ACK) && (ackno == pcb->snd_nxt)) {
×
842
      pcb->state = FIN_WAIT_2;
×
843
    }
844
    break;
×
845
  case FIN_WAIT_2:
846
    tcp_receive(pcb);
×
847
    if (recv_flags & TF_GOT_FIN) {
×
848
      LWIP_DEBUGF(TCP_DEBUG, ("TCP connection closed: FIN_WAIT_2 %"U16_F" -> %"U16_F".\n", inseg.tcphdr->src, inseg.tcphdr->dest));
849
      tcp_ack_now(pcb);
×
850
      tcp_pcb_purge(pcb);
×
851
      TCP_RMV_ACTIVE(pcb);
×
852
      pcb->state = TIME_WAIT;
×
853
      TCP_REG(&tcp_tw_pcbs, pcb);
×
854
    }
855
    break;
×
856
  case CLOSING:
857
    tcp_receive(pcb);
×
858
    if (flags & TCP_ACK && ackno == pcb->snd_nxt) {
×
859
      LWIP_DEBUGF(TCP_DEBUG, ("TCP connection closed: CLOSING %"U16_F" -> %"U16_F".\n", inseg.tcphdr->src, inseg.tcphdr->dest));
860
      tcp_pcb_purge(pcb);
×
861
      TCP_RMV_ACTIVE(pcb);
×
862
      pcb->state = TIME_WAIT;
×
863
      TCP_REG(&tcp_tw_pcbs, pcb);
×
864
    }
865
    break;
×
866
  case LAST_ACK:
867
    tcp_receive(pcb);
×
868
    if (flags & TCP_ACK && ackno == pcb->snd_nxt) {
×
869
      LWIP_DEBUGF(TCP_DEBUG, ("TCP connection closed: LAST_ACK %"U16_F" -> %"U16_F".\n", inseg.tcphdr->src, inseg.tcphdr->dest));
870
      /* bugfix #21699: don't set pcb->state to CLOSED here or we risk leaking segments */
871
      recv_flags |= TF_CLOSED;
×
872
    }
873
    break;
×
874
  default:
875
    break;
×
876
  }
877
  return ERR_OK;
102✔
878
}
879

880
#if TCP_QUEUE_OOSEQ
881
/**
882
 * Insert segment into the list (segments covered with new one will be deleted)
883
 *
884
 * Called from tcp_receive()
885
 */
886
static void
887
tcp_oos_insert_segment(struct tcp_seg *cseg, struct tcp_seg *next)
5✔
888
{
889
  struct tcp_seg *old_seg;
890

891
  if (TCPH_FLAGS(cseg->tcphdr) & TCP_FIN) {
5✔
892
    /* received segment overlaps all following segments */
893
    tcp_segs_free(next);
×
894
    next = NULL;
×
895
  }
896
  else {
897
    /* delete some following segments
898
       oos queue may have segments with FIN flag */
899
    while (next &&
22✔
900
           TCP_SEQ_GEQ((seqno + cseg->len),
7✔
901
                      (next->tcphdr->seqno + next->len))) {
902
      /* cseg with FIN already processed */
903
      if (TCPH_FLAGS(next->tcphdr) & TCP_FIN) {
5✔
904
        TCPH_SET_FLAG(cseg->tcphdr, TCP_FIN);
1✔
905
      }
906
      old_seg = next;
5✔
907
      next = next->next;
5✔
908
      tcp_seg_free(old_seg);
5✔
909
    }
910
    if (next &&
7✔
911
        TCP_SEQ_GT(seqno + cseg->len, next->tcphdr->seqno)) {
2✔
912
      /* We need to trim the incoming segment. */
913
      cseg->len = (u16_t)(next->tcphdr->seqno - seqno);
2✔
914
      pbuf_realloc(cseg->p, cseg->len);
2✔
915
    }
916
  }
917
  cseg->next = next;
5✔
918
}
5✔
919
#endif /* TCP_QUEUE_OOSEQ */
920

921
/**
922
 * Called by tcp_process. Checks if the given segment is an ACK for outstanding
923
 * data, and if so frees the memory of the buffered data. Next, is places the
924
 * segment on any of the receive queues (pcb->recved or pcb->ooseq). If the segment
925
 * is buffered, the pbuf is referenced by pbuf_ref so that it will not be freed until
926
 * it has been removed from the buffer.
927
 *
928
 * If the incoming segment constitutes an ACK for a segment that was used for RTT
929
 * estimation, the RTT is estimated here as well.
930
 *
931
 * Called from tcp_process().
932
 */
933
static void
934
tcp_receive(struct tcp_pcb *pcb)
102✔
935
{
936
  struct tcp_seg *next;
937
#if TCP_QUEUE_OOSEQ
938
  struct tcp_seg *prev, *cseg;
939
#endif /* TCP_QUEUE_OOSEQ */
940
  struct pbuf *p;
941
  s32_t off;
942
  s16_t m;
943
  u32_t right_wnd_edge;
944
  u16_t new_tot_len;
945
  int found_dupack = 0;
102✔
946
#if TCP_OOSEQ_MAX_BYTES || TCP_OOSEQ_MAX_PBUFS
947
  u32_t ooseq_blen;
948
  u16_t ooseq_qlen;
949
#endif /* TCP_OOSEQ_MAX_BYTES || TCP_OOSEQ_MAX_PBUFS */
950

951
  LWIP_ASSERT("tcp_receive: wrong state", pcb->state >= ESTABLISHED);
102✔
952

953
  if (flags & TCP_ACK) {
102✔
954
    right_wnd_edge = pcb->snd_wnd + pcb->snd_wl2;
101✔
955

956
    /* Update window. */
957
    if (TCP_SEQ_LT(pcb->snd_wl1, seqno) ||
140✔
958
       (pcb->snd_wl1 == seqno && TCP_SEQ_LT(pcb->snd_wl2, ackno)) ||
87✔
959
       (pcb->snd_wl2 == ackno && tcphdr->wnd > pcb->snd_wnd)) {
70✔
960
      pcb->snd_wnd = SND_WND_SCALE(pcb, tcphdr->wnd); 
66✔
961
      /* keep track of the biggest window announced by the remote host to calculate
962
         the maximum segment size */
963
      if (pcb->snd_wnd_max < pcb->snd_wnd) {
66✔
964
        pcb->snd_wnd_max = pcb->snd_wnd; 
×
965
      }
966
      pcb->snd_wl1 = seqno;
66✔
967
      pcb->snd_wl2 = ackno;
66✔
968
      if (pcb->snd_wnd == 0) {
66✔
969
        if (pcb->persist_backoff == 0) {
1✔
970
          /* start persist timer */
971
          pcb->persist_cnt = 0;
1✔
972
          pcb->persist_backoff = 1;
1✔
973
        }
974
      } else if (pcb->persist_backoff > 0) {
65✔
975
        /* stop persist timer */
976
          pcb->persist_backoff = 0;
×
977
      }
978
      LWIP_DEBUGF(TCP_WND_DEBUG, ("tcp_receive: window update %"U16_F"\n", pcb->snd_wnd));
979
#if TCP_WND_DEBUG
980
    } else {
981
      if (pcb->snd_wnd != tcphdr->wnd) {
982
        LWIP_DEBUGF(TCP_WND_DEBUG, 
983
                    ("tcp_receive: no window update lastack %"U32_F" ackno %"
984
                     U32_F" wl1 %"U32_F" seqno %"U32_F" wl2 %"U32_F"\n",
985
                     pcb->lastack, ackno, pcb->snd_wl1, seqno, pcb->snd_wl2));
986
      }
987
#endif /* TCP_WND_DEBUG */
988
    }
989

990
    /* (From Stevens TCP/IP Illustrated Vol II, p970.) Its only a
991
     * duplicate ack if:
992
     * 1) It doesn't ACK new data 
993
     * 2) length of received packet is zero (i.e. no payload) 
994
     * 3) the advertised window hasn't changed 
995
     * 4) There is outstanding unacknowledged data (retransmission timer running)
996
     * 5) The ACK is == biggest ACK sequence number so far seen (snd_una)
997
     * 
998
     * If it passes all five, should process as a dupack: 
999
     * a) dupacks < 3: do nothing 
1000
     * b) dupacks == 3: fast retransmit 
1001
     * c) dupacks > 3: increase cwnd 
1002
     * 
1003
     * If it only passes 1-3, should reset dupack counter (and add to
1004
     * stats, which we don't do in lwIP)
1005
     *
1006
     * If it only passes 1, should reset dupack counter
1007
     *
1008
     */
1009

1010
    /* Clause 1 */
1011
    if (TCP_SEQ_LEQ(ackno, pcb->lastack)) {
101✔
1012
      pcb->acked = 0;
97✔
1013
      /* Clause 2 */
1014
      if (tcplen == 0) {
97✔
1015
        /* Clause 3 */
1016
        if (pcb->snd_wl2 + pcb->snd_wnd == right_wnd_edge){
8✔
1017
          /* Clause 4 */
1018
          if (pcb->rtime >= 0) {
8✔
1019
            /* Clause 5 */
1020
            if (pcb->lastack == ackno) {
8✔
1021
              found_dupack = 1;
8✔
1022
              if ((u8_t)(pcb->dupacks + 1) > pcb->dupacks) {
8✔
1023
                ++pcb->dupacks;
8✔
1024
              }
1025
              if (pcb->dupacks > 3) {
8✔
1026
                /* Inflate the congestion window, but not if it means that
1027
                   the value overflows. */
1028
                if ((tcpwnd_size_t)(pcb->cwnd + pcb->mss) > pcb->cwnd) {
×
1029
                  pcb->cwnd += pcb->mss;
×
1030
                }
1031
              } else if (pcb->dupacks == 3) {
8✔
1032
                /* Do fast retransmit */
1033
                tcp_rexmit_fast(pcb);
2✔
1034
              }
1035
            }
1036
          }
1037
        }
1038
      }
1039
      /* If Clause (1) or more is true, but not a duplicate ack, reset
1040
       * count of consecutive duplicate acks */
1041
      if (!found_dupack) {
97✔
1042
        pcb->dupacks = 0;
89✔
1043
      }
1044
    } else if (TCP_SEQ_BETWEEN(ackno, pcb->lastack+1, pcb->snd_nxt)){
4✔
1045
      /* We come here when the ACK acknowledges new data. */
1046

1047
      /* Reset the "IN Fast Retransmit" flag, since we are no longer
1048
         in fast retransmit. Also reset the congestion window to the
1049
         slow start threshold. */
1050
      if (pcb->flags & TF_INFR) {
4✔
1051
        pcb->flags &= ~TF_INFR;
1✔
1052
        pcb->cwnd = pcb->ssthresh;
1✔
1053
      }
1054

1055
      /* Reset the number of retransmissions. */
1056
      pcb->nrtx = 0;
4✔
1057

1058
      /* Reset the retransmission time-out. */
1059
      pcb->rto = (pcb->sa >> 3) + pcb->sv;
4✔
1060

1061
      /* Update the send buffer space. Diff between the two can never exceed 64K
1062
         unless window scaling is used. */
1063
      pcb->acked = (tcpwnd_size_t)(ackno - pcb->lastack);
4✔
1064

1065
      pcb->snd_buf += pcb->acked;
4✔
1066

1067
      /* Reset the fast retransmit variables. */
1068
      pcb->dupacks = 0;
4✔
1069
      pcb->lastack = ackno;
4✔
1070

1071
      /* Update the congestion control variables (cwnd and
1072
         ssthresh). */
1073
      if (pcb->state >= ESTABLISHED) {
4✔
1074
        if (pcb->cwnd < pcb->ssthresh) {
4✔
1075
          if ((tcpwnd_size_t)(pcb->cwnd + pcb->mss) > pcb->cwnd) {
×
1076
            pcb->cwnd += pcb->mss;
×
1077
          }
1078
          LWIP_DEBUGF(TCP_CWND_DEBUG, ("tcp_receive: slow start cwnd %"TCPWNDSIZE_F"\n", pcb->cwnd));
1079
        } else {
1080
          tcpwnd_size_t new_cwnd = (pcb->cwnd + pcb->mss * pcb->mss / pcb->cwnd);
4✔
1081
          if (new_cwnd > pcb->cwnd) {
4✔
1082
            pcb->cwnd = new_cwnd;
4✔
1083
          }
1084
          LWIP_DEBUGF(TCP_CWND_DEBUG, ("tcp_receive: congestion avoidance cwnd %"TCPWNDSIZE_F"\n", pcb->cwnd));
1085
        }
1086
      }
1087
      LWIP_DEBUGF(TCP_INPUT_DEBUG, ("tcp_receive: ACK for %"U32_F", unacked->seqno %"U32_F":%"U32_F"\n",
1088
                                    ackno,
1089
                                    pcb->unacked != NULL?
1090
                                    ntohl(pcb->unacked->tcphdr->seqno): 0,
1091
                                    pcb->unacked != NULL?
1092
                                    ntohl(pcb->unacked->tcphdr->seqno) + TCP_TCPLEN(pcb->unacked): 0));
1093

1094
      /* Remove segment from the unacknowledged list if the incoming
1095
         ACK acknowledges them. */
1096
      while (pcb->unacked != NULL &&
38✔
1097
             TCP_SEQ_LEQ(ntohl(pcb->unacked->tcphdr->seqno) +
16✔
1098
                         TCP_TCPLEN(pcb->unacked), ackno)) {
1099
        LWIP_DEBUGF(TCP_INPUT_DEBUG, ("tcp_receive: removing %"U32_F":%"U32_F" from pcb->unacked\n",
1100
                                      ntohl(pcb->unacked->tcphdr->seqno),
1101
                                      ntohl(pcb->unacked->tcphdr->seqno) +
1102
                                      TCP_TCPLEN(pcb->unacked)));
1103

1104
        next = pcb->unacked;
14✔
1105
        pcb->unacked = pcb->unacked->next;
14✔
1106

1107
        LWIP_DEBUGF(TCP_QLEN_DEBUG, ("tcp_receive: queuelen %"TCPWNDSIZE_F" ... ", (tcpwnd_size_t)pcb->snd_queuelen));
1108
        LWIP_ASSERT("pcb->snd_queuelen >= pbuf_clen(next->p)", (pcb->snd_queuelen >= pbuf_clen(next->p)));
14✔
1109
        /* Prevent ACK for FIN to generate a sent event */
1110
        if ((pcb->acked != 0) && ((TCPH_FLAGS(next->tcphdr) & TCP_FIN) != 0)) {
14✔
1111
          pcb->acked--;
×
1112
        }
1113

1114
        pcb->snd_queuelen -= pbuf_clen(next->p);
14✔
1115
        tcp_seg_free(next);
14✔
1116

1117
        LWIP_DEBUGF(TCP_QLEN_DEBUG, ("%"TCPWNDSIZE_F" (after freeing unacked)\n", (tcpwnd_size_t)pcb->snd_queuelen));
1118
        if (pcb->snd_queuelen != 0) {
14✔
1119
          LWIP_ASSERT("tcp_receive: valid queue length", pcb->unacked != NULL ||
12✔
1120
                      pcb->unsent != NULL);
1121
        }
1122
      }
1123

1124
      /* If there's nothing left to acknowledge, stop the retransmit
1125
         timer, otherwise reset it to start again */
1126
      if (pcb->unacked == NULL) {
4✔
1127
        pcb->rtime = -1;
2✔
1128
      } else {
1129
        pcb->rtime = 0;
2✔
1130
      }
1131

1132
      pcb->polltmr = 0;
4✔
1133

1134
#if LWIP_IPV6 && LWIP_ND6_TCP_REACHABILITY_HINTS
1135
      if (PCB_ISIPV6(pcb)) {
1136
        /* Inform neighbor reachability of forward progress. */
1137
        nd6_reachability_hint(ip6_current_src_addr());
1138
      }
1139
#endif /* LWIP_IPV6 && LWIP_ND6_TCP_REACHABILITY_HINTS*/
1140
    } else {
1141
      /* Out of sequence ACK, didn't really ack anything */
1142
      pcb->acked = 0;
×
1143
      tcp_send_empty_ack(pcb);
×
1144
    }
1145

1146
    /* We go through the ->unsent list to see if any of the segments
1147
       on the list are acknowledged by the ACK. This may seem
1148
       strange since an "unsent" segment shouldn't be acked. The
1149
       rationale is that lwIP puts all outstanding segments on the
1150
       ->unsent list after a retransmission, so these segments may
1151
       in fact have been sent once. */
1152
    while (pcb->unsent != NULL &&
209✔
1153
           TCP_SEQ_BETWEEN(ackno, ntohl(pcb->unsent->tcphdr->seqno) + 
7✔
1154
                           TCP_TCPLEN(pcb->unsent), pcb->snd_nxt)) {
1155
      LWIP_DEBUGF(TCP_INPUT_DEBUG, ("tcp_receive: removing %"U32_F":%"U32_F" from pcb->unsent\n",
1156
                                    ntohl(pcb->unsent->tcphdr->seqno), ntohl(pcb->unsent->tcphdr->seqno) +
1157
                                    TCP_TCPLEN(pcb->unsent)));
1158

1159
      next = pcb->unsent;
×
1160
      pcb->unsent = pcb->unsent->next;
×
1161
#if TCP_OVERSIZE
1162
      if (pcb->unsent == NULL) {
×
1163
        pcb->unsent_oversize = 0;
×
1164
      }
1165
#endif /* TCP_OVERSIZE */ 
1166
      LWIP_DEBUGF(TCP_QLEN_DEBUG, ("tcp_receive: queuelen %"TCPWNDSIZE_F" ... ", (tcpwnd_size_t)pcb->snd_queuelen));
1167
      LWIP_ASSERT("pcb->snd_queuelen >= pbuf_clen(next->p)", (pcb->snd_queuelen >= pbuf_clen(next->p)));
×
1168
      /* Prevent ACK for FIN to generate a sent event */
1169
      if ((pcb->acked != 0) && ((TCPH_FLAGS(next->tcphdr) & TCP_FIN) != 0)) {
×
1170
        pcb->acked--;
×
1171
      }
1172
      pcb->snd_queuelen -= pbuf_clen(next->p);
×
1173
      tcp_seg_free(next);
×
1174
      LWIP_DEBUGF(TCP_QLEN_DEBUG, ("%"TCPWNDSIZE_F" (after freeing unsent)\n", (tcpwnd_size_t)pcb->snd_queuelen));
1175
      if (pcb->snd_queuelen != 0) {
×
1176
        LWIP_ASSERT("tcp_receive: valid queue length",
×
1177
          pcb->unacked != NULL || pcb->unsent != NULL);
1178
      }
1179
    }
1180
    /* End of ACK for new data processing. */
1181

1182
    LWIP_DEBUGF(TCP_RTO_DEBUG, ("tcp_receive: pcb->rttest %"U32_F" rtseq %"U32_F" ackno %"U32_F"\n",
1183
                                pcb->rttest, pcb->rtseq, ackno));
1184

1185
    /* RTT estimation calculations. This is done by checking if the
1186
       incoming segment acknowledges the segment we use to take a
1187
       round-trip time measurement. */
1188
    if (pcb->rttest && TCP_SEQ_LT(pcb->rtseq, ackno)) {
101✔
1189
      /* diff between this shouldn't exceed 32K since this are tcp timer ticks
1190
         and a round-trip shouldn't be that long... */
1191
      m = (s16_t)(tcp_ticks - pcb->rttest);
1✔
1192

1193
      LWIP_DEBUGF(TCP_RTO_DEBUG, ("tcp_receive: experienced rtt %"U16_F" ticks (%"U16_F" msec).\n",
1194
                                  m, m * TCP_SLOW_INTERVAL));
1195

1196
      /* This is taken directly from VJs original code in his paper */
1197
      m = m - (pcb->sa >> 3);
1✔
1198
      pcb->sa += m;
1✔
1199
      if (m < 0) {
1✔
1200
        m = -m;
×
1201
      }
1202
      m = m - (pcb->sv >> 2);
1✔
1203
      pcb->sv += m;
1✔
1204
      pcb->rto = (pcb->sa >> 3) + pcb->sv;
1✔
1205

1206
      LWIP_DEBUGF(TCP_RTO_DEBUG, ("tcp_receive: RTO %"U16_F" (%"U16_F" milliseconds)\n",
1207
                                  pcb->rto, pcb->rto * TCP_SLOW_INTERVAL));
1208

1209
      pcb->rttest = 0;
1✔
1210
    }
1211
  }
1212

1213
  /* If the incoming segment contains data, we must process it
1214
     further unless the pcb already received a FIN.
1215
     (RFC 793, chapter 3.9, "SEGMENT ARRIVES" in states CLOSE-WAIT, CLOSING,
1216
     LAST-ACK and TIME-WAIT: "Ignore the segment text.") */
1217
  if ((tcplen > 0) && (pcb->state < CLOSE_WAIT)) {
102✔
1218
    /* This code basically does three things:
1219

1220
    +) If the incoming segment contains data that is the next
1221
    in-sequence data, this data is passed to the application. This
1222
    might involve trimming the first edge of the data. The rcv_nxt
1223
    variable and the advertised window are adjusted.
1224

1225
    +) If the incoming segment has data that is above the next
1226
    sequence number expected (->rcv_nxt), the segment is placed on
1227
    the ->ooseq queue. This is done by finding the appropriate
1228
    place in the ->ooseq queue (which is ordered by sequence
1229
    number) and trim the segment in both ends if needed. An
1230
    immediate ACK is sent to indicate that we received an
1231
    out-of-sequence segment.
1232

1233
    +) Finally, we check if the first segment on the ->ooseq queue
1234
    now is in sequence (i.e., if rcv_nxt >= ooseq->seqno). If
1235
    rcv_nxt > ooseq->seqno, we must trim the first edge of the
1236
    segment on ->ooseq before we adjust rcv_nxt. The data in the
1237
    segments that are now on sequence are chained onto the
1238
    incoming segment so that we only need to call the application
1239
    once.
1240
    */
1241

1242
    /* First, we check if we must trim the first edge. We have to do
1243
       this if the sequence number of the incoming segment is less
1244
       than rcv_nxt, and the sequence number plus the length of the
1245
       segment is larger than rcv_nxt. */
1246
    /*    if (TCP_SEQ_LT(seqno, pcb->rcv_nxt)){
1247
          if (TCP_SEQ_LT(pcb->rcv_nxt, seqno + tcplen)) {*/
1248
    if (TCP_SEQ_BETWEEN(pcb->rcv_nxt, seqno + 1, seqno + tcplen - 1)){
70✔
1249
      /* Trimming the first edge is done by pushing the payload
1250
         pointer in the pbuf downwards. This is somewhat tricky since
1251
         we do not want to discard the full contents of the pbuf up to
1252
         the new starting point of the data since we have to keep the
1253
         TCP header which is present in the first pbuf in the chain.
1254

1255
         What is done is really quite a nasty hack: the first pbuf in
1256
         the pbuf chain is pointed to by inseg.p. Since we need to be
1257
         able to deallocate the whole pbuf, we cannot change this
1258
         inseg.p pointer to point to any of the later pbufs in the
1259
         chain. Instead, we point the ->payload pointer in the first
1260
         pbuf to data in one of the later pbufs. We also set the
1261
         inseg.data pointer to point to the right place. This way, the
1262
         ->p pointer will still point to the first pbuf, but the
1263
         ->p->payload pointer will point to data in another pbuf.
1264

1265
         After we are done with adjusting the pbuf pointers we must
1266
         adjust the ->data pointer in the seg and the segment
1267
         length.*/
1268

1269
      off = pcb->rcv_nxt - seqno;
×
1270
      p = inseg.p;
×
1271
      LWIP_ASSERT("inseg.p != NULL", inseg.p);
×
1272
      LWIP_ASSERT("insane offset!", (off < 0x7fff));
1273
      if (inseg.p->len < off) {
×
1274
        LWIP_ASSERT("pbuf too short!", (((s32_t)inseg.p->tot_len) >= off));
×
1275
        new_tot_len = (u16_t)(inseg.p->tot_len - off);
×
1276
        while (p->len < off) {
×
1277
          off -= p->len;
×
1278
          /* KJM following line changed (with addition of new_tot_len var)
1279
             to fix bug #9076
1280
             inseg.p->tot_len -= p->len; */
1281
          p->tot_len = new_tot_len;
×
1282
          p->len = 0;
×
1283
          p = p->next;
×
1284
        }
1285
        if(pbuf_header(p, (s16_t)-off)) {
×
1286
          /* Do we need to cope with this failing?  Assert for now */
1287
          LWIP_ASSERT("pbuf_header failed", 0);
1288
        }
1289
      } else {
1290
        if(pbuf_header(inseg.p, (s16_t)-off)) {
×
1291
          /* Do we need to cope with this failing?  Assert for now */
1292
          LWIP_ASSERT("pbuf_header failed", 0);
1293
        }
1294
      }
1295
      inseg.len -= (u16_t)(pcb->rcv_nxt - seqno);
×
1296
      inseg.tcphdr->seqno = seqno = pcb->rcv_nxt;
×
1297
    }
1298
    else {
1299
      if (TCP_SEQ_LT(seqno, pcb->rcv_nxt)){
70✔
1300
        /* the whole segment is < rcv_nxt */
1301
        /* must be a duplicate of a packet that has already been correctly handled */
1302

1303
        LWIP_DEBUGF(TCP_INPUT_DEBUG, ("tcp_receive: duplicate seqno %"U32_F"\n", seqno));
1304
        tcp_ack_now(pcb);
×
1305
      }
1306
    }
1307

1308
    /* The sequence number must be within the window (above rcv_nxt
1309
       and below rcv_nxt + rcv_wnd) in order to be further
1310
       processed. */
1311
    if (TCP_SEQ_BETWEEN(seqno, pcb->rcv_nxt, 
140✔
1312
                        pcb->rcv_nxt + pcb->rcv_wnd - 1)){
1313
      if (pcb->rcv_nxt == seqno) {
138✔
1314
        /* The incoming segment is the next in sequence. We check if
1315
           we have to trim the end of the segment and update rcv_nxt
1316
           and pass the data to the application. */
1317
        tcplen = TCP_TCPLEN(&inseg);
33✔
1318

1319
        if (tcplen > pcb->rcv_wnd) {
33✔
1320
          LWIP_DEBUGF(TCP_INPUT_DEBUG, 
1321
                      ("tcp_receive: other end overran receive window"
1322
                       "seqno %"U32_F" len %"U16_F" right edge %"U32_F"\n",
1323
                       seqno, tcplen, pcb->rcv_nxt + pcb->rcv_wnd));
1324
          if (TCPH_FLAGS(inseg.tcphdr) & TCP_FIN) {
×
1325
            /* Must remove the FIN from the header as we're trimming 
1326
             * that byte of sequence-space from the packet */
1327
            TCPH_FLAGS_SET(inseg.tcphdr, TCPH_FLAGS(inseg.tcphdr) &~ TCP_FIN);
×
1328
          }
1329
          /* Adjust length of segment to fit in the window. */
1330
          inseg.len = pcb->rcv_wnd;
×
1331
          if (TCPH_FLAGS(inseg.tcphdr) & TCP_SYN) {
×
1332
            inseg.len -= 1;
×
1333
          }
1334
          pbuf_realloc(inseg.p, inseg.len);
×
1335
          tcplen = TCP_TCPLEN(&inseg);
×
1336
          LWIP_ASSERT("tcp_receive: segment not trimmed correctly to rcv_wnd\n",
×
1337
                      (seqno + tcplen) == (pcb->rcv_nxt + pcb->rcv_wnd));
1338
        }
1339
#if TCP_QUEUE_OOSEQ
1340
        /* Received in-sequence data, adjust ooseq data if:
1341
           - FIN has been received or
1342
           - inseq overlaps with ooseq */
1343
        if (pcb->ooseq != NULL) {
33✔
1344
          if (TCPH_FLAGS(inseg.tcphdr) & TCP_FIN) {
17✔
1345
            LWIP_DEBUGF(TCP_INPUT_DEBUG, 
1346
                        ("tcp_receive: received in-order FIN, binning ooseq queue\n"));
1347
            /* Received in-order FIN means anything that was received
1348
             * out of order must now have been received in-order, so
1349
             * bin the ooseq queue */
1350
            while (pcb->ooseq != NULL) {
23✔
1351
              struct tcp_seg *old_ooseq = pcb->ooseq;
9✔
1352
              pcb->ooseq = pcb->ooseq->next;
9✔
1353
              tcp_seg_free(old_ooseq);
9✔
1354
            }
1355
          } else {
1356
            next = pcb->ooseq;
10✔
1357
            /* Remove all segments on ooseq that are covered by inseg already.
1358
             * FIN is copied from ooseq to inseg if present. */
1359
            while (next &&
36✔
1360
                   TCP_SEQ_GEQ(seqno + tcplen,
11✔
1361
                               next->tcphdr->seqno + next->len)) {
1362
              /* inseg cannot have FIN here (already processed above) */
1363
              if (TCPH_FLAGS(next->tcphdr) & TCP_FIN &&
9✔
1364
                  (TCPH_FLAGS(inseg.tcphdr) & TCP_SYN) == 0) {
4✔
1365
                TCPH_SET_FLAG(inseg.tcphdr, TCP_FIN);
4✔
1366
                tcplen = TCP_TCPLEN(&inseg);
4✔
1367
              }
1368
              prev = next;
5✔
1369
              next = next->next;
5✔
1370
              tcp_seg_free(prev);
5✔
1371
            }
1372
            /* Now trim right side of inseg if it overlaps with the first
1373
             * segment on ooseq */
1374
            if (next &&
16✔
1375
                TCP_SEQ_GT(seqno + tcplen,
6✔
1376
                           next->tcphdr->seqno)) {
1377
              /* inseg cannot have FIN here (already processed above) */
1378
              inseg.len = (u16_t)(next->tcphdr->seqno - seqno);
2✔
1379
              if (TCPH_FLAGS(inseg.tcphdr) & TCP_SYN) {
2✔
1380
                inseg.len -= 1;
×
1381
              }
1382
              pbuf_realloc(inseg.p, inseg.len);
2✔
1383
              tcplen = TCP_TCPLEN(&inseg);
2✔
1384
              LWIP_ASSERT("tcp_receive: segment not trimmed correctly to ooseq queue\n",
2✔
1385
                          (seqno + tcplen) == next->tcphdr->seqno);
1386
            }
1387
            pcb->ooseq = next;
10✔
1388
          }
1389
        }
1390
#endif /* TCP_QUEUE_OOSEQ */
1391

1392
        pcb->rcv_nxt = seqno + tcplen;
33✔
1393

1394
        /* Update the receiver's (our) window. */
1395
        LWIP_ASSERT("tcp_receive: tcplen > rcv_wnd\n", pcb->rcv_wnd >= tcplen);
33✔
1396
        pcb->rcv_wnd -= tcplen;
33✔
1397

1398
        tcp_update_rcv_ann_wnd(pcb);
33✔
1399

1400
        /* If there is data in the segment, we make preparations to
1401
           pass this up to the application. The ->recv_data variable
1402
           is used for holding the pbuf that goes to the
1403
           application. The code for reassembling out-of-sequence data
1404
           chains its data on this pbuf as well.
1405

1406
           If the segment was a FIN, we set the TF_GOT_FIN flag that will
1407
           be used to indicate to the application that the remote side has
1408
           closed its end of the connection. */
1409
        if (inseg.p->tot_len > 0) {
33✔
1410
          recv_data = inseg.p;
21✔
1411
          /* Since this pbuf now is the responsibility of the
1412
             application, we delete our reference to it so that we won't
1413
             (mistakingly) deallocate it. */
1414
          inseg.p = NULL;
21✔
1415
        }
1416
        if (TCPH_FLAGS(inseg.tcphdr) & TCP_FIN) {
33✔
1417
          LWIP_DEBUGF(TCP_INPUT_DEBUG, ("tcp_receive: received FIN.\n"));
1418
          recv_flags |= TF_GOT_FIN;
17✔
1419
        }
1420

1421
#if TCP_QUEUE_OOSEQ
1422
        /* We now check if we have segments on the ->ooseq queue that
1423
           are now in sequence. */
1424
        while (pcb->ooseq != NULL &&
91✔
1425
               pcb->ooseq->tcphdr->seqno == pcb->rcv_nxt) {
14✔
1426

1427
          cseg = pcb->ooseq;
11✔
1428
          seqno = pcb->ooseq->tcphdr->seqno;
11✔
1429

1430
          pcb->rcv_nxt += TCP_TCPLEN(cseg);
11✔
1431
          LWIP_ASSERT("tcp_receive: ooseq tcplen > rcv_wnd\n",
11✔
1432
                      pcb->rcv_wnd >= TCP_TCPLEN(cseg));
1433
          pcb->rcv_wnd -= TCP_TCPLEN(cseg);
11✔
1434

1435
          tcp_update_rcv_ann_wnd(pcb);
11✔
1436

1437
          if (cseg->p->tot_len > 0) {
11✔
1438
            /* Chain this pbuf onto the pbuf that we will pass to
1439
               the application. */
1440
            /* With window scaling, this can overflow recv_data->tot_len, but
1441
               that's not a problem since we explicitly fix that before passing
1442
               recv_data to the application. */
1443
            if (recv_data) {
11✔
1444
              pbuf_cat(recv_data, cseg->p);
11✔
1445
            } else {
1446
              recv_data = cseg->p;
×
1447
            }
1448
            cseg->p = NULL;
11✔
1449
          }
1450
          if (TCPH_FLAGS(cseg->tcphdr) & TCP_FIN) {
11✔
1451
            LWIP_DEBUGF(TCP_INPUT_DEBUG, ("tcp_receive: dequeued FIN.\n"));
1452
            recv_flags |= TF_GOT_FIN;
1✔
1453
            if (pcb->state == ESTABLISHED) { /* force passive close or we can move to active close */
1✔
1454
              pcb->state = CLOSE_WAIT;
1✔
1455
            } 
1456
          }
1457

1458
          pcb->ooseq = cseg->next;
11✔
1459
          tcp_seg_free(cseg);
11✔
1460
        }
1461
#endif /* TCP_QUEUE_OOSEQ */
1462

1463

1464
        /* Acknowledge the segment(s). */
1465
        tcp_ack(pcb);
33✔
1466

1467
#if LWIP_IPV6 && LWIP_ND6_TCP_REACHABILITY_HINTS
1468
        if (PCB_ISIPV6(pcb)) {
1469
          /* Inform neighbor reachability of forward progress. */
1470
          nd6_reachability_hint(ip6_current_src_addr());
1471
        }
1472
#endif /* LWIP_IPV6 && LWIP_ND6_TCP_REACHABILITY_HINTS*/
1473

1474
      } else {
1475
        /* We get here if the incoming segment is out-of-sequence. */
1476
        tcp_send_empty_ack(pcb);
36✔
1477
#if TCP_QUEUE_OOSEQ
1478
        /* We queue the segment on the ->ooseq queue. */
1479
        if (pcb->ooseq == NULL) {
36✔
1480
          pcb->ooseq = tcp_seg_copy(&inseg);
14✔
1481
        } else {
1482
          /* If the queue is not empty, we walk through the queue and
1483
             try to find a place where the sequence number of the
1484
             incoming segment is between the sequence numbers of the
1485
             previous and the next segment on the ->ooseq queue. That is
1486
             the place where we put the incoming segment. If needed, we
1487
             trim the second edges of the previous and the incoming
1488
             segment so that it will fit into the sequence.
1489

1490
             If the incoming segment has the same sequence number as a
1491
             segment on the ->ooseq queue, we discard the segment that
1492
             contains less data. */
1493

1494
          prev = NULL;
22✔
1495
          for(next = pcb->ooseq; next != NULL; next = next->next) {
52✔
1496
            if (seqno == next->tcphdr->seqno) {
52✔
1497
              /* The sequence number of the incoming segment is the
1498
                 same as the sequence number of the segment on
1499
                 ->ooseq. We check the lengths to see which one to
1500
                 discard. */
1501
              if (inseg.len > next->len) {
2✔
1502
                /* The incoming segment is larger than the old
1503
                   segment. We replace some segments with the new
1504
                   one. */
1505
                cseg = tcp_seg_copy(&inseg);
1✔
1506
                if (cseg != NULL) {
1✔
1507
                  if (prev != NULL) {
1✔
1508
                    prev->next = cseg;
×
1509
                  } else {
1510
                    pcb->ooseq = cseg;
1✔
1511
                  }
1512
                  tcp_oos_insert_segment(cseg, next);
1✔
1513
                }
1514
                break;
1✔
1515
              } else {
1516
                /* Either the lengths are the same or the incoming
1517
                   segment was smaller than the old one; in either
1518
                   case, we ditch the incoming segment. */
1519
                break;
1✔
1520
              }
1521
            } else {
1522
              if (prev == NULL) {
50✔
1523
                if (TCP_SEQ_LT(seqno, next->tcphdr->seqno)) {
20✔
1524
                  /* The sequence number of the incoming segment is lower
1525
                     than the sequence number of the first segment on the
1526
                     queue. We put the incoming segment first on the
1527
                     queue. */
1528
                  cseg = tcp_seg_copy(&inseg);
2✔
1529
                  if (cseg != NULL) {
2✔
1530
                    pcb->ooseq = cseg;
2✔
1531
                    tcp_oos_insert_segment(cseg, next);
2✔
1532
                  }
1533
                  break;
2✔
1534
                }
1535
              } else {
1536
                /*if (TCP_SEQ_LT(prev->tcphdr->seqno, seqno) &&
1537
                  TCP_SEQ_LT(seqno, next->tcphdr->seqno)) {*/
1538
                if (TCP_SEQ_BETWEEN(seqno, prev->tcphdr->seqno+1, next->tcphdr->seqno-1)) {
30✔
1539
                  /* The sequence number of the incoming segment is in
1540
                     between the sequence numbers of the previous and
1541
                     the next segment on ->ooseq. We trim trim the previous
1542
                     segment, delete next segments that included in received segment
1543
                     and trim received, if needed. */
1544
                  cseg = tcp_seg_copy(&inseg);
2✔
1545
                  if (cseg != NULL) {
2✔
1546
                    if (TCP_SEQ_GT(prev->tcphdr->seqno + prev->len, seqno)) {
2✔
1547
                      /* We need to trim the prev segment. */
1548
                      prev->len = (u16_t)(seqno - prev->tcphdr->seqno);
1✔
1549
                      pbuf_realloc(prev->p, prev->len);
1✔
1550
                    }
1551
                    prev->next = cseg;
2✔
1552
                    tcp_oos_insert_segment(cseg, next);
2✔
1553
                  }
1554
                  break;
2✔
1555
                }
1556
              }
1557
              /* If the "next" segment is the last segment on the
1558
                 ooseq queue, we add the incoming segment to the end
1559
                 of the list. */
1560
              if (next->next == NULL &&
62✔
1561
                  TCP_SEQ_GT(seqno, next->tcphdr->seqno)) {
16✔
1562
                if (TCPH_FLAGS(next->tcphdr) & TCP_FIN) {
16✔
1563
                  /* segment "next" already contains all data */
1564
                  break;
5✔
1565
                }
1566
                next->next = tcp_seg_copy(&inseg);
11✔
1567
                if (next->next != NULL) {
11✔
1568
                  if (TCP_SEQ_GT(next->tcphdr->seqno + next->len, seqno)) {
11✔
1569
                    /* We need to trim the last segment. */
1570
                    next->len = (u16_t)(seqno - next->tcphdr->seqno);
×
1571
                    pbuf_realloc(next->p, next->len);
×
1572
                  }
1573
                  /* check if the remote side overruns our receive window */
1574
                  if ((u32_t)tcplen + seqno > pcb->rcv_nxt + (u32_t)pcb->rcv_wnd) {
11✔
1575
                    LWIP_DEBUGF(TCP_INPUT_DEBUG, 
1576
                                ("tcp_receive: other end overran receive window"
1577
                                 "seqno %"U32_F" len %"U16_F" right edge %"U32_F"\n",
1578
                                 seqno, tcplen, pcb->rcv_nxt + pcb->rcv_wnd));
1579
                    if (TCPH_FLAGS(next->next->tcphdr) & TCP_FIN) {
×
1580
                      /* Must remove the FIN from the header as we're trimming 
1581
                       * that byte of sequence-space from the packet */
1582
                      TCPH_FLAGS_SET(next->next->tcphdr, TCPH_FLAGS(next->next->tcphdr) &~ TCP_FIN);
×
1583
                    }
1584
                    /* Adjust length of segment to fit in the window. */
1585
                    next->next->len = pcb->rcv_nxt + pcb->rcv_wnd - seqno;
×
1586
                    pbuf_realloc(next->next->p, next->next->len);
×
1587
                    tcplen = TCP_TCPLEN(next->next);
×
1588
                    LWIP_ASSERT("tcp_receive: segment not trimmed correctly to rcv_wnd\n",
×
1589
                                (seqno + tcplen) == (pcb->rcv_nxt + pcb->rcv_wnd));
1590
                  }
1591
                }
1592
                break;
11✔
1593
              }
1594
            }
1595
            prev = next;
30✔
1596
          }
1597
        }
1598
#if TCP_OOSEQ_MAX_BYTES || TCP_OOSEQ_MAX_PBUFS
1599
        /* Check that the data on ooseq doesn't exceed one of the limits
1600
           and throw away everything above that limit. */
1601
        ooseq_blen = 0;
1602
        ooseq_qlen = 0;
1603
        prev = NULL;
1604
        for(next = pcb->ooseq; next != NULL; prev = next, next = next->next) {
1605
          struct pbuf *p = next->p;
1606
          ooseq_blen += p->tot_len;
1607
          ooseq_qlen += pbuf_clen(p);
1608
          if ((ooseq_blen > TCP_OOSEQ_MAX_BYTES) ||
1609
              (ooseq_qlen > TCP_OOSEQ_MAX_PBUFS)) {
1610
             /* too much ooseq data, dump this and everything after it */
1611
             tcp_segs_free(next);
1612
             if (prev == NULL) {
1613
               /* first ooseq segment is too much, dump the whole queue */
1614
               pcb->ooseq = NULL;
1615
             } else {
1616
               /* just dump 'next' and everything after it */
1617
               prev->next = NULL;
1618
             }
1619
             break;
1620
          }
1621
        }
1622
#endif /* TCP_OOSEQ_MAX_BYTES || TCP_OOSEQ_MAX_PBUFS */
1623
#endif /* TCP_QUEUE_OOSEQ */
1624
      }
1625
    } else {
1626
      /* The incoming segment is not within the window. */
1627
      tcp_send_empty_ack(pcb);
1✔
1628
    }
1629
  } else {
1630
    /* Segments with length 0 is taken care of here. Segments that
1631
       fall out of the window are ACKed. */
1632
    /*if (TCP_SEQ_GT(pcb->rcv_nxt, seqno) ||
1633
      TCP_SEQ_GEQ(seqno, pcb->rcv_nxt + pcb->rcv_wnd)) {*/
1634
    if(!TCP_SEQ_BETWEEN(seqno, pcb->rcv_nxt, pcb->rcv_nxt + pcb->rcv_wnd-1)){
32✔
1635
      tcp_ack_now(pcb);
×
1636
    }
1637
  }
1638
}
102✔
1639

1640
static u8_t tcp_getoptbyte(void)
1641
{
1642
  if ((tcphdr_opt2 == NULL) || (tcp_optidx < tcphdr_opt1len)) {
×
1643
    u8_t* opts = (u8_t *)tcphdr + TCP_HLEN;
×
1644
    return opts[tcp_optidx++];
×
1645
  } else {
1646
    u8_t idx = tcp_optidx++ - tcphdr_opt1len;
×
1647
    return tcphdr_opt2[idx];
×
1648
  }
1649
}
1650

1651
/**
1652
 * Parses the options contained in the incoming segment.
1653
 *
1654
 * Called from tcp_listen_input() and tcp_process().
1655
 * Currently, only the MSS option is supported!
1656
 *
1657
 * @param pcb the tcp_pcb for which a segment arrived
1658
 */
1659
static void
1660
tcp_parseopt(struct tcp_pcb *pcb)
102✔
1661
{
1662
  u8_t data;
1663
  u16_t mss;
1664
#if LWIP_TCP_TIMESTAMPS
1665
  u32_t tsval;
1666
#endif
1667

1668
  /* Parse the TCP MSS option, if present. */
1669
  if (TCPH_HDRLEN(tcphdr) > 0x5) {
102✔
1670
    u16_t max_c = (TCPH_HDRLEN(tcphdr) - 5) << 2;
×
1671
    for (tcp_optidx = 0; tcp_optidx < max_c; ) {
×
1672
      u8_t opt = tcp_getoptbyte();
×
1673
      switch (opt) {
×
1674
      case LWIP_TCP_OPT_EOL:
1675
        /* End of options. */
1676
        LWIP_DEBUGF(TCP_INPUT_DEBUG, ("tcp_parseopt: EOL\n"));
1677
        return;
×
1678
      case LWIP_TCP_OPT_NOP:
1679
        /* NOP option. */
1680
        LWIP_DEBUGF(TCP_INPUT_DEBUG, ("tcp_parseopt: NOP\n"));
1681
        break;
×
1682
      case LWIP_TCP_OPT_MSS:
1683
        LWIP_DEBUGF(TCP_INPUT_DEBUG, ("tcp_parseopt: MSS\n"));
1684
        if (tcp_getoptbyte() != LWIP_TCP_OPT_LEN_MSS || (tcp_optidx - 2 + LWIP_TCP_OPT_LEN_MSS) > max_c) {
×
1685
          /* Bad length */
1686
          LWIP_DEBUGF(TCP_INPUT_DEBUG, ("tcp_parseopt: bad length\n"));
1687
          return;
×
1688
        }
1689
        /* An MSS option with the right option length. */
1690
        mss = (tcp_getoptbyte() << 8);
×
1691
        mss |= tcp_getoptbyte();
×
1692
        /* Limit the mss to the configured TCP_MSS and prevent division by zero */
1693
        pcb->mss = ((mss > TCP_MSS) || (mss == 0)) ? TCP_MSS : mss;
×
1694
        break;
×
1695
#if LWIP_WND_SCALE
1696
      case LWIP_TCP_OPT_WS:
1697
        LWIP_DEBUGF(TCP_INPUT_DEBUG, ("tcp_parseopt: WND_SCALE\n"));
1698
        if (tcp_getoptbyte() != LWIP_TCP_OPT_LEN_WS || (tcp_optidx - 2 + LWIP_TCP_OPT_LEN_WS) > max_c) {
×
1699
          /* Bad length */
1700
          LWIP_DEBUGF(TCP_INPUT_DEBUG, ("tcp_parseopt: bad length\n"));
1701
          return;
×
1702
        }
1703
        /* If syn was received with wnd scale option,
1704
           activate wnd scale opt */
1705
        data = tcp_getoptbyte();
×
1706
        if (flags & TCP_SYN) {
×
1707
          /* An WND_SCALE option with the right option length. */
1708
          pcb->snd_scale = data;
×
1709
          if (pcb->snd_scale > 14U) {
×
1710
            pcb->snd_scale = 14U;
×
1711
          }
1712
          pcb->rcv_scale = TCP_RCV_SCALE;
×
1713
          pcb->flags |= TF_WND_SCALE;
×
1714
        }
1715
        break;
×
1716
#endif
1717
#if LWIP_TCP_TIMESTAMPS
1718
      case LWIP_TCP_OPT_TS:
1719
        LWIP_DEBUGF(TCP_INPUT_DEBUG, ("tcp_parseopt: TS\n"));
1720
        if (tcp_getoptbyte() != LWIP_TCP_OPT_LEN_TS || (tcp_optidx - 2 + LWIP_TCP_OPT_LEN_TS) > max_c) {
1721
          /* Bad length */
1722
          LWIP_DEBUGF(TCP_INPUT_DEBUG, ("tcp_parseopt: bad length\n"));
1723
          return;
1724
        }
1725
        /* TCP timestamp option with valid length */
1726
        tsval = tcp_getoptbyte();
1727
        tsval |= (tcp_getoptbyte() << 8);
1728
        tsval |= (tcp_getoptbyte() << 16);
1729
        tsval |= (tcp_getoptbyte() << 24);
1730
        if (flags & TCP_SYN) {
1731
          pcb->ts_recent = ntohl(tsval);
1732
          /* Enable sending timestamps in every segment now that we know
1733
             the remote host supports it. */
1734
          pcb->flags |= TF_TIMESTAMP;
1735
        } else if (TCP_SEQ_BETWEEN(pcb->ts_lastacksent, seqno, seqno+tcplen)) {
1736
          pcb->ts_recent = ntohl(tsval);
1737
        }
1738
        /* Advance to next option (6 bytes already read) */
1739
        tcp_optidx += LWIP_TCP_OPT_LEN_TS - 6;
1740
        break;
1741
#endif
1742
      default:
1743
        LWIP_DEBUGF(TCP_INPUT_DEBUG, ("tcp_parseopt: other\n"));
1744
        data = tcp_getoptbyte();
×
1745
        if (data < 2) {
×
1746
          LWIP_DEBUGF(TCP_INPUT_DEBUG, ("tcp_parseopt: bad length\n"));
1747
          /* If the length field is zero, the options are malformed
1748
             and we don't process them further. */
1749
          return;
×
1750
        }
1751
        /* All other options have a length field, so that we easily
1752
           can skip past them. */
1753
        tcp_optidx += data - 2;
×
1754
      }
1755
    }
1756
  }
1757
}
1758

1759
#endif /* LWIP_TCP */
  • Back to Build 14
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2023 Coveralls, Inc