treewide: drop executable file attrib for non-executable files
[oweals/u-boot_mod.git] / u-boot / httpd / uip.c
1 /**
2  * \addtogroup uip
3  * @{
4  */
5
6 /**
7  * \file
8  * The uIP TCP/IP stack code.
9  * \author Adam Dunkels <adam@dunkels.com>
10  */
11
12 /*
13  * Copyright (c) 2001-2003, Adam Dunkels.
14  * All rights reserved. 
15  *
16  * Redistribution and use in source and binary forms, with or without 
17  * modification, are permitted provided that the following conditions 
18  * are met: 
19  * 1. Redistributions of source code must retain the above copyright 
20  *    notice, this list of conditions and the following disclaimer. 
21  * 2. Redistributions in binary form must reproduce the above copyright 
22  *    notice, this list of conditions and the following disclaimer in the 
23  *    documentation and/or other materials provided with the distribution. 
24  * 3. The name of the author may not be used to endorse or promote
25  *    products derived from this software without specific prior
26  *    written permission.  
27  *
28  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
29  * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
30  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
31  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
32  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
33  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
34  * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
35  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
36  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
37  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
38  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.  
39  *
40  * This file is part of the uIP TCP/IP stack.
41  *
42  * $Id: uip.c,v 1.62.2.10 2003/10/07 13:23:01 adam Exp $
43  *
44  */
45
46 /*
47 This is a small implementation of the IP and TCP protocols (as well as
48 some basic ICMP stuff). The implementation couples the IP, TCP and the
49 application layers very tightly. To keep the size of the compiled code
50 down, this code also features heavy usage of the goto statement.
51
52 The principle is that we have a small buffer, called the uip_buf, in
53 which the device driver puts an incoming packet. The TCP/IP stack
54 parses the headers in the packet, and calls upon the application. If
55 the remote host has sent data to the application, this data is present
56 in the uip_buf and the application read the data from there. It is up
57 to the application to put this data into a byte stream if needed. The
58 application will not be fed with data that is out of sequence.
59
60 If the application whishes to send data to the peer, it should put its
61 data into the uip_buf, 40 bytes from the start of the buffer. The
62 TCP/IP stack will calculate the checksums, and fill in the necessary
63 header fields and finally send the packet back to the peer.
64 */
65
66 #include "uip.h"
67 #include "uipopt.h"
68 #include "uip_arch.h"
69
70 /*-----------------------------------------------------------------------------------*/
71 /* Variable definitions. */
72
73
74 /* The IP address of this host. If it is defined to be fixed (by setting UIP_FIXEDADDR to 1 in uipopt.h), the address is set here. Otherwise, the address */
75 #if UIP_FIXEDADDR > 0
76 const unsigned short int uip_hostaddr[2] =
77   {HTONS((UIP_IPADDR0 << 8) | UIP_IPADDR1),
78    HTONS((UIP_IPADDR2 << 8) | UIP_IPADDR3)};
79 const unsigned short int uip_arp_draddr[2] =
80   {HTONS((UIP_DRIPADDR0 << 8) | UIP_DRIPADDR1),
81    HTONS((UIP_DRIPADDR2 << 8) | UIP_DRIPADDR3)};
82 const unsigned short int uip_arp_netmask[2] =
83   {HTONS((UIP_NETMASK0 << 8) | UIP_NETMASK1),
84    HTONS((UIP_NETMASK2 << 8) | UIP_NETMASK3)};
85 #else
86 unsigned short int uip_hostaddr[2];       
87 unsigned short int uip_arp_draddr[2], uip_arp_netmask[2];
88 #endif /* UIP_FIXEDADDR */
89
90 u8_t uip_buf[UIP_BUFSIZE+2];   /* The packet buffer that contains
91                                 incoming packets. */
92 volatile u8_t *uip_appdata;  /* The uip_appdata pointer points to
93                                 application data. */
94 volatile u8_t *uip_sappdata;  /* The uip_appdata pointer points to the
95                                  application data which is to be sent. */
96 #if UIP_URGDATA > 0
97 volatile u8_t *uip_urgdata;  /* The uip_urgdata pointer points to
98                                 urgent data (out-of-band data), if
99                                 present. */
100 volatile u8_t uip_urglen, uip_surglen;
101 #endif /* UIP_URGDATA > 0 */
102
103 volatile unsigned short int uip_len, uip_slen;
104                              /* The uip_len is either 8 or 16 bits,
105                                 depending on the maximum packet
106                                 size. */
107
108 volatile u8_t uip_flags;     /* The uip_flags variable is used for
109                                 communication between the TCP/IP stack
110                                 and the application program. */
111 struct uip_conn *uip_conn;   /* uip_conn always points to the current
112                                 connection. */
113
114 struct uip_conn uip_conns[UIP_CONNS];
115                              /* The uip_conns array holds all TCP
116                                 connections. */
117 unsigned short int uip_listenports[UIP_LISTENPORTS];
118                              /* The uip_listenports list all currently
119                                 listning ports. */
120 #if UIP_UDP
121 struct uip_udp_conn *uip_udp_conn;
122 struct uip_udp_conn uip_udp_conns[UIP_UDP_CONNS];
123 #endif /* UIP_UDP */
124
125
126 static unsigned short int ipid;           /* Ths ipid variable is an increasing
127                                 number that is used for the IP ID
128                                 field. */
129
130 static u8_t iss[4];          /* The iss variable is used for the TCP
131                                 initial sequence number. */
132
133 #if UIP_ACTIVE_OPEN
134 static unsigned short int lastport;       /* Keeps track of the last port used for
135                                 a new connection. */
136 #endif /* UIP_ACTIVE_OPEN */
137
138 /* Temporary variables. */
139 volatile u8_t uip_acc32[4];
140 static u8_t c, opt;
141 static unsigned short int tmp16;
142
143 /* Structures and definitions. */
144 #define TCP_FIN 0x01
145 #define TCP_SYN 0x02
146 #define TCP_RST 0x04
147 #define TCP_PSH 0x08
148 #define TCP_ACK 0x10
149 #define TCP_URG 0x20
150 #define TCP_CTL 0x3f
151
152 #define ICMP_ECHO_REPLY 0
153 #define ICMP_ECHO       8     
154
155 /* Macros. */
156 #define BUF ((uip_tcpip_hdr *)&uip_buf[UIP_LLH_LEN])
157 #define FBUF ((uip_tcpip_hdr *)&uip_reassbuf[0])
158 #define ICMPBUF ((uip_icmpip_hdr *)&uip_buf[UIP_LLH_LEN])
159 #define UDPBUF ((uip_udpip_hdr *)&uip_buf[UIP_LLH_LEN])
160
161 #if UIP_STATISTICS == 1
162 struct uip_stats uip_stat;
163 #define UIP_STAT(s) s
164 #else
165 #define UIP_STAT(s)
166 #endif /* UIP_STATISTICS == 1 */
167
168 #if UIP_LOGGING == 1
169 extern void puts(const char *s);
170 #define UIP_LOG(m) puts(m)
171 #else
172 #define UIP_LOG(m)
173 #endif /* UIP_LOGGING == 1 */
174
175 /*-----------------------------------------------------------------------------------*/
176 void
177 uip_init(void)
178 {
179   for(c = 0; c < UIP_LISTENPORTS; ++c) {
180     uip_listenports[c] = 0;
181   }
182   for(c = 0; c < UIP_CONNS; ++c) {
183     uip_conns[c].tcpstateflags = CLOSED;
184   }
185 #if UIP_ACTIVE_OPEN
186   lastport = 1024;
187 #endif /* UIP_ACTIVE_OPEN */
188
189 #if UIP_UDP
190   for(c = 0; c < UIP_UDP_CONNS; ++c) {
191     uip_udp_conns[c].lport = 0;
192   }
193 #endif /* UIP_UDP */
194   
195
196   /* IPv4 initialization. */
197 #if UIP_FIXEDADDR == 0
198   uip_hostaddr[0] = uip_hostaddr[1] = 0;
199 #endif /* UIP_FIXEDADDR */
200
201 }
202 /*-----------------------------------------------------------------------------------*/
203 #if UIP_ACTIVE_OPEN
204 struct uip_conn *
205 uip_connect(unsigned short int *ripaddr, unsigned short int rport)
206 {
207   register struct uip_conn *conn, *cconn;
208   
209   /* Find an unused local port. */
210  again:
211   ++lastport;
212
213   if(lastport >= 32000) {
214     lastport = 4096;
215   }
216
217   /* Check if this port is already in use, and if so try to find
218      another one. */
219   for(c = 0; c < UIP_CONNS; ++c) {
220     conn = &uip_conns[c];
221     if(conn->tcpstateflags != CLOSED &&
222        conn->lport == htons(lastport)) {
223       goto again;
224     }
225   }
226
227
228   conn = 0;
229   for(c = 0; c < UIP_CONNS; ++c) {
230     cconn = &uip_conns[c]; 
231     if(cconn->tcpstateflags == CLOSED) {
232       conn = cconn;
233       break;
234     }
235     if(cconn->tcpstateflags == TIME_WAIT) {
236       if(conn == 0 ||
237          cconn->timer > uip_conn->timer) {
238         conn = cconn;
239       }
240     }
241   }
242
243   if(conn == 0) {
244     return 0;
245   }
246   
247   conn->tcpstateflags = SYN_SENT;
248
249   conn->snd_nxt[0] = iss[0];
250   conn->snd_nxt[1] = iss[1];
251   conn->snd_nxt[2] = iss[2];
252   conn->snd_nxt[3] = iss[3];
253
254   conn->initialmss = conn->mss = UIP_TCP_MSS;
255   
256   conn->len = 1;   /* TCP length of the SYN is one. */
257   conn->nrtx = 0;
258   conn->timer = 1; /* Send the SYN next time around. */
259   conn->rto = UIP_RTO;
260   conn->sa = 0;
261   conn->sv = 16;
262   conn->lport = htons(lastport);
263   conn->rport = rport;
264   conn->ripaddr[0] = ripaddr[0];
265   conn->ripaddr[1] = ripaddr[1];
266   
267   return conn;
268 }
269 #endif /* UIP_ACTIVE_OPEN */
270 /*-----------------------------------------------------------------------------------*/
271 #if UIP_UDP
272 struct uip_udp_conn *
273 uip_udp_new(unsigned short int *ripaddr, unsigned short int rport)
274 {
275   register struct uip_udp_conn *conn;
276   
277   /* Find an unused local port. */
278  again:
279   ++lastport;
280
281   if(lastport >= 32000) {
282     lastport = 4096;
283   }
284   
285   for(c = 0; c < UIP_UDP_CONNS; ++c) {
286     if(uip_udp_conns[c].lport == lastport) {
287       goto again;
288     }
289   }
290
291
292   conn = 0;
293   for(c = 0; c < UIP_UDP_CONNS; ++c) {
294     if(uip_udp_conns[c].lport == 0) {
295       conn = &uip_udp_conns[c]; 
296       break;
297     }
298   }
299
300   if(conn == 0) {
301     return 0;
302   }
303   
304   conn->lport = HTONS(lastport);
305   conn->rport = HTONS(rport);
306   conn->ripaddr[0] = ripaddr[0];
307   conn->ripaddr[1] = ripaddr[1];
308   
309   return conn;
310 }
311 #endif /* UIP_UDP */
312 /*-----------------------------------------------------------------------------------*/
313 void
314 uip_unlisten(unsigned short int port)
315 {
316   for(c = 0; c < UIP_LISTENPORTS; ++c) {
317     if(uip_listenports[c] == port) {
318       uip_listenports[c] = 0;
319       return;
320     }
321   }
322 }
323 /*-----------------------------------------------------------------------------------*/
324 void
325 uip_listen(unsigned short int port)
326 {
327   for(c = 0; c < UIP_LISTENPORTS; ++c) {
328     if(uip_listenports[c] == 0) {
329       uip_listenports[c] = port;
330       return;
331     }
332   }
333 }
334 /*-----------------------------------------------------------------------------------*/
335 /* XXX: IP fragment reassembly: not well-tested. */
336
337 #if UIP_REASSEMBLY
338 #define UIP_REASS_BUFSIZE (UIP_BUFSIZE - UIP_LLH_LEN)
339 static u8_t uip_reassbuf[UIP_REASS_BUFSIZE];
340 static u8_t uip_reassbitmap[UIP_REASS_BUFSIZE / (8 * 8)];
341 static const u8_t bitmap_bits[8] = {0xff, 0x7f, 0x3f, 0x1f,
342                                     0x0f, 0x07, 0x03, 0x01};
343 static unsigned short int uip_reasslen;
344 static u8_t uip_reassflags;
345 #define UIP_REASS_FLAG_LASTFRAG 0x01
346 static u8_t uip_reasstmr;
347
348 #define IP_HLEN 20
349 #define IP_MF   0x20
350
351 static u8_t
352 uip_reass(void)
353 {
354   unsigned short int offset, len;
355   unsigned short int i;
356
357   /* If ip_reasstmr is zero, no packet is present in the buffer, so we
358      write the IP header of the fragment into the reassembly
359      buffer. The timer is updated with the maximum age. */
360   if(uip_reasstmr == 0) {
361     memcpy(uip_reassbuf, &BUF->vhl, IP_HLEN);
362     uip_reasstmr = UIP_REASS_MAXAGE;
363     uip_reassflags = 0;
364     /* Clear the bitmap. */
365     memset(uip_reassbitmap, sizeof(uip_reassbitmap), 0);
366   }
367
368   /* Check if the incoming fragment matches the one currently present
369      in the reasembly buffer. If so, we proceed with copying the
370      fragment into the buffer. */
371   if(BUF->srcipaddr[0] == FBUF->srcipaddr[0] &&
372      BUF->srcipaddr[1] == FBUF->srcipaddr[1] &&
373      BUF->destipaddr[0] == FBUF->destipaddr[0] &&
374      BUF->destipaddr[1] == FBUF->destipaddr[1] &&
375      BUF->ipid[0] == FBUF->ipid[0] &&
376      BUF->ipid[1] == FBUF->ipid[1]) {
377
378     len = (BUF->len[0] << 8) + BUF->len[1] - (BUF->vhl & 0x0f) * 4;
379     offset = (((BUF->ipoffset[0] & 0x3f) << 8) + BUF->ipoffset[1]) * 8;
380
381     /* If the offset or the offset + fragment length overflows the
382        reassembly buffer, we discard the entire packet. */
383     if(offset > UIP_REASS_BUFSIZE ||
384        offset + len > UIP_REASS_BUFSIZE) {
385       uip_reasstmr = 0;
386       goto nullreturn;
387     }
388
389     /* Copy the fragment into the reassembly buffer, at the right
390        offset. */
391     memcpy(&uip_reassbuf[IP_HLEN + offset],
392            (char *)BUF + (int)((BUF->vhl & 0x0f) * 4),
393            len);
394       
395     /* Update the bitmap. */
396     if(offset / (8 * 8) == (offset + len) / (8 * 8)) {
397       /* If the two endpoints are in the same byte, we only update
398          that byte. */
399              
400       uip_reassbitmap[offset / (8 * 8)] |=
401              bitmap_bits[(offset / 8 ) & 7] &
402              ~bitmap_bits[((offset + len) / 8 ) & 7];
403     } else {
404       /* If the two endpoints are in different bytes, we update the
405          bytes in the endpoints and fill the stuff inbetween with
406          0xff. */
407       uip_reassbitmap[offset / (8 * 8)] |=
408         bitmap_bits[(offset / 8 ) & 7];
409       for(i = 1 + offset / (8 * 8); i < (offset + len) / (8 * 8); ++i) {
410         uip_reassbitmap[i] = 0xff;
411       }      
412       uip_reassbitmap[(offset + len) / (8 * 8)] |=
413         ~bitmap_bits[((offset + len) / 8 ) & 7];
414     }
415     
416     /* If this fragment has the More Fragments flag set to zero, we
417        know that this is the last fragment, so we can calculate the
418        size of the entire packet. We also set the
419        IP_REASS_FLAG_LASTFRAG flag to indicate that we have received
420        the final fragment. */
421
422     if((BUF->ipoffset[0] & IP_MF) == 0) {
423       uip_reassflags |= UIP_REASS_FLAG_LASTFRAG;
424       uip_reasslen = offset + len;
425     }
426     
427     /* Finally, we check if we have a full packet in the buffer. We do
428        this by checking if we have the last fragment and if all bits
429        in the bitmap are set. */
430     if(uip_reassflags & UIP_REASS_FLAG_LASTFRAG) {
431       /* Check all bytes up to and including all but the last byte in
432          the bitmap. */
433       for(i = 0; i < uip_reasslen / (8 * 8) - 1; ++i) {
434         if(uip_reassbitmap[i] != 0xff) {
435           goto nullreturn;
436         }
437       }
438       /* Check the last byte in the bitmap. It should contain just the
439          right amount of bits. */
440       if(uip_reassbitmap[uip_reasslen / (8 * 8)] !=
441          (u8_t)~bitmap_bits[uip_reasslen / 8 & 7]) {
442         goto nullreturn;
443       }
444
445       /* If we have come this far, we have a full packet in the
446          buffer, so we allocate a pbuf and copy the packet into it. We
447          also reset the timer. */
448       uip_reasstmr = 0;
449       memcpy(BUF, FBUF, uip_reasslen);
450
451       /* Pretend to be a "normal" (i.e., not fragmented) IP packet
452          from now on. */
453       BUF->ipoffset[0] = BUF->ipoffset[1] = 0;
454       BUF->len[0] = uip_reasslen >> 8;
455       BUF->len[1] = uip_reasslen & 0xff;
456       BUF->ipchksum = 0;
457       BUF->ipchksum = ~(uip_ipchksum());
458
459       return uip_reasslen;
460     }
461   }
462
463  nullreturn:
464   return 0;
465 }
466 #endif /* UIP_REASSEMBL */
467 /*-----------------------------------------------------------------------------------*/
468 static void
469 uip_add_rcv_nxt(unsigned short int n)
470 {
471   uip_add32(uip_conn->rcv_nxt, n);
472   uip_conn->rcv_nxt[0] = uip_acc32[0];
473   uip_conn->rcv_nxt[1] = uip_acc32[1];
474   uip_conn->rcv_nxt[2] = uip_acc32[2];
475   uip_conn->rcv_nxt[3] = uip_acc32[3];
476 }
477 /*-----------------------------------------------------------------------------------*/
478 void
479 uip_process(u8_t flag)
480 {
481   register struct uip_conn *uip_connr = uip_conn;
482   
483   uip_appdata = &uip_buf[40 + UIP_LLH_LEN];
484
485   
486   /* Check if we were invoked because of the perodic timer fireing. */
487   if(flag == UIP_TIMER) {
488 #if UIP_REASSEMBLY
489     if(uip_reasstmr != 0) {
490       --uip_reasstmr;
491     }
492 #endif /* UIP_REASSEMBLY */
493     /* Increase the initial sequence number. */
494     if(++iss[3] == 0) {
495       if(++iss[2] == 0) {
496         if(++iss[1] == 0) {
497           ++iss[0];
498         }
499       }
500     }    
501     uip_len = 0;
502     if(uip_connr->tcpstateflags == TIME_WAIT ||
503        uip_connr->tcpstateflags == FIN_WAIT_2) {
504       ++(uip_connr->timer);
505       if(uip_connr->timer == UIP_TIME_WAIT_TIMEOUT) {
506         uip_connr->tcpstateflags = CLOSED;
507       }
508     } else if(uip_connr->tcpstateflags != CLOSED) {
509       /* If the connection has outstanding data, we increase the
510          connection's timer and see if it has reached the RTO value
511          in which case we retransmit. */
512       if(uip_outstanding(uip_connr)) {
513         if(uip_connr->timer-- == 0) {
514           if(uip_connr->nrtx == UIP_MAXRTX ||
515              ((uip_connr->tcpstateflags == SYN_SENT ||
516                uip_connr->tcpstateflags == SYN_RCVD) &&
517               uip_connr->nrtx == UIP_MAXSYNRTX)) {
518             uip_connr->tcpstateflags = CLOSED;
519
520             /* We call UIP_APPCALL() with uip_flags set to
521                UIP_TIMEDOUT to inform the application that the
522                connection has timed out. */
523             uip_flags = UIP_TIMEDOUT;
524             UIP_APPCALL();
525
526             /* We also send a reset packet to the remote host. */
527             BUF->flags = TCP_RST | TCP_ACK;
528             goto tcp_send_nodata;
529           }
530
531           /* Exponential backoff. */
532           uip_connr->timer = UIP_RTO << (uip_connr->nrtx > 4?
533                                          4:
534                                          uip_connr->nrtx);
535           ++(uip_connr->nrtx);
536           
537           /* Ok, so we need to retransmit. We do this differently
538              depending on which state we are in. In ESTABLISHED, we
539              call upon the application so that it may prepare the
540              data for the retransmit. In SYN_RCVD, we resend the
541              SYNACK that we sent earlier and in LAST_ACK we have to
542              retransmit our FINACK. */
543           UIP_STAT(++uip_stat.tcp.rexmit);
544           switch(uip_connr->tcpstateflags & TS_MASK) {
545           case SYN_RCVD:
546             /* In the SYN_RCVD state, we should retransmit our
547                SYNACK. */
548             goto tcp_send_synack;
549             
550 #if UIP_ACTIVE_OPEN
551           case SYN_SENT:
552             /* In the SYN_SENT state, we retransmit out SYN. */
553             BUF->flags = 0;
554             goto tcp_send_syn;
555 #endif /* UIP_ACTIVE_OPEN */
556             
557           case ESTABLISHED:
558             /* In the ESTABLISHED state, we call upon the application
559                to do the actual retransmit after which we jump into
560                the code for sending out the packet (the apprexmit
561                label). */
562             uip_len = 0;
563             uip_slen = 0;
564             uip_flags = UIP_REXMIT;
565             UIP_APPCALL();
566             goto apprexmit;
567             
568           case FIN_WAIT_1:
569           case CLOSING:
570           case LAST_ACK:
571             /* In all these states we should retransmit a FINACK. */
572             goto tcp_send_finack;
573             
574           }
575         }
576       } else if((uip_connr->tcpstateflags & TS_MASK) == ESTABLISHED) {
577         /* If there was no need for a retransmission, we poll the
578            application for new data. */
579         uip_len = 0;
580         uip_slen = 0;
581         uip_flags = UIP_POLL;
582         UIP_APPCALL();
583         goto appsend;
584       }
585     }
586     goto drop;
587   }
588 #if UIP_UDP 
589   if(flag == UIP_UDP_TIMER) {
590     if(uip_udp_conn->lport != 0) {
591       uip_appdata = &uip_buf[UIP_LLH_LEN + 28];
592       uip_len = uip_slen = 0;
593       uip_flags = UIP_POLL;
594       UIP_UDP_APPCALL();
595       goto udp_send;
596     } else {
597       goto drop;
598     }
599   }
600 #endif
601
602   /* This is where the input processing starts. */
603   UIP_STAT(++uip_stat.ip.recv);
604
605
606   /* Start of IPv4 input header processing code. */
607   
608   /* Check validity of the IP header. */  
609   if(BUF->vhl != 0x45)  { /* IP version and header length. */
610     UIP_STAT(++uip_stat.ip.drop);
611     UIP_STAT(++uip_stat.ip.vhlerr);
612     UIP_LOG("ip: invalid version or header length.");
613     goto drop;
614   }
615   
616   /* Check the size of the packet. If the size reported to us in
617      uip_len doesn't match the size reported in the IP header, there
618      has been a transmission error and we drop the packet. */
619   
620   if(BUF->len[0] != (uip_len >> 8)) { /* IP length, high byte. */
621     uip_len = (uip_len & 0xff) | (BUF->len[0] << 8);
622   }
623   if(BUF->len[1] != (uip_len & 0xff)) { /* IP length, low byte. */
624     uip_len = (uip_len & 0xff00) | BUF->len[1];
625   }
626
627   /* Check the fragment flag. */
628   if((BUF->ipoffset[0] & 0x3f) != 0 ||
629      BUF->ipoffset[1] != 0) { 
630 #if UIP_REASSEMBLY
631     uip_len = uip_reass();
632     if(uip_len == 0) {
633       goto drop;
634     }
635 #else
636     UIP_STAT(++uip_stat.ip.drop);
637     UIP_STAT(++uip_stat.ip.fragerr);
638     UIP_LOG("ip: fragment dropped.");    
639     goto drop;
640 #endif /* UIP_REASSEMBLY */
641   }
642
643   /* If we are configured to use ping IP address configuration and
644      hasn't been assigned an IP address yet, we accept all ICMP
645      packets. */
646 #if UIP_PINGADDRCONF
647   if((uip_hostaddr[0] | uip_hostaddr[1]) == 0) {
648     if(BUF->proto == UIP_PROTO_ICMP) {
649       UIP_LOG("ip: possible ping config packet received.");
650       goto icmp_input;
651     } else {
652       UIP_LOG("ip: packet dropped since no address assigned.");
653       goto drop;
654     }
655   }
656 #endif /* UIP_PINGADDRCONF */
657   
658   /* Check if the packet is destined for our IP address. */  
659   if(BUF->destipaddr[0] != uip_hostaddr[0]) {
660     UIP_STAT(++uip_stat.ip.drop);
661     UIP_LOG("ip: packet not for us.");        
662     goto drop;
663   }
664   if(BUF->destipaddr[1] != uip_hostaddr[1]) {
665     UIP_STAT(++uip_stat.ip.drop);
666     UIP_LOG("ip: packet not for us.");        
667     goto drop;
668   }
669
670   if(uip_ipchksum() != 0xffff) { /* Compute and check the IP header
671                                     checksum. */
672     UIP_STAT(++uip_stat.ip.drop);
673     UIP_STAT(++uip_stat.ip.chkerr);
674     UIP_LOG("ip: bad checksum.");    
675     goto drop;
676   }
677
678   if(BUF->proto == UIP_PROTO_TCP)  /* Check for TCP packet. If so, jump
679                                      to the tcp_input label. */
680     goto tcp_input;
681
682 #if UIP_UDP
683   if(BUF->proto == UIP_PROTO_UDP)
684     goto udp_input;
685 #endif /* UIP_UDP */
686
687   if(BUF->proto != UIP_PROTO_ICMP) { /* We only allow ICMP packets from
688                                         here. */
689     UIP_STAT(++uip_stat.ip.drop);
690     UIP_STAT(++uip_stat.ip.protoerr);
691     UIP_LOG("ip: neither tcp nor icmp.");        
692     goto drop;
693   }
694   
695  //icmp_input:
696   UIP_STAT(++uip_stat.icmp.recv);
697   
698   /* ICMP echo (i.e., ping) processing. This is simple, we only change
699      the ICMP type from ECHO to ECHO_REPLY and adjust the ICMP
700      checksum before we return the packet. */
701   if(ICMPBUF->type != ICMP_ECHO) {
702     UIP_STAT(++uip_stat.icmp.drop);
703     UIP_STAT(++uip_stat.icmp.typeerr);
704     UIP_LOG("icmp: not icmp echo.");
705     goto drop;
706   }
707
708   /* If we are configured to use ping IP address assignment, we use
709      the destination IP address of this ping packet and assign it to
710      ourself. */
711 #if UIP_PINGADDRCONF
712   if((uip_hostaddr[0] | uip_hostaddr[1]) == 0) {
713     uip_hostaddr[0] = BUF->destipaddr[0];
714     uip_hostaddr[1] = BUF->destipaddr[1];
715   }
716 #endif /* UIP_PINGADDRCONF */  
717   
718   ICMPBUF->type = ICMP_ECHO_REPLY;
719   
720   if(ICMPBUF->icmpchksum >= HTONS(0xffff - (ICMP_ECHO << 8))) {
721     ICMPBUF->icmpchksum += HTONS(ICMP_ECHO << 8) + 1;
722   } else {
723     ICMPBUF->icmpchksum += HTONS(ICMP_ECHO << 8);
724   }
725   
726   /* Swap IP addresses. */
727   tmp16 = BUF->destipaddr[0];
728   BUF->destipaddr[0] = BUF->srcipaddr[0];
729   BUF->srcipaddr[0] = tmp16;
730   tmp16 = BUF->destipaddr[1];
731   BUF->destipaddr[1] = BUF->srcipaddr[1];
732   BUF->srcipaddr[1] = tmp16;
733
734   UIP_STAT(++uip_stat.icmp.sent);
735   goto send;
736
737   /* End of IPv4 input header processing code. */
738   
739
740 #if UIP_UDP
741   /* UDP input processing. */
742  udp_input:
743   /* UDP processing is really just a hack. We don't do anything to the
744      UDP/IP headers, but let the UDP application do all the hard
745      work. If the application sets uip_slen, it has a packet to
746      send. */
747 #if UIP_UDP_CHECKSUMS
748   if(uip_udpchksum() != 0xffff) { 
749     UIP_STAT(++uip_stat.udp.drop);
750     UIP_STAT(++uip_stat.udp.chkerr);
751     UIP_LOG("udp: bad checksum.");    
752     goto drop;
753   }  
754 #endif /* UIP_UDP_CHECKSUMS */
755
756   /* Demultiplex this UDP packet between the UDP "connections". */
757   for(uip_udp_conn = &uip_udp_conns[0];
758       uip_udp_conn < &uip_udp_conns[UIP_UDP_CONNS];
759       ++uip_udp_conn) {
760     if(uip_udp_conn->lport != 0 &&
761        UDPBUF->destport == uip_udp_conn->lport &&
762        (uip_udp_conn->rport == 0 ||
763         UDPBUF->srcport == uip_udp_conn->rport) &&
764        BUF->srcipaddr[0] == uip_udp_conn->ripaddr[0] &&
765        BUF->srcipaddr[1] == uip_udp_conn->ripaddr[1]) {
766       goto udp_found; 
767     }
768   }
769   goto drop;
770   
771  udp_found:
772   uip_len = uip_len - 28;
773   uip_appdata = &uip_buf[UIP_LLH_LEN + 28];
774   uip_flags = UIP_NEWDATA;
775   uip_slen = 0;
776   UIP_UDP_APPCALL();
777  udp_send:
778   if(uip_slen == 0) {
779     goto drop;      
780   }
781   uip_len = uip_slen + 28;
782
783   BUF->len[0] = (uip_len >> 8);
784   BUF->len[1] = (uip_len & 0xff);
785   
786   BUF->proto = UIP_PROTO_UDP;
787
788   UDPBUF->udplen = HTONS(uip_slen + 8);
789   UDPBUF->udpchksum = 0;
790 #if UIP_UDP_CHECKSUMS 
791   /* Calculate UDP checksum. */
792   UDPBUF->udpchksum = ~(uip_udpchksum());
793   if(UDPBUF->udpchksum == 0) {
794     UDPBUF->udpchksum = 0xffff;
795   }
796 #endif /* UIP_UDP_CHECKSUMS */
797
798   BUF->srcport  = uip_udp_conn->lport;
799   BUF->destport = uip_udp_conn->rport;
800
801   BUF->srcipaddr[0] = uip_hostaddr[0];
802   BUF->srcipaddr[1] = uip_hostaddr[1];
803   BUF->destipaddr[0] = uip_udp_conn->ripaddr[0];
804   BUF->destipaddr[1] = uip_udp_conn->ripaddr[1];
805  
806   uip_appdata = &uip_buf[UIP_LLH_LEN + 40];
807   goto ip_send_nolen;
808 #endif /* UIP_UDP */
809   
810   /* TCP input processing. */  
811  tcp_input:
812   UIP_STAT(++uip_stat.tcp.recv);
813
814   /* Start of TCP input header processing code. */
815   
816   if(uip_tcpchksum() != 0xffff) {   /* Compute and check the TCP
817                                        checksum. */
818     UIP_STAT(++uip_stat.tcp.drop);
819     UIP_STAT(++uip_stat.tcp.chkerr);
820     UIP_LOG("tcp: bad checksum.");    
821     goto drop;
822   }
823   
824   /* Demultiplex this segment. */
825   /* First check any active connections. */
826   for(uip_connr = &uip_conns[0]; uip_connr < &uip_conns[UIP_CONNS]; ++uip_connr) {
827     if(uip_connr->tcpstateflags != CLOSED &&
828        BUF->destport == uip_connr->lport &&
829        BUF->srcport == uip_connr->rport &&
830        BUF->srcipaddr[0] == uip_connr->ripaddr[0] &&
831        BUF->srcipaddr[1] == uip_connr->ripaddr[1]) {
832       goto found;    
833     }
834   }
835
836   /* If we didn't find and active connection that expected the packet,
837      either this packet is an old duplicate, or this is a SYN packet
838      destined for a connection in LISTEN. If the SYN flag isn't set,
839      it is an old packet and we send a RST. */
840   if((BUF->flags & TCP_CTL) != TCP_SYN)
841     goto reset;
842   
843   tmp16 = BUF->destport;
844   /* Next, check listening connections. */  
845   for(c = 0; c < UIP_LISTENPORTS; ++c) {
846     if(tmp16 == uip_listenports[c])
847       goto found_listen;
848   }
849   
850   /* No matching connection found, so we send a RST packet. */
851   UIP_STAT(++uip_stat.tcp.synrst);
852  reset:
853
854   /* We do not send resets in response to resets. */
855   if(BUF->flags & TCP_RST) 
856     goto drop;
857
858   UIP_STAT(++uip_stat.tcp.rst);
859   
860   BUF->flags = TCP_RST | TCP_ACK;
861   uip_len = 40;
862   BUF->tcpoffset = 5 << 4;
863
864   /* Flip the seqno and ackno fields in the TCP header. */
865   c = BUF->seqno[3];
866   BUF->seqno[3] = BUF->ackno[3];  
867   BUF->ackno[3] = c;
868   
869   c = BUF->seqno[2];
870   BUF->seqno[2] = BUF->ackno[2];  
871   BUF->ackno[2] = c;
872   
873   c = BUF->seqno[1];
874   BUF->seqno[1] = BUF->ackno[1];
875   BUF->ackno[1] = c;
876   
877   c = BUF->seqno[0];
878   BUF->seqno[0] = BUF->ackno[0];  
879   BUF->ackno[0] = c;
880
881   /* We also have to increase the sequence number we are
882      acknowledging. If the least significant byte overflowed, we need
883      to propagate the carry to the other bytes as well. */
884   if(++BUF->ackno[3] == 0) {
885     if(++BUF->ackno[2] == 0) {
886       if(++BUF->ackno[1] == 0) {
887         ++BUF->ackno[0];
888       }
889     }
890   }
891  
892   /* Swap port numbers. */
893   tmp16 = BUF->srcport;
894   BUF->srcport = BUF->destport;
895   BUF->destport = tmp16;
896   
897   /* Swap IP addresses. */
898   tmp16 = BUF->destipaddr[0];
899   BUF->destipaddr[0] = BUF->srcipaddr[0];
900   BUF->srcipaddr[0] = tmp16;
901   tmp16 = BUF->destipaddr[1];
902   BUF->destipaddr[1] = BUF->srcipaddr[1];
903   BUF->srcipaddr[1] = tmp16;
904
905   
906   /* And send out the RST packet! */
907   goto tcp_send_noconn;
908
909   /* This label will be jumped to if we matched the incoming packet
910      with a connection in LISTEN. In that case, we should create a new
911      connection and send a SYNACK in return. */
912  found_listen:
913   /* First we check if there are any connections avaliable. Unused
914      connections are kept in the same table as used connections, but
915      unused ones have the tcpstate set to CLOSED. Also, connections in
916      TIME_WAIT are kept track of and we'll use the oldest one if no
917      CLOSED connections are found. Thanks to Eddie C. Dost for a very
918      nice algorithm for the TIME_WAIT search. */
919   uip_connr = 0;
920   for(c = 0; c < UIP_CONNS; ++c) {
921     if(uip_conns[c].tcpstateflags == CLOSED) {
922       uip_connr = &uip_conns[c];
923       break;
924     }
925     if(uip_conns[c].tcpstateflags == TIME_WAIT) {
926       if(uip_connr == 0 ||
927          uip_conns[c].timer > uip_connr->timer) {
928         uip_connr = &uip_conns[c];
929       }
930     }
931   }
932
933   if(uip_connr == 0) {
934     /* All connections are used already, we drop packet and hope that
935        the remote end will retransmit the packet at a time when we
936        have more spare connections. */
937     UIP_STAT(++uip_stat.tcp.syndrop);
938     UIP_LOG("tcp: found no unused connections.");
939     goto drop;
940   }
941   uip_conn = uip_connr;
942   
943   /* Fill in the necessary fields for the new connection. */
944   uip_connr->rto = uip_connr->timer = UIP_RTO;
945   uip_connr->sa = 0;
946   uip_connr->sv = 4;  
947   uip_connr->nrtx = 0;
948   uip_connr->lport = BUF->destport;
949   uip_connr->rport = BUF->srcport;
950   uip_connr->ripaddr[0] = BUF->srcipaddr[0];
951   uip_connr->ripaddr[1] = BUF->srcipaddr[1];
952   uip_connr->tcpstateflags = SYN_RCVD;
953
954   uip_connr->snd_nxt[0] = iss[0];
955   uip_connr->snd_nxt[1] = iss[1];
956   uip_connr->snd_nxt[2] = iss[2];
957   uip_connr->snd_nxt[3] = iss[3];
958   uip_connr->len = 1;
959
960   /* rcv_nxt should be the seqno from the incoming packet + 1. */
961   uip_connr->rcv_nxt[3] = BUF->seqno[3];
962   uip_connr->rcv_nxt[2] = BUF->seqno[2];
963   uip_connr->rcv_nxt[1] = BUF->seqno[1];
964   uip_connr->rcv_nxt[0] = BUF->seqno[0];
965   uip_add_rcv_nxt(1);
966
967   /* Parse the TCP MSS option, if present. */
968   if((BUF->tcpoffset & 0xf0) > 0x50) {
969     for(c = 0; c < ((BUF->tcpoffset >> 4) - 5) << 2 ;) {
970       opt = uip_buf[UIP_TCPIP_HLEN + UIP_LLH_LEN + c];
971       if(opt == 0x00) {
972         /* End of options. */   
973         break;
974       } else if(opt == 0x01) {
975         ++c;
976         /* NOP option. */
977       } else if(opt == 0x02 &&
978                 uip_buf[UIP_TCPIP_HLEN + UIP_LLH_LEN + 1 + c] == 0x04) {
979         /* An MSS option with the right option length. */       
980         tmp16 = ((unsigned short int)uip_buf[UIP_TCPIP_HLEN + UIP_LLH_LEN + 2 + c] << 8) |
981           (unsigned short int)uip_buf[40 + UIP_LLH_LEN + 3 + c];
982         uip_connr->initialmss = uip_connr->mss =
983           tmp16 > UIP_TCP_MSS? UIP_TCP_MSS: tmp16;
984         
985         /* And we are done processing options. */
986         break;
987       } else {
988         /* All other options have a length field, so that we easily
989            can skip past them. */
990         if(uip_buf[UIP_TCPIP_HLEN + UIP_LLH_LEN + 1 + c] == 0) {
991           /* If the length field is zero, the options are malformed
992              and we don't process them further. */
993           break;
994         }
995         c += uip_buf[UIP_TCPIP_HLEN + UIP_LLH_LEN + 1 + c];
996       }      
997     }
998   }
999   
1000   /* Our response will be a SYNACK. */
1001 #if UIP_ACTIVE_OPEN
1002  tcp_send_synack:
1003   BUF->flags = TCP_ACK;    
1004   
1005  tcp_send_syn:
1006   BUF->flags |= TCP_SYN;    
1007 #else /* UIP_ACTIVE_OPEN */
1008  tcp_send_synack:
1009   BUF->flags = TCP_SYN | TCP_ACK;    
1010 #endif /* UIP_ACTIVE_OPEN */
1011   
1012   /* We send out the TCP Maximum Segment Size option with our
1013      SYNACK. */
1014   BUF->optdata[0] = 2;
1015   BUF->optdata[1] = 4;
1016   BUF->optdata[2] = (UIP_TCP_MSS) / 256;
1017   BUF->optdata[3] = (UIP_TCP_MSS) & 255;
1018   uip_len = 44;
1019   BUF->tcpoffset = 6 << 4;
1020   goto tcp_send;
1021
1022   /* This label will be jumped to if we found an active connection. */
1023  found:
1024   uip_conn = uip_connr;
1025   uip_flags = 0;
1026
1027   /* We do a very naive form of TCP reset processing; we just accept
1028      any RST and kill our connection. We should in fact check if the
1029      sequence number of this reset is wihtin our advertised window
1030      before we accept the reset. */
1031   if(BUF->flags & TCP_RST) {
1032     uip_connr->tcpstateflags = CLOSED;
1033     UIP_LOG("tcp: got reset, aborting connection.");
1034     uip_flags = UIP_ABORT;
1035     UIP_APPCALL();
1036     goto drop;
1037   }      
1038   /* Calculated the length of the data, if the application has sent
1039      any data to us. */
1040   c = (BUF->tcpoffset >> 4) << 2;
1041   /* uip_len will contain the length of the actual TCP data. This is
1042      calculated by subtracing the length of the TCP header (in
1043      c) and the length of the IP header (20 bytes). */
1044   uip_len = uip_len - c - 20;
1045
1046   /* First, check if the sequence number of the incoming packet is
1047      what we're expecting next. If not, we send out an ACK with the
1048      correct numbers in. */
1049   if(uip_len > 0 &&
1050      (BUF->seqno[0] != uip_connr->rcv_nxt[0] ||
1051       BUF->seqno[1] != uip_connr->rcv_nxt[1] ||
1052       BUF->seqno[2] != uip_connr->rcv_nxt[2] ||
1053       BUF->seqno[3] != uip_connr->rcv_nxt[3])) {
1054     goto tcp_send_ack;
1055   }
1056
1057   /* Next, check if the incoming segment acknowledges any outstanding
1058      data. If so, we update the sequence number, reset the length of
1059      the outstanding data, calculate RTT estimations, and reset the
1060      retransmission timer. */
1061   if((BUF->flags & TCP_ACK) && uip_outstanding(uip_connr)) {
1062     uip_add32(uip_connr->snd_nxt, uip_connr->len);
1063     if(BUF->ackno[0] == uip_acc32[0] &&
1064        BUF->ackno[1] == uip_acc32[1] &&
1065        BUF->ackno[2] == uip_acc32[2] &&
1066        BUF->ackno[3] == uip_acc32[3]) {
1067       /* Update sequence number. */
1068       uip_connr->snd_nxt[0] = uip_acc32[0];
1069       uip_connr->snd_nxt[1] = uip_acc32[1];
1070       uip_connr->snd_nxt[2] = uip_acc32[2];
1071       uip_connr->snd_nxt[3] = uip_acc32[3];
1072         
1073
1074       /* Do RTT estimation, unless we have done retransmissions. */
1075       if(uip_connr->nrtx == 0) {
1076         signed char m;
1077         m = uip_connr->rto - uip_connr->timer;
1078         /* This is taken directly from VJs original code in his paper */
1079         m = m - (uip_connr->sa >> 3);
1080         uip_connr->sa += m;
1081         if(m < 0) {
1082           m = -m;
1083         }
1084         m = m - (uip_connr->sv >> 2);
1085         uip_connr->sv += m;
1086         uip_connr->rto = (uip_connr->sa >> 3) + uip_connr->sv;
1087
1088       }
1089       /* Set the acknowledged flag. */
1090       uip_flags = UIP_ACKDATA;
1091       /* Reset the retransmission timer. */
1092       uip_connr->timer = uip_connr->rto;
1093     }
1094     
1095   }
1096
1097   /* Do different things depending on in what state the connection is. */
1098   switch(uip_connr->tcpstateflags & TS_MASK) {
1099     /* CLOSED and LISTEN are not handled here. CLOSE_WAIT is not
1100         implemented, since we force the application to close when the
1101         peer sends a FIN (hence the application goes directly from
1102         ESTABLISHED to LAST_ACK). */
1103   case SYN_RCVD:
1104     /* In SYN_RCVD we have sent out a SYNACK in response to a SYN, and
1105        we are waiting for an ACK that acknowledges the data we sent
1106        out the last time. Therefore, we want to have the UIP_ACKDATA
1107        flag set. If so, we enter the ESTABLISHED state. */
1108     if(uip_flags & UIP_ACKDATA) {
1109       uip_connr->tcpstateflags = ESTABLISHED;
1110       uip_flags = UIP_CONNECTED;
1111       uip_connr->len = 0;
1112       if(uip_len > 0) {
1113         uip_flags |= UIP_NEWDATA;
1114         uip_add_rcv_nxt(uip_len);
1115       }
1116       uip_slen = 0;
1117       UIP_APPCALL();
1118       goto appsend;
1119     }
1120     goto drop;
1121 #if UIP_ACTIVE_OPEN
1122   case SYN_SENT:
1123     /* In SYN_SENT, we wait for a SYNACK that is sent in response to
1124        our SYN. The rcv_nxt is set to sequence number in the SYNACK
1125        plus one, and we send an ACK. We move into the ESTABLISHED
1126        state. */
1127     if((uip_flags & UIP_ACKDATA) &&
1128        BUF->flags == (TCP_SYN | TCP_ACK)) {
1129
1130       /* Parse the TCP MSS option, if present. */
1131       if((BUF->tcpoffset & 0xf0) > 0x50) {
1132         for(c = 0; c < ((BUF->tcpoffset >> 4) - 5) << 2 ;) {
1133           opt = uip_buf[40 + UIP_LLH_LEN + c];
1134           if(opt == 0x00) {
1135             /* End of options. */       
1136             break;
1137           } else if(opt == 0x01) {
1138             ++c;
1139             /* NOP option. */
1140           } else if(opt == 0x02 &&
1141                     uip_buf[UIP_TCPIP_HLEN + UIP_LLH_LEN + 1 + c] == 0x04) {
1142             /* An MSS option with the right option length. */
1143             tmp16 = (uip_buf[UIP_TCPIP_HLEN + UIP_LLH_LEN + 2 + c] << 8) |
1144               uip_buf[UIP_TCPIP_HLEN + UIP_LLH_LEN + 3 + c];
1145             uip_connr->initialmss =
1146               uip_connr->mss = tmp16 > UIP_TCP_MSS? UIP_TCP_MSS: tmp16;
1147
1148             /* And we are done processing options. */
1149             break;
1150           } else {
1151             /* All other options have a length field, so that we easily
1152                can skip past them. */
1153             if(uip_buf[UIP_TCPIP_HLEN + UIP_LLH_LEN + 1 + c] == 0) {
1154               /* If the length field is zero, the options are malformed
1155                  and we don't process them further. */
1156               break;
1157             }
1158             c += uip_buf[UIP_TCPIP_HLEN + UIP_LLH_LEN + 1 + c];
1159           }      
1160         }
1161       }
1162       uip_connr->tcpstateflags = ESTABLISHED;      
1163       uip_connr->rcv_nxt[0] = BUF->seqno[0];
1164       uip_connr->rcv_nxt[1] = BUF->seqno[1];
1165       uip_connr->rcv_nxt[2] = BUF->seqno[2];
1166       uip_connr->rcv_nxt[3] = BUF->seqno[3];
1167       uip_add_rcv_nxt(1);
1168       uip_flags = UIP_CONNECTED | UIP_NEWDATA;
1169       uip_connr->len = 0;
1170       uip_len = 0;
1171       uip_slen = 0;
1172       UIP_APPCALL();
1173       goto appsend;
1174     }
1175     goto reset;
1176 #endif /* UIP_ACTIVE_OPEN */
1177     
1178   case ESTABLISHED:
1179     /* In the ESTABLISHED state, we call upon the application to feed
1180     data into the uip_buf. If the UIP_ACKDATA flag is set, the
1181     application should put new data into the buffer, otherwise we are
1182     retransmitting an old segment, and the application should put that
1183     data into the buffer.
1184
1185     If the incoming packet is a FIN, we should close the connection on
1186     this side as well, and we send out a FIN and enter the LAST_ACK
1187     state. We require that there is no outstanding data; otherwise the
1188     sequence numbers will be screwed up. */
1189
1190     if(BUF->flags & TCP_FIN) {
1191       if(uip_outstanding(uip_connr)) {
1192         goto drop;
1193       }
1194       uip_add_rcv_nxt(1 + uip_len);      
1195       uip_flags = UIP_CLOSE;
1196       if(uip_len > 0) {
1197         uip_flags |= UIP_NEWDATA;
1198       }
1199       UIP_APPCALL();
1200       uip_connr->len = 1;
1201       uip_connr->tcpstateflags = LAST_ACK;
1202       uip_connr->nrtx = 0;
1203     tcp_send_finack:
1204       BUF->flags = TCP_FIN | TCP_ACK;      
1205       goto tcp_send_nodata;
1206     }
1207
1208     /* Check the URG flag. If this is set, the segment carries urgent
1209        data that we must pass to the application. */
1210     if(BUF->flags & TCP_URG) {
1211 #if UIP_URGDATA > 0
1212       uip_urglen = (BUF->urgp[0] << 8) | BUF->urgp[1];
1213       if(uip_urglen > uip_len) {
1214         /* There is more urgent data in the next segment to come. */
1215         uip_urglen = uip_len;
1216       }
1217       uip_add_rcv_nxt(uip_urglen);
1218       uip_len -= uip_urglen;
1219       uip_urgdata = uip_appdata;
1220       uip_appdata += uip_urglen;
1221     } else {
1222       uip_urglen = 0;
1223 #endif /* UIP_URGDATA > 0 */
1224       uip_appdata += (BUF->urgp[0] << 8) | BUF->urgp[1];
1225       uip_len -= (BUF->urgp[0] << 8) | BUF->urgp[1];
1226     }
1227     
1228     
1229     /* If uip_len > 0 we have TCP data in the packet, and we flag this
1230        by setting the UIP_NEWDATA flag and update the sequence number
1231        we acknowledge. If the application has stopped the dataflow
1232        using uip_stop(), we must not accept any data packets from the
1233        remote host. */
1234     if(uip_len > 0 && !(uip_connr->tcpstateflags & UIP_STOPPED)) {
1235       uip_flags |= UIP_NEWDATA;
1236       uip_add_rcv_nxt(uip_len);
1237     }
1238
1239     /* Check if the available buffer space advertised by the other end
1240        is smaller than the initial MSS for this connection. If so, we
1241        set the current MSS to the window size to ensure that the
1242        application does not send more data than the other end can
1243        handle.
1244
1245        If the remote host advertises a zero window, we set the MSS to
1246        the initial MSS so that the application will send an entire MSS
1247        of data. This data will not be acknowledged by the receiver,
1248        and the application will retransmit it. This is called the
1249        "persistent timer" and uses the retransmission mechanim.
1250     */
1251     tmp16 = ((unsigned short int)BUF->wnd[0] << 8) + (unsigned short int)BUF->wnd[1];
1252     if(tmp16 > uip_connr->initialmss ||
1253        tmp16 == 0) {
1254       tmp16 = uip_connr->initialmss;
1255     }
1256     uip_connr->mss = tmp16;
1257
1258     /* If this packet constitutes an ACK for outstanding data (flagged
1259        by the UIP_ACKDATA flag, we should call the application since it
1260        might want to send more data. If the incoming packet had data
1261        from the peer (as flagged by the UIP_NEWDATA flag), the
1262        application must also be notified.
1263
1264        When the application is called, the global variable uip_len
1265        contains the length of the incoming data. The application can
1266        access the incoming data through the global pointer
1267        uip_appdata, which usually points 40 bytes into the uip_buf
1268        array.
1269
1270        If the application wishes to send any data, this data should be
1271        put into the uip_appdata and the length of the data should be
1272        put into uip_len. If the application don't have any data to
1273        send, uip_len must be set to 0. */
1274         if(uip_flags & (UIP_NEWDATA | UIP_ACKDATA)) {
1275       uip_slen = 0;
1276       UIP_APPCALL();
1277
1278     appsend:
1279       
1280           if(uip_flags & UIP_ABORT) {
1281         uip_slen = 0;
1282         uip_connr->tcpstateflags = CLOSED;
1283         BUF->flags = TCP_RST | TCP_ACK;
1284         goto tcp_send_nodata;
1285       }
1286
1287       if(uip_flags & UIP_CLOSE) {
1288         uip_slen = 0;
1289         uip_connr->len = 1;
1290         uip_connr->tcpstateflags = FIN_WAIT_1;
1291         uip_connr->nrtx = 0;
1292         BUF->flags = TCP_FIN | TCP_ACK;
1293         goto tcp_send_nodata;   
1294       }
1295
1296           /* If uip_slen > 0, the application has data to be sent. */
1297       if(uip_slen > 0) {
1298
1299         /* If the connection has acknowledged data, the contents of
1300            the ->len variable should be discarded. */ 
1301         if((uip_flags & UIP_ACKDATA) != 0) {
1302           uip_connr->len = 0;
1303         }
1304
1305         /* If the ->len variable is non-zero the connection has
1306            already data in transit and cannot send anymore right
1307            now. */
1308         if(uip_connr->len == 0) {
1309
1310           /* The application cannot send more than what is allowed by
1311              the mss (the minumum of the MSS and the available
1312              window). */
1313           if(uip_slen > uip_connr->mss) {
1314                 uip_slen = uip_connr->mss;
1315           }
1316
1317           /* Remember how much data we send out now so that we know
1318              when everything has been acknowledged. */
1319           uip_connr->len = uip_slen;
1320         } else {
1321
1322           /* If the application already had unacknowledged data, we
1323              make sure that the application does not send (i.e.,
1324              retransmit) out more than it previously sent out. */
1325           uip_slen = uip_connr->len;
1326         }
1327       } else {
1328         uip_connr->len = 0;
1329       }
1330       uip_connr->nrtx = 0;
1331     apprexmit:
1332       uip_appdata = uip_sappdata;
1333
1334       /* If the application has data to be sent, or if the incoming
1335          packet had new data in it, we must send out a packet. */
1336       if(uip_slen > 0 && uip_connr->len > 0) {
1337         /* Add the length of the IP and TCP headers. */
1338         uip_len = uip_connr->len + UIP_TCPIP_HLEN;
1339         /* We always set the ACK flag in response packets. */
1340         BUF->flags = TCP_ACK | TCP_PSH;
1341         /* Send the packet. */
1342         goto tcp_send_noopts;
1343       }
1344       /* If there is no data to send, just send out a pure ACK if
1345          there is newdata. */
1346       if(uip_flags & UIP_NEWDATA) {
1347         uip_len = UIP_TCPIP_HLEN;
1348         BUF->flags = TCP_ACK;
1349         goto tcp_send_noopts;
1350       }
1351     }
1352         goto drop;
1353   case LAST_ACK:
1354     /* We can close this connection if the peer has acknowledged our
1355        FIN. This is indicated by the UIP_ACKDATA flag. */     
1356     if(uip_flags & UIP_ACKDATA) {
1357       uip_connr->tcpstateflags = CLOSED;
1358       uip_flags = UIP_CLOSE;
1359       UIP_APPCALL();
1360     }
1361     break;
1362     
1363   case FIN_WAIT_1:
1364     /* The application has closed the connection, but the remote host
1365        hasn't closed its end yet. Thus we do nothing but wait for a
1366        FIN from the other side. */
1367     if(uip_len > 0) {
1368       uip_add_rcv_nxt(uip_len);
1369     }
1370     if(BUF->flags & TCP_FIN) {
1371       if(uip_flags & UIP_ACKDATA) {
1372         uip_connr->tcpstateflags = TIME_WAIT;
1373         uip_connr->timer = 0;
1374         uip_connr->len = 0;
1375       } else {
1376         uip_connr->tcpstateflags = CLOSING;
1377       }
1378       uip_add_rcv_nxt(1);
1379       uip_flags = UIP_CLOSE;
1380       UIP_APPCALL();
1381       goto tcp_send_ack;
1382     } else if(uip_flags & UIP_ACKDATA) {
1383       uip_connr->tcpstateflags = FIN_WAIT_2;
1384       uip_connr->len = 0;
1385       goto drop;
1386     }
1387     if(uip_len > 0) {
1388       goto tcp_send_ack;
1389     }
1390     goto drop;
1391       
1392   case FIN_WAIT_2:
1393     if(uip_len > 0) {
1394       uip_add_rcv_nxt(uip_len);
1395     }
1396     if(BUF->flags & TCP_FIN) {
1397       uip_connr->tcpstateflags = TIME_WAIT;
1398       uip_connr->timer = 0;
1399       uip_add_rcv_nxt(1);
1400       uip_flags = UIP_CLOSE;
1401       UIP_APPCALL();
1402       goto tcp_send_ack;
1403     }
1404     if(uip_len > 0) {
1405       goto tcp_send_ack;
1406     }
1407     goto drop;
1408
1409   case TIME_WAIT:
1410     goto tcp_send_ack;
1411     
1412   case CLOSING:
1413     if(uip_flags & UIP_ACKDATA) {
1414       uip_connr->tcpstateflags = TIME_WAIT;
1415       uip_connr->timer = 0;
1416     }
1417   }  
1418   goto drop;
1419   
1420
1421   /* We jump here when we are ready to send the packet, and just want
1422      to set the appropriate TCP sequence numbers in the TCP header. */
1423  tcp_send_ack:
1424   BUF->flags = TCP_ACK;
1425  tcp_send_nodata:
1426   uip_len = 40;
1427  tcp_send_noopts:
1428   BUF->tcpoffset = 5 << 4;
1429  tcp_send:
1430   /* We're done with the input processing. We are now ready to send a
1431      reply. Our job is to fill in all the fields of the TCP and IP
1432      headers before calculating the checksum and finally send the
1433      packet. */
1434   BUF->ackno[0] = uip_connr->rcv_nxt[0];
1435   BUF->ackno[1] = uip_connr->rcv_nxt[1];
1436   BUF->ackno[2] = uip_connr->rcv_nxt[2];
1437   BUF->ackno[3] = uip_connr->rcv_nxt[3];
1438   
1439   BUF->seqno[0] = uip_connr->snd_nxt[0];
1440   BUF->seqno[1] = uip_connr->snd_nxt[1];
1441   BUF->seqno[2] = uip_connr->snd_nxt[2];
1442   BUF->seqno[3] = uip_connr->snd_nxt[3];
1443
1444   BUF->proto = UIP_PROTO_TCP;
1445   
1446   BUF->srcport  = uip_connr->lport;
1447   BUF->destport = uip_connr->rport;
1448
1449   BUF->srcipaddr[0] = uip_hostaddr[0];
1450   BUF->srcipaddr[1] = uip_hostaddr[1];
1451   BUF->destipaddr[0] = uip_connr->ripaddr[0];
1452   BUF->destipaddr[1] = uip_connr->ripaddr[1];
1453  
1454
1455   if(uip_connr->tcpstateflags & UIP_STOPPED) {
1456     /* If the connection has issued uip_stop(), we advertise a zero
1457        window so that the remote host will stop sending data. */
1458     BUF->wnd[0] = BUF->wnd[1] = 0;
1459   } else {
1460     BUF->wnd[0] = ((UIP_RECEIVE_WINDOW) >> 8);
1461     BUF->wnd[1] = ((UIP_RECEIVE_WINDOW) & 0xff); 
1462   }
1463
1464  tcp_send_noconn:
1465
1466   BUF->len[0] = (uip_len >> 8);
1467   BUF->len[1] = (uip_len & 0xff);
1468
1469   /* Calculate TCP checksum. */
1470   BUF->tcpchksum = 0;
1471   BUF->tcpchksum = ~(uip_tcpchksum());
1472   
1473  //ip_send_nolen:
1474
1475   BUF->vhl = 0x45;
1476   BUF->tos = 0;
1477   BUF->ipoffset[0] = BUF->ipoffset[1] = 0;
1478   BUF->ttl  = UIP_TTL;
1479   ++ipid;
1480   BUF->ipid[0] = ipid >> 8;
1481   BUF->ipid[1] = ipid & 0xff;
1482   
1483   /* Calculate IP checksum. */
1484   BUF->ipchksum = 0;
1485   BUF->ipchksum = ~(uip_ipchksum());
1486
1487   UIP_STAT(++uip_stat.tcp.sent);
1488  send:
1489   UIP_STAT(++uip_stat.ip.sent);
1490   /* Return and let the caller do the actual transmission. */
1491   return;
1492  drop:
1493   uip_len = 0;
1494   return;
1495 }
1496 /*-----------------------------------------------------------------------------------*/
1497 /*unsigned short int
1498 htons(unsigned short int val)
1499 {
1500   return HTONS(val);
1501 }*/
1502 /*-----------------------------------------------------------------------------------*/
1503 /** @} */