fuzix: netd
authorBrett Gordon <beretta42@gmail.com>
Tue, 15 Nov 2016 20:27:50 +0000 (15:27 -0500)
committerAlan Cox <alan@linux.intel.com>
Sun, 20 Nov 2016 19:30:16 +0000 (19:30 +0000)
enclosed is a patch for netd.  Have fun figuring out netd.c :)  This gives me
(active open only) native networking.  Me and Ron Klein have been testing
this with success.  Please advise,

brett

34 files changed:
Applications/netd/Makefile.6809 [new file with mode: 0644]
Applications/netd/clock-arch.c [new file with mode: 0644]
Applications/netd/clock-arch.h [new file with mode: 0644]
Applications/netd/clock.h [new file with mode: 0644]
Applications/netd/coconic.c [new file with mode: 0644]
Applications/netd/device.h [new file with mode: 0644]
Applications/netd/dig.c [new file with mode: 0644]
Applications/netd/echoping.c [new file with mode: 0644]
Applications/netd/fuzix-conf.h [new file with mode: 0644]
Applications/netd/fuzix-netd.pkg [new file with mode: 0644]
Applications/netd/gethostbyname.c [new file with mode: 0644]
Applications/netd/httpd.c [new file with mode: 0644]
Applications/netd/lwwire.c [new file with mode: 0644]
Applications/netd/netd.c [new file with mode: 0644]
Applications/netd/netd.h [new file with mode: 0644]
Applications/netd/netdb.h [new file with mode: 0644]
Applications/netd/netrc [new file with mode: 0644]
Applications/netd/resolv.conf [new file with mode: 0644]
Applications/netd/telnet.c [new file with mode: 0644]
Applications/netd/timer.c [new file with mode: 0644]
Applications/netd/timer.h [new file with mode: 0644]
Applications/netd/uip.c [new file with mode: 0644]
Applications/netd/uip.h [new file with mode: 0644]
Applications/netd/uip_arch.h [new file with mode: 0644]
Applications/netd/uip_arp.c [new file with mode: 0644]
Applications/netd/uip_arp.h [new file with mode: 0644]
Applications/netd/uiplib.c [new file with mode: 0644]
Applications/netd/uiplib.h [new file with mode: 0644]
Applications/netd/uipopt.h [new file with mode: 0644]
Kernel/platform-coco3/Makefile
Kernel/platform-coco3/build
Kernel/platform-coco3/devices.c
Kernel/platform-coco3/main.c
Library/include/sys/net_native.h [new file with mode: 0644]

diff --git a/Applications/netd/Makefile.6809 b/Applications/netd/Makefile.6809
new file mode 100644 (file)
index 0000000..0ab7971
--- /dev/null
@@ -0,0 +1,45 @@
+PLATFORM = 6809
+CC = m6809-unknown-gcc
+# These are wrappers for lwasm and lwar
+ASM = m6809-unknown-as
+AR = m6809-unknown-ar
+LINKER = lwlink
+CFLAGS = -I../../Library/include -I../../Library/include/6809
+CFLAGS += -O0 -msoft-reg-count=0 -mfar-stack-param -fomit-frame-pointer
+LINKER_OPT = --format=raw -L../../Library/libs -lc6809
+LIBGCCDIR = $(dir $(shell $(CC) -print-libgcc-file-name))
+LINKER_OPT += -L$(LIBGCCDIR) -lgcc
+LINKER_OPT += --script=../util/$(TARGET).link
+ASM_OPT = -o
+CRT0 = ../../Library/libs/crt0_6809.o
+
+.SUFFIXES: .c .o
+
+SRCS  = netd.c uip.c uiplib.c timer.c clock-arch.c uip_arp.c telnet.c lwwire.c
+SRCS += echoping.c dig.c gethostbyname.c httpd.c coconic.c
+
+OBJS = $(SRCS:.c=.o)
+
+APPS = netd
+
+all: $(APPS)
+
+
+netd: $(OBJS)
+       $(LINKER) $(LINKER_OPT) -o netd-lwwire $(CRT0) netd.o uip.o uiplib.o timer.o clock-arch.o uip_arp.o lwwire.o
+       $(LINKER) $(LINKER_OPT) -o netd-coconic $(CRT0) netd.o uip.o uiplib.o timer.o clock-arch.o uip_arp.o coconic.o
+       $(LINKER) $(LINKER_OPT) -o telnet $(CRT0) telnet.o gethostbyname.o
+       $(LINKER) $(LINKER_OPT) -o echoping $(CRT0) echoping.o
+       $(LINKER) $(LINKER_OPT) -o dig $(CRT0) dig.o
+       $(LINKER) $(LINKER_OPT) -o httpd $(CRT0) httpd.o
+
+
+
+size.report: $(APPS)
+       ls -l $^ > $@
+
+clean:
+       rm -f $(OBJS) $(APPS) $(SRCS:.c=) core *~ *.asm *.lst *.sym *.map *.noi *.lk *.ihx *.tmp *.bin size.report *~
+
+rmbak:
+       rm -f *~ core
diff --git a/Applications/netd/clock-arch.c b/Applications/netd/clock-arch.c
new file mode 100644 (file)
index 0000000..596017e
--- /dev/null
@@ -0,0 +1,61 @@
+/*
+ * Copyright (c) 2006, Swedish Institute of Computer Science.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * This file is part of the uIP TCP/IP stack
+ *
+ * $Id: clock-arch.c,v 1.2 2006/06/12 08:00:31 adam Exp $
+ */
+
+/**
+ * \file
+ *         Implementation of architecture-specific clock functionality
+ * \author
+ *         Adam Dunkels <adam@sics.se>
+ */
+#include <syscalls.h>
+#include <sys/types.h>
+#include "clock-arch.h"
+#include <sys/time.h>
+
+/*---------------------------------------------------------------------------*/
+clock_time_t
+clock_time(void)
+{
+  struct timeval tv;
+  struct timezone tz;
+
+  //  gettimeofday(&tv, &tz);
+  struct{
+      uint16_t high;
+      uint16_t low;
+  }now;
+  _time((__ktime_t *)&now,1);
+  return now.low;
+  //  return tv.tv_sec * 1000 + tv.tv_usec / 1000;
+}
+/*---------------------------------------------------------------------------*/
diff --git a/Applications/netd/clock-arch.h b/Applications/netd/clock-arch.h
new file mode 100644 (file)
index 0000000..063b30f
--- /dev/null
@@ -0,0 +1,40 @@
+/*
+ * Copyright (c) 2006, Swedish Institute of Computer Science.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * This file is part of the uIP TCP/IP stack
+ *
+ * $Id: clock-arch.h,v 1.2 2006/06/12 08:00:31 adam Exp $
+ */
+
+#ifndef __CLOCK_ARCH_H__
+#define __CLOCK_ARCH_H__
+
+typedef int clock_time_t;
+#define CLOCK_CONF_SECOND 10
+
+#endif /* __CLOCK_ARCH_H__ */
diff --git a/Applications/netd/clock.h b/Applications/netd/clock.h
new file mode 100644 (file)
index 0000000..f34d78f
--- /dev/null
@@ -0,0 +1,88 @@
+/**
+ * \defgroup clock Clock interface
+ *
+ * The clock interface is the interface between the \ref timer "timer library"
+ * and the platform specific clock functionality. The clock
+ * interface must be implemented for each platform that uses the \ref
+ * timer "timer library".
+ *
+ * The clock interface does only one this: it measures time. The clock
+ * interface provides a macro, CLOCK_SECOND, which corresponds to one
+ * second of system time.
+ *
+ * \sa \ref timer "Timer library"
+ *
+ * @{
+ */
+
+/*
+ * Copyright (c) 2004, Swedish Institute of Computer Science.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * This file is part of the uIP TCP/IP stack
+ *
+ * Author: Adam Dunkels <adam@sics.se>
+ *
+ * $Id: clock.h,v 1.3 2006/06/11 21:46:39 adam Exp $
+ */
+#ifndef __CLOCK_H__
+#define __CLOCK_H__
+
+#include "clock-arch.h"
+
+/**
+ * Initialize the clock library.
+ *
+ * This function initializes the clock library and should be called
+ * from the main() function of the system.
+ *
+ */
+void clock_init(void);
+
+/**
+ * Get the current clock time.
+ *
+ * This function returns the current system clock time.
+ *
+ * \return The current clock time, measured in system ticks.
+ */
+clock_time_t clock_time(void);
+
+/**
+ * A second, measured in system clock time.
+ *
+ * \hideinitializer
+ */
+#ifdef CLOCK_CONF_SECOND
+#define CLOCK_SECOND CLOCK_CONF_SECOND
+#else
+#define CLOCK_SECOND (clock_time_t)32
+#endif
+
+#endif /* __CLOCK_H__ */
+
+/** @} */
diff --git a/Applications/netd/coconic.c b/Applications/netd/coconic.c
new file mode 100644 (file)
index 0000000..a42c2d7
--- /dev/null
@@ -0,0 +1,160 @@
+/*
+  This is a net_native device driver for Jim Brain's CoCoNIC card. This
+  card is based on the CS8900A, and Jim's design uses the "I/O Memory Access",
+  mapping the NIC's 16 bytes of access regs to 0xff40.
+
+  note: This plays with I/O memory, of course, and shouldn't be in userspace!!!
+
+  TODO: dedicated polling routine for in-kernel operation
+
+*/
+
+#include <types.h>
+#include <stdio.h>
+#include "device.h"
+#include "uip.h"
+
+
+#define rxtx     *(volatile uint16_t *)0xff40 /* rxrx data */
+#define rxtx8low *(volatile uint8_t *)0xff40 /* Low byte of rxtx data */
+#define rxtx8hi  *(volatile uint8_t *)0xff41 /* high byte of rxtx data */
+#define txcmd  *(volatile uint16_t *)0xff44 /* transmit command register */
+#define txlen  *(volatile uint16_t *)0xff46 /* transmit length register */
+#define pageptr  *(volatile uint16_t *)0xff4a  /* packetpage pointer register */
+#define pagedata *(volatile uint16_t *)0xff4c /* packetpage data register */
+#define page8low *(volatile uint8_t *)0xff4c /* packetpage data register */
+#define page8hi  *(volatile uint8_t *)0xff4d /* packetpage data register */
+
+
+
+/* swap bytes in word */
+#define bswap( v )  ( v << 8 ) | ( v >> 8 )
+
+
+/* Get 16 bit word from NIC */
+static uint16_t getpp( uint16_t addr )
+{
+    /* for 16 bit read fixed card
+        pageptr = bswap( addr );
+        return bswap( pagedata );
+    */
+    pageptr = bswap( addr );
+    return ( page8hi << 8 ) | page8low;
+}
+
+/* set 16 bit word to packetpage */
+static void setpp( uint16_t addr, uint16_t data ){
+    pageptr = bswap( addr );
+    pagedata =  bswap( data );
+}
+
+/* get status / length */
+static uint16_t getlen( void )
+{
+    return (rxtx8hi << 8 ) | rxtx8low ;
+}
+
+/* drop a frame */
+static void drop( void )
+{
+    setpp( 0x102, getpp( 0x102 ) | 0x40 );
+}
+
+
+
+
+/* send sbuf, size len to the device
+   returns 0 on success, -1 on error
+ */
+int device_send( char *sbuf, int len )
+{
+    int alen;
+    uint16_t *ptr = (uint16_t *)sbuf;
+
+    /* send transmit command, length */
+    txcmd = bswap( 0x00c0 );
+    txlen = bswap( len );
+    /* round up for word acesses to NIC */
+    alen = (len + 1) / 2;
+    /* wait for room in NIC, drop received frames if necessary */
+    while( ! (getpp( 0x138 ) & 0x0100) )
+       drop();
+    /* send words from frame to NIC */
+    while( alen-- ){
+       //rxtx = *ptr++;
+       rxtx8low = *sbuf++;
+       rxtx8hi  = *sbuf++;
+    }
+    return 0;
+}
+
+
+/* get sbuf, max size len from the device 
+   returns size of recieved packets, 0 if nothing waiting
+*/
+int device_read( char *buf, int len )
+{
+    int rlen, alen;
+    uint16_t *ptr = (uint16_t *)buf;
+
+    /* return if there is no packet waiting for us */
+    if( ! (getpp( 0x124 ) & 0xd00) )
+       return 0;
+    /* drop status */
+    rlen = getlen();
+    /* get length */
+    rlen = getlen();
+    /* word access round-up */
+    alen = (rlen + 1) / 2;
+    /* packet too big for our buffer?*/
+    if( alen*2 > len ){
+       drop();
+       return 0;
+    }
+    /* get words from NIC into buffer */
+    while( alen-- ){
+       //*ptr++ = rxtx;
+       *buf++ = rxtx8low;
+       *buf++ = rxtx8hi;
+    }
+    return rlen;
+}
+
+
+
+/* initialize device
+   returns 0 on success, -1 on error
+*/
+int device_init( void )
+{
+    /* check for card */
+    uint16_t id = getpp( 0x0000 );
+    if( id != 0x630e ){
+       fprintf( stderr, "CoCoNIC card not found\n", id );
+       return -1;
+    }
+    /* set MAC address of card */
+    pageptr = bswap( 0x158 );
+    page8low = uip_lladdr.addr[0];
+    page8hi  = uip_lladdr.addr[1];
+
+    pageptr = bswap( 0x15a );
+    page8low = uip_lladdr.addr[2];
+    page8hi  = uip_lladdr.addr[3];
+
+    pageptr = bswap( 0x15c );
+    page8low = uip_lladdr.addr[4];
+    page8hi  = uip_lladdr.addr[5];
+
+    /* turn on receiver / transmitter */
+    setpp( 0x112, 0x00d3 );
+    /* allow reception of our address frames and broadcasts */
+    setpp( 0x104, 0x0d05 );
+
+    return 0;
+}
+
+
+
+
+
diff --git a/Applications/netd/device.h b/Applications/netd/device.h
new file mode 100644 (file)
index 0000000..e3844aa
--- /dev/null
@@ -0,0 +1,27 @@
+/*
+
+  Device Driver header for uip/fuzix
+
+
+ */
+
+/* implemented by device: */
+
+/* send sbuf, size len to the device
+   returns 0 on success, -1 on error
+ */
+int device_send( char *sbuf, int len );
+
+
+/* get sbuf, max size len from the device 
+   returns size of recieved packets, 0 if nothing waiting
+*/
+int device_read( char *buf, int len );
+
+
+
+/* initialize device
+   returns 0 on success, -1 on error
+*/
+int device_init( void );
+
diff --git a/Applications/netd/dig.c b/Applications/netd/dig.c
new file mode 100644 (file)
index 0000000..eceae76
--- /dev/null
@@ -0,0 +1,238 @@
+/*
+  A Cheesey Dig Client
+
+  todo:  
+     allow setting of dns server :)
+
+*/
+
+#include <stdio.h>
+#include <string.h>
+#include <unistd.h>
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+#include <signal.h>
+#include "netdb.h"
+
+struct header{
+    uint16_t id;
+    uint8_t  cntl;
+    uint8_t  ret;
+    uint16_t qdcount;
+    uint16_t ancount;
+    uint16_t nscount;
+    uint16_t arcount;
+};
+
+struct RRtail{
+    uint16_t type;
+    uint16_t class;
+    uint32_t ttl;
+    uint16_t rdlen;
+};
+
+
+int fd;
+char buf[1024];
+
+
+void alarm_handler( int signum ){
+    return;
+}
+
+
+int send_question( char *name ){
+    struct header *p=( struct header *)buf;
+    struct RRtail *t;
+    
+    memset( p, 0, sizeof(buf) );
+    p->id = 42;     /* "random" query ID */
+    p->cntl = 0x1;  /* request a recursive query */
+    p->qdcount = 1; /* one question */
+    /* fill out name string */
+    char *i = name;
+    char *o = buf + sizeof(struct header);
+    char *l = o++;
+    
+    while(1){
+       if( ! *i )
+           break;
+       if( *i == '.' ){
+           *l = o - l - 1 ;
+           i++;
+           l = o++;
+       }
+       else
+           *o++ = *i++;
+    }
+    *l = o - l - 1;
+    *o++ = 0;
+    /* fill out rest of RR */
+    t = (struct RRtail *)o;
+    /* type: A record */
+    t->type = htons(1);
+    /* class: inet */
+    t->class = htons(1);
+    o += 4;
+    
+    write( fd, buf, (int)(o - buf) );
+    
+}
+
+void print_name( char *ptr ){
+    while(1){
+       if( *ptr == 0 ){
+           break;
+       }
+       if( (*ptr & 0xc0) == 0xc0 ){
+           ptr = buf + *(ptr + 1);
+           continue;
+       }
+       fwrite( ptr + 1, *ptr, 1, stdout );
+       //      write(1, ptr + 1, *ptr );
+       printf(".");
+       ptr += *ptr + 1;
+    }
+    printf("\t\t");
+    return;
+}
+
+
+print_entry( char **pptr, int no ){
+    struct RRtail *t;
+    int i,j;
+    char *ptr = *pptr;
+    for( i = 0; i < no; i++ ){
+       print_name( ptr );
+       while(1){
+           if( *ptr == 0 ){
+               ptr++;
+               break;
+           }
+           if( (*ptr & 0xc0) == 0xc0 ){
+               ptr += 2;
+               break;
+           }
+           ptr += *ptr + 1;
+       }
+       t = (struct RRtail *)ptr;
+       ptr += sizeof( struct RRtail);
+
+       /* cname */
+       if( t->type == 6 ){
+           printf( "SOA   ");
+           print_name( ptr );
+           ptr += t->rdlen;
+       }
+       else if( t->type == 5 ){
+           printf( "CNAME ");
+           print_name( ptr );
+           ptr += t->rdlen;
+       }
+       else if( t->type == 1 ){
+           printf( "A     ");
+           for( j=0; j<t->rdlen; j++ )
+               printf("%d.",*ptr++ );
+       }
+       else{
+           printf( "???   ");
+           ptr += t->rdlen;
+       }
+       printf("\n");
+    }
+    *pptr = ptr;
+}
+
+int main( int argc, char *argv[] ){
+
+    struct sockaddr_in addr;
+    int x;
+    int tries = 5;
+
+    fd = socket( AF_INET, SOCK_DGRAM, 0);
+    if( fd < 0 ){
+       perror("socket");
+       exit(1);
+    }
+
+    addr.sin_family = AF_INET;
+    addr.sin_port = htons( 53 );
+    inet_pton( AF_INET, "192.168.1.1", &addr.sin_addr.s_addr );
+
+    if( connect( fd, (struct sockaddr *)&addr, sizeof(addr) ) < 0 ){
+       perror("connect");
+       exit(1);
+    }
+
+    for( ; tries ; tries-- ){
+       send_question( argv[1] );
+       signal( SIGALRM, alarm_handler );
+       alarm(2);
+       x = read( fd, buf, 1024 );
+       if( x <= 0 )
+           continue;
+       goto process;
+    }
+    perror("timeout");
+    exit(1);
+
+ process:
+    /* process packet */
+    {
+       struct header *h = (struct header *)buf;
+
+       char *ptr;
+       int i,j;
+       
+       if( h->id != 42 ){
+           fprintf( stderr, "bad ID\n");
+           exit(1);
+       }
+
+       if( ! h->cntl & 0x80 ){
+           fprintf( stderr, "not an answer\n");
+           exit(1);
+       }
+
+       if( ! h->ret & 0x80 ){
+           fprintf( stderr, "server doesn't do recursion\n");
+       }
+       /* skip over our question(s) */
+       printf("qust: %d, ans: %d, ns: %d, add: %d\n",
+              h->qdcount, h->ancount, h->nscount, h->arcount );
+       ptr = buf + sizeof( struct header );
+       printf("questions:\n");
+       /* move ptr past questions */
+       for( i = 0; i < h->qdcount; i++ ){
+           print_name( ptr );
+           printf("\n");
+           while(1){
+               if( *ptr == 0 ){
+                   ptr++;
+                   break;
+               }
+               if( (*ptr & 0xc0) == 0xc0 ){
+                   ptr += 2;
+                   break;
+               }
+               ptr += *ptr + 1;
+           }
+           ptr +=4;
+       }   
+       /* print out answers */
+       if( h->ancount ){
+           printf("answers:\n");
+           print_entry( &ptr, h->ancount );
+       }
+       if( h->nscount ){
+           printf("authority:\n");
+           print_entry( &ptr, h->nscount );
+       }
+       if( h->arcount ){
+           printf("addional:\n");
+           print_entry( &ptr, h->arcount );
+       }
+    }
+    exit(0);
+}
diff --git a/Applications/netd/echoping.c b/Applications/netd/echoping.c
new file mode 100644 (file)
index 0000000..7fc824f
--- /dev/null
@@ -0,0 +1,45 @@
+/* 
+   Echoping - A udp test client
+   send some text to an udp echo server, waits for reply, prints it.
+ */
+
+#include <stdio.h>
+#include <string.h>
+#include <unistd.h>
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+
+
+int main( int argc, char *argv[] ){
+
+    struct sockaddr_in addr;
+    int fd;
+    char buf[1024];
+    int x;
+
+    fd = socket(AF_INET, SOCK_DGRAM, 0);
+    if( fd < 0 ){
+       perror("socket()");
+       exit(1);
+    }
+
+    addr.sin_family = AF_INET;
+    addr.sin_port = htons(7);
+    inet_pton( AF_INET, "192.168.42.1", &addr.sin_addr.s_addr );
+    
+    if( connect( fd, (struct sockaddr *) &addr, sizeof(addr)) < 0 ){
+       perror("connect");
+       exit(1);
+    }
+
+    write( fd, "This is a test!", 16 ); 
+    sleep(1);
+    write( fd, "This is a test!", 16 );
+
+    x=read( fd, buf, 1024 );
+    printf("read %d: >%s<\n", x, buf );
+
+    exit(0);
+
+}
diff --git a/Applications/netd/fuzix-conf.h b/Applications/netd/fuzix-conf.h
new file mode 100644 (file)
index 0000000..76f5051
--- /dev/null
@@ -0,0 +1,23 @@
+#include <stdint.h>
+#include <sys/netdev.h>
+#include <sys/net_native.h>
+
+#define UIP_CONF_STATISTICS 0
+#define CCIF
+
+typedef uint8_t uip_tcp_appstate_t;
+typedef uint8_t uip_udp_appstate_t;
+typedef uint8_t uip_stats_t;
+
+#define UIP_APPCALL netd_appcall
+#define UIP_UDP_APPCALL netd_udp_appcall
+
+#define UIP_CONF_LLH_LEN 14
+
+#define UIP_CONF_BYTE_ORDER      UIP_BIG_ENDIAN
+
+#define UIP_CONF_ACTIVE_OPEN 1
+
+#define UIP_CONF_RECEIVE_WINDOW 1500 
+
+#define MIN(n, m)   (((n) < (m)) ? (n) : (m))
diff --git a/Applications/netd/fuzix-netd.pkg b/Applications/netd/fuzix-netd.pkg
new file mode 100644 (file)
index 0000000..90b46c9
--- /dev/null
@@ -0,0 +1,20 @@
+package  netd-base
+if-file  dig
+f 0644 /etc/netrc             netrc
+f 0644 /etc/resolv.conf        resolv.conf
+f 0755 /usr/bin/dig           dig
+f 0755 /usr/bin/echoping       echoping
+f 0755 /usr/bin/telnet        telnet
+n 20666 1089 /dev/net 
+
+
+package  netd-lwwire
+if-file  netd-lwwire
+f 0755 /usr/bin/netd-lwwire    netd-lwwire
+n 060666 2048 /dev/dw0
+
+package  netd-coconic
+if-file  netd-coconic
+f 0755 /usr/bin/netd-coconic   netd-coconic
+
+
diff --git a/Applications/netd/gethostbyname.c b/Applications/netd/gethostbyname.c
new file mode 100644 (file)
index 0000000..3f1135a
--- /dev/null
@@ -0,0 +1,252 @@
+/* A stab at a resolver
+
+   NOTES:
+   * only does recursive querries, doesn't to iterative.
+
+   TODO:
+   * needs to read rc file
+   * retranslate textual IP address
+   * should work with TCP too
+   * fill out more of hostent struct
+
+*/
+
+#include <unistd.h>
+#include <string.h>
+#include <fcntl.h>
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+#include "netdb.h"
+
+/* DNS packet header */
+struct header{
+    uint16_t id;       /* unique session ID */
+    uint8_t  cntl;     /* bit fields - mostly request stuff */
+    uint8_t  ret;      /* bit feilds - mostly return/stat stuff */
+    uint16_t qdcount;  /* number of queries */
+    uint16_t ancount;  /* number of answers */
+    uint16_t nscount;  /* number of suggested name servers */
+    uint16_t arcount;  /* number of suggested name server IP addresses */
+};
+
+/* Tail of Returned resource records (RR's) */
+struct RRtail{
+    uint16_t type;    /* which type of record, 1 = A, IP address */
+    uint16_t class;   /* which network class, 1 = inet */
+    uint32_t ttl;     /* time to live of records in secounds */
+    uint16_t rdlen;   /* length of following data field, 4 for IP addresses */
+};
+
+#define MAXADDRS 4  /* max number of address stored in hostent struct */
+
+
+/* Does nothing, used for timing out waiting for DNS packet(s) */
+static void alarm_handler( int signum ){
+    return;
+}
+
+static int fd;          /* file descriptor for inet socket */
+static char buf[512];   /* packet buffer */
+
+
+/* formulate and send a DNS query packet */
+static int send_question( char *name ){
+    struct header *p=( struct header *)buf;
+    struct RRtail *t;
+    
+    memset( p, 0, sizeof(buf) );
+    p->id = 42;     /* "random" query ID */
+    p->cntl = 0x1;  /* request a recursive query */
+    p->qdcount = 1; /* one question */
+    /* fill out name string */
+    char *i = name;
+    char *o = buf + sizeof(struct header);
+    char *l = o++;
+    
+    while(1){
+       if( ! *i )
+           break;
+       if( *i == '.' ){
+           *l = o - l - 1 ;
+           i++;
+           l = o++;
+       }
+       else
+           *o++ = *i++;
+    }
+    *l = o - l - 1;
+    *o++ = 0;
+    /* fill out rest of RR */
+    t = (struct RRtail *)o;
+    /* type: A record */
+    t->type = htons(1);
+    /* class: inet */
+    t->class = htons(1);
+    o += 4;
+    
+    write( fd, buf, (int)(o - buf) );
+    
+}
+
+
+
+int h_errno;  /* Return error indicator */
+
+static char addrs[MAXADDRS][4];   /* hostent static address table */
+
+static char *list[MAXADDRS+1];    /* hostent static list of addresses */
+
+static struct hostent host={      /* static returned hostent struct */
+    NULL,
+    NULL,
+    AF_INET,
+    4,
+    list
+};
+
+
+/* Get a host by it's name */ 
+struct hostent *gethostbyname( char *name ){
+    struct sockaddr_in addr;
+    int x;
+    int tries = 5;
+    int lno=0;
+    char *ptr;
+    char server[17];
+    char *ws = " \f\n\r\t\v";
+
+    /* Try to just translate passed stringified IP address */
+    x = inet_pton( AF_INET, name, list[0] );
+    if( x == 1 ){
+       list[1] = NULL;
+       return &host;
+    }
+
+    /* open up /etc/resolv.conf and read in
+       fixme: handles only small config files < 512 bytes
+       fixme: if we have other gethostby-whatever functions, this should
+       be factored out as it's own static function */
+    fd = open( "/etc/resolv.conf", O_RDONLY );
+    if( fd < 0 ){
+       return NULL;
+    }
+    x = read( fd, buf, 511 );
+    if( x < 1 ){
+       close( fd );
+       return NULL;
+    }
+    buf[x]=0;
+    ptr = strtok( buf, ws );
+    while( ptr ){
+       if( ! strcmp( ptr, "nameserver" ) ){
+           ptr=strtok( NULL, ws );
+           if( ptr == NULL ){
+               return NULL;
+           }
+           strcpy( server, ptr );
+       }
+       ptr = strtok( NULL, ws );
+    }
+
+
+    fd = socket( AF_INET, SOCK_DGRAM, 0);
+    if( fd < 0 ){
+       return NULL;
+    }
+
+    addr.sin_family = AF_INET;
+    addr.sin_port = htons( 53 );
+
+    inet_pton( AF_INET, server, &addr.sin_addr.s_addr );
+
+    if( connect( fd, (struct sockaddr *)&addr, sizeof(addr) ) < 0 )
+       goto error;
+
+    for( ; tries ; tries-- ){
+       send_question( name );
+       signal( SIGALRM, alarm_handler );
+       alarm(2);
+       x = read( fd, buf, 512 );
+       if( x < 0 )
+           continue;
+       goto process;
+    }
+    h_errno = HOST_NOT_FOUND;
+    goto error;
+
+ process:
+    /* process packet */
+    {
+       struct header *h = (struct header *)buf;
+       struct RRtail *t;
+       char *ptr;
+       int i,j;
+
+       if( h->id != 42 )  /* correct session ID ? */
+           goto error;
+
+       if( ! h->cntl & 0x80 )  /* is an answer packet? */
+           goto error;
+
+       if( ! h->ret & 0x80 )  /* is a recursive answer? */
+           goto error;
+
+       if( ! h->ancount ) /* is there any answers? */
+           goto error;
+
+       /* skip over our question(s) */
+       ptr = buf + sizeof( struct header );
+       for( i = 0; i < h->qdcount && i < 4; i++ ){
+           while(1){
+               if( *ptr == 0 ){
+                   ptr++;
+                   break;
+               }
+               if( (*ptr & 0xc0) == 0xc0 ){
+                   ptr += 2;
+                   break;
+               }
+               ptr += *ptr + 1;
+           }
+           ptr +=4;
+       }
+       /* cap answers at MAXADDRS */
+       if( h->ancount > MAXADDRS )
+           h->ancount = MAXADDRS;
+       /* Iterate over answers */
+       for( i = 0; i < h->ancount; i++ ){
+           /* parse off name */
+           while(1){
+               if( *ptr == 0 ){
+                   ptr++;
+                   break;
+               }
+               if( (*ptr & 0xc0) == 0xc0 ){
+                   ptr += 2;
+                   break;
+               }
+               ptr += *ptr + 1;
+           }
+           /* point to rest of RR structure */
+           t = (struct RRtail *)ptr;
+           ptr += sizeof( struct RRtail);
+           if( t->type == 0x01 ){
+               for( j=0; j<t->rdlen; j++ )
+                   addrs[lno][j] = *ptr++;
+           }
+           else{
+               ptr += t->rdlen;
+           }
+           list[lno] = &addrs[lno][0];
+           lno++;
+       }
+       list[lno] = NULL;
+    }
+    close(fd);
+    return &host;
+ error:
+    close(fd);
+    return NULL;
+}
+
diff --git a/Applications/netd/httpd.c b/Applications/netd/httpd.c
new file mode 100644 (file)
index 0000000..0a6d27b
--- /dev/null
@@ -0,0 +1,57 @@
+/* 
+
+   A simple http server
+
+ */
+#include <string.h>
+#include <unistd.h>
+#include <stdlib.h>
+#include <fcntl.h>
+#include <termios.h>
+#include <stdio.h>
+#include <errno.h>
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+
+
+struct sockaddr_in addr;
+struct sockaddr_in laddr;
+int lfd;
+
+
+my_open( int argc, char *argv[]){
+    int port = 80;    /* default port */
+
+    addr.sin_port = htons(port);
+    addr.sin_family = AF_INET;
+
+    lfd = socket(AF_INET, SOCK_STREAM, 0);
+    if (lfd < 0) {
+       perror("af_inet sock_stream 0");
+       exit(1);
+    }
+
+    if( bind( lfd, &addr, sizeof(addr) ) ){
+       perror("bind");
+       exit(1);
+    }
+
+    if( listen( lfd, 1 ) ){
+       perror("connect");
+       exit(1);
+    }
+}
+
+int main( int argc, char *argv[]){
+       int len;
+
+       my_open( argc, argv );
+       printf("httpd server\n");
+       while(1);
+       return 0;
+
+
+}
+
+
diff --git a/Applications/netd/lwwire.c b/Applications/netd/lwwire.c
new file mode 100644 (file)
index 0000000..469b050
--- /dev/null
@@ -0,0 +1,160 @@
+/* 
+
+   Network via the LWWire standard for DW4
+
+*/
+  
+#include <stdio.h>
+#include <stdlib.h>
+#include <fcntl.h>
+#include <string.h>
+#include <unistd.h>
+#include <sys/drivewire.h>
+
+#include "device.h"
+
+static int fd;  /* fd of drivewire block device fd */
+
+/* returns number of byte in next packet, 0 = nothing waiting */
+static int dwnet_poll( void )
+{
+    int ret;
+    struct dw_trans d;
+    unsigned char buf[3];
+    buf[0] = 0xf3;   /* lwwire's extension op */
+    buf[1] = 0x01;   /* extension no */
+    buf[2] = 0x00;   /* op = poll */
+    d.sbuf = buf;
+    d.sbufz = 3;
+    d.rbuf = buf;
+    d.rbufz = 2;
+    ret = ioctl( fd, DRIVEWIREC_TRANS, &d );
+    if( ret < 0 ){
+       return -1;
+    }
+    return (buf[0]<<8) + buf[1];
+}
+
+
+/* drop the current packet */
+static int dwnet_drop( void )
+{
+    int ret;
+    struct dw_trans d;
+    unsigned char buf[3];
+    buf[0] = 0xf3;   /* lwwire's extension op */
+    buf[1] = 0x01;   /* extension no */
+    buf[2] = 0x04;   /* op = drop */
+    d.sbuf = buf;
+    d.sbufz = 3;
+    d.rbuf = NULL;
+    d.rbufz = 0;
+    ret = ioctl( fd, DRIVEWIREC_TRANS, &d );
+    if( ret < 0 ){
+       return -1;
+    }
+    return 0;
+}
+
+/* receive packet to a buffer */
+static int dwnet_recv( unsigned char *b, int len )
+{
+    int ret;
+    struct dw_trans d;
+    unsigned char buf[3];
+    buf[0] = 0xf3;   /* lwwire's extension op */
+    buf[1] = 0x01;   /* extension no */
+    buf[2] = 0x01;   /* op = read */
+    d.sbuf = buf;
+    d.sbufz = 3;
+    d.rbuf = b;
+    d.rbufz = len;
+    ret = ioctl( fd, DRIVEWIREC_TRANS, &d );
+    if( ret < 0 ){
+       return -1;
+    }
+    return 0;
+}
+
+/* received a chunked packets */
+static int dwnet_recv_chunk( unsigned char *b, int size )
+{
+    int ret;
+    struct dw_trans d;
+    unsigned char buf[3];
+    buf[0] = 0xf3;   /* lwwire's extension op */
+    buf[1] = 0x01;   /* extension no */
+    buf[2] = 0x03;   /* op = read chunk */
+    d.sbuf = buf;
+    d.sbufz = 3;
+    d.rbuf = b;
+    d.rbufz = size;
+    ret = ioctl( fd, DRIVEWIREC_TRANS, &d );
+    if( ret < 0 ){
+       return -1;
+    }
+    return 0;
+}
+
+/* send packet to net device */
+int device_send( char *sbuf, int len )
+{
+    int ret;
+    struct dw_trans d;
+    unsigned char buf[5];
+    buf[0] = 0xf3;   /* lwwire's extension op */
+    buf[1] = 0x01;   /* extension no */
+    buf[2] = 0x02;   /* op = send */
+    buf[3] = len >> 8;
+    buf[4] = len & 0xff ;
+    d.sbuf = buf;
+    d.sbufz = 5;
+    d.rbuf = 0;
+    d.rbufz = 0;
+    ret = ioctl( fd, DRIVEWIREC_TRANS, &d );
+    if( ret < 0 )
+       return -1;
+    d.sbuf = sbuf;
+    d.sbufz = len;
+    d.rbuf = 0;
+    d.rbufz = 0;
+    ret = ioctl( fd, DRIVEWIREC_TRANS, &d );
+    if( ret < 0 )
+       return -1;
+    return 0;
+}
+
+#define CHUNKZ 511
+
+
+int device_read( char *buf, int len )
+{
+    int packetz;
+    int l;
+    int s;
+    l = packetz = dwnet_poll();
+    if( l > len ){
+       dwnet_drop();
+    }
+    while( l > 0 ){
+       if( l > CHUNKZ )
+           s = CHUNKZ;
+       else 
+           s = l;
+       dwnet_recv_chunk( buf, s );
+       buf += CHUNKZ;
+       l -= CHUNKZ;
+    }
+    return packetz;
+}
+
+/* initialize network device */
+int device_init( void )
+{
+    fd=open( "/dev/dw0", O_RDONLY, 0 );
+    if( fd < 0 ){
+       return -1;
+    }
+    return 0;
+}
+
diff --git a/Applications/netd/netd.c b/Applications/netd/netd.c
new file mode 100644 (file)
index 0000000..22d2789
--- /dev/null
@@ -0,0 +1,760 @@
+/*
+
+*** Experimental ****
+
+A Contiki/uIP based net_native implementation for Fuzix.  This runs
+as a user-space daemon.
+
+
+There are two event "threads" - one for the kernel messages, and one for
+uIP's messages... these "threads" are round-robin'ed together in main().
+
+
+issues:
+* is this the correct kernel call / data struct for ticks ?
+* select() is not used, but should be.
+
+todo:
+
+* deamonize (detach) this proggie. (will we always have setsid() ? )
+* UDP local bind
+* TCP passive open
+
+
+*/
+
+
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <fcntl.h>
+#include <string.h>
+#include <unistd.h>
+#include <sys/drivewire.h>
+#include <sys/netdev.h>
+#include <sys/net_native.h>
+
+#include "uip.h"
+#include "timer.h"
+#include "uip_arp.h"
+#include "clock.h"
+#include "netd.h"
+#include "uiplib.h"
+#include "device.h"
+
+#define BUF ((struct uip_eth_hdr *)&uip_buf[0])
+
+int bfd;   /* fd of data backing file */
+int knet;  /* fd of kernel's network inface */
+int rc;    /* fd of rc file */
+struct sockmsg sm; /* event from kernel iface */
+struct netevent ne; /* event to kernel iface */
+struct timer periodic_timer, arp_timer;
+
+/* 'links' associate a kernel socket no to a uIP connection pointer
+   and hold some useful state.  Fuzix inits a new socket well before
+   uIP, so a separate linkage/state struct is needed.
+*/
+struct link map[NSOCKET];
+int freelist[NSOCKET];
+int freeptr = 0;
+
+
+/* print an error message */
+void printe( char *mesg )
+{
+       write(2, mesg, strlen(mesg));
+}
+
+/* print an error message an quit w/ error */
+void exit_err( char *mesg )
+{
+       printe( mesg );
+       exit(1);
+}
+
+/* wrapper around writing to kernel net device */
+void ksend( int event )
+{
+       ne.ret = 0;
+       ne.event = event;
+       if ( write( knet, &ne, sizeof(ne) ) < 0 )
+               exit_err("cannot write kernel net dev\n");
+}
+
+
+/* allocate a connection linkage */
+int get_map( void )
+{
+       int new = freelist[ --freeptr ];
+       memset( &map[new], 0, sizeof( map[new] ) );
+       return new;
+}
+
+/* release a linkage */
+void rel_map( int n )
+{
+       freelist[ freeptr++ ] = n;
+}
+
+/* initialize the free map of links */
+void init_map( void )
+{
+       int n;
+       for ( n = 0; n<NSOCKET; n++)
+               rel_map( n );
+}
+
+
+/* send or resend tcp data */
+void send_tcp( struct link *s )
+{
+       uint32_t base = s->socketn * RINGSIZ * 2 + RINGSIZ;
+       if ( ! s->len ) return;
+       lseek( bfd, base + s->tstart, SEEK_SET );
+       if ( read( bfd, uip_appdata, s->len ) < 0 )
+               exit_err("cannot read from backing file\n");
+       uip_send( uip_appdata, s->len );
+}
+
+/* send udp data */
+void send_udp( struct link *s )
+{
+       /* Send packet to net */
+       uint32_t base = s->socketn * RINGSIZ * 2 + RINGSIZ;
+       uint16_t len = s->tsize[s->tstart];
+       lseek( bfd, base + s->tstart * TXPKTSIZ, SEEK_SET );
+       if ( read( bfd, uip_appdata, len ) < 0 )
+               exit_err("cannot read from backing file\n");
+       uip_udp_send( len );
+       if ( ++s->tstart == NSOCKBUF )
+               s->tstart = 0;
+       /* Send Room event back to kernel */
+       ne.socket = s->socketn;
+       ne.data = s->tstart;
+       ksend( NE_ROOM );
+}
+
+/* return amout of free room for adding data in recv ring buffer */
+uint16_t room( struct link *s )
+{
+       uint16_t t = 0;
+       if ( s->rstart > s->rend )
+               t = s->rstart - s->rend;
+       else
+               t = RINGSIZ - (s->rend - s->rstart);
+       return t-1;
+}
+
+/* return capacity of data in transmit ring buffer */
+uint16_t cap( struct link *s )
+{
+       if ( s->tstart > s->tend )
+               return RINGSIZ - (s->tstart - s->tend);
+       else
+               return s->tend - s->tstart;
+}
+
+/* uIP callback for TCP events */
+void netd_appcall()
+{
+       /*
+         printe( "appcall: " );
+         if( uip_aborted() ) printe("aborted.\n");
+         if( uip_acked() )  printe("acked.\n");
+         if( uip_closed() ) printe("closed.\n");
+         if( uip_newdata() ) printe("new data.\n");
+         if( uip_poll() ) printe("polled.\n");
+         if( uip_rexmit() ) printe("rexmit.\n");
+         if( uip_timedout() ) printe("timed out.\n");
+         if( uip_connected() ) printe("connected.\n" );
+       */
+       struct link *s = & map[uip_conn->appstate];
+       ne.socket = s->socketn;
+
+       /* uIP sends up a connected event for both
+          active and passive opens */
+       if ( uip_connected() ){
+               int flag = 0;
+               /* find see if anything is listening on this port */
+               {
+                       int i;
+                       for ( i = 0; i< NSOCKET; i++ ){
+                               if ( map[i].port == uip_conn->lport ){
+                                       /* found a listening port */
+                                       /* FIXME: what am I supposed to send to the
+                                          listening socket?
+                                       */
+                                       ne.data = SS_ACCEPTWAIT;
+                                       ksend( NE_EVENT );
+                                       /* make a new link and Associate the new uip_connection
+                                          with some lcn/socket the kernel readied */
+                                       flag = 1;
+                                       break;
+                               }
+                       }
+               }
+               if ( ! flag ){
+                       /* Not a listing port so assume a active open */
+                       ne.data = SS_CONNECTED;
+                       ksend( NE_NEWSTATE );
+               }
+       }
+
+
+       if ( uip_newdata() ){
+               /* there new data in the packet buffer */
+               uint16_t len = uip_datalen();
+               uint16_t l;
+               char *ptr = uip_appdata;
+               uint32_t base = ne.socket * RINGSIZ * 2;
+               if ( room(s) < len )
+                       exit_err("RECV OVERFLOW!\n");
+               while ( len ){
+                       if ( s->rend >= s->rstart ) /* not wrapped */
+                               l = RINGSIZ - s->rend;
+                       else
+                               l = s->rstart - s->rend - 1;
+                       if ( l > len )
+                               l = len;
+                       lseek( bfd, base + s->rend, SEEK_SET );
+                       if ( write( bfd, ptr, l ) < 0 )
+                           exit_err("cannot write to backing file\n");
+                       ptr += l;
+                       s->rend += l;
+                       if ( s->rend == RINGSIZ )
+                               s->rend = 0;
+                       len -= l;
+               }
+               /* throttle incoming data if there's no room in ring buf */
+               if ( room(s) < UIP_RECEIVE_WINDOW )
+                       uip_stop();
+               /* tell kernel we have data */
+               ne.data = s->rend;
+               /* ne.info = ???; for udp only? */
+               ksend( NE_DATA );
+       }
+
+       if ( uip_acked() ){
+               /* actually remove the bytes from the ring
+                * and send ROOM notice to kernel */
+               ne.data = (s->tstart + s->len) & (RINGSIZ - 1);
+               s->tstart = ne.data;  /* adjust local copy also!!! */
+               ksend( NE_ROOM );
+               s->len = 0;
+       }
+
+       if ( uip_poll() ){
+               uint16_t len;
+
+               /* if flow stopped, check to see if there's enough room
+                  to start it again.
+               */
+               if ( uip_stopped(uip_conn) && ( room(s) >= UIP_RECEIVE_WINDOW) )
+                       uip_restart();
+
+               /* send data if there is some in the xmit ringbuf */
+               if ( ! s->len ){
+                       if ( s->tend != s->tstart ){
+                               if ( s->tend > s->tstart ) /* not wrapped */
+                                       len = s->tend - s->tstart;
+                               else  /* wrapped - just go to logical end of data */
+                                       len = RINGSIZ - s->tstart;
+                               /* don't send more than TCP will actually send */
+                               if ( uip_mss() < len )
+                                       s->len = uip_mss();
+                               else
+                                       s->len = len;
+                               send_tcp( s );
+                       }
+               }
+
+               /* test for local close - LINK_CLOSED is set by kernel event thread */
+               if ( s->flags & LINK_CLOSED ){
+                       uip_close();
+                       s->flags &= ~LINK_CLOSED;
+                       s->flags |= LINK_SHUTW;
+                       if ( s->flags & LINK_SHUTR )
+                               rel_map( uip_conn->appstate );
+               }
+
+       }
+
+       if ( uip_rexmit() ){
+               /* resend data */
+               send_tcp( s );
+       }
+
+       if ( uip_closed() || uip_aborted() ){
+               int e;
+               switch ( s->flags & (LINK_SHUTR | LINK_SHUTW) ){
+               case 0:
+                       e = NE_SHUTR;
+                       break;
+               case LINK_SHUTR:
+                       goto close;
+               case LINK_SHUTW:
+                       e = NE_NEWSTATE;
+                       break;
+               case LINK_SHUTR | LINK_SHUTW:
+                       return;
+               }
+               /* formulate and send reset of message */
+               ne.data = SS_CLOSED;
+               ksend( e );
+               /* release link resource if both sides closed */
+               /* mark link as remote closed */
+       close:
+               s->flags |= LINK_SHUTR;
+               if ( s->flags & LINK_SHUTW )
+                       rel_map( uip_conn->appstate );
+       }
+}
+
+
+
+/* uIP callbck for UDP event */
+void netd_udp_appcall()
+{
+       /* debug
+          printe( "appcall udp: " );
+          if( uip_aborted() ) printe("aborted");
+          if( uip_acked() )  printe("acked");
+          if( uip_closed() ) printe("closed");
+          if( uip_newdata() ) printe("new data");
+          if( uip_poll() ) printe("polled");
+          if( uip_rexmit() ) printe("rexmit");
+          if( uip_timedout() ) printe("timed out");
+          if( uip_connected() ) printe("connected" );
+          printe("\n");
+       */
+
+       struct link *s = & map[uip_udp_conn->appstate];
+       ne.socket = s->socketn;
+
+       if ( uip_poll() ){
+               /* send data if there's data waiting on this connection */
+               /*    doing this before testing for close ??? */
+               if ( s->tend != s->tstart ){
+                       send_udp( s );
+                       return; /* short circuit LINK_CLOSED until EOD. */
+               }
+               /* if flagged close from kernel, then really close, confirm w/ kernel */
+               if ( s->flags & LINK_CLOSED ){
+                       /* send closed event back to kernel */
+                       ne.socket = sm.s.s_num;
+                       ne.data = SS_CLOSED;
+                       ksend( NE_NEWSTATE );
+                       /* release private link resource */
+                       rel_map( uip_udp_conn->appstate );
+                       uip_udp_remove( uip_udp_conn );
+                       return;
+               }
+       }
+
+       if ( uip_newdata() ){
+               /* there new data in the packet buffer */
+               uint16_t len = uip_datalen();
+               char *ptr = uip_appdata;
+               uint32_t base = ne.socket * RINGSIZ * 2;
+
+               if ( (s->rend + 1)&(NSOCKBUF-1) == s->rstart )
+                       return; /* full - drop it */
+               s->rsize[s->rend] = len;
+               memcpy( &ne.info, s->rsize, sizeof(uint16_t) * NSOCKBUF );
+               lseek( bfd, base + s->rend * RXPKTSIZ, SEEK_SET );
+               if ( write( bfd, ptr, len ) < 0 )
+                   exit_err("cannot write to backing file\n");
+               if ( ++s->rend == NSOCKBUF )
+                       s->rend = 0;
+               /* FIXME: throttle incoming data if there's no room in ring buf */
+               /* tell kernel we have data */
+               ne.data = s->rend;
+               /* ne.info = ???; for udp only? */
+               ksend( NE_DATA );
+       }
+}
+
+
+/* unused (for now) */
+void uip_log(char *m)
+{
+       fprintf( stderr, "uIP: %s\n", m);
+}
+
+
+/* handle events from kernel */
+/* returns 0 if nothing going on */
+int dokernel( void )
+{
+       struct link *m;
+       int i = read( knet, &sm, sizeof(sm) );
+       if ( i < 0 ){
+               return 0;
+       }
+       else if ( i == sizeof( sm ) && sm.sd.event & 127 ){
+               /* debug
+                  fprintf(stderr,"read size: %d ", i );
+                  fprintf(stderr,"knet lcn: %d ", sm.sd.lcn );
+                  fprintf(stderr,"event: %x ", sm.sd.event );
+                  fprintf(stderr,"newstat: %x\n", sm.sd.newstate );
+               */
+               m = & map[sm.sd.lcn];
+               if ( sm.sd.event & NEV_STATE ){
+                       ne.socket = sm.s.s_num;
+                       switch ( sm.sd.newstate ){
+                       case SS_UNCONNECTED:
+                               ne.data = get_map(); /* becomes lcn */
+                               map[ne.data].len = 0;
+                               map[ne.data].socketn = sm.s.s_num;
+                               ksend( NE_INIT );
+                               break;
+                       case SS_BOUND:
+                               /* FIXME: probably needs to do something here  */
+                               ne.data = SS_BOUND;
+                               ksend( NE_NEWSTATE );
+                               break;
+                       case SS_CONNECTING:
+                               if ( sm.s.s_type == SOCKTYPE_TCP ){
+                                       struct uip_conn *conptr;
+                                       uip_ipaddr_t addr;
+                                       int port = sm.s.s_addr[SADDR_DST].port;
+                                       uip_ipaddr_copy( &addr, (uip_ipaddr_t *)
+                                                        &sm.s.s_addr[SADDR_DST].addr );
+                                       /* need some HTONS'ing done here? */
+                                       conptr = uip_connect( &addr, port );
+                                       if ( !conptr ){
+                                               break; /* fixme: actually handler the error */
+                                       }
+                                       m->conn = conptr; /* fixme: needed? */
+                                       conptr->appstate = sm.sd.lcn;
+                                       break;
+                               }
+                               else if ( sm.s.s_type == SOCKTYPE_UDP ){
+                                       struct uip_udp_conn *conptr;
+                                       uip_ipaddr_t addr;
+                                       int port = sm.s.s_addr[SADDR_DST].port;
+                                       uip_ipaddr_copy( &addr, (uip_ipaddr_t *)
+                                                        &sm.s.s_addr[SADDR_DST].addr );
+                                       /* need some HTONS'ing done here? */
+                                       conptr = uip_udp_new( &addr, port );
+                                       if ( !conptr ){
+                                               break; /* fixme: actually handler the error */
+                                       }
+                                       m->conn = ( struct uip_conn *)conptr; /* fixme: needed? */
+                                       conptr->appstate = sm.sd.lcn;
+                                       /* fixme: assign local address/port !!! */
+                                       /* refactor: same as tcp action from connect event */
+                                       ne.data = SS_CONNECTED;
+                                       ksend( NE_NEWSTATE );
+                                       break;
+                               }
+                               break; /* FIXME: handle unknown/unhandled sock types here */
+                       case SS_CLOSED:
+                               if ( sm.s.s_type == SOCKTYPE_TCP ){
+                                       m->flags += LINK_SHUTW;
+                                       /* if remote already closed then send closing synch event
+                                          directly back to kernel, and release our link */
+                                       if ( m->flags & LINK_SHUTR ){
+                                               ne.data = SS_CLOSED;
+                                               ksend( NE_NEWSTATE );
+                                               rel_map( sm.sd.lcn );
+                                       }
+                                       /* tell uIP thread that local has closed, but we
+                                          cant send anything directly to uIP from here -
+                                          so set a flag and let uip_poll() handler do the job
+                                          the next time through the main program loop
+                                       */
+                                       else {
+                                               m->flags += LINK_CLOSED;
+                                       }
+                               }
+                               else if ( sm.s.s_type == SOCKTYPE_UDP ){
+                                       m->flags += LINK_CLOSED;
+                               }
+                               break;
+                       case SS_LISTENING:
+                               /* htons here? */
+                               uip_listen( sm.s.s_addr[0].port );
+                               m->port = sm.s.s_addr[0].port;
+                               ne.data = SS_LISTENING;
+                               ksend( NE_NEWSTATE );
+                               break;
+                       default:
+                               break;
+                       }
+               }
+               if ( sm.sd.event & NEV_WRITE ){
+                       /* can't send data now, so store needed buffer info */
+                       int last;
+                       m->tstart = sm.sd.tbuf;
+                       m->tend = sm.sd.tnext;
+                       last = m->tend-1 & NSOCKBUF-1;
+                       /* tsize is for udp only, but copy it anyway */
+                       m->tsize[last] = sm.sd.tlen[last];
+               }
+               if ( sm.sd.event & NEV_READ ){
+                       int last;
+                       m->rstart = sm.sd.rbuf;
+                       m->rend = sm.sd.rnext;
+               }
+               return 1;
+       }
+       return 0;
+}
+
+/* handle events from uIP */
+/* returns 0 if nothing going on */
+int douip( void )
+{
+       int ret = 0;
+       int i = device_read( uip_buf, UIP_BUFSIZE );
+       if (i > 0){
+               ret = 1;
+               uip_len = i;
+               if (uip_len > 0) {
+                       if ( BUF->type == UIP_HTONS(UIP_ETHTYPE_IP)){
+                               uip_arp_ipin();
+                               uip_input();
+                               if (uip_len > 0) {
+                                       uip_arp_out();
+                                       device_send( uip_buf, uip_len);
+                               }
+                       }else if ( BUF->type == UIP_HTONS(UIP_ETHTYPE_ARP)){
+                               uip_arp_arpin();
+                               if (uip_len > 0 )
+                                       device_send( uip_buf, uip_len);
+                       }
+               }
+       } else if (timer_expired(&periodic_timer)) {
+               timer_reset(&periodic_timer);
+               for (i = 0; i < UIP_CONNS; i++) {
+                       uip_periodic(i);
+                       if (uip_len > 0) {
+                               uip_arp_out();
+                               device_send( uip_buf, uip_len );
+                       }
+               }
+               for (i = 0; i < UIP_UDP_CONNS; i++) {
+                       uip_udp_periodic(i);
+                       if (uip_len > 0) {
+                               uip_arp_out();
+                               device_send( uip_buf, uip_len );
+                       }
+               }
+               if ( timer_expired(&arp_timer)){
+                       timer_reset(&arp_timer);
+                       uip_arp_timer();
+               }
+       }
+       return ret;
+}
+
+
+
+
+/* Get charactor from rc file */
+/*   returns charactor from file, -1 on EOF */
+int mygetc( )
+{
+       static char *ibuf[80];
+       static char *pos;
+       static int len = 0;
+       if ( ! len ){
+               pos = (char *)ibuf;
+               len = read( rc, ibuf, 80 );
+               if( len < -1 )
+                       exit_err( "Error Reading rc file.\n" );
+               if( ! len )
+                       return -1;
+       }
+       len--;
+       return *pos++;
+}
+
+/* parse next token from rc file */
+/*   return -1 on EOF, */
+int word( char *buf, int max)
+{
+       int c;
+       int len = 0;
+
+       max -= 1;
+       /* skip spaces */
+       do {
+               c = mygetc();
+               if ( c < 0 )
+                       return -1;
+       } while ( isspace( c ) );
+       /* build token */
+       while ( ! isspace( c ) && c != -1 && len < max ){
+               *buf++ = c;
+               len++;
+               c = mygetc();
+       }
+       *buf = 0;
+       return 0;
+}
+
+/* parse a mac address from rc file */
+/*    need dynamic conversion base ? */
+int macaddrconv( char *buf, uip_eth_addr *addr )
+{
+       int i;
+       char *e;
+       for ( i = 0; i < 6; i++){
+               addr->addr[i] = strtol( buf, &e, 16 );
+               if ( e == buf )
+                       return 0;
+               buf = ++e;
+       }
+       return -1;
+}
+
+/* return various errors for rcfile problems */
+void exit_badrc( void )
+{
+       exit_err("error reading rc file\n" );
+}
+
+void exit_badaddr( void )
+{
+       exit_err("rc file: bad address" );
+}
+
+/* get ip address from rc file */
+int getaddr( uip_ipaddr_t *ipaddr )
+{
+       char buf[80];
+       if ( word( buf, 80 ) )
+               exit_badrc();
+       if ( ! uiplib_ip4addrconv( buf, ipaddr) )
+               exit_badaddr();
+       return -1;
+}
+
+
+/* read, parse, and apply rc file */
+int parse_rcfile( void ){
+
+       int x;
+       char buf[80];
+       uip_ipaddr_t ipaddr;        /* ip address buffer */
+       uip_eth_addr ethaddr;       /* mac address buffer */
+
+       rc = open("/etc/netrc", O_RDONLY, 0 );
+       if ( rc < 0 ){
+               exit_err("cannot open rc file\n");
+       }
+       while ( ! word( buf, 80 ) ){
+               if ( ! strcmp( buf, "ipaddr" ) ){
+                       getaddr( &ipaddr );
+                       uip_sethostaddr(&ipaddr);
+                       continue;
+               }
+               if ( ! strcmp( buf, "gateway" ) ){
+                       getaddr( &ipaddr );
+                       uip_setdraddr(&ipaddr);
+                       continue;
+               }
+               if ( ! strcmp( buf, "netmask" ) ){
+                       getaddr( &ipaddr );
+                       uip_setnetmask(&ipaddr);
+                       continue;
+               }
+               if ( ! strcmp( buf, "mac" ) ){
+                       if ( word( buf, 80 ) )
+                               exit_badrc();
+                       if ( ! macaddrconv( buf, &ethaddr ) )
+                               exit_err("bad mac address\n");
+                       uip_setethaddr( ethaddr );
+                       continue;
+               }
+               if ( buf[0]== '#' ){
+                       int c;
+                       do {
+                               c = mygetc();
+                       } while ( c != '\n' && c != -1 );
+               }
+       }
+       close(rc);
+       return 0;
+}
+
+
+
+int main( int argc, char *argv[] )
+{
+       int ret;
+       uip_ipaddr_t ipaddr;
+       uip_eth_addr ethaddr;       /* mac address buffer */
+       
+       /* where should backing file go? /var, /tmp, other?  */
+       bfd = open( "/tmp/net.back", O_RDWR|O_CREAT, 0644 );
+       if ( bfd < 0 ){
+               exit_err( "cannot open backing file\n");
+       }
+
+       /*open Kernel's net device */
+       knet = open( "/dev/net", O_RDWR|O_NDELAY, 0 );
+       if ( knet < 0 ){
+               exit_err( "cannot open kernel net iface device\n");
+       }
+
+       /* Attach our backing file to the network device */
+       ret = ioctl( knet, NET_INIT, &bfd );
+       if ( ret < 0 ){
+               exit_err( "cannot attach backing file\n");
+       }
+
+       /* initialize our map */
+       init_map();
+
+
+       /*
+        * Set up uIP
+        */
+
+       timer_set(&periodic_timer, CLOCK_SECOND / 4);
+       timer_set(&arp_timer, CLOCK_SECOND * 10 );
+
+       uip_init();
+
+       /*
+        * set default addresses structures for uIP.
+        */
+
+       /* set hostname - need a config file or cmd line here */
+       /* what are a good defaults here? */
+       uip_ipaddr(&ipaddr, 192,168,42,2);
+       uip_sethostaddr(&ipaddr);
+       uip_ipaddr(&ipaddr, 192,168,42,1);
+       uip_setdraddr(&ipaddr);
+       uip_ipaddr(&ipaddr, 255,255,255,0);
+       uip_setnetmask(&ipaddr);
+
+       /* set default MAC address */
+       ethaddr.addr[0] = 0x00;
+       ethaddr.addr[1] = 0x01;
+       ethaddr.addr[2] = 0x02;
+       ethaddr.addr[3] = 0x03;
+       ethaddr.addr[4] = 0x04;
+       ethaddr.addr[5] = 0x05;
+       uip_setethaddr(ethaddr);
+
+
+       parse_rcfile();
+
+       if( device_init() ){
+               exit_err( "cannot init net device\n");
+       }
+
+
+       while(1) {
+               int a,b;
+               a = dokernel();
+               b = douip();
+               if( ! (a || b) )
+                       _pause(3);
+       }
+}
diff --git a/Applications/netd/netd.h b/Applications/netd/netd.h
new file mode 100644 (file)
index 0000000..009210d
--- /dev/null
@@ -0,0 +1,34 @@
+/* dwnet.h interface
+
+
+
+ */
+#ifndef DWNET_H
+#define DWNET_H
+
+struct link{
+    uint8_t flags;          /* flags */
+#define LINK_CLOSED 1
+#define LINK_SHUTR  2       /* don't release our link/state until */
+#define LINK_SHUTW  4       /* both are set */
+    uint8_t socketn;        /* Kernel's socket no */
+    uint8_t lcn;            /* Kernel's idea of lcn ???*/
+    struct uip_conn *conn;  /* uIP's idea of lcn */
+    uint16_t tstart;     /* start of data in transmit ring */
+    uint16_t tend;       /* end of data in transmit ring */
+    uint16_t len;        /* length of data last transmitted */
+    uint16_t rstart;     /* start of data in recv ring */
+    uint16_t rend;       /* end of data in recv ring*/
+    uint16_t port;       /* which port are we listening on? */
+    /* for udp only */
+    uint16_t tsize[NSOCKBUF]; /* number of bytes to xmit in buffer */
+    uint16_t rsize[NSOCKBUF]; /* number of bytes to recv in buffers */
+};
+
+
+typedef uint8_t uip_tcp_appstate_t; /* index to link info */
+typedef uint8_t uip_udp_appstate_t;
+void netd_appcall( void );
+void netd_udp_appcall( void );
+
+#endif
diff --git a/Applications/netd/netdb.h b/Applications/netd/netdb.h
new file mode 100644 (file)
index 0000000..397ec08
--- /dev/null
@@ -0,0 +1,55 @@
+  /* Copyright (C) 1996-2004, 2009, 2010 Free Software Foundation, Inc.
+   This file is part of the GNU C Library.
+
+   The GNU C Library is free software; you can redistribute it and/or
+   modify it under the terms of the GNU Lesser General Public
+   License as published by the Free Software Foundation; either
+   version 2.1 of the License, or (at your option) any later version.
+
+   The GNU C Library is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+   Lesser General Public License for more details.
+
+   You should have received a copy of the GNU Lesser General Public
+   License along with the GNU C Library; if not, write to the Free
+   Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+   02111-1307 USA.  */
+
+/* All data returned by the network data base library are supplied in
+   host order and returned in network order (suitable for use in
+   system calls).  */
+
+
+/* Modified for fuzix by Brett M. Gordon */
+
+#ifndef _NETDB_H
+#define _NETDB_H
+
+/* Description of data base entry for a single host.  */
+struct hostent
+{
+  char *h_name;                        /* Official name of host.  */
+  char **h_aliases;            /* Alias list.  */
+  int h_addrtype;              /* Host address type.  */
+  int h_length;                        /* Length of address.  */
+  char **h_addr_list;          /* List of addresses from name server.  */
+};
+
+extern int h_errno;
+
+/* Possible values left in `h_errno'.  */
+#define HOST_NOT_FOUND 1       /* Authoritative Answer Host not found.  */
+#define TRY_AGAIN      2       /* Non-Authoritative Host not found,
+                                  or SERVERFAIL.  */
+#define NO_RECOVERY    3       /* Non recoverable errors, FORMERR, REFUSED,
+                                  NOTIMP.  */
+#define NO_DATA        4       /* Valid name, no data record of requested
+                                  type.  */
+
+
+extern struct hostent *gethostbyname (char *name);
+
+
+
+#endif /* netdb.h */
diff --git a/Applications/netd/netrc b/Applications/netd/netrc
new file mode 100644 (file)
index 0000000..ad90a05
--- /dev/null
@@ -0,0 +1,6 @@
+# netd rc file
+# Please change to suite.
+ipaddr  192.168.42.2
+gateway 192.168.42.1
+netmask 255.255.255.0
+mac     0:1:2:3:4:5
diff --git a/Applications/netd/resolv.conf b/Applications/netd/resolv.conf
new file mode 100644 (file)
index 0000000..1ea217a
--- /dev/null
@@ -0,0 +1 @@
+nameserver 192.168.1.1
diff --git a/Applications/netd/telnet.c b/Applications/netd/telnet.c
new file mode 100644 (file)
index 0000000..21f8077
--- /dev/null
@@ -0,0 +1,511 @@
+/* dwtelnet - Drivewire - raw Telnet
+ */
+#include <string.h>
+#include <unistd.h>
+#include <stdlib.h>
+#include <fcntl.h>
+#include <termios.h>
+#include <stdio.h>
+#include <errno.h>
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+#include "netdb.h"
+
+
+#define TESC 0x19
+#define ESC 0x1b
+
+
+char ibuf[256];
+int opos=0;
+
+int flags;
+struct termios prior,new;
+struct termios lprior,lnew;
+int fddw;
+int para[4]={0,0,0,0};
+int no=0;
+char colors[8]={
+       '0', '2', '4', '6',
+       '1', '3', '5', '7'
+};
+
+int linemode=0;
+int lecho=-1;
+int hex=0;
+int del=0;
+int crnl=-1;
+int fc=7;
+int bc=0;
+int inten=0;
+
+#define AF_INET                1
+#define SOCK_STREAM    3
+
+
+struct sockaddr_in addr;
+struct sockaddr_in laddr;
+
+void puterr( char *str ){
+       write(2, str, strlen(str));
+}
+
+void putstr( char *str ){
+       write(1, str, strlen(str));
+}
+
+int isnum( char c ){
+       if( c>='0' && c<='9' ) return 1;
+       return 0;
+}
+
+int tonum( char c ){
+       return c-'0';
+}
+
+void out52( char c ){
+       write(1, "\x1b", 1 );
+       write(1,&c, 1 );
+}
+
+void out52n( char c, char n ){
+       out52( c );
+       write(1,&n, 1 );
+}
+
+void out52nn( char c, char n, char m){
+       out52( c );
+       write(1,&n,1);
+       write(1,&m,1);
+}
+
+
+char cconv( char c ){
+       return colors[c];
+}
+
+
+/* check for matching fore/background colors w/ intensity bit
+   we can't do intensity - so text disappears */
+void ckint(){
+       if( (fc ==  bc)  &&  inten ){
+               fc = fc + 1 & 0x7 ;
+               out52n( 'b', fc );
+       }
+}
+
+/* Send a char to the console, processing for ANSI/TELNET chars */
+void charout( char c ){
+       static char mode=0;
+       int i;
+
+       switch( mode ){
+               /* normal mode */
+       case 0: 
+               if( c == 255 ){
+                       mode=3;
+                       return;
+               }
+               if( c != ESC )  write( 1, &c ,1 );
+               else{ 
+                       mode=1;
+               }
+               return;
+               /* ESC detected */
+       case 1:
+               if( c=='[' ){
+                       mode=2;
+                       return;
+               }
+               return;
+               /* Multi-byte detected */
+       case 2: 
+               if( isnum(c) ){
+                       para[no]=para[no]*10+tonum(c);
+                       return;
+               }
+               if( c == ';' ){
+                       no++;
+                       return;
+               }
+               no++;
+               goto final;
+               /* Telnet IAC detected */
+       case 3:
+               switch( c ){
+               case 255:
+                       write(1,&c,1);
+                       mode=0;
+                       return;
+
+               case 251:
+                       mode=5;
+                       return;
+               case 252:
+                       mode=6;
+                       return;
+               case 253:
+               case 254:
+                       if(hex) printf("<IAC><%x>",c);
+                       mode=4;
+                       return;
+               }
+               mode=0;
+               return;
+               /* send Telnet's WILLNOTs to server */
+       case 4:
+               if( hex )printf("<%x>\n", c );
+               write( fddw, "\xff\xfc",2);
+               write( fddw, &c, 1 );
+               mode = 0;
+               return;
+               /* received a WILL */
+       case 5:
+               if( c == 1 ){
+                       lecho = 0;
+                       //write(fddw,"\xff\xfd",2);
+                       //write(fddw, &c, 1 );
+                       mode = 0;
+                       return;
+               }
+               write( fddw,"\xff\xfe",2);
+               write( fddw, &c, 1);
+               mode = 0;
+               return;
+               /* received a WONT */
+       case 6:
+               if( hex ) printf("opt<%x>\n", c );
+               if( c == 1 ) lecho = -1;
+               else{
+                       write( fddw, "\xff\xfe", 2 );
+                       write( fddw, &c, 1 );
+               }
+               mode = 0;
+               return;
+
+       }
+       /* and the trailing command */
+ final:
+       //      printf("DEBUG: %d %d %d %c\n", para[0], para[1], para[2], c);
+       switch( c ){
+       case 'J':
+               if( para[0] == 2 ){
+                       out52( 'H' );
+                       out52( 'J' );
+                       break;
+               }
+               if( para[1] == 0 ){
+                       out52( 'J' );
+                       break;
+               }
+       case 'H':
+       case 'f':
+               if( para[0]==0 && para[1]==0 ){
+                       out52( 'H' );
+                       break;
+               }
+               if( para[0]==0 ) para[0]=1;
+               if( para[1]==0 ) para[1]=1;
+               out52nn( 'Y', para[0]+' ', para[1]+' ');
+               break;
+       case 'K':
+               if( para[0] == 0 ){
+                       out52( 'K');
+                       break;
+               }
+       case 'm':
+               for( i=0; i<no; i++ ){
+                       if( para[i]>=30 && para[i]<=37 ){
+                               fc=cconv(para[i]-30);
+                               out52n( 'b', fc );
+                               ckint();
+                       }
+                       if( para[i]>=40 && para[i]<=47 ){
+                               bc=cconv(para[i]-40);
+                               out52n( 'c', bc );
+                               ckint();
+                       }
+                       if( para[i]==0 ){
+                               out52n( 'b', '4' );
+                               out52n( 'c', '0' );
+                               inten=0;
+                       }
+                       if( para[i]==1 ){
+                               inten=1;
+                               ckint();
+                       }               
+               }
+               break;
+       case 'C':
+       case 'D':
+       case 'A':
+       case 'B':
+               if( para[0]==0 ) para[0]=1;
+               for( i=0; i<para[0]; i++) out52(c);
+               break;
+       case 'n':
+               if( para[0]==6 ){
+                       write(fddw,"\x1b[1;1R",6);
+                       out52( 'H' );
+                       out52( 'J' );
+               } 
+               break;
+               //      default:
+
+       }
+       para[0]=0;
+       para[1]=0;
+       para[2]=0;
+       para[3]=0;
+       no=0;
+       mode = 0;
+}
+
+/* print string to console under ANSI/TELNET */
+int mywrite( char *ptr, int len ){
+       int i=len;
+       while( i-- ) charout( *ptr++ );
+       return len;
+}
+
+void quit(){
+       tcsetattr( 0, TCSANOW, &lprior );
+       fcntl(0, F_SETFL, flags );
+       close( fddw );
+       exit(0);
+}
+
+/* Add string to input buffer */
+void addstr(char *s){
+       for( ; ibuf[opos++]=*s; s++ )
+               if( lecho ) write(1,s,1);
+       opos--;
+}
+
+void printd( char *s ){
+       while( *s ) write( 1, s++, 1);
+       write( 1, "\n", 1 );
+}
+
+void printhelp( void ){
+       printd( "l linemode toggle" );
+       printd( "e echo toggle");
+       printd( "q quit");
+       printd( "h IAC TELNET hex debugging");
+       printd( "n NL / CRNL");
+       printd( "^A send ^A to remote");
+}
+
+/* Read from standard input, nonblocking */
+int myread( void ){
+       static int icount=0;
+       static int ipos=0;
+       static char kbuf[256];
+       static int mode=0;
+       static int cmode=0;
+       int l;
+
+       switch( mode ){
+       case 0: // waiting for input buffer to fill middle 
+               l=read( 0, kbuf, 256 );
+               if( ! l ) return 0;
+               if( l < 0 ){
+                       if( errno == EAGAIN ){
+                               return 0;
+                       }
+                       else
+                           quit();
+               }
+               ipos=0;
+               icount=l;
+               mode=1;
+       case 1: // processing middle buffer to input buffer
+               for( ; ipos<icount; ipos++ ){
+                       char c=kbuf[ipos];
+                       if( cmode ){
+                               switch( c ){
+                                   /*
+                               case '1':
+                                       addstr( "tcp connect " );
+                                       break;
+                               case '2':
+                                       addstr( "nostalgiamud.l-w.ca 4000");
+                                       break;
+                               case '3':
+                                       addstr( "aardmud.org 23" );
+                                       break;
+                               case '4':
+                                       addstr( "vert.synchro.net 23" );
+                                       break;
+                               case '5':
+                                       addstr( "madworld.bounceme.net 6400");
+                                       break;
+                                   */
+                               case 'l':
+                                       linemode = ~linemode ;
+                                       break;
+                               case 'e':
+                                       lecho = ~lecho;
+                                       break;
+                               case 'q':
+                                       quit();
+                               case 'h':
+                                       hex= ~hex;
+                                       break;
+                               case 'd':
+                                       del= ~del;
+                                       break;
+                               case 'n':
+                                       crnl= ~crnl;
+                                       break;
+                               case 1:
+                                       ibuf[opos++]=1;
+                                       break;
+                               case '?':
+                                       printhelp();
+                                       break;
+                               }
+                               cmode=0;
+                               continue;
+                       }
+                       if( c == 1 ){
+                               cmode=1;
+                               continue;
+                       }
+                       if( linemode ){
+                               if( c == 8 ){
+                                       if( opos ){
+                                               opos--;
+                                               write(1,"\b \b",3);
+                                               continue;
+                                       }
+                                       continue;
+                               }
+                               write(1,&c,1);
+                               if( c == '\n' ){
+                                       int t=opos;
+                                       opos=0;
+                                       ibuf[t]=c;
+                                       ipos++;
+                                       return ++t;
+                               }
+                               ibuf[opos++]=c;
+                               continue;
+                       }
+                       if( lecho ) write(1,&c,1);
+                       if( (c == 8) && del ){
+                               ibuf[opos++]=127;
+                               continue;
+                       }
+                       if( (c== 0x0a) && crnl ){
+                               ibuf[opos++]=0x0d;
+                               ibuf[opos++]=0x0a;
+                               continue;
+                       }
+                       ibuf[opos++]=c;
+                       continue;
+               }
+               mode=0;
+               if( ! linemode ){
+                       int t=opos;
+                       opos=0;
+                       return t;
+               }
+               return 0;
+       }
+}
+
+my_open( int argc, char *argv[]){
+    int port = 23;    /* default port */
+    struct hostent *h;
+
+    if( argc == 3 )
+       port = atol(argv[2] );
+
+    addr.sin_port = htons(port);
+    addr.sin_family = AF_INET;
+
+    h=gethostbyname( argv[1] );
+    if( ! h ){
+       write(2, "cannot resolve hostname\n", 24 );
+       exit(1);
+    }
+    memcpy( &addr.sin_addr.s_addr, h->h_addr_list[0], 4 );
+
+    fddw = socket(AF_INET, SOCK_STREAM, 0);
+    if (fddw < 0) {
+       perror("af_inet sock_stream 0");
+       exit(1);
+    }
+
+    if (connect(fddw, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
+       perror("connect");
+       exit(1);
+    }
+    fcntl( fddw, F_SETFL, O_NDELAY );
+}
+
+int main( int argc, char *argv[]){
+       int len;
+
+       if( argc < 2 ){
+           write(2, "telnet: server [port]\n", 22 );
+           exit(1);
+       }
+
+       tcgetattr( 0, &lprior );
+
+       my_open( argc, argv );
+
+       flags = fcntl(0, F_GETFL, 0);
+       fcntl(0, F_SETFL, flags | O_NDELAY );
+
+
+       tcgetattr( 0, &lnew );
+       lnew.c_lflag &= ~ICANON;
+       lnew.c_lflag &= ~ECHO;
+       tcsetattr( 0, TCSANOW, &lnew );
+
+       printf("Use Cntl-A ? for help.\n");
+
+       while(1){
+               char *pos=ibuf;
+               len=myread();
+               while( len > 0 ){
+                       int ret = write( fddw, pos, len );
+                       if( ret < 0 ){
+                           if( errno == EAGAIN ){
+                               ret=0;
+                           }
+                           else
+                               quit();
+                       }
+                       len=len-ret;
+                       pos+=ret;
+               }
+               len=read( fddw, ibuf, 127 );
+               if( ! len )
+                   quit();
+               if( len < 0 ){
+                   if( errno != EAGAIN ){
+                       quit();
+                   }
+               }
+               pos = ibuf;
+               while( len > 0){
+                   int ret = mywrite( pos, len );
+                   if( ret < 0 ){
+                       if( errno == EWOULDBLOCK ){
+                           ret=0;
+                       }
+                       else quit();
+                   }
+                   len=len-ret;
+                   pos+=ret;
+               }
+       }
+}
+
+
+
diff --git a/Applications/netd/timer.c b/Applications/netd/timer.c
new file mode 100644 (file)
index 0000000..74eedf6
--- /dev/null
@@ -0,0 +1,127 @@
+/**
+ * \addtogroup timer
+ * @{
+ */
+
+/**
+ * \file
+ * Timer library implementation.
+ * \author
+ * Adam Dunkels <adam@sics.se>
+ */
+
+/*
+ * Copyright (c) 2004, Swedish Institute of Computer Science.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * This file is part of the uIP TCP/IP stack
+ *
+ * Author: Adam Dunkels <adam@sics.se>
+ *
+ * $Id: timer.c,v 1.2 2006/06/12 08:00:30 adam Exp $
+ */
+
+#include "clock.h"
+#include "timer.h"
+
+/*---------------------------------------------------------------------------*/
+/**
+ * Set a timer.
+ *
+ * This function is used to set a timer for a time sometime in the
+ * future. The function timer_expired() will evaluate to true after
+ * the timer has expired.
+ *
+ * \param t A pointer to the timer
+ * \param interval The interval before the timer expires.
+ *
+ */
+void
+timer_set(struct timer *t, clock_time_t interval)
+{
+  t->interval = interval;
+  t->start = clock_time();
+}
+/*---------------------------------------------------------------------------*/
+/**
+ * Reset the timer with the same interval.
+ *
+ * This function resets the timer with the same interval that was
+ * given to the timer_set() function. The start point of the interval
+ * is the exact time that the timer last expired. Therefore, this
+ * function will cause the timer to be stable over time, unlike the
+ * timer_rester() function.
+ *
+ * \param t A pointer to the timer.
+ *
+ * \sa timer_restart()
+ */
+void
+timer_reset(struct timer *t)
+{
+  t->start += t->interval;
+}
+/*---------------------------------------------------------------------------*/
+/**
+ * Restart the timer from the current point in time
+ *
+ * This function restarts a timer with the same interval that was
+ * given to the timer_set() function. The timer will start at the
+ * current time.
+ *
+ * \note A periodic timer will drift if this function is used to reset
+ * it. For preioric timers, use the timer_reset() function instead.
+ *
+ * \param t A pointer to the timer.
+ *
+ * \sa timer_reset()
+ */
+void
+timer_restart(struct timer *t)
+{
+  t->start = clock_time();
+}
+/*---------------------------------------------------------------------------*/
+/**
+ * Check if a timer has expired.
+ *
+ * This function tests if a timer has expired and returns true or
+ * false depending on its status.
+ *
+ * \param t A pointer to the timer
+ *
+ * \return Non-zero if the timer has expired, zero otherwise.
+ *
+ */
+int
+timer_expired(struct timer *t)
+{
+  return (clock_time_t)(clock_time() - t->start) >= (clock_time_t)t->interval;
+}
+/*---------------------------------------------------------------------------*/
+
+/** @} */
diff --git a/Applications/netd/timer.h b/Applications/netd/timer.h
new file mode 100644 (file)
index 0000000..057bea4
--- /dev/null
@@ -0,0 +1,86 @@
+/**
+ * \defgroup timer Timer library
+ *
+ * The timer library provides functions for setting, resetting and
+ * restarting timers, and for checking if a timer has expired. An
+ * application must "manually" check if its timers have expired; this
+ * is not done automatically.
+ *
+ * A timer is declared as a \c struct \c timer and all access to the
+ * timer is made by a pointer to the declared timer.
+ *
+ * \note The timer library uses the \ref clock "Clock library" to
+ * measure time. Intervals should be specified in the format used by
+ * the clock library.
+ *
+ * @{
+ */
+
+
+/**
+ * \file
+ * Timer library header file.
+ * \author
+ * Adam Dunkels <adam@sics.se>
+ */
+
+/*
+ * Copyright (c) 2004, Swedish Institute of Computer Science.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * This file is part of the uIP TCP/IP stack
+ *
+ * Author: Adam Dunkels <adam@sics.se>
+ *
+ * $Id: timer.h,v 1.3 2006/06/11 21:46:39 adam Exp $
+ */
+#ifndef __TIMER_H__
+#define __TIMER_H__
+
+#include "clock.h"
+
+/**
+ * A timer.
+ *
+ * This structure is used for declaring a timer. The timer must be set
+ * with timer_set() before it can be used.
+ *
+ * \hideinitializer
+ */
+struct timer {
+  clock_time_t start;
+  clock_time_t interval;
+};
+
+void timer_set(struct timer *t, clock_time_t interval);
+void timer_reset(struct timer *t);
+void timer_restart(struct timer *t);
+int timer_expired(struct timer *t);
+
+#endif /* __TIMER_H__ */
+
+/** @} */
diff --git a/Applications/netd/uip.c b/Applications/netd/uip.c
new file mode 100644 (file)
index 0000000..50de805
--- /dev/null
@@ -0,0 +1,1973 @@
+/*
+ * Copyright (c) 2001-2003, Adam Dunkels.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote
+ *    products derived from this software without specific prior
+ *    written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
+ * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
+ * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * This file is part of the uIP TCP/IP stack.
+ *
+ *
+ */
+
+/**
+ * \file
+ * The uIP TCP/IP stack code.
+ * \author Adam Dunkels <adam@dunkels.com>
+ */
+
+/**
+ * \addtogroup uip
+ * @{
+ */
+
+#define DEBUG_PRINTF(...) /*printf(__VA_ARGS__)*/
+
+/*
+ * uIP is a small implementation of the IP, UDP and TCP protocols (as
+ * well as some basic ICMP stuff). The implementation couples the IP,
+ * UDP, TCP and the application layers very tightly. To keep the size
+ * of the compiled code down, this code frequently uses the goto
+ * statement. While it would be possible to break the uip_process()
+ * function into many smaller functions, this would increase the code
+ * size because of the overhead of parameter passing and the fact that
+ * the optimier would not be as efficient.
+ *
+ * The principle is that we have a small buffer, called the uip_buf,
+ * in which the device driver puts an incoming packet. The TCP/IP
+ * stack parses the headers in the packet, and calls the
+ * application. If the remote host has sent data to the application,
+ * this data is present in the uip_buf and the application read the
+ * data from there. It is up to the application to put this data into
+ * a byte stream if needed. The application will not be fed with data
+ * that is out of sequence.
+ *
+ * If the application whishes to send data to the peer, it should put
+ * its data into the uip_buf. The uip_appdata pointer points to the
+ * first available byte. The TCP/IP stack will calculate the
+ * checksums, and fill in the necessary header fields and finally send
+ * the packet back to the peer.
+*/
+
+#include "uip.h"
+#include "uipopt.h"
+#include "uip_arp.h"
+#include "uip_arch.h"
+
+// #include "../ipv4/uip-neighbor.h"
+
+#include <string.h>
+// #include "../ip/cc.h"
+
+/*---------------------------------------------------------------------------*/
+/* Variable definitions. */
+
+
+/* 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 */
+#if UIP_FIXEDADDR > 0
+const uip_ipaddr_t uip_hostaddr =
+  { UIP_IPADDR0, UIP_IPADDR1, UIP_IPADDR2, UIP_IPADDR3 };
+const uip_ipaddr_t uip_draddr =
+  { UIP_DRIPADDR0, UIP_DRIPADDR1, UIP_DRIPADDR2, UIP_DRIPADDR3 };
+const uip_ipaddr_t uip_netmask =
+  { UIP_NETMASK0, UIP_NETMASK1, UIP_NETMASK2, UIP_NETMASK3 };
+#else
+uip_ipaddr_t uip_hostaddr, uip_draddr, uip_netmask;
+#endif /* UIP_FIXEDADDR */
+
+const uip_ipaddr_t uip_broadcast_addr =
+#if NETSTACK_CONF_WITH_IPV6
+  { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+      0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff } };
+#else /* NETSTACK_CONF_WITH_IPV6 */
+  { { 0xff, 0xff, 0xff, 0xff } };
+#endif /* NETSTACK_CONF_WITH_IPV6 */
+const uip_ipaddr_t uip_all_zeroes_addr = { { 0x0, /* rest is 0 */ } };
+
+#if UIP_FIXEDETHADDR
+const uip_lladdr_t uip_lladdr = {{UIP_ETHADDR0,
+                                         UIP_ETHADDR1,
+                                         UIP_ETHADDR2,
+                                         UIP_ETHADDR3,
+                                         UIP_ETHADDR4,
+                                         UIP_ETHADDR5}};
+#else
+uip_lladdr_t uip_lladdr = {{0,0,0,0,0,0}};
+#endif
+
+/* The packet buffer that contains incoming packets. */
+uip_buf_t uip_aligned_buf;
+
+void *uip_appdata;               /* The uip_appdata pointer points to
+                                   application data. */
+void *uip_sappdata;              /* The uip_appdata pointer points to
+                                   the application data which is to
+                                   be sent. */
+#if UIP_URGDATA > 0
+void *uip_urgdata;               /* The uip_urgdata pointer points to
+                                   urgent data (out-of-band data), if
+                                   present. */
+uint16_t uip_urglen, uip_surglen;
+#endif /* UIP_URGDATA > 0 */
+
+uint16_t uip_len, uip_slen;
+                             /* The uip_len is either 8 or 16 bits,
+                               depending on the maximum packet
+                               size. */
+
+uint8_t uip_flags;     /* The uip_flags variable is used for
+                               communication between the TCP/IP stack
+                               and the application program. */
+struct uip_conn *uip_conn;   /* uip_conn always points to the current
+                               connection. */
+
+struct uip_conn uip_conns[UIP_CONNS];
+                             /* The uip_conns array holds all TCP
+                               connections. */
+uint16_t uip_listenports[UIP_LISTENPORTS];
+                             /* The uip_listenports list all currently
+                               listning ports. */
+#if UIP_UDP
+struct uip_udp_conn *uip_udp_conn;
+struct uip_udp_conn uip_udp_conns[UIP_UDP_CONNS];
+#endif /* UIP_UDP */
+
+static uint16_t ipid;           /* Ths ipid variable is an increasing
+                               number that is used for the IP ID
+                               field. */
+
+void uip_setipid(uint16_t id) { ipid = id; }
+
+static uint8_t iss[4];          /* The iss variable is used for the TCP
+                               initial sequence number. */
+
+#if UIP_ACTIVE_OPEN || UIP_UDP
+static uint16_t lastport;       /* Keeps track of the last port used for
+                               a new connection. */
+#endif /* UIP_ACTIVE_OPEN || UIP_UDP */
+
+/* Temporary variables. */
+uint8_t uip_acc32[4];
+static uint8_t c, opt;
+static uint16_t tmp16;
+
+/* Structures and definitions. */
+#define TCP_FIN 0x01
+#define TCP_SYN 0x02
+#define TCP_RST 0x04
+#define TCP_PSH 0x08
+#define TCP_ACK 0x10
+#define TCP_URG 0x20
+#define TCP_CTL 0x3f
+
+#define TCP_OPT_END     0   /* End of TCP options list */
+#define TCP_OPT_NOOP    1   /* "No-operation" TCP option */
+#define TCP_OPT_MSS     2   /* Maximum segment size TCP option */
+
+#define TCP_OPT_MSS_LEN 4   /* Length of TCP MSS option. */
+
+#define ICMP_ECHO_REPLY 0
+#define ICMP_ECHO       8
+
+#define ICMP_DEST_UNREACHABLE        3
+#define ICMP_PORT_UNREACHABLE        3
+
+#define ICMP6_ECHO_REPLY             129
+#define ICMP6_ECHO                   128
+#define ICMP6_NEIGHBOR_SOLICITATION  135
+#define ICMP6_NEIGHBOR_ADVERTISEMENT 136
+
+#define ICMP6_FLAG_S (1 << 6)
+
+#define ICMP6_OPTION_SOURCE_LINK_ADDRESS 1
+#define ICMP6_OPTION_TARGET_LINK_ADDRESS 2
+
+
+/* Macros. */
+#define BUF ((struct uip_tcpip_hdr *)&uip_buf[UIP_LLH_LEN])
+#define FBUF ((struct uip_tcpip_hdr *)&uip_reassbuf[0])
+#define ICMPBUF ((struct uip_icmpip_hdr *)&uip_buf[UIP_LLH_LEN])
+#define UDPBUF ((struct uip_udpip_hdr *)&uip_buf[UIP_LLH_LEN])
+
+
+#if UIP_STATISTICS == 1
+struct uip_stats uip_stat;
+#define UIP_STAT(s) s
+#else
+#define UIP_STAT(s)
+#endif /* UIP_STATISTICS == 1 */
+
+#if UIP_LOGGING == 1
+#include <stdio.h>
+void uip_log(char *msg);
+#define UIP_LOG(m) uip_log(m)
+#else
+#define UIP_LOG(m)
+#endif /* UIP_LOGGING == 1 */
+
+#if ! UIP_ARCH_ADD32
+void
+uip_add32(uint8_t *op32, uint16_t op16)
+{
+  uip_acc32[3] = op32[3] + (op16 & 0xff);
+  uip_acc32[2] = op32[2] + (op16 >> 8);
+  uip_acc32[1] = op32[1];
+  uip_acc32[0] = op32[0];
+
+  if(uip_acc32[2] < (op16 >> 8)) {
+    ++uip_acc32[1];
+    if(uip_acc32[1] == 0) {
+      ++uip_acc32[0];
+    }
+  }
+
+
+  if(uip_acc32[3] < (op16 & 0xff)) {
+    ++uip_acc32[2];
+    if(uip_acc32[2] == 0) {
+      ++uip_acc32[1];
+      if(uip_acc32[1] == 0) {
+       ++uip_acc32[0];
+      }
+    }
+  }
+}
+
+#endif /* UIP_ARCH_ADD32 */
+
+#if ! UIP_ARCH_CHKSUM
+/*---------------------------------------------------------------------------*/
+static uint16_t
+chksum(uint16_t sum, const uint8_t *data, uint16_t len)
+{
+  uint16_t t;
+  const uint8_t *dataptr;
+  const uint8_t *last_byte;
+
+  dataptr = data;
+  last_byte = data + len - 1;
+
+  while(dataptr < last_byte) { /* At least two more bytes */
+    t = (dataptr[0] << 8) + dataptr[1];
+    sum += t;
+    if(sum < t) {
+      sum++;           /* carry */
+    }
+    dataptr += 2;
+  }
+
+  if(dataptr == last_byte) {
+    t = (dataptr[0] << 8) + 0;
+    sum += t;
+    if(sum < t) {
+      sum++;           /* carry */
+    }
+  }
+
+  /* Return sum in host byte order. */
+  return sum;
+}
+/*---------------------------------------------------------------------------*/
+uint16_t
+uip_chksum(uint16_t *data, uint16_t len)
+{
+  return uip_htons(chksum(0, (uint8_t *)data, len));
+}
+/*---------------------------------------------------------------------------*/
+#ifndef UIP_ARCH_IPCHKSUM
+uint16_t
+uip_ipchksum(void)
+{
+  uint16_t sum;
+
+  sum = chksum(0, &uip_buf[UIP_LLH_LEN], UIP_IPH_LEN);
+  DEBUG_PRINTF("uip_ipchksum: sum 0x%04x\n", sum);
+  return (sum == 0) ? 0xffff : uip_htons(sum);
+}
+#endif
+/*---------------------------------------------------------------------------*/
+static uint16_t
+upper_layer_chksum(uint8_t proto)
+{
+  uint16_t upper_layer_len;
+  uint16_t sum;
+
+#if NETSTACK_CONF_WITH_IPV6
+  upper_layer_len = (((uint16_t)(BUF->len[0]) << 8) + BUF->len[1]);
+#else /* NETSTACK_CONF_WITH_IPV6 */
+  upper_layer_len = (((uint16_t)(BUF->len[0]) << 8) + BUF->len[1]) - UIP_IPH_LEN;
+#endif /* NETSTACK_CONF_WITH_IPV6 */
+
+  /* First sum pseudoheader. */
+
+  /* IP protocol and length fields. This addition cannot carry. */
+  sum = upper_layer_len + proto;
+  /* Sum IP source and destination addresses. */
+  sum = chksum(sum, (uint8_t *)&BUF->srcipaddr, 2 * sizeof(uip_ipaddr_t));
+
+  /* Sum TCP header and data. */
+  sum = chksum(sum, &uip_buf[UIP_IPH_LEN + UIP_LLH_LEN],
+              upper_layer_len);
+
+  return (sum == 0) ? 0xffff : uip_htons(sum);
+}
+/*---------------------------------------------------------------------------*/
+#if NETSTACK_CONF_WITH_IPV6
+uint16_t
+uip_icmp6chksum(void)
+{
+  return upper_layer_chksum(UIP_PROTO_ICMP6);
+
+}
+#endif /* NETSTACK_CONF_WITH_IPV6 */
+/*---------------------------------------------------------------------------*/
+uint16_t
+uip_tcpchksum(void)
+{
+  return upper_layer_chksum(UIP_PROTO_TCP);
+}
+/*---------------------------------------------------------------------------*/
+#if UIP_UDP_CHECKSUMS
+uint16_t
+uip_udpchksum(void)
+{
+  return upper_layer_chksum(UIP_PROTO_UDP);
+}
+#endif /* UIP_UDP_CHECKSUMS */
+#endif /* UIP_ARCH_CHKSUM */
+/*---------------------------------------------------------------------------*/
+void
+uip_init(void)
+{
+  for(c = 0; c < UIP_LISTENPORTS; ++c) {
+    uip_listenports[c] = 0;
+  }
+  for(c = 0; c < UIP_CONNS; ++c) {
+    uip_conns[c].tcpstateflags = UIP_CLOSED;
+  }
+#if UIP_ACTIVE_OPEN || UIP_UDP
+  lastport = 1024;
+#endif /* UIP_ACTIVE_OPEN || UIP_UDP */
+
+#if UIP_UDP
+  for(c = 0; c < UIP_UDP_CONNS; ++c) {
+    uip_udp_conns[c].lport = 0;
+  }
+#endif /* UIP_UDP */
+
+
+  /* IPv4 initialization. */
+#if UIP_FIXEDADDR == 0
+  /*  uip_hostaddr[0] = uip_hostaddr[1] = 0;*/
+#endif /* UIP_FIXEDADDR */
+
+}
+/*---------------------------------------------------------------------------*/
+#if UIP_ACTIVE_OPEN
+struct uip_conn *
+uip_connect(const uip_ipaddr_t *ripaddr, uint16_t rport)
+{
+  register struct uip_conn *conn, *cconn;
+
+  /* Find an unused local port. */
+ again:
+  ++lastport;
+
+  if(lastport >= 32000) {
+    lastport = 4096;
+  }
+
+  /* Check if this port is already in use, and if so try to find
+     another one. */
+  for(c = 0; c < UIP_CONNS; ++c) {
+    conn = &uip_conns[c];
+    if(conn->tcpstateflags != UIP_CLOSED &&
+       conn->lport == uip_htons(lastport)) {
+      goto again;
+    }
+  }
+
+  conn = 0;
+  for(c = 0; c < UIP_CONNS; ++c) {
+    cconn = &uip_conns[c];
+    if(cconn->tcpstateflags == UIP_CLOSED) {
+      conn = cconn;
+      break;
+    }
+    if(cconn->tcpstateflags == UIP_TIME_WAIT) {
+      if(conn == 0 ||
+        cconn->timer > conn->timer) {
+       conn = cconn;
+      }
+    }
+  }
+
+  if(conn == 0) {
+    return 0;
+  }
+
+  conn->tcpstateflags = UIP_SYN_SENT;
+
+  conn->snd_nxt[0] = iss[0];
+  conn->snd_nxt[1] = iss[1];
+  conn->snd_nxt[2] = iss[2];
+  conn->snd_nxt[3] = iss[3];
+
+  conn->rcv_nxt[0] = 0;
+  conn->rcv_nxt[1] = 0;
+  conn->rcv_nxt[2] = 0;
+  conn->rcv_nxt[3] = 0;
+
+  conn->initialmss = conn->mss = UIP_TCP_MSS;
+
+  conn->len = 1;   /* TCP length of the SYN is one. */
+  conn->nrtx = 0;
+  conn->timer = 1; /* Send the SYN next time around. */
+  conn->rto = UIP_RTO;
+  conn->sa = 0;
+  conn->sv = 16;   /* Initial value of the RTT variance. */
+  conn->lport = uip_htons(lastport);
+  conn->rport = rport;
+  uip_ipaddr_copy(&conn->ripaddr, ripaddr);
+
+  return conn;
+}
+#endif /* UIP_ACTIVE_OPEN */
+/*---------------------------------------------------------------------------*/
+#if UIP_UDP
+struct uip_udp_conn *
+uip_udp_new(const uip_ipaddr_t *ripaddr, uint16_t rport)
+{
+  register struct uip_udp_conn *conn;
+
+  /* Find an unused local port. */
+ again:
+  ++lastport;
+
+  if(lastport >= 32000) {
+    lastport = 4096;
+  }
+
+  for(c = 0; c < UIP_UDP_CONNS; ++c) {
+    if(uip_udp_conns[c].lport == uip_htons(lastport)) {
+      goto again;
+    }
+  }
+
+
+  conn = 0;
+  for(c = 0; c < UIP_UDP_CONNS; ++c) {
+    if(uip_udp_conns[c].lport == 0) {
+      conn = &uip_udp_conns[c];
+      break;
+    }
+  }
+
+  if(conn == 0) {
+    return 0;
+  }
+
+  conn->lport = UIP_HTONS(lastport);
+  conn->rport = rport;
+  if(ripaddr == NULL) {
+    memset(&conn->ripaddr, 0, sizeof(uip_ipaddr_t));
+  } else {
+    uip_ipaddr_copy(&conn->ripaddr, ripaddr);
+  }
+  conn->ttl = UIP_TTL;
+
+  return conn;
+}
+#endif /* UIP_UDP */
+/*---------------------------------------------------------------------------*/
+void
+uip_unlisten(uint16_t port)
+{
+  for(c = 0; c < UIP_LISTENPORTS; ++c) {
+    if(uip_listenports[c] == port) {
+      uip_listenports[c] = 0;
+      return;
+    }
+  }
+}
+/*---------------------------------------------------------------------------*/
+void
+uip_listen(uint16_t port)
+{
+  for(c = 0; c < UIP_LISTENPORTS; ++c) {
+    if(uip_listenports[c] == 0) {
+      uip_listenports[c] = port;
+      return;
+    }
+  }
+}
+/*---------------------------------------------------------------------------*/
+/* XXX: IP fragment reassembly: not well-tested. */
+
+#if UIP_REASSEMBLY && !NETSTACK_CONF_WITH_IPV6
+#define UIP_REASS_BUFSIZE (UIP_BUFSIZE - UIP_LLH_LEN)
+static uint8_t uip_reassbuf[UIP_REASS_BUFSIZE];
+static uint8_t uip_reassbitmap[UIP_REASS_BUFSIZE / (8 * 8)];
+static const uint8_t bitmap_bits[8] = {0xff, 0x7f, 0x3f, 0x1f,
+                                   0x0f, 0x07, 0x03, 0x01};
+static uint16_t uip_reasslen;
+static uint8_t uip_reassflags;
+#define UIP_REASS_FLAG_LASTFRAG 0x01
+static uint8_t uip_reasstmr;
+
+#define IP_MF   0x20
+
+static uint8_t
+uip_reass(void)
+{
+  uint16_t offset, len;
+  uint16_t i;
+
+  /* If ip_reasstmr is zero, no packet is present in the buffer, so we
+     write the IP header of the fragment into the reassembly
+     buffer. The timer is updated with the maximum age. */
+  if(uip_reasstmr == 0) {
+    memcpy(uip_reassbuf, &BUF->vhl, UIP_IPH_LEN);
+    uip_reasstmr = UIP_REASS_MAXAGE;
+    uip_reassflags = 0;
+    /* Clear the bitmap. */
+    memset(uip_reassbitmap, 0, sizeof(uip_reassbitmap));
+  }
+
+  /* Check if the incoming fragment matches the one currently present
+     in the reasembly buffer. If so, we proceed with copying the
+     fragment into the buffer. */
+  if(BUF->srcipaddr[0] == FBUF->srcipaddr[0] &&
+     BUF->srcipaddr[1] == FBUF->srcipaddr[1] &&
+     BUF->destipaddr[0] == FBUF->destipaddr[0] &&
+     BUF->destipaddr[1] == FBUF->destipaddr[1] &&
+     BUF->ipid[0] == FBUF->ipid[0] &&
+     BUF->ipid[1] == FBUF->ipid[1]) {
+
+    len = (BUF->len[0] << 8) + BUF->len[1] - (BUF->vhl & 0x0f) * 4;
+    offset = (((BUF->ipoffset[0] & 0x3f) << 8) + BUF->ipoffset[1]) * 8;
+
+    /* If the offset or the offset + fragment length overflows the
+       reassembly buffer, we discard the entire packet. */
+    if(offset > UIP_REASS_BUFSIZE ||
+       offset + len > UIP_REASS_BUFSIZE) {
+      uip_reasstmr = 0;
+      goto nullreturn;
+    }
+
+    /* Copy the fragment into the reassembly buffer, at the right
+       offset. */
+    memcpy(&uip_reassbuf[UIP_IPH_LEN + offset],
+          (char *)BUF + (int)((BUF->vhl & 0x0f) * 4),
+          len);
+
+    /* Update the bitmap. */
+    if(offset / (8 * 8) == (offset + len) / (8 * 8)) {
+      /* If the two endpoints are in the same byte, we only update
+        that byte. */
+
+      uip_reassbitmap[offset / (8 * 8)] |=
+            bitmap_bits[(offset / 8 ) & 7] &
+            ~bitmap_bits[((offset + len) / 8 ) & 7];
+    } else {
+      /* If the two endpoints are in different bytes, we update the
+        bytes in the endpoints and fill the stuff inbetween with
+        0xff. */
+      uip_reassbitmap[offset / (8 * 8)] |=
+       bitmap_bits[(offset / 8 ) & 7];
+      for(i = 1 + offset / (8 * 8); i < (offset + len) / (8 * 8); ++i) {
+       uip_reassbitmap[i] = 0xff;
+      }
+      uip_reassbitmap[(offset + len) / (8 * 8)] |=
+       ~bitmap_bits[((offset + len) / 8 ) & 7];
+    }
+
+    /* If this fragment has the More Fragments flag set to zero, we
+       know that this is the last fragment, so we can calculate the
+       size of the entire packet. We also set the
+       IP_REASS_FLAG_LASTFRAG flag to indicate that we have received
+       the final fragment. */
+
+    if((BUF->ipoffset[0] & IP_MF) == 0) {
+      uip_reassflags |= UIP_REASS_FLAG_LASTFRAG;
+      uip_reasslen = offset + len;
+    }
+
+    /* Finally, we check if we have a full packet in the buffer. We do
+       this by checking if we have the last fragment and if all bits
+       in the bitmap are set. */
+    if(uip_reassflags & UIP_REASS_FLAG_LASTFRAG) {
+      /* Check all bytes up to and including all but the last byte in
+        the bitmap. */
+      for(i = 0; i < uip_reasslen / (8 * 8) - 1; ++i) {
+       if(uip_reassbitmap[i] != 0xff) {
+         goto nullreturn;
+       }
+      }
+      /* Check the last byte in the bitmap. It should contain just the
+        right amount of bits. */
+      if(uip_reassbitmap[uip_reasslen / (8 * 8)] !=
+        (uint8_t)~bitmap_bits[uip_reasslen / 8 & 7]) {
+       goto nullreturn;
+      }
+
+      /* If we have come this far, we have a full packet in the
+        buffer, so we allocate a pbuf and copy the packet into it. We
+        also reset the timer. */
+      uip_reasstmr = 0;
+      memcpy(BUF, FBUF, uip_reasslen);
+
+      /* Pretend to be a "normal" (i.e., not fragmented) IP packet
+        from now on. */
+      BUF->ipoffset[0] = BUF->ipoffset[1] = 0;
+      BUF->len[0] = uip_reasslen >> 8;
+      BUF->len[1] = uip_reasslen & 0xff;
+      BUF->ipchksum = 0;
+      BUF->ipchksum = ~(uip_ipchksum());
+
+      return uip_reasslen;
+    }
+  }
+
+ nullreturn:
+  return 0;
+}
+#endif /* UIP_REASSEMBLY */
+/*---------------------------------------------------------------------------*/
+static void
+uip_add_rcv_nxt(uint16_t n)
+{
+  uip_add32(uip_conn->rcv_nxt, n);
+  uip_conn->rcv_nxt[0] = uip_acc32[0];
+  uip_conn->rcv_nxt[1] = uip_acc32[1];
+  uip_conn->rcv_nxt[2] = uip_acc32[2];
+  uip_conn->rcv_nxt[3] = uip_acc32[3];
+}
+/*---------------------------------------------------------------------------*/
+void
+uip_process(uint8_t flag)
+{
+  register struct uip_conn *uip_connr = uip_conn;
+
+#if UIP_UDP
+  if(flag == UIP_UDP_SEND_CONN) {
+    goto udp_send;
+  }
+#endif /* UIP_UDP */
+
+  uip_sappdata = uip_appdata = &uip_buf[UIP_IPTCPH_LEN + UIP_LLH_LEN];
+
+  /* Check if we were invoked because of a poll request for a
+     particular connection. */
+  if(flag == UIP_POLL_REQUEST) {
+    if((uip_connr->tcpstateflags & UIP_TS_MASK) == UIP_ESTABLISHED &&
+       !uip_outstanding(uip_connr)) {
+       uip_flags = UIP_POLL;
+       UIP_APPCALL();
+       goto appsend;
+#if UIP_ACTIVE_OPEN && UIP_TCP
+    } else if((uip_connr->tcpstateflags & UIP_TS_MASK) == UIP_SYN_SENT) {
+      /* In the SYN_SENT state, we retransmit out SYN. */
+      BUF->flags = 0;
+      goto tcp_send_syn;
+#endif /* UIP_ACTIVE_OPEN */
+    }
+    goto drop;
+
+    /* Check if we were invoked because of the periodic timer firing. */
+  } else if(flag == UIP_TIMER) {
+#if UIP_REASSEMBLY
+    if(uip_reasstmr != 0) {
+      --uip_reasstmr;
+    }
+#endif /* UIP_REASSEMBLY */
+    /* Increase the initial sequence number. */
+    if(++iss[3] == 0) {
+      if(++iss[2] == 0) {
+       if(++iss[1] == 0) {
+         ++iss[0];
+       }
+      }
+    }
+
+    /* Reset the length variables. */
+    uip_clear_buf();
+    uip_slen = 0;
+
+#if UIP_TCP
+    /* Check if the connection is in a state in which we simply wait
+       for the connection to time out. If so, we increase the
+       connection's timer and remove the connection if it times
+       out. */
+    if(uip_connr->tcpstateflags == UIP_TIME_WAIT ||
+       uip_connr->tcpstateflags == UIP_FIN_WAIT_2) {
+      ++(uip_connr->timer);
+      if(uip_connr->timer == UIP_TIME_WAIT_TIMEOUT) {
+       uip_connr->tcpstateflags = UIP_CLOSED;
+      }
+    } else if(uip_connr->tcpstateflags != UIP_CLOSED) {
+      /* If the connection has outstanding data, we increase the
+        connection's timer and see if it has reached the RTO value
+        in which case we retransmit. */
+
+      if(uip_outstanding(uip_connr)) {
+       if(uip_connr->timer-- == 0) {
+         if(uip_connr->nrtx == UIP_MAXRTX ||
+            ((uip_connr->tcpstateflags == UIP_SYN_SENT ||
+              uip_connr->tcpstateflags == UIP_SYN_RCVD) &&
+             uip_connr->nrtx == UIP_MAXSYNRTX)) {
+           uip_connr->tcpstateflags = UIP_CLOSED;
+
+           /* We call UIP_APPCALL() with uip_flags set to
+              UIP_TIMEDOUT to inform the application that the
+              connection has timed out. */
+           uip_flags = UIP_TIMEDOUT;
+           UIP_APPCALL();
+
+           /* We also send a reset packet to the remote host. */
+           BUF->flags = TCP_RST | TCP_ACK;
+           goto tcp_send_nodata;
+         }
+
+         /* Exponential backoff. */
+         uip_connr->timer = UIP_RTO << (uip_connr->nrtx > 4?
+                                        4:
+                                        uip_connr->nrtx);
+         ++(uip_connr->nrtx);
+
+         /* Ok, so we need to retransmit. We do this differently
+            depending on which state we are in. In ESTABLISHED, we
+            call upon the application so that it may prepare the
+            data for the retransmit. In SYN_RCVD, we resend the
+            SYNACK that we sent earlier and in LAST_ACK we have to
+            retransmit our FINACK. */
+         UIP_STAT(++uip_stat.tcp.rexmit);
+         switch(uip_connr->tcpstateflags & UIP_TS_MASK) {
+         case UIP_SYN_RCVD:
+           /* In the SYN_RCVD state, we should retransmit our
+               SYNACK. */
+           goto tcp_send_synack;
+
+#if UIP_ACTIVE_OPEN
+         case UIP_SYN_SENT:
+           /* In the SYN_SENT state, we retransmit out SYN. */
+           BUF->flags = 0;
+           goto tcp_send_syn;
+#endif /* UIP_ACTIVE_OPEN */
+
+         case UIP_ESTABLISHED:
+           /* In the ESTABLISHED state, we call upon the application
+               to do the actual retransmit after which we jump into
+               the code for sending out the packet (the apprexmit
+               label). */
+           uip_flags = UIP_REXMIT;
+           UIP_APPCALL();
+           goto apprexmit;
+
+         case UIP_FIN_WAIT_1:
+         case UIP_CLOSING:
+         case UIP_LAST_ACK:
+           /* In all these states we should retransmit a FINACK. */
+           goto tcp_send_finack;
+
+         }
+       }
+      } else if((uip_connr->tcpstateflags & UIP_TS_MASK) == UIP_ESTABLISHED) {
+       /* If there was no need for a retransmission, we poll the
+           application for new data. */
+       uip_flags = UIP_POLL;
+       UIP_APPCALL();
+       goto appsend;
+      }
+    }
+#endif
+    goto drop;
+  }
+#if UIP_UDP
+  if(flag == UIP_UDP_TIMER) {
+    if(uip_udp_conn->lport != 0) {
+      uip_conn = NULL;
+      uip_sappdata = uip_appdata = &uip_buf[UIP_LLH_LEN + UIP_IPUDPH_LEN];
+      uip_len = uip_slen = 0;
+      uip_flags = UIP_POLL;
+      UIP_UDP_APPCALL();
+      goto udp_send;
+    } else {
+      goto drop;
+    }
+  }
+#endif
+
+  /* This is where the input processing starts. */
+  UIP_STAT(++uip_stat.ip.recv);
+
+  /* Start of IP input header processing code. */
+
+#if NETSTACK_CONF_WITH_IPV6
+  /* Check validity of the IP header. */
+  if((BUF->vtc & 0xf0) != 0x60)  { /* IP version and header length. */
+    UIP_STAT(++uip_stat.ip.drop);
+    UIP_STAT(++uip_stat.ip.vhlerr);
+    UIP_LOG("ipv6: invalid version.");
+    goto drop;
+  }
+#else /* NETSTACK_CONF_WITH_IPV6 */
+  /* Check validity of the IP header. */
+  if(BUF->vhl != 0x45)  { /* IP version and header length. */
+    UIP_STAT(++uip_stat.ip.drop);
+    UIP_STAT(++uip_stat.ip.vhlerr);
+    UIP_LOG("ip: invalid version or header length.");
+    goto drop;
+  }
+#endif /* NETSTACK_CONF_WITH_IPV6 */
+
+  /* Check the size of the packet. If the size reported to us in
+     uip_len is smaller the size reported in the IP header, we assume
+     that the packet has been corrupted in transit. If the size of
+     uip_len is larger than the size reported in the IP packet header,
+     the packet has been padded and we set uip_len to the correct
+     value. */
+
+  if((BUF->len[0] << 8) + BUF->len[1] <= uip_len) {
+    uip_len = (BUF->len[0] << 8) + BUF->len[1];
+#if NETSTACK_CONF_WITH_IPV6
+    uip_len += 40; /* The length reported in the IPv6 header is the
+                     length of the payload that follows the
+                     header. However, uIP uses the uip_len variable
+                     for holding the size of the entire packet,
+                     including the IP header. For IPv4 this is not a
+                     problem as the length field in the IPv4 header
+                     contains the length of the entire packet. But
+                     for IPv6 we need to add the size of the IPv6
+                     header (40 bytes). */
+#endif /* NETSTACK_CONF_WITH_IPV6 */
+  } else {
+    UIP_LOG("ip: packet shorter than reported in IP header.");
+    goto drop;
+  }
+
+#if !NETSTACK_CONF_WITH_IPV6
+  /* Check the fragment flag. */
+  if((BUF->ipoffset[0] & 0x3f) != 0 ||
+     BUF->ipoffset[1] != 0) {
+#if UIP_REASSEMBLY
+    uip_len = uip_reass();
+    if(uip_len == 0) {
+      goto drop;
+    }
+#else /* UIP_REASSEMBLY */
+    UIP_STAT(++uip_stat.ip.drop);
+    UIP_STAT(++uip_stat.ip.fragerr);
+    UIP_LOG("ip: fragment dropped.");
+    goto drop;
+#endif /* UIP_REASSEMBLY */
+  }
+#endif /* NETSTACK_CONF_WITH_IPV6 */
+
+  if(uip_ipaddr_cmp(&uip_hostaddr, &uip_all_zeroes_addr)) {
+    /* If we are configured to use ping IP address configuration and
+       haven't been assigned an IP address yet, we accept all ICMP
+       packets. */
+#if UIP_PINGADDRCONF && !NETSTACK_CONF_WITH_IPV6
+    if(BUF->proto == UIP_PROTO_ICMP) {
+      UIP_LOG("ip: possible ping config packet received.");
+      goto icmp_input;
+    } else {
+      UIP_LOG("ip: packet dropped since no address assigned.");
+      goto drop;
+    }
+#endif /* UIP_PINGADDRCONF */
+
+  } else {
+    /* If IP broadcast support is configured, we check for a broadcast
+       UDP packet, which may be destined to us. */
+#if UIP_BROADCAST
+    DEBUG_PRINTF("UDP IP checksum 0x%04x\n", uip_ipchksum());
+    if(BUF->proto == UIP_PROTO_UDP &&
+       (uip_ipaddr_cmp(&BUF->destipaddr, &uip_broadcast_addr) ||
+       (BUF->destipaddr.u8[0] & 224) == 224)) {  /* XXX this is a
+                                                    hack to be able
+                                                    to receive UDP
+                                                    multicast
+                                                    packets. We check
+                                                    for the bit
+                                                    pattern of the
+                                                    multicast
+                                                    prefix. */
+      goto udp_input;
+    }
+#endif /* UIP_BROADCAST */
+
+    /* Check if the packet is destined for our IP address. */
+#if !NETSTACK_CONF_WITH_IPV6
+    if(!uip_ipaddr_cmp(&BUF->destipaddr, &uip_hostaddr)) {
+      UIP_STAT(++uip_stat.ip.drop);
+      goto drop;
+    }
+#else /* NETSTACK_CONF_WITH_IPV6 */
+    /* For IPv6, packet reception is a little trickier as we need to
+       make sure that we listen to certain multicast addresses (all
+       hosts multicast address, and the solicited-node multicast
+       address) as well. However, we will cheat here and accept all
+       multicast packets that are sent to the ff02::/16 addresses. */
+    if(!uip_ipaddr_cmp(&BUF->destipaddr, &uip_hostaddr) &&
+       BUF->destipaddr.u16[0] != UIP_HTONS(0xff02)) {
+      UIP_STAT(++uip_stat.ip.drop);
+      goto drop;
+    }
+#endif /* NETSTACK_CONF_WITH_IPV6 */
+  }
+
+#if !NETSTACK_CONF_WITH_IPV6
+  if(uip_ipchksum() != 0xffff) { /* Compute and check the IP header
+                                   checksum. */
+    UIP_STAT(++uip_stat.ip.drop);
+    UIP_STAT(++uip_stat.ip.chkerr);
+    UIP_LOG("ip: bad checksum.");
+    goto drop;
+  }
+#endif /* NETSTACK_CONF_WITH_IPV6 */
+
+#if UIP_TCP
+  if(BUF->proto == UIP_PROTO_TCP) { /* Check for TCP packet. If so,
+                                      proceed with TCP input
+                                      processing. */
+    goto tcp_input;
+  }
+#endif
+
+#if UIP_UDP
+  if(BUF->proto == UIP_PROTO_UDP) {
+    goto udp_input;
+  }
+#endif /* UIP_UDP */
+
+#if !NETSTACK_CONF_WITH_IPV6
+  /* ICMPv4 processing code follows. */
+  if(BUF->proto != UIP_PROTO_ICMP) { /* We only allow ICMP packets from
+                                       here. */
+    UIP_STAT(++uip_stat.ip.drop);
+    UIP_STAT(++uip_stat.ip.protoerr);
+    UIP_LOG("ip: neither tcp nor icmp.");
+    goto drop;
+  }
+
+#if UIP_PINGADDRCONF
+ icmp_input:
+#endif /* UIP_PINGADDRCONF */
+  UIP_STAT(++uip_stat.icmp.recv);
+
+  /* ICMP echo (i.e., ping) processing. This is simple, we only change
+     the ICMP type from ECHO to ECHO_REPLY and adjust the ICMP
+     checksum before we return the packet. */
+  if(ICMPBUF->type != ICMP_ECHO) {
+    UIP_STAT(++uip_stat.icmp.drop);
+    UIP_STAT(++uip_stat.icmp.typeerr);
+    UIP_LOG("icmp: not icmp echo.");
+    goto drop;
+  }
+
+  /* If we are configured to use ping IP address assignment, we use
+     the destination IP address of this ping packet and assign it to
+     ourself. */
+#if UIP_PINGADDRCONF
+  if(uip_ipaddr_cmp(&uip_hostaddr, &uip_all_zeroes_addr)) {
+    uip_hostaddr = BUF->destipaddr;
+  }
+#endif /* UIP_PINGADDRCONF */
+
+  ICMPBUF->type = ICMP_ECHO_REPLY;
+
+  if(ICMPBUF->icmpchksum >= UIP_HTONS(0xffff - (ICMP_ECHO << 8))) {
+    ICMPBUF->icmpchksum += UIP_HTONS(ICMP_ECHO << 8) + 1;
+  } else {
+    ICMPBUF->icmpchksum += UIP_HTONS(ICMP_ECHO << 8);
+  }
+
+  /* Swap IP addresses. */
+  uip_ipaddr_copy(&BUF->destipaddr, &BUF->srcipaddr);
+  uip_ipaddr_copy(&BUF->srcipaddr, &uip_hostaddr);
+
+  UIP_STAT(++uip_stat.icmp.sent);
+  BUF->ttl = UIP_TTL;
+  goto ip_send_nolen;
+
+  /* End of IPv4 input header processing code. */
+#else /* !NETSTACK_CONF_WITH_IPV6 */
+
+  /* This is IPv6 ICMPv6 processing code. */
+  DEBUG_PRINTF("icmp6_input: length %d\n", uip_len);
+
+  if(BUF->proto != UIP_PROTO_ICMP6) { /* We only allow ICMPv6 packets from
+                                        here. */
+    UIP_STAT(++uip_stat.ip.drop);
+    UIP_STAT(++uip_stat.ip.protoerr);
+    UIP_LOG("ip: neither tcp nor icmp6.");
+    goto drop;
+  }
+
+  UIP_STAT(++uip_stat.icmp.recv);
+
+  /* If we get a neighbor solicitation for our address we should send
+     a neighbor advertisement message back. */
+  if(ICMPBUF->type == ICMP6_NEIGHBOR_SOLICITATION) {
+    if(uip_ipaddr_cmp(&ICMPBUF->icmp6data, &uip_hostaddr)) {
+
+      if(ICMPBUF->options[0] == ICMP6_OPTION_SOURCE_LINK_ADDRESS) {
+       /* Save the sender's address in our neighbor list. */
+       uip_neighbor_add(&ICMPBUF->srcipaddr, &(ICMPBUF->options[2]));
+      }
+
+      /* We should now send a neighbor advertisement back to where the
+        neighbor solicication came from. */
+      ICMPBUF->type = ICMP6_NEIGHBOR_ADVERTISEMENT;
+      ICMPBUF->flags = ICMP6_FLAG_S; /* Solicited flag. */
+
+      ICMPBUF->reserved1 = ICMPBUF->reserved2 = ICMPBUF->reserved3 = 0;
+
+      uip_ipaddr_copy(&ICMPBUF->destipaddr, &ICMPBUF->srcipaddr);
+      uip_ipaddr_copy(&ICMPBUF->srcipaddr, &uip_hostaddr);
+      ICMPBUF->options[0] = ICMP6_OPTION_TARGET_LINK_ADDRESS;
+      ICMPBUF->options[1] = 1;  /* Options length, 1 = 8 bytes. */
+      memcpy(&(ICMPBUF->options[2]), &uip_lladdr, sizeof(uip_lladdr));
+      ICMPBUF->icmpchksum = 0;
+      ICMPBUF->icmpchksum = ~uip_icmp6chksum();
+
+      goto send;
+
+    }
+    goto drop;
+  } else if(ICMPBUF->type == ICMP6_ECHO) {
+    /* ICMP echo (i.e., ping) processing. This is simple, we only
+       change the ICMP type from ECHO to ECHO_REPLY and update the
+       ICMP checksum before we return the packet. */
+
+    ICMPBUF->type = ICMP6_ECHO_REPLY;
+
+    uip_ipaddr_copy(&BUF->destipaddr, &BUF->srcipaddr);
+    uip_ipaddr_copy(&BUF->srcipaddr, &uip_hostaddr);
+    ICMPBUF->icmpchksum = 0;
+    ICMPBUF->icmpchksum = ~uip_icmp6chksum();
+
+    UIP_STAT(++uip_stat.icmp.sent);
+    goto send;
+  } else {
+    DEBUG_PRINTF("Unknown icmp6 message type %d\n", ICMPBUF->type);
+    UIP_STAT(++uip_stat.icmp.drop);
+    UIP_STAT(++uip_stat.icmp.typeerr);
+    UIP_LOG("icmp: unknown ICMP message.");
+    goto drop;
+  }
+
+  /* End of IPv6 ICMP processing. */
+
+#endif /* !NETSTACK_CONF_WITH_IPV6 */
+
+#if UIP_UDP
+  /* UDP input processing. */
+ udp_input:
+  /* UDP processing is really just a hack. We don't do anything to the
+     UDP/IP headers, but let the UDP application do all the hard
+     work. If the application sets uip_slen, it has a packet to
+     send. */
+#if UIP_UDP_CHECKSUMS
+  uip_len = uip_len - UIP_IPUDPH_LEN;
+  uip_appdata = &uip_buf[UIP_LLH_LEN + UIP_IPUDPH_LEN];
+  if(UDPBUF->udpchksum != 0 && uip_udpchksum() != 0xffff) {
+    UIP_STAT(++uip_stat.udp.drop);
+    UIP_STAT(++uip_stat.udp.chkerr);
+    UIP_LOG("udp: bad checksum.");
+    goto drop;
+  }
+#else /* UIP_UDP_CHECKSUMS */
+  uip_len = uip_len - UIP_IPUDPH_LEN;
+#endif /* UIP_UDP_CHECKSUMS */
+
+  /* Make sure that the UDP destination port number is not zero. */
+  if(UDPBUF->destport == 0) {
+    UIP_LOG("udp: zero port.");
+    goto drop;
+  }
+
+  /* Demultiplex this UDP packet between the UDP "connections". */
+  for(uip_udp_conn = &uip_udp_conns[0];
+      uip_udp_conn < &uip_udp_conns[UIP_UDP_CONNS];
+      ++uip_udp_conn) {
+    /* If the local UDP port is non-zero, the connection is considered
+       to be used. If so, the local port number is checked against the
+       destination port number in the received packet. If the two port
+       numbers match, the remote port number is checked if the
+       connection is bound to a remote port. Finally, if the
+       connection is bound to a remote IP address, the source IP
+       address of the packet is checked. */
+    if(uip_udp_conn->lport != 0 &&
+       UDPBUF->destport == uip_udp_conn->lport &&
+       (uip_udp_conn->rport == 0 ||
+        UDPBUF->srcport == uip_udp_conn->rport) &&
+       (uip_ipaddr_cmp(&uip_udp_conn->ripaddr, &uip_all_zeroes_addr) ||
+       uip_ipaddr_cmp(&uip_udp_conn->ripaddr, &uip_broadcast_addr) ||
+       uip_ipaddr_cmp(&BUF->srcipaddr, &uip_udp_conn->ripaddr))) {
+      goto udp_found;
+    }
+  }
+  UIP_LOG("udp: no matching connection found");
+  UIP_STAT(++uip_stat.udp.drop);
+#if UIP_CONF_ICMP_DEST_UNREACH && !NETSTACK_CONF_WITH_IPV6
+  /* Copy fields from packet header into payload of this ICMP packet. */
+  memcpy(&(ICMPBUF->payload[0]), ICMPBUF, UIP_IPH_LEN + 8);
+
+  /* Set the ICMP type and code. */
+  ICMPBUF->type = ICMP_DEST_UNREACHABLE;
+  ICMPBUF->icode = ICMP_PORT_UNREACHABLE;
+
+  /* Calculate the ICMP checksum. */
+  ICMPBUF->icmpchksum = 0;
+  ICMPBUF->icmpchksum = ~uip_chksum((uint16_t *)&(ICMPBUF->type), 36);
+
+  /* Set the IP destination address to be the source address of the
+     original packet. */
+  uip_ipaddr_copy(&BUF->destipaddr, &BUF->srcipaddr);
+
+  /* Set our IP address as the source address. */
+  uip_ipaddr_copy(&BUF->srcipaddr, &uip_hostaddr);
+
+  /* The size of the ICMP destination unreachable packet is 36 + the
+     size of the IP header (20) = 56. */
+  uip_len = 36 + UIP_IPH_LEN;
+  ICMPBUF->len[0] = 0;
+  ICMPBUF->len[1] = (uint8_t)uip_len;
+  ICMPBUF->ttl = UIP_TTL;
+  ICMPBUF->proto = UIP_PROTO_ICMP;
+
+  goto ip_send_nolen;
+#else /* UIP_CONF_ICMP_DEST_UNREACH */
+  goto drop;
+#endif /* UIP_CONF_ICMP_DEST_UNREACH */
+
+ udp_found:
+  UIP_STAT(++uip_stat.udp.recv);
+  uip_conn = NULL;
+  uip_flags = UIP_NEWDATA;
+  uip_sappdata = uip_appdata = &uip_buf[UIP_LLH_LEN + UIP_IPUDPH_LEN];
+  uip_slen = 0;
+  UIP_UDP_APPCALL();
+
+ udp_send:
+  if(uip_slen == 0) {
+    goto drop;
+  }
+  uip_len = uip_slen + UIP_IPUDPH_LEN;
+
+#if NETSTACK_CONF_WITH_IPV6
+  /* For IPv6, the IP length field does not include the IPv6 IP header
+     length. */
+  BUF->len[0] = ((uip_len - UIP_IPH_LEN) >> 8);
+  BUF->len[1] = ((uip_len - UIP_IPH_LEN) & 0xff);
+#else /* NETSTACK_CONF_WITH_IPV6 */
+  BUF->len[0] = (uip_len >> 8);
+  BUF->len[1] = (uip_len & 0xff);
+#endif /* NETSTACK_CONF_WITH_IPV6 */
+
+  BUF->ttl = uip_udp_conn->ttl;
+  BUF->proto = UIP_PROTO_UDP;
+
+  UDPBUF->udplen = UIP_HTONS(uip_slen + UIP_UDPH_LEN);
+  UDPBUF->udpchksum = 0;
+
+  BUF->srcport  = uip_udp_conn->lport;
+  BUF->destport = uip_udp_conn->rport;
+
+  uip_ipaddr_copy(&BUF->srcipaddr, &uip_hostaddr);
+  uip_ipaddr_copy(&BUF->destipaddr, &uip_udp_conn->ripaddr);
+
+  uip_appdata = &uip_buf[UIP_LLH_LEN + UIP_IPTCPH_LEN];
+
+#if UIP_UDP_CHECKSUMS
+  /* Calculate UDP checksum. */
+  UDPBUF->udpchksum = ~(uip_udpchksum());
+  if(UDPBUF->udpchksum == 0) {
+    UDPBUF->udpchksum = 0xffff;
+  }
+#endif /* UIP_UDP_CHECKSUMS */
+
+  UIP_STAT(++uip_stat.udp.sent);
+  goto ip_send_nolen;
+#endif /* UIP_UDP */
+
+  /* TCP input processing. */
+#if UIP_TCP
+ tcp_input:
+  UIP_STAT(++uip_stat.tcp.recv);
+
+  /* Start of TCP input header processing code. */
+
+  if(uip_tcpchksum() != 0xffff) {   /* Compute and check the TCP
+                                      checksum. */
+    UIP_STAT(++uip_stat.tcp.drop);
+    UIP_STAT(++uip_stat.tcp.chkerr);
+    UIP_LOG("tcp: bad checksum.");
+    goto drop;
+  }
+
+  /* Make sure that the TCP port number is not zero. */
+  if(BUF->destport == 0 || BUF->srcport == 0) {
+    UIP_LOG("tcp: zero port.");
+    goto drop;
+  }
+
+  /* Demultiplex this segment. */
+  /* First check any active connections. */
+  for(uip_connr = &uip_conns[0]; uip_connr <= &uip_conns[UIP_CONNS - 1];
+      ++uip_connr) {
+    if(uip_connr->tcpstateflags != UIP_CLOSED &&
+       BUF->destport == uip_connr->lport &&
+       BUF->srcport == uip_connr->rport &&
+       uip_ipaddr_cmp(&BUF->srcipaddr, &uip_connr->ripaddr)) {
+      goto found;
+    }
+  }
+
+  /* If we didn't find an active connection that expected the packet,
+     either this packet is an old duplicate, or this is a SYN packet
+     destined for a connection in LISTEN. If the SYN flag isn't set,
+     it is an old packet and we send a RST. */
+  if((BUF->flags & TCP_CTL) != TCP_SYN) {
+    goto reset;
+  }
+
+  tmp16 = BUF->destport;
+  /* Next, check listening connections. */
+  for(c = 0; c < UIP_LISTENPORTS; ++c) {
+    if(tmp16 == uip_listenports[c]) {
+      goto found_listen;
+    }
+  }
+
+  /* No matching connection found, so we send a RST packet. */
+  UIP_STAT(++uip_stat.tcp.synrst);
+
+ reset:
+  /* We do not send resets in response to resets. */
+  if(BUF->flags & TCP_RST) {
+    goto drop;
+  }
+
+  UIP_STAT(++uip_stat.tcp.rst);
+
+  BUF->flags = TCP_RST | TCP_ACK;
+  uip_len = UIP_IPTCPH_LEN;
+  BUF->tcpoffset = 5 << 4;
+
+  /* Flip the seqno and ackno fields in the TCP header. */
+  c = BUF->seqno[3];
+  BUF->seqno[3] = BUF->ackno[3];
+  BUF->ackno[3] = c;
+
+  c = BUF->seqno[2];
+  BUF->seqno[2] = BUF->ackno[2];
+  BUF->ackno[2] = c;
+
+  c = BUF->seqno[1];
+  BUF->seqno[1] = BUF->ackno[1];
+  BUF->ackno[1] = c;
+
+  c = BUF->seqno[0];
+  BUF->seqno[0] = BUF->ackno[0];
+  BUF->ackno[0] = c;
+
+  /* We also have to increase the sequence number we are
+     acknowledging. If the least significant byte overflowed, we need
+     to propagate the carry to the other bytes as well. */
+  if(++BUF->ackno[3] == 0) {
+    if(++BUF->ackno[2] == 0) {
+      if(++BUF->ackno[1] == 0) {
+       ++BUF->ackno[0];
+      }
+    }
+  }
+
+  /* Swap port numbers. */
+  tmp16 = BUF->srcport;
+  BUF->srcport = BUF->destport;
+  BUF->destport = tmp16;
+
+  /* Swap IP addresses. */
+  uip_ipaddr_copy(&BUF->destipaddr, &BUF->srcipaddr);
+  uip_ipaddr_copy(&BUF->srcipaddr, &uip_hostaddr);
+
+  /* And send out the RST packet! */
+  goto tcp_send_noconn;
+
+  /* This label will be jumped to if we matched the incoming packet
+     with a connection in LISTEN. In that case, we should create a new
+     connection and send a SYNACK in return. */
+ found_listen:
+  /* First we check if there are any connections avaliable. Unused
+     connections are kept in the same table as used connections, but
+     unused ones have the tcpstate set to CLOSED. Also, connections in
+     TIME_WAIT are kept track of and we'll use the oldest one if no
+     CLOSED connections are found. Thanks to Eddie C. Dost for a very
+     nice algorithm for the TIME_WAIT search. */
+  uip_connr = 0;
+  for(c = 0; c < UIP_CONNS; ++c) {
+    if(uip_conns[c].tcpstateflags == UIP_CLOSED) {
+      uip_connr = &uip_conns[c];
+      break;
+    }
+    if(uip_conns[c].tcpstateflags == UIP_TIME_WAIT) {
+      if(uip_connr == 0 ||
+        uip_conns[c].timer > uip_connr->timer) {
+       uip_connr = &uip_conns[c];
+      }
+    }
+  }
+
+  if(uip_connr == 0) {
+    /* All connections are used already, we drop packet and hope that
+       the remote end will retransmit the packet at a time when we
+       have more spare connections. */
+    UIP_STAT(++uip_stat.tcp.syndrop);
+    UIP_LOG("tcp: found no unused connections.");
+    goto drop;
+  }
+  uip_conn = uip_connr;
+
+  /* Fill in the necessary fields for the new connection. */
+  uip_connr->rto = uip_connr->timer = UIP_RTO;
+  uip_connr->sa = 0;
+  uip_connr->sv = 4;
+  uip_connr->nrtx = 0;
+  uip_connr->lport = BUF->destport;
+  uip_connr->rport = BUF->srcport;
+  uip_ipaddr_copy(&uip_connr->ripaddr, &BUF->srcipaddr);
+  uip_connr->tcpstateflags = UIP_SYN_RCVD;
+
+  uip_connr->snd_nxt[0] = iss[0];
+  uip_connr->snd_nxt[1] = iss[1];
+  uip_connr->snd_nxt[2] = iss[2];
+  uip_connr->snd_nxt[3] = iss[3];
+  uip_connr->len = 1;
+
+  /* rcv_nxt should be the seqno from the incoming packet + 1. */
+  uip_connr->rcv_nxt[0] = BUF->seqno[0];
+  uip_connr->rcv_nxt[1] = BUF->seqno[1];
+  uip_connr->rcv_nxt[2] = BUF->seqno[2];
+  uip_connr->rcv_nxt[3] = BUF->seqno[3];
+  uip_add_rcv_nxt(1);
+
+  /* Parse the TCP MSS option, if present. */
+  if((BUF->tcpoffset & 0xf0) > 0x50) {
+    for(c = 0; c < ((BUF->tcpoffset >> 4) - 5) << 2 ;) {
+      opt = uip_buf[UIP_TCPIP_HLEN + UIP_LLH_LEN + c];
+      if(opt == TCP_OPT_END) {
+       /* End of options. */
+       break;
+      } else if(opt == TCP_OPT_NOOP) {
+       ++c;
+       /* NOP option. */
+      } else if(opt == TCP_OPT_MSS &&
+               uip_buf[UIP_TCPIP_HLEN + UIP_LLH_LEN + 1 + c] == TCP_OPT_MSS_LEN) {
+       /* An MSS option with the right option length. */
+       tmp16 = ((uint16_t)uip_buf[UIP_TCPIP_HLEN + UIP_LLH_LEN + 2 + c] << 8) |
+         (uint16_t)uip_buf[UIP_IPTCPH_LEN + UIP_LLH_LEN + 3 + c];
+       uip_connr->initialmss = uip_connr->mss =
+         tmp16 > UIP_TCP_MSS? UIP_TCP_MSS: tmp16;
+
+       /* And we are done processing options. */
+       break;
+      } else {
+       /* All other options have a length field, so that we easily
+          can skip past them. */
+       if(uip_buf[UIP_TCPIP_HLEN + UIP_LLH_LEN + 1 + c] == 0) {
+         /* If the length field is zero, the options are malformed
+            and we don't process them further. */
+         break;
+       }
+       c += uip_buf[UIP_TCPIP_HLEN + UIP_LLH_LEN + 1 + c];
+      }
+    }
+  }
+
+  /* Our response will be a SYNACK. */
+#if UIP_ACTIVE_OPEN
+ tcp_send_synack:
+  BUF->flags = TCP_ACK;
+
+ tcp_send_syn:
+  BUF->flags |= TCP_SYN;
+#else /* UIP_ACTIVE_OPEN */
+ tcp_send_synack:
+  BUF->flags = TCP_SYN | TCP_ACK;
+#endif /* UIP_ACTIVE_OPEN */
+
+  /* We send out the TCP Maximum Segment Size option with our
+     SYNACK. */
+  BUF->optdata[0] = TCP_OPT_MSS;
+  BUF->optdata[1] = TCP_OPT_MSS_LEN;
+  BUF->optdata[2] = (UIP_TCP_MSS) / 256;
+  BUF->optdata[3] = (UIP_TCP_MSS) & 255;
+  uip_len = UIP_IPTCPH_LEN + TCP_OPT_MSS_LEN;
+  BUF->tcpoffset = ((UIP_TCPH_LEN + TCP_OPT_MSS_LEN) / 4) << 4;
+  goto tcp_send;
+
+  /* This label will be jumped to if we found an active connection. */
+ found:
+  uip_conn = uip_connr;
+  uip_flags = 0;
+  /* We do a very naive form of TCP reset processing; we just accept
+     any RST and kill our connection. We should in fact check if the
+     sequence number of this reset is within our advertised window
+     before we accept the reset. */
+  if(BUF->flags & TCP_RST) {
+    uip_connr->tcpstateflags = UIP_CLOSED;
+    UIP_LOG("tcp: got reset, aborting connection.");
+    uip_flags = UIP_ABORT;
+    UIP_APPCALL();
+    goto drop;
+  }
+  /* Calculate the length of the data, if the application has sent
+     any data to us. */
+  c = (BUF->tcpoffset >> 4) << 2;
+  /* uip_len will contain the length of the actual TCP data. This is
+     calculated by subtracing the length of the TCP header (in
+     c) and the length of the IP header (20 bytes). */
+  uip_len = uip_len - c - UIP_IPH_LEN;
+
+  /* First, check if the sequence number of the incoming packet is
+     what we're expecting next. If not, we send out an ACK with the
+     correct numbers in, unless we are in the SYN_RCVD state and
+     receive a SYN, in which case we should retransmit our SYNACK
+     (which is done futher down). */
+  if(!((((uip_connr->tcpstateflags & UIP_TS_MASK) == UIP_SYN_SENT) &&
+       ((BUF->flags & TCP_CTL) == (TCP_SYN | TCP_ACK))) ||
+       (((uip_connr->tcpstateflags & UIP_TS_MASK) == UIP_SYN_RCVD) &&
+       ((BUF->flags & TCP_CTL) == TCP_SYN)))) {
+    if((uip_len > 0 || ((BUF->flags & (TCP_SYN | TCP_FIN)) != 0)) &&
+       (BUF->seqno[0] != uip_connr->rcv_nxt[0] ||
+       BUF->seqno[1] != uip_connr->rcv_nxt[1] ||
+       BUF->seqno[2] != uip_connr->rcv_nxt[2] ||
+       BUF->seqno[3] != uip_connr->rcv_nxt[3])) {
+      goto tcp_send_ack;
+    }
+  }
+
+  /* Next, check if the incoming segment acknowledges any outstanding
+     data. If so, we update the sequence number, reset the length of
+     the outstanding data, calculate RTT estimations, and reset the
+     retransmission timer. */
+  if((BUF->flags & TCP_ACK) && uip_outstanding(uip_connr)) {
+    uip_add32(uip_connr->snd_nxt, uip_connr->len);
+
+    if(BUF->ackno[0] == uip_acc32[0] &&
+       BUF->ackno[1] == uip_acc32[1] &&
+       BUF->ackno[2] == uip_acc32[2] &&
+       BUF->ackno[3] == uip_acc32[3]) {
+      /* Update sequence number. */
+      uip_connr->snd_nxt[0] = uip_acc32[0];
+      uip_connr->snd_nxt[1] = uip_acc32[1];
+      uip_connr->snd_nxt[2] = uip_acc32[2];
+      uip_connr->snd_nxt[3] = uip_acc32[3];
+
+      /* Do RTT estimation, unless we have done retransmissions. */
+      if(uip_connr->nrtx == 0) {
+       signed char m;
+       m = uip_connr->rto - uip_connr->timer;
+       /* This is taken directly from VJs original code in his paper */
+       m = m - (uip_connr->sa >> 3);
+       uip_connr->sa += m;
+       if(m < 0) {
+         m = -m;
+       }
+       m = m - (uip_connr->sv >> 2);
+       uip_connr->sv += m;
+       uip_connr->rto = (uip_connr->sa >> 3) + uip_connr->sv;
+
+      }
+      /* Set the acknowledged flag. */
+      uip_flags = UIP_ACKDATA;
+      /* Reset the retransmission timer. */
+      uip_connr->timer = uip_connr->rto;
+
+      /* Reset length of outstanding data. */
+      uip_connr->len = 0;
+    }
+
+  }
+
+  /* Do different things depending on in what state the connection is. */
+  switch(uip_connr->tcpstateflags & UIP_TS_MASK) {
+    /* CLOSED and LISTEN are not handled here. CLOSE_WAIT is not
+       implemented, since we force the application to close when the
+       peer sends a FIN (hence the application goes directly from
+       ESTABLISHED to LAST_ACK). */
+  case UIP_SYN_RCVD:
+    /* In SYN_RCVD we have sent out a SYNACK in response to a SYN, and
+       we are waiting for an ACK that acknowledges the data we sent
+       out the last time. Therefore, we want to have the UIP_ACKDATA
+       flag set. If so, we enter the ESTABLISHED state. */
+    if(uip_flags & UIP_ACKDATA) {
+      uip_connr->tcpstateflags = UIP_ESTABLISHED;
+      uip_flags = UIP_CONNECTED;
+      uip_connr->len = 0;
+      if(uip_len > 0) {
+        uip_flags |= UIP_NEWDATA;
+        uip_add_rcv_nxt(uip_len);
+      }
+      uip_slen = 0;
+      UIP_APPCALL();
+      goto appsend;
+    }
+    /* We need to retransmit the SYNACK */
+    if((BUF->flags & TCP_CTL) == TCP_SYN) {
+      goto tcp_send_synack;
+    }
+    goto drop;
+#if UIP_ACTIVE_OPEN
+  case UIP_SYN_SENT:
+    /* In SYN_SENT, we wait for a SYNACK that is sent in response to
+       our SYN. The rcv_nxt is set to sequence number in the SYNACK
+       plus one, and we send an ACK. We move into the ESTABLISHED
+       state. */
+    if((uip_flags & UIP_ACKDATA) &&
+       (BUF->flags & TCP_CTL) == (TCP_SYN | TCP_ACK)) {
+
+      /* Parse the TCP MSS option, if present. */
+      if((BUF->tcpoffset & 0xf0) > 0x50) {
+       for(c = 0; c < ((BUF->tcpoffset >> 4) - 5) << 2 ;) {
+         opt = uip_buf[UIP_IPTCPH_LEN + UIP_LLH_LEN + c];
+         if(opt == TCP_OPT_END) {
+           /* End of options. */
+           break;
+         } else if(opt == TCP_OPT_NOOP) {
+           ++c;
+           /* NOP option. */
+         } else if(opt == TCP_OPT_MSS &&
+                   uip_buf[UIP_TCPIP_HLEN + UIP_LLH_LEN + 1 + c] == TCP_OPT_MSS_LEN) {
+           /* An MSS option with the right option length. */
+           tmp16 = (uip_buf[UIP_TCPIP_HLEN + UIP_LLH_LEN + 2 + c] << 8) |
+             uip_buf[UIP_TCPIP_HLEN + UIP_LLH_LEN + 3 + c];
+           uip_connr->initialmss =
+             uip_connr->mss = tmp16 > UIP_TCP_MSS? UIP_TCP_MSS: tmp16;
+
+           /* And we are done processing options. */
+           break;
+         } else {
+           /* All other options have a length field, so that we easily
+              can skip past them. */
+           if(uip_buf[UIP_TCPIP_HLEN + UIP_LLH_LEN + 1 + c] == 0) {
+             /* If the length field is zero, the options are malformed
+                and we don't process them further. */
+             break;
+           }
+           c += uip_buf[UIP_TCPIP_HLEN + UIP_LLH_LEN + 1 + c];
+         }
+       }
+      }
+      uip_connr->tcpstateflags = UIP_ESTABLISHED;
+      uip_connr->rcv_nxt[0] = BUF->seqno[0];
+      uip_connr->rcv_nxt[1] = BUF->seqno[1];
+      uip_connr->rcv_nxt[2] = BUF->seqno[2];
+      uip_connr->rcv_nxt[3] = BUF->seqno[3];
+      uip_add_rcv_nxt(1);
+      uip_flags = UIP_CONNECTED | UIP_NEWDATA;
+      uip_connr->len = 0;
+      uip_clear_buf();
+      uip_slen = 0;
+      UIP_APPCALL();
+      goto appsend;
+    }
+    /* Inform the application that the connection failed */
+    uip_flags = UIP_ABORT;
+    UIP_APPCALL();
+    /* The connection is closed after we send the RST */
+    uip_conn->tcpstateflags = UIP_CLOSED;
+    goto reset;
+#endif /* UIP_ACTIVE_OPEN */
+
+  case UIP_ESTABLISHED:
+    /* In the ESTABLISHED state, we call upon the application to feed
+    data into the uip_buf. If the UIP_ACKDATA flag is set, the
+    application should put new data into the buffer, otherwise we are
+    retransmitting an old segment, and the application should put that
+    data into the buffer.
+
+    If the incoming packet is a FIN, we should close the connection on
+    this side as well, and we send out a FIN and enter the LAST_ACK
+    state. We require that there is no outstanding data; otherwise the
+    sequence numbers will be screwed up. */
+
+    if(BUF->flags & TCP_FIN && !(uip_connr->tcpstateflags & UIP_STOPPED)) {
+      if(uip_outstanding(uip_connr)) {
+       goto drop;
+      }
+      uip_add_rcv_nxt(1 + uip_len);
+      uip_flags |= UIP_CLOSE;
+      if(uip_len > 0) {
+       uip_flags |= UIP_NEWDATA;
+      }
+      UIP_APPCALL();
+      uip_connr->len = 1;
+      uip_connr->tcpstateflags = UIP_LAST_ACK;
+      uip_connr->nrtx = 0;
+    tcp_send_finack:
+      BUF->flags = TCP_FIN | TCP_ACK;
+      goto tcp_send_nodata;
+    }
+
+    /* Check the URG flag. If this is set, the segment carries urgent
+       data that we must pass to the application. */
+    if((BUF->flags & TCP_URG) != 0) {
+#if UIP_URGDATA > 0
+      uip_urglen = (BUF->urgp[0] << 8) | BUF->urgp[1];
+      if(uip_urglen > uip_len) {
+       /* There is more urgent data in the next segment to come. */
+       uip_urglen = uip_len;
+      }
+      uip_add_rcv_nxt(uip_urglen);
+      uip_len -= uip_urglen;
+      uip_urgdata = uip_appdata;
+      uip_appdata += uip_urglen;
+    } else {
+      uip_urglen = 0;
+#else /* UIP_URGDATA > 0 */
+      uip_appdata = ((char *)uip_appdata) + ((BUF->urgp[0] << 8) | BUF->urgp[1]);
+      uip_len -= (BUF->urgp[0] << 8) | BUF->urgp[1];
+#endif /* UIP_URGDATA > 0 */
+    }
+
+    /* If uip_len > 0 we have TCP data in the packet, and we flag this
+       by setting the UIP_NEWDATA flag and update the sequence number
+       we acknowledge. If the application has stopped the dataflow
+       using uip_stop(), we must not accept any data packets from the
+       remote host. */
+    if(uip_len > 0 && !(uip_connr->tcpstateflags & UIP_STOPPED)) {
+      uip_flags |= UIP_NEWDATA;
+      uip_add_rcv_nxt(uip_len);
+    }
+
+    /* Check if the available buffer space advertised by the other end
+       is smaller than the initial MSS for this connection. If so, we
+       set the current MSS to the window size to ensure that the
+       application does not send more data than the other end can
+       handle.
+
+       If the remote host advertises a zero window, we set the MSS to
+       the initial MSS so that the application will send an entire MSS
+       of data. This data will not be acknowledged by the receiver,
+       and the application will retransmit it. This is called the
+       "persistent timer" and uses the retransmission mechanim.
+    */
+    tmp16 = ((uint16_t)BUF->wnd[0] << 8) + (uint16_t)BUF->wnd[1];
+    if(tmp16 > uip_connr->initialmss ||
+       tmp16 == 0) {
+      tmp16 = uip_connr->initialmss;
+    }
+    uip_connr->mss = tmp16;
+
+    /* If this packet constitutes an ACK for outstanding data (flagged
+       by the UIP_ACKDATA flag, we should call the application since it
+       might want to send more data. If the incoming packet had data
+       from the peer (as flagged by the UIP_NEWDATA flag), the
+       application must also be notified.
+
+       When the application is called, the global variable uip_len
+       contains the length of the incoming data. The application can
+       access the incoming data through the global pointer
+       uip_appdata, which usually points UIP_IPTCPH_LEN + UIP_LLH_LEN
+       bytes into the uip_buf array.
+
+       If the application wishes to send any data, this data should be
+       put into the uip_appdata and the length of the data should be
+       put into uip_len. If the application don't have any data to
+       send, uip_len must be set to 0. */
+    if(uip_flags & (UIP_NEWDATA | UIP_ACKDATA)) {
+      uip_slen = 0;
+      UIP_APPCALL();
+
+    appsend:
+
+      if(uip_flags & UIP_ABORT) {
+       uip_slen = 0;
+       uip_connr->tcpstateflags = UIP_CLOSED;
+       BUF->flags = TCP_RST | TCP_ACK;
+       goto tcp_send_nodata;
+      }
+
+      if(uip_flags & UIP_CLOSE) {
+       uip_slen = 0;
+       uip_connr->len = 1;
+       uip_connr->tcpstateflags = UIP_FIN_WAIT_1;
+       uip_connr->nrtx = 0;
+       BUF->flags = TCP_FIN | TCP_ACK;
+       goto tcp_send_nodata;
+      }
+
+      /* If uip_slen > 0, the application has data to be sent. */
+      if(uip_slen > 0) {
+
+       /* If the connection has acknowledged data, the contents of
+          the ->len variable should be discarded. */
+       if((uip_flags & UIP_ACKDATA) != 0) {
+         uip_connr->len = 0;
+       }
+
+       /* If the ->len variable is non-zero the connection has
+          already data in transit and cannot send anymore right
+          now. */
+       if(uip_connr->len == 0) {
+
+         /* The application cannot send more than what is allowed by
+            the mss (the minumum of the MSS and the available
+            window). */
+         if(uip_slen > uip_connr->mss) {
+           uip_slen = uip_connr->mss;
+         }
+
+         /* Remember how much data we send out now so that we know
+            when everything has been acknowledged. */
+         uip_connr->len = uip_slen;
+       } else {
+
+         /* If the application already had unacknowledged data, we
+            make sure that the application does not send (i.e.,
+            retransmit) out more than it previously sent out. */
+         uip_slen = uip_connr->len;
+       }
+      }
+      uip_connr->nrtx = 0;
+    apprexmit:
+      uip_appdata = uip_sappdata;
+
+      /* If the application has data to be sent, or if the incoming
+         packet had new data in it, we must send out a packet. */
+      if(uip_slen > 0 && uip_connr->len > 0) {
+       /* Add the length of the IP and TCP headers. */
+       uip_len = uip_connr->len + UIP_TCPIP_HLEN;
+       /* We always set the ACK flag in response packets. */
+       BUF->flags = TCP_ACK | TCP_PSH;
+       /* Send the packet. */
+       goto tcp_send_noopts;
+      }
+      /* If there is no data to send, just send out a pure ACK if
+        there is newdata. */
+      if(uip_flags & UIP_NEWDATA) {
+       uip_len = UIP_TCPIP_HLEN;
+       BUF->flags = TCP_ACK;
+       goto tcp_send_noopts;
+      }
+    }
+    goto drop;
+  case UIP_LAST_ACK:
+    /* We can close this connection if the peer has acknowledged our
+       FIN. This is indicated by the UIP_ACKDATA flag. */
+    if(uip_flags & UIP_ACKDATA) {
+      uip_connr->tcpstateflags = UIP_CLOSED;
+      uip_flags = UIP_CLOSE;
+      UIP_APPCALL();
+    }
+    break;
+
+  case UIP_FIN_WAIT_1:
+    /* The application has closed the connection, but the remote host
+       hasn't closed its end yet. Thus we do nothing but wait for a
+       FIN from the other side. */
+    if(uip_len > 0) {
+      uip_add_rcv_nxt(uip_len);
+    }
+    if(BUF->flags & TCP_FIN) {
+      if(uip_flags & UIP_ACKDATA) {
+       uip_connr->tcpstateflags = UIP_TIME_WAIT;
+       uip_connr->timer = 0;
+       uip_connr->len = 0;
+      } else {
+       uip_connr->tcpstateflags = UIP_CLOSING;
+      }
+      uip_add_rcv_nxt(1);
+      uip_flags = UIP_CLOSE;
+      UIP_APPCALL();
+      goto tcp_send_ack;
+    } else if(uip_flags & UIP_ACKDATA) {
+      uip_connr->tcpstateflags = UIP_FIN_WAIT_2;
+      uip_connr->len = 0;
+      goto drop;
+    }
+    if(uip_len > 0) {
+      goto tcp_send_ack;
+    }
+    goto drop;
+
+  case UIP_FIN_WAIT_2:
+    if(uip_len > 0) {
+      uip_add_rcv_nxt(uip_len);
+    }
+    if(BUF->flags & TCP_FIN) {
+      uip_connr->tcpstateflags = UIP_TIME_WAIT;
+      uip_connr->timer = 0;
+      uip_add_rcv_nxt(1);
+      uip_flags = UIP_CLOSE;
+      UIP_APPCALL();
+      goto tcp_send_ack;
+    }
+    if(uip_len > 0) {
+      goto tcp_send_ack;
+    }
+    goto drop;
+
+  case UIP_TIME_WAIT:
+    goto tcp_send_ack;
+
+  case UIP_CLOSING:
+    if(uip_flags & UIP_ACKDATA) {
+      uip_connr->tcpstateflags = UIP_TIME_WAIT;
+      uip_connr->timer = 0;
+    }
+  }
+  goto drop;
+
+  /* We jump here when we are ready to send the packet, and just want
+     to set the appropriate TCP sequence numbers in the TCP header. */
+ tcp_send_ack:
+  BUF->flags = TCP_ACK;
+
+ tcp_send_nodata:
+  uip_len = UIP_IPTCPH_LEN;
+
+ tcp_send_noopts:
+  BUF->tcpoffset = (UIP_TCPH_LEN / 4) << 4;
+
+  /* We're done with the input processing. We are now ready to send a
+     reply. Our job is to fill in all the fields of the TCP and IP
+     headers before calculating the checksum and finally send the
+     packet. */
+ tcp_send:
+  BUF->ackno[0] = uip_connr->rcv_nxt[0];
+  BUF->ackno[1] = uip_connr->rcv_nxt[1];
+  BUF->ackno[2] = uip_connr->rcv_nxt[2];
+  BUF->ackno[3] = uip_connr->rcv_nxt[3];
+
+  BUF->seqno[0] = uip_connr->snd_nxt[0];
+  BUF->seqno[1] = uip_connr->snd_nxt[1];
+  BUF->seqno[2] = uip_connr->snd_nxt[2];
+  BUF->seqno[3] = uip_connr->snd_nxt[3];
+
+  BUF->srcport  = uip_connr->lport;
+  BUF->destport = uip_connr->rport;
+
+  uip_ipaddr_copy(&BUF->srcipaddr, &uip_hostaddr);
+  uip_ipaddr_copy(&BUF->destipaddr, &uip_connr->ripaddr);
+
+  if(uip_connr->tcpstateflags & UIP_STOPPED) {
+    /* If the connection has issued uip_stop(), we advertise a zero
+       window so that the remote host will stop sending data. */
+    BUF->wnd[0] = BUF->wnd[1] = 0;
+  } else {
+    BUF->wnd[0] = ((UIP_RECEIVE_WINDOW) >> 8);
+    BUF->wnd[1] = ((UIP_RECEIVE_WINDOW) & 0xff);
+  }
+
+ tcp_send_noconn:
+  BUF->proto = UIP_PROTO_TCP;
+
+  BUF->ttl = UIP_TTL;
+#if NETSTACK_CONF_WITH_IPV6
+  /* For IPv6, the IP length field does not include the IPv6 IP header
+     length. */
+  BUF->len[0] = ((uip_len - UIP_IPH_LEN) >> 8);
+  BUF->len[1] = ((uip_len - UIP_IPH_LEN) & 0xff);
+#else /* NETSTACK_CONF_WITH_IPV6 */
+  BUF->len[0] = (uip_len >> 8);
+  BUF->len[1] = (uip_len & 0xff);
+#endif /* NETSTACK_CONF_WITH_IPV6 */
+
+  BUF->urgp[0] = BUF->urgp[1] = 0;
+
+  /* Calculate TCP checksum. */
+  BUF->tcpchksum = 0;
+  BUF->tcpchksum = ~(uip_tcpchksum());
+#endif
+
+ ip_send_nolen:
+#if NETSTACK_CONF_WITH_IPV6
+  BUF->vtc = 0x60;
+  BUF->tcflow = 0x00;
+  BUF->flow = 0x00;
+#else /* NETSTACK_CONF_WITH_IPV6 */
+  BUF->vhl = 0x45;
+  BUF->tos = 0;
+  BUF->ipoffset[0] = BUF->ipoffset[1] = 0;
+  ++ipid;
+  BUF->ipid[0] = ipid >> 8;
+  BUF->ipid[1] = ipid & 0xff;
+  /* Calculate IP checksum. */
+  BUF->ipchksum = 0;
+  BUF->ipchksum = ~(uip_ipchksum());
+  DEBUG_PRINTF("uip ip_send_nolen: chkecum 0x%04x\n", uip_ipchksum());
+#endif /* NETSTACK_CONF_WITH_IPV6 */
+  UIP_STAT(++uip_stat.tcp.sent);
+#if NETSTACK_CONF_WITH_IPV6
+ send:
+#endif /* NETSTACK_CONF_WITH_IPV6 */
+  DEBUG_PRINTF("Sending packet with length %d (%d)\n", uip_len,
+              (BUF->len[0] << 8) | BUF->len[1]);
+
+  UIP_STAT(++uip_stat.ip.sent);
+  /* Return and let the caller do the actual transmission. */
+  uip_flags = 0;
+  return;
+
+ drop:
+  uip_clear_buf();
+  uip_flags = 0;
+  return;
+}
+/*---------------------------------------------------------------------------*/
+uint16_t
+uip_htons(uint16_t val)
+{
+  return UIP_HTONS(val);
+}
+
+uint32_t
+uip_htonl(uint32_t val)
+{
+  return UIP_HTONL(val);
+}
+/*---------------------------------------------------------------------------*/
+void
+uip_send(const void *data, int len)
+{
+  int copylen;
+  copylen = MIN(len, UIP_BUFSIZE - UIP_LLH_LEN - UIP_TCPIP_HLEN -
+               (int)((char *)uip_sappdata - (char *)&uip_buf[UIP_LLH_LEN + UIP_TCPIP_HLEN]));
+  if(copylen > 0) {
+    uip_slen = copylen;
+    if(data != uip_sappdata) {
+      memcpy(uip_sappdata, (data), uip_slen);
+    }
+  }
+}
+/*---------------------------------------------------------------------------*/
+/** @}*/
diff --git a/Applications/netd/uip.h b/Applications/netd/uip.h
new file mode 100644 (file)
index 0000000..7903104
--- /dev/null
@@ -0,0 +1,2237 @@
+/*
+ * Copyright (c) 2001-2003, Adam Dunkels.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote
+ *    products derived from this software without specific prior
+ *    written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
+ * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
+ * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * This file is part of the uIP TCP/IP stack.
+ *
+ *
+ */
+
+/**
+ * \addtogroup uip
+ * @{
+ */
+
+/**
+ * \file
+ * Header file for the uIP TCP/IP stack.
+ * \author  Adam Dunkels <adam@dunkels.com>
+ * \author  Julien Abeille <jabeille@cisco.com> (IPv6 related code)
+ * \author  Mathilde Durvy <mdurvy@cisco.com> (IPv6 related code)
+ *
+ * The uIP TCP/IP stack header file contains definitions for a number
+ * of C macros that are used by uIP programs as well as internal uIP
+ * structures, TCP/IP header structures and function declarations.
+ *
+ */
+
+#ifndef UIP_H_
+#define UIP_H_
+
+/* Header sizes. */
+#if NETSTACK_CONF_WITH_IPV6
+#define UIP_IPH_LEN    40
+#define UIP_FRAGH_LEN  8
+#else /* NETSTACK_CONF_WITH_IPV6 */
+#define UIP_IPH_LEN    20    /* Size of IP header */
+#endif /* NETSTACK_CONF_WITH_IPV6 */
+
+#define UIP_UDPH_LEN    8    /* Size of UDP header */
+#define UIP_TCPH_LEN   20    /* Size of TCP header */
+#define UIP_ICMPH_LEN   4    /* Size of ICMP header */
+
+#define UIP_IPUDPH_LEN (UIP_UDPH_LEN + UIP_IPH_LEN)   /* Size of IP + UDP header */
+#define UIP_IPTCPH_LEN (UIP_TCPH_LEN + UIP_IPH_LEN)   /* Size of IP + TCP header */
+#define UIP_TCPIP_HLEN UIP_IPTCPH_LEN
+#define UIP_IPICMPH_LEN (UIP_IPH_LEN + UIP_ICMPH_LEN) /* Size of ICMP + IP header */
+#define UIP_LLIPH_LEN (UIP_LLH_LEN + UIP_IPH_LEN)     /* Size of L2 + IP header */
+#if NETSTACK_CONF_WITH_IPV6
+/**
+ * The sums below are quite used in ND. When used for uip_buf, we
+ * include link layer length when used for uip_len, we do not, hence
+ * we need values with and without LLH_LEN we do not use capital
+ * letters as these values are variable
+ */
+#define uip_l2_l3_hdr_len (UIP_LLH_LEN + UIP_IPH_LEN + uip_ext_len)
+#define uip_l2_l3_icmp_hdr_len (UIP_LLH_LEN + UIP_IPH_LEN + uip_ext_len + UIP_ICMPH_LEN)
+#define uip_l3_hdr_len (UIP_IPH_LEN + uip_ext_len)
+#define uip_l3_icmp_hdr_len (UIP_IPH_LEN + uip_ext_len + UIP_ICMPH_LEN)
+#endif /*NETSTACK_CONF_WITH_IPV6*/
+
+
+#include "uipopt.h"
+
+/* For memcmp */
+#include <string.h>
+
+/**
+ * Representation of an IP address.
+ *
+ */
+typedef union uip_ip4addr_t {
+  uint8_t  u8[4];                       /* Initializer, must come first. */
+  uint16_t u16[2];
+} uip_ip4addr_t;
+
+typedef union uip_ip6addr_t {
+  uint8_t  u8[16];                      /* Initializer, must come first. */
+  uint16_t u16[8];
+} uip_ip6addr_t;
+
+#if NETSTACK_CONF_WITH_IPV6
+typedef uip_ip6addr_t uip_ipaddr_t;
+#else /* NETSTACK_CONF_WITH_IPV6 */
+typedef uip_ip4addr_t uip_ipaddr_t;
+#endif /* NETSTACK_CONF_WITH_IPV6 */
+
+
+/*---------------------------------------------------------------------------*/
+
+/** \brief 16 bit 802.15.4 address */
+typedef struct uip_802154_shortaddr {
+  uint8_t addr[2];
+} uip_802154_shortaddr;
+/** \brief 64 bit 802.15.4 address */
+typedef struct uip_802154_longaddr {
+  uint8_t addr[8];
+} uip_802154_longaddr;
+
+/** \brief 802.11 address */
+typedef struct uip_80211_addr {
+  uint8_t addr[6];
+} uip_80211_addr;
+
+/** \brief 802.3 address */
+typedef struct uip_eth_addr {
+  uint8_t addr[6];
+} uip_eth_addr;
+
+
+#if UIP_CONF_LL_802154
+/** \brief 802.15.4 address */
+typedef uip_802154_longaddr uip_lladdr_t;
+#define UIP_802154_SHORTADDR_LEN 2
+#define UIP_802154_LONGADDR_LEN  8
+/** \brief Link layer address length */
+#define UIP_LLADDR_LEN UIP_802154_LONGADDR_LEN
+#else /*UIP_CONF_LL_802154*/
+#if UIP_CONF_LL_80211
+/** \brief 802.11 address */
+typedef uip_80211_addr uip_lladdr_t;
+/** \brief Link layer address length */
+#define UIP_LLADDR_LEN 6
+#else /*UIP_CONF_LL_80211*/
+/** \brief Ethernet address */
+typedef uip_eth_addr uip_lladdr_t;
+/** \brief Link layer address length */
+#define UIP_LLADDR_LEN 6
+#endif /*UIP_CONF_LL_80211*/
+#endif /*UIP_CONF_LL_802154*/
+
+//#include "tcpip.h"
+
+/*---------------------------------------------------------------------------*/
+/* First, the functions that should be called from the
+ * system. Initialization, the periodic timer, and incoming packets are
+ * handled by the following three functions.
+ */
+/**
+ * \defgroup uipconffunc uIP configuration functions
+ * @{
+ *
+ * The uIP configuration functions are used for setting run-time
+ * parameters in uIP such as IP addresses.
+ */
+
+/**
+ * Set the IP address of this host.
+ *
+ * The IP address is represented as a 4-byte array where the first
+ * octet of the IP address is put in the first member of the 4-byte
+ * array.
+ *
+ * Example:
+ \code
+
+ uip_ipaddr_t addr;
+
+ uip_ipaddr(&addr, 192,168,1,2);
+ uip_sethostaddr(&addr);
+
+ \endcode
+ * \param addr A pointer to an IP address of type uip_ipaddr_t;
+ *
+ * \sa uip_ipaddr()
+ *
+ * \hideinitializer
+ */
+#define uip_sethostaddr(addr) uip_ipaddr_copy(&uip_hostaddr, (addr))
+
+/**
+ * Get the IP address of this host.
+ *
+ * The IP address is represented as a 4-byte array where the first
+ * octet of the IP address is put in the first member of the 4-byte
+ * array.
+ *
+ * Example:
+ \code
+ uip_ipaddr_t hostaddr;
+
+ uip_gethostaddr(&hostaddr);
+ \endcode
+ * \param addr A pointer to a uip_ipaddr_t variable that will be
+ * filled in with the currently configured IP address.
+ *
+ * \hideinitializer
+ */
+#define uip_gethostaddr(addr) uip_ipaddr_copy((addr), &uip_hostaddr)
+
+/**
+ * Set the default router's IP address.
+ *
+ * \param addr A pointer to a uip_ipaddr_t variable containing the IP
+ * address of the default router.
+ *
+ * \sa uip_ipaddr()
+ *
+ * \hideinitializer
+ */
+#define uip_setdraddr(addr) uip_ipaddr_copy(&uip_draddr, (addr))
+
+/**
+ * Set the netmask.
+ *
+ * \param addr A pointer to a uip_ipaddr_t variable containing the IP
+ * address of the netmask.
+ *
+ * \sa uip_ipaddr()
+ *
+ * \hideinitializer
+ */
+#define uip_setnetmask(addr) uip_ipaddr_copy(&uip_netmask, (addr))
+
+
+/**
+ * Get the default router's IP address.
+ *
+ * \param addr A pointer to a uip_ipaddr_t variable that will be
+ * filled in with the IP address of the default router.
+ *
+ * \hideinitializer
+ */
+#define uip_getdraddr(addr) uip_ipaddr_copy((addr), &uip_draddr)
+
+/**
+ * Get the netmask.
+ *
+ * \param addr A pointer to a uip_ipaddr_t variable that will be
+ * filled in with the value of the netmask.
+ *
+ * \hideinitializer
+ */
+#define uip_getnetmask(addr) uip_ipaddr_copy((addr), &uip_netmask)
+
+/** @} */
+
+/**
+ * \defgroup uipinit uIP initialization functions
+ * @{
+ *
+ * The uIP initialization functions are used for booting uIP.
+ */
+
+/**
+ * uIP initialization function.
+ *
+ * This function should be called at boot up to initilize the uIP
+ * TCP/IP stack.
+ */
+void uip_init(void);
+
+/**
+ * uIP initialization function.
+ *
+ * This function may be used at boot time to set the initial ip_id.
+ */
+void uip_setipid(uint16_t id);
+
+/** @} */
+
+/**
+ * \defgroup uipdevfunc uIP device driver functions
+ * @{
+ *
+ * These functions are used by a network device driver for interacting
+ * with uIP.
+ */
+
+/**
+ * Process an incoming packet.
+ *
+ * This function should be called when the device driver has received
+ * a packet from the network. The packet from the device driver must
+ * be present in the uip_buf buffer, and the length of the packet
+ * should be placed in the uip_len variable.
+ *
+ * When the function returns, there may be an outbound packet placed
+ * in the uip_buf packet buffer. If so, the uip_len variable is set to
+ * the length of the packet. If no packet is to be sent out, the
+ * uip_len variable is set to 0.
+ *
+ * The usual way of calling the function is presented by the source
+ * code below.
+ \code
+ uip_len = devicedriver_poll();
+ if(uip_len > 0) {
+ uip_input();
+ if(uip_len > 0) {
+ devicedriver_send();
+ }
+ }
+ \endcode
+ *
+ * \note If you are writing a uIP device driver that needs ARP
+ * (Address Resolution Protocol), e.g., when running uIP over
+ * Ethernet, you will need to call the uIP ARP code before calling
+ * this function:
+ \code
+ #define BUF ((struct uip_eth_hdr *)&uip_buf[0])
+ uip_len = ethernet_devicedrver_poll();
+ if(uip_len > 0) {
+ if(BUF->type == UIP_HTONS(UIP_ETHTYPE_IP)) {
+ uip_arp_ipin();
+ uip_input();
+ if(uip_len > 0) {
+ uip_arp_out();
+ ethernet_devicedriver_send();
+ }
+ } else if(BUF->type == UIP_HTONS(UIP_ETHTYPE_ARP)) {
+ uip_arp_arpin();
+ if(uip_len > 0) {
+ ethernet_devicedriver_send();
+ }
+ }
+ \endcode
+ *
+ * \hideinitializer
+ */
+#define uip_input()        uip_process(UIP_DATA)
+
+
+/**
+ * Periodic processing for a connection identified by its number.
+ *
+ * This function does the necessary periodic processing (timers,
+ * polling) for a uIP TCP connection, and should be called when the
+ * periodic uIP timer goes off. It should be called for every
+ * connection, regardless of whether they are open of closed.
+ *
+ * When the function returns, it may have an outbound packet waiting
+ * for service in the uIP packet buffer, and if so the uip_len
+ * variable is set to a value larger than zero. The device driver
+ * should be called to send out the packet.
+ *
+ * The usual way of calling the function is through a for() loop like
+ * this:
+ \code
+ for(i = 0; i < UIP_CONNS; ++i) {
+ uip_periodic(i);
+ if(uip_len > 0) {
+ devicedriver_send();
+ }
+ }
+ \endcode
+ *
+ * \note If you are writing a uIP device driver that needs ARP
+ * (Address Resolution Protocol), e.g., when running uIP over
+ * Ethernet, you will need to call the uip_arp_out() function before
+ * calling the device driver:
+ \code
+ for(i = 0; i < UIP_CONNS; ++i) {
+ uip_periodic(i);
+ if(uip_len > 0) {
+ uip_arp_out();
+ ethernet_devicedriver_send();
+ }
+ }
+ \endcode
+ *
+ * \param conn The number of the connection which is to be periodically polled.
+ *
+ * \hideinitializer
+ */
+#if UIP_TCP
+#define uip_periodic(conn) do { uip_conn = &uip_conns[conn];    \
+    uip_process(UIP_TIMER); } while (0)
+
+/**
+ * Macro to determine whether a specific uIP connection is active
+ *
+ * \param conn The connection's number
+ * \retval 0 Connection closed
+ */
+#define uip_conn_active(conn) (uip_conns[conn].tcpstateflags != UIP_CLOSED)
+
+/**
+ * Perform periodic processing for a connection identified by a pointer
+ * to its structure.
+ *
+ * Same as uip_periodic() but takes a pointer to the actual uip_conn
+ * struct instead of an integer as its argument. This function can be
+ * used to force periodic processing of a specific connection.
+ *
+ * \param conn A pointer to the uip_conn struct for the connection to
+ * be processed.
+ *
+ * \hideinitializer
+ */
+#define uip_periodic_conn(conn) do { uip_conn = conn;   \
+    uip_process(UIP_TIMER); } while (0)
+
+/**
+ * Request that a particular connection should be polled.
+ *
+ * Similar to uip_periodic_conn() but does not perform any timer
+ * processing. The application is polled for new data.
+ *
+ * \param conn A pointer to the uip_conn struct for the connection to
+ * be processed.
+ *
+ * \hideinitializer
+ */
+#define uip_poll_conn(conn) do { uip_conn = conn;       \
+    uip_process(UIP_POLL_REQUEST); } while (0)
+
+#endif /* UIP_TCP */
+
+#if UIP_UDP
+/**
+ * Periodic processing for a UDP connection identified by its number.
+ *
+ * This function is essentially the same as uip_periodic(), but for
+ * UDP connections. It is called in a similar fashion as the
+ * uip_periodic() function:
+ \code
+ for(i = 0; i < UIP_UDP_CONNS; i++) {
+ uip_udp_periodic(i);
+ if(uip_len > 0) {
+ devicedriver_send();
+ }
+ }
+ \endcode
+ *
+ * \note As for the uip_periodic() function, special care has to be
+ * taken when using uIP together with ARP and Ethernet:
+ \code
+ for(i = 0; i < UIP_UDP_CONNS; i++) {
+ uip_udp_periodic(i);
+ if(uip_len > 0) {
+ uip_arp_out();
+ ethernet_devicedriver_send();
+ }
+ }
+ \endcode
+ *
+ * \param conn The number of the UDP connection to be processed.
+ *
+ * \hideinitializer
+ */
+#define uip_udp_periodic(conn) do { uip_udp_conn = &uip_udp_conns[conn]; \
+    uip_process(UIP_UDP_TIMER); } while(0)
+
+/**
+ * Periodic processing for a UDP connection identified by a pointer to
+ * its structure.
+ *
+ * Same as uip_udp_periodic() but takes a pointer to the actual
+ * uip_conn struct instead of an integer as its argument. This
+ * function can be used to force periodic processing of a specific
+ * connection.
+ *
+ * \param conn A pointer to the uip_udp_conn struct for the connection
+ * to be processed.
+ *
+ * \hideinitializer
+ */
+#define uip_udp_periodic_conn(conn) do { uip_udp_conn = conn;   \
+    uip_process(UIP_UDP_TIMER); } while(0)
+#endif /* UIP_UDP */
+
+/** \brief Abandon the reassembly of the current packet */
+void uip_reass_over(void);
+
+/**
+ * The uIP packet buffer.
+ *
+ * The uip_aligned_buf array is used to hold incoming and outgoing
+ * packets. The device driver should place incoming data into this
+ * buffer. When sending data, the device driver should read the link
+ * level headers and the TCP/IP headers from this buffer. The size of
+ * the link level headers is configured by the UIP_LLH_LEN define.
+ *
+ * \note The application data need not be placed in this buffer, so
+ * the device driver must read it from the place pointed to by the
+ * uip_appdata pointer as illustrated by the following example:
+ \code
+ void
+ devicedriver_send(void)
+ {
+ hwsend(&uip_buf[0], UIP_LLH_LEN);
+ if(uip_len <= UIP_LLH_LEN + UIP_TCPIP_HLEN) {
+ hwsend(&uip_buf[UIP_LLH_LEN], uip_len - UIP_LLH_LEN);
+ } else {
+ hwsend(&uip_buf[UIP_LLH_LEN], UIP_TCPIP_HLEN);
+ hwsend(uip_appdata, uip_len - UIP_TCPIP_HLEN - UIP_LLH_LEN);
+ }
+ }
+ \endcode
+*/
+
+typedef union {
+  uint32_t u32[(UIP_BUFSIZE + 3) / 4];
+  uint8_t u8[UIP_BUFSIZE];
+} uip_buf_t;
+
+CCIF extern uip_buf_t uip_aligned_buf;
+
+/** Macro to access uip_aligned_buf as an array of bytes */
+#define uip_buf (uip_aligned_buf.u8)
+
+
+/** @} */
+
+/*---------------------------------------------------------------------------*/
+/* Functions that are used by the uIP application program. Opening and
+ * closing connections, sending and receiving data, etc. is all
+ * handled by the functions below.
+ */
+/**
+ * \defgroup uipappfunc uIP application functions
+ * @{
+ *
+ * Functions used by an application running on top of uIP.
+ */
+
+/**
+ * Start listening to the specified port.
+ *
+ * \note Since this function expects the port number in network byte
+ * order, a conversion using UIP_HTONS() or uip_htons() is necessary.
+ *
+ \code
+ uip_listen(UIP_HTONS(80));
+ \endcode
+ *
+ * \param port A 16-bit port number in network byte order.
+ */
+void uip_listen(uint16_t port);
+
+/**
+ * Stop listening to the specified port.
+ *
+ * \note Since this function expects the port number in network byte
+ * order, a conversion using UIP_HTONS() or uip_htons() is necessary.
+ *
+ \code
+ uip_unlisten(UIP_HTONS(80));
+ \endcode
+ *
+ * \param port A 16-bit port number in network byte order.
+ */
+void uip_unlisten(uint16_t port);
+
+/**
+ * Connect to a remote host using TCP.
+ *
+ * This function is used to start a new connection to the specified
+ * port on the specified host. It allocates a new connection identifier,
+ * sets the connection to the SYN_SENT state and sets the
+ * retransmission timer to 0. This will cause a TCP SYN segment to be
+ * sent out the next time this connection is periodically processed,
+ * which usually is done within 0.5 seconds after the call to
+ * uip_connect().
+ *
+ * \note This function is available only if support for active open
+ * has been configured by defining UIP_ACTIVE_OPEN to 1 in uipopt.h.
+ *
+ * \note Since this function requires the port number to be in network
+ * byte order, a conversion using UIP_HTONS() or uip_htons() is necessary.
+ *
+ \code
+ uip_ipaddr_t ipaddr;
+
+ uip_ipaddr(&ipaddr, 192,168,1,2);
+ uip_connect(&ipaddr, UIP_HTONS(80));
+ \endcode
+ *
+ * \param ripaddr The IP address of the remote host.
+ *
+ * \param port A 16-bit port number in network byte order.
+ *
+ * \return A pointer to the uIP connection identifier for the new connection,
+ * or NULL if no connection could be allocated.
+ *
+ */
+struct uip_conn *uip_connect(const uip_ipaddr_t *ripaddr, uint16_t port);
+
+
+
+/**
+ * \internal
+ *
+ * Check if a connection has outstanding (i.e., unacknowledged) data.
+ *
+ * \param conn A pointer to the uip_conn structure for the connection.
+ *
+ * \hideinitializer
+ */
+#define uip_outstanding(conn) ((conn)->len)
+
+/**
+ * Send data on the current connection.
+ *
+ * This function is used to send out a single segment of TCP
+ * data. Only applications that have been invoked by uIP for event
+ * processing can send data.
+ *
+ * The amount of data that actually is sent out after a call to this
+ * function is determined by the maximum amount of data TCP allows. uIP
+ * will automatically crop the data so that only the appropriate
+ * amount of data is sent. The function uip_mss() can be used to query
+ * uIP for the amount of data that actually will be sent.
+ *
+ * \note This function does not guarantee that the sent data will
+ * arrive at the destination. If the data is lost in the network, the
+ * application will be invoked with the uip_rexmit() event being
+ * set. The application will then have to resend the data using this
+ * function.
+ *
+ * \param data A pointer to the data which is to be sent.
+ *
+ * \param len The maximum amount of data bytes to be sent.
+ *
+ * \hideinitializer
+ */
+CCIF void uip_send(const void *data, int len);
+
+/**
+ * The length of any incoming data that is currently available (if available)
+ * in the uip_appdata buffer.
+ *
+ * The test function uip_data() must first be used to check if there
+ * is any data available at all.
+ *
+ * \hideinitializer
+ */
+/*void uip_datalen(void);*/
+#define uip_datalen()       uip_len
+
+/**
+ * The length of any out-of-band data (urgent data) that has arrived
+ * on the connection.
+ *
+ * \note The configuration parameter UIP_URGDATA must be set for this
+ * function to be enabled.
+ *
+ * \hideinitializer
+ */
+#define uip_urgdatalen()    uip_urglen
+
+/**
+ * Close the current connection.
+ *
+ * This function will close the current connection in a nice way.
+ *
+ * \hideinitializer
+ */
+#define uip_close()         (uip_flags = UIP_CLOSE)
+
+/**
+ * Abort the current connection.
+ *
+ * This function will abort (reset) the current connection, and is
+ * usually used when an error has occurred that prevents using the
+ * uip_close() function.
+ *
+ * \hideinitializer
+ */
+#define uip_abort()         (uip_flags = UIP_ABORT)
+
+/**
+ * Tell the sending host to stop sending data.
+ *
+ * This function will close our receiver's window so that we stop
+ * receiving data for the current connection.
+ *
+ * \hideinitializer
+ */
+#define uip_stop()          (uip_conn->tcpstateflags |= UIP_STOPPED)
+
+/**
+ * Find out if the current connection has been previously stopped with
+ * uip_stop().
+ *
+ * \hideinitializer
+ */
+#define uip_stopped(conn)   ((conn)->tcpstateflags & UIP_STOPPED)
+
+/**
+ * Restart the current connection, if is has previously been stopped
+ * with uip_stop().
+ *
+ * This function will open the receiver's window again so that we
+ * start receiving data for the current connection.
+ *
+ * \hideinitializer
+ */
+#define uip_restart()         do { uip_flags |= UIP_NEWDATA;    \
+    uip_conn->tcpstateflags &= ~UIP_STOPPED;                    \
+  } while(0)
+
+
+/* uIP tests that can be made to determine in what state the current
+   connection is, and what the application function should do. */
+
+/**
+ * Is the current connection a UDP connection?
+ *
+ * This function checks whether the current connection is a UDP connection.
+ *
+ * \hideinitializer
+ *
+ */
+#define uip_udpconnection() (uip_conn == NULL)
+
+/**
+ * Is new incoming data available?
+ *
+ * Will reduce to non-zero if there is new data for the application
+ * present at the uip_appdata pointer. The size of the data is
+ * available through the uip_len variable.
+ *
+ * \hideinitializer
+ */
+#define uip_newdata()   (uip_flags & UIP_NEWDATA)
+
+/**
+ * Has previously sent data been acknowledged?
+ *
+ * Will reduce to non-zero if the previously sent data has been
+ * acknowledged by the remote host. This means that the application
+ * can send new data.
+ *
+ * \hideinitializer
+ */
+#define uip_acked()   (uip_flags & UIP_ACKDATA)
+
+/**
+ * Has the connection just been connected?
+ *
+ * Reduces to non-zero if the current connection has been connected to
+ * a remote host. This will happen both if the connection has been
+ * actively opened (with uip_connect()) or passively opened (with
+ * uip_listen()).
+ *
+ * \hideinitializer
+ */
+#define uip_connected() (uip_flags & UIP_CONNECTED)
+
+/**
+ * Has the connection been closed by the other end?
+ *
+ * Is non-zero if the connection has been closed by the remote
+ * host. The application may then do the necessary clean-ups.
+ *
+ * \hideinitializer
+ */
+#define uip_closed()    (uip_flags & UIP_CLOSE)
+
+/**
+ * Has the connection been aborted by the other end?
+ *
+ * Non-zero if the current connection has been aborted (reset) by the
+ * remote host.
+ *
+ * \hideinitializer
+ */
+#define uip_aborted()    (uip_flags & UIP_ABORT)
+
+/**
+ * Has the connection timed out?
+ *
+ * Non-zero if the current connection has been aborted due to too many
+ * retransmissions.
+ *
+ * \hideinitializer
+ */
+#define uip_timedout()    (uip_flags & UIP_TIMEDOUT)
+
+/**
+ * Do we need to retransmit previously data?
+ *
+ * Reduces to non-zero if the previously sent data has been lost in
+ * the network, and the application should retransmit it. The
+ * application should send the exact same data as it did the last
+ * time, using the uip_send() function.
+ *
+ * \hideinitializer
+ */
+#define uip_rexmit()     (uip_flags & UIP_REXMIT)
+
+/**
+ * Is the connection being polled by uIP?
+ *
+ * Is non-zero if the reason the application is invoked is that the
+ * current connection has been idle for a while and should be
+ * polled.
+ *
+ * The polling event can be used for sending data without having to
+ * wait for the remote host to send data.
+ *
+ * \hideinitializer
+ */
+#define uip_poll()       (uip_flags & UIP_POLL)
+
+/**
+ * Get the initial maximum segment size (MSS) of the current
+ * connection.
+ *
+ * \hideinitializer
+ */
+#define uip_initialmss()             (uip_conn->initialmss)
+
+/**
+ * Get the current maximum segment size that can be sent on the current
+ * connection.
+ *
+ * The current maximum segment size that can be sent on the
+ * connection is computed from the receiver's window and the MSS of
+ * the connection (which also is available by calling
+ * uip_initialmss()).
+ *
+ * \hideinitializer
+ */
+#define uip_mss()             (uip_conn->mss)
+
+/**
+ * Set up a new UDP connection.
+ *
+ * This function sets up a new UDP connection. The function will
+ * automatically allocate an unused local port for the new
+ * connection. However, another port can be chosen by using the
+ * uip_udp_bind() call, after the uip_udp_new() function has been
+ * called.
+ *
+ * Example:
+ \code
+ uip_ipaddr_t addr;
+ struct uip_udp_conn *c;
+
+ uip_ipaddr(&addr, 192,168,2,1);
+ c = uip_udp_new(&addr, UIP_HTONS(12345));
+ if(c != NULL) {
+ uip_udp_bind(c, UIP_HTONS(12344));
+ }
+ \endcode
+ * \param ripaddr The IP address of the remote host.
+ *
+ * \param rport The remote port number in network byte order.
+ *
+ * \return The uip_udp_conn structure for the new connection, or NULL
+ * if no connection could be allocated.
+ */
+struct uip_udp_conn *uip_udp_new(const uip_ipaddr_t *ripaddr, uint16_t rport);
+
+/**
+ * Remove a UDP connection.
+ *
+ * \param conn A pointer to the uip_udp_conn structure for the connection.
+ *
+ * \hideinitializer
+ */
+#define uip_udp_remove(conn) (conn)->lport = 0
+
+/**
+ * Bind a UDP connection to a local port.
+ *
+ * \param conn A pointer to the uip_udp_conn structure for the
+ * connection.
+ *
+ * \param port The local port number, in network byte order.
+ *
+ * \hideinitializer
+ */
+#define uip_udp_bind(conn, port) (conn)->lport = port
+
+/**
+ * Send a UDP datagram of length len on the current connection.
+ *
+ * This function can only be called in response to a UDP event (poll
+ * or newdata). The data must be present in the uip_buf buffer, at the
+ * place pointed to by the uip_appdata pointer.
+ *
+ * \param len The length of the data in the uip_buf buffer.
+ *
+ * \hideinitializer
+ */
+#define uip_udp_send(len) uip_send((char *)uip_appdata, len)
+
+/** @} */
+
+/* uIP convenience and converting functions. */
+
+/**
+ * \defgroup uipconvfunc uIP conversion functions
+ * @{
+ *
+ * These functions can be used for converting between different data
+ * formats used by uIP.
+ */
+
+/**
+ * Convert an IP address to four bytes separated by commas.
+ *
+ * Example:
+ \code
+ uip_ipaddr_t ipaddr;
+ printf("ipaddr=%d.%d.%d.%d\n", uip_ipaddr_to_quad(&ipaddr));
+ \endcode
+ *
+ * \param a A pointer to a uip_ipaddr_t.
+ * \hideinitializer
+ */
+#define uip_ipaddr_to_quad(a) (a)->u8[0],(a)->u8[1],(a)->u8[2],(a)->u8[3]
+
+/**
+ * Construct an IP address from four bytes.
+ *
+ * This function constructs an IP address of the type that uIP handles
+ * internally from four bytes. The function is handy for specifying IP
+ * addresses to use with e.g. the uip_connect() function.
+ *
+ * Example:
+ \code
+ uip_ipaddr_t ipaddr;
+ struct uip_conn *c;
+
+ uip_ipaddr(&ipaddr, 192,168,1,2);
+ c = uip_connect(&ipaddr, UIP_HTONS(80));
+ \endcode
+ *
+ * \param addr A pointer to a uip_ipaddr_t variable that will be
+ * filled in with the IP address.
+ *
+ * \param addr0 The first octet of the IP address.
+ * \param addr1 The second octet of the IP address.
+ * \param addr2 The third octet of the IP address.
+ * \param addr3 The forth octet of the IP address.
+ *
+ * \hideinitializer
+ */
+#define uip_ipaddr(addr, addr0,addr1,addr2,addr3) do {  \
+    (addr)->u8[0] = addr0;                              \
+    (addr)->u8[1] = addr1;                              \
+    (addr)->u8[2] = addr2;                              \
+    (addr)->u8[3] = addr3;                              \
+  } while(0)
+
+/**
+ * Construct an IPv6 address from eight 16-bit words.
+ *
+ * This function constructs an IPv6 address.
+ *
+ * \hideinitializer
+ */
+#define uip_ip6addr(addr, addr0,addr1,addr2,addr3,addr4,addr5,addr6,addr7) do { \
+    (addr)->u16[0] = UIP_HTONS(addr0);                                      \
+    (addr)->u16[1] = UIP_HTONS(addr1);                                      \
+    (addr)->u16[2] = UIP_HTONS(addr2);                                      \
+    (addr)->u16[3] = UIP_HTONS(addr3);                                      \
+    (addr)->u16[4] = UIP_HTONS(addr4);                                      \
+    (addr)->u16[5] = UIP_HTONS(addr5);                                      \
+    (addr)->u16[6] = UIP_HTONS(addr6);                                      \
+    (addr)->u16[7] = UIP_HTONS(addr7);                                      \
+  } while(0)
+
+/**
+ * Construct an IPv6 address from sixteen 8-bit words.
+ *
+ * This function constructs an IPv6 address.
+ *
+ * \hideinitializer
+ */
+#define uip_ip6addr_u8(addr, addr0,addr1,addr2,addr3,addr4,addr5,addr6,addr7,addr8,addr9,addr10,addr11,addr12,addr13,addr14,addr15) do { \
+    (addr)->u8[0] = addr0;                                       \
+    (addr)->u8[1] = addr1;                                       \
+    (addr)->u8[2] = addr2;                                       \
+    (addr)->u8[3] = addr3;                                       \
+    (addr)->u8[4] = addr4;                                       \
+    (addr)->u8[5] = addr5;                                       \
+    (addr)->u8[6] = addr6;                                       \
+    (addr)->u8[7] = addr7;                                       \
+    (addr)->u8[8] = addr8;                                       \
+    (addr)->u8[9] = addr9;                                       \
+    (addr)->u8[10] = addr10;                                     \
+    (addr)->u8[11] = addr11;                                     \
+    (addr)->u8[12] = addr12;                                     \
+    (addr)->u8[13] = addr13;                                     \
+    (addr)->u8[14] = addr14;                                     \
+    (addr)->u8[15] = addr15;                                     \
+  } while(0)
+
+
+/**
+ * Copy an IP address from one place to another.
+ *
+ * Copies an IP address from one place to another.
+ *
+ * Example:
+ \code
+ uip_ipaddr_t ipaddr1, ipaddr2;
+
+ uip_ipaddr(&ipaddr1, 192,16,1,2);
+ uip_ipaddr_copy(&ipaddr2, &ipaddr1);
+ \endcode
+ *
+ * \param dest The destination for the copy.
+ * \param src The source from where to copy.
+ *
+ * \hideinitializer
+ */
+#ifndef uip_ipaddr_copy
+#define uip_ipaddr_copy(dest, src) (*(dest) = *(src))
+#endif
+#ifndef uip_ip4addr_copy
+#define uip_ip4addr_copy(dest, src) (*((uip_ip4addr_t *)dest) = *((uip_ip4addr_t *)src))
+#endif
+#ifndef uip_ip6addr_copy
+#define uip_ip6addr_copy(dest, src) (*((uip_ip6addr_t *)dest) = *((uip_ip6addr_t *)src))
+#endif
+
+/**
+ * Compare two IP addresses
+ *
+ * Compares two IP addresses.
+ *
+ * Example:
+ \code
+ uip_ipaddr_t ipaddr1, ipaddr2;
+
+ uip_ipaddr(&ipaddr1, 192,16,1,2);
+ if(uip_ipaddr_cmp(&ipaddr2, &ipaddr1)) {
+  printf("They are the same");
+ }
+ \endcode
+ *
+ * \param addr1 The first IP address.
+ * \param addr2 The second IP address.
+ *
+ * \hideinitializer
+ */
+#define uip_ip4addr_cmp(addr1, addr2) ((addr1)->u16[0] == (addr2)->u16[0] && \
+                                       (addr1)->u16[1] == (addr2)->u16[1])
+#define uip_ip6addr_cmp(addr1, addr2) (memcmp(addr1, addr2, sizeof(uip_ip6addr_t)) == 0)
+
+#if NETSTACK_CONF_WITH_IPV6
+#define uip_ipaddr_cmp(addr1, addr2) uip_ip6addr_cmp(addr1, addr2)
+#else /* NETSTACK_CONF_WITH_IPV6 */
+#define uip_ipaddr_cmp(addr1, addr2) uip_ip4addr_cmp(addr1, addr2)
+#endif /* NETSTACK_CONF_WITH_IPV6 */
+
+/**
+ * Compare two IP addresses with netmasks
+ *
+ * Compares two IP addresses with netmasks. The masks are used to mask
+ * out the bits that are to be compared.
+ *
+ * Example:
+ \code
+ uip_ipaddr_t ipaddr1, ipaddr2, mask;
+
+ uip_ipaddr(&mask, 255,255,255,0);
+ uip_ipaddr(&ipaddr1, 192,16,1,2);
+ uip_ipaddr(&ipaddr2, 192,16,1,3);
+ if(uip_ipaddr_maskcmp(&ipaddr1, &ipaddr2, &mask)) {
+ printf("They are the same");
+ }
+ \endcode
+ *
+ * \param addr1 The first IP address.
+ * \param addr2 The second IP address.
+ * \param mask The netmask.
+ *
+ * \hideinitializer
+ */
+
+#define uip_ipaddr_maskcmp(addr1, addr2, mask)          \
+  (((((uint16_t *)addr1)[0] & ((uint16_t *)mask)[0]) ==       \
+    (((uint16_t *)addr2)[0] & ((uint16_t *)mask)[0])) &&      \
+   ((((uint16_t *)addr1)[1] & ((uint16_t *)mask)[1]) ==       \
+    (((uint16_t *)addr2)[1] & ((uint16_t *)mask)[1])))
+
+#define uip_ipaddr_prefixcmp(addr1, addr2, length) (memcmp(addr1, addr2, length>>3) == 0)
+
+
+
+/*
+ * Check if an address is a broadcast address for a network.
+ *
+ * Checks if an address is the broadcast address for a network. The
+ * network is defined by an IP address that is on the network and the
+ * network's netmask.
+ *
+ * \param addr The IP address.
+ * \param netaddr The network's IP address.
+ * \param netmask The network's netmask.
+ *
+ * \hideinitializer
+ */
+/*#define uip_ipaddr_isbroadcast(addr, netaddr, netmask)
+  ((uip_ipaddr_t *)(addr)).u16 & ((uip_ipaddr_t *)(addr)).u16*/
+
+
+
+/**
+ * Mask out the network part of an IP address.
+ *
+ * Masks out the network part of an IP address, given the address and
+ * the netmask.
+ *
+ * Example:
+ \code
+ uip_ipaddr_t ipaddr1, ipaddr2, netmask;
+
+ uip_ipaddr(&ipaddr1, 192,16,1,2);
+ uip_ipaddr(&netmask, 255,255,255,0);
+ uip_ipaddr_mask(&ipaddr2, &ipaddr1, &netmask);
+ \endcode
+ *
+ * In the example above, the variable "ipaddr2" will contain the IP
+ * address 192.168.1.0.
+ *
+ * \param dest Where the result is to be placed.
+ * \param src The IP address.
+ * \param mask The netmask.
+ *
+ * \hideinitializer
+ */
+#define uip_ipaddr_mask(dest, src, mask) do {                           \
+    ((uint16_t *)dest)[0] = ((uint16_t *)src)[0] & ((uint16_t *)mask)[0];        \
+    ((uint16_t *)dest)[1] = ((uint16_t *)src)[1] & ((uint16_t *)mask)[1];        \
+  } while(0)
+
+/**
+ * Pick the first octet of an IP address.
+ *
+ * Picks out the first octet of an IP address.
+ *
+ * Example:
+ \code
+ uip_ipaddr_t ipaddr;
+ uint8_t octet;
+
+ uip_ipaddr(&ipaddr, 1,2,3,4);
+ octet = uip_ipaddr1(&ipaddr);
+ \endcode
+ *
+ * In the example above, the variable "octet" will contain the value 1.
+ *
+ * \hideinitializer
+ */
+#define uip_ipaddr1(addr) ((addr)->u8[0])
+
+/**
+ * Pick the second octet of an IP address.
+ *
+ * Picks out the second octet of an IP address.
+ *
+ * Example:
+ \code
+ uip_ipaddr_t ipaddr;
+ uint8_t octet;
+
+ uip_ipaddr(&ipaddr, 1,2,3,4);
+ octet = uip_ipaddr2(&ipaddr);
+ \endcode
+ *
+ * In the example above, the variable "octet" will contain the value 2.
+ *
+ * \hideinitializer
+ */
+#define uip_ipaddr2(addr) ((addr)->u8[1])
+
+/**
+ * Pick the third octet of an IP address.
+ *
+ * Picks out the third octet of an IP address.
+ *
+ * Example:
+ \code
+ uip_ipaddr_t ipaddr;
+ uint8_t octet;
+
+ uip_ipaddr(&ipaddr, 1,2,3,4);
+ octet = uip_ipaddr3(&ipaddr);
+ \endcode
+ *
+ * In the example above, the variable "octet" will contain the value 3.
+ *
+ * \hideinitializer
+ */
+#define uip_ipaddr3(addr) ((addr)->u8[2])
+
+/**
+ * Pick the fourth octet of an IP address.
+ *
+ * Picks out the fourth octet of an IP address.
+ *
+ * Example:
+ \code
+ uip_ipaddr_t ipaddr;
+ uint8_t octet;
+
+ uip_ipaddr(&ipaddr, 1,2,3,4);
+ octet = uip_ipaddr4(&ipaddr);
+ \endcode
+ *
+ * In the example above, the variable "octet" will contain the value 4.
+ *
+ * \hideinitializer
+ */
+#define uip_ipaddr4(addr) ((addr)->u8[3])
+
+/**
+ * Convert 16-bit quantity from host byte order to network byte order.
+ *
+ * This macro is primarily used for converting constants from host
+ * byte order to network byte order. For converting variables to
+ * network byte order, use the uip_htons() function instead.
+ *
+ * \hideinitializer
+ */
+#ifndef UIP_HTONS
+#   if UIP_BYTE_ORDER == UIP_BIG_ENDIAN
+#      define UIP_HTONS(n) (n)
+#      define UIP_HTONL(n) (n)
+#   else /* UIP_BYTE_ORDER == UIP_BIG_ENDIAN */
+#      define UIP_HTONS(n) (uint16_t)((((uint16_t) (n)) << 8) | (((uint16_t) (n)) >> 8))
+#      define UIP_HTONL(n) (((uint32_t)UIP_HTONS(n) << 16) | UIP_HTONS((uint32_t)(n) >> 16))
+#   endif /* UIP_BYTE_ORDER == UIP_BIG_ENDIAN */
+#else
+#error "UIP_HTONS already defined!"
+#endif /* UIP_HTONS */
+
+/**
+ * Convert a 16-bit quantity from host byte order to network byte order.
+ *
+ * This function is primarily used for converting variables from host
+ * byte order to network byte order. For converting constants to
+ * network byte order, use the UIP_HTONS() macro instead.
+ */
+#ifndef uip_htons
+CCIF uint16_t uip_htons(uint16_t val);
+#endif /* uip_htons */
+#ifndef uip_ntohs
+#define uip_ntohs uip_htons
+#endif
+
+#ifndef uip_htonl
+CCIF uint32_t uip_htonl(uint32_t val);
+#endif /* uip_htonl */
+#ifndef uip_ntohl
+#define uip_ntohl uip_htonl
+#endif
+
+/** @} */
+
+/**
+ * Pointer to the application data in the packet buffer.
+ *
+ * This pointer points to the application data when the application is
+ * called. If the application wishes to send data, the application may
+ * use this space to write the data into before calling uip_send().
+ */
+CCIF extern void *uip_appdata;
+
+#if UIP_URGDATA > 0
+/* uint8_t *uip_urgdata:
+ *
+ * This pointer points to any urgent data that has been received. Only
+ * present if compiled with support for urgent data (UIP_URGDATA).
+ */
+extern void *uip_urgdata;
+#endif /* UIP_URGDATA > 0 */
+
+
+/**
+ * \defgroup uipdrivervars Variables used in uIP device drivers
+ * @{
+ *
+ * uIP has a few global variables that are used in device drivers for
+ * uIP.
+ */
+
+/**
+ * The length of the packet in the uip_buf buffer.
+ *
+ * The global variable uip_len holds the length of the packet in the
+ * uip_buf buffer.
+ *
+ * When the network device driver calls the uIP input function,
+ * uip_len should be set to the length of the packet in the uip_buf
+ * buffer.
+ *
+ * When sending packets, the device driver should use the contents of
+ * the uip_len variable to determine the length of the outgoing
+ * packet.
+ *
+ */
+CCIF extern uint16_t uip_len;
+
+/**
+ * The length of the extension headers
+ */
+extern uint8_t uip_ext_len;
+/** @} */
+
+#if UIP_URGDATA > 0
+extern uint16_t uip_urglen, uip_surglen;
+#endif /* UIP_URGDATA > 0 */
+
+/*
+ * Clear uIP buffer
+ *
+ * This function clears the uIP buffer by reseting the uip_len and
+ * uip_ext_len pointers.
+ */
+#if NETSTACK_CONF_WITH_IPV6
+#define uip_clear_buf() { \
+  uip_len = 0; \
+  uip_ext_len = 0; \
+}
+#else /*NETSTACK_CONF_WITH_IPV6*/
+#define uip_clear_buf() { \
+  uip_len = 0; \
+}
+#endif /*NETSTACK_CONF_WITH_IPV6*/
+
+/**
+ * Representation of a uIP TCP connection.
+ *
+ * The uip_conn structure is used for identifying a connection. All
+ * but one field in the structure are to be considered read-only by an
+ * application. The only exception is the appstate field whose purpose
+ * is to let the application store application-specific state (e.g.,
+ * file pointers) for the connection. The type of this field is
+ * configured in the "uipopt.h" header file.
+ */
+struct uip_conn {
+  uip_ipaddr_t ripaddr;   /**< The IP address of the remote host. */
+
+  uint16_t lport;        /**< The local TCP port, in network byte order. */
+  uint16_t rport;        /**< The local remote TCP port, in network byte
+                         order. */
+
+  uint8_t rcv_nxt[4];    /**< The sequence number that we expect to
+                              receive next. */
+  uint8_t snd_nxt[4];    /**< The sequence number that was last sent by us. */
+  uint16_t len;          /**< Length of the data that was previously sent. */
+  uint16_t mss;          /**< Current maximum segment size for the connection. */
+  uint16_t initialmss;   /**< Initial maximum segment size for the connection. */
+  uint8_t sa;            /**< Retransmission time-out calculation state variable. */
+  uint8_t sv;            /**< Retransmission time-out calculation state variable. */
+  uint8_t rto;           /**< Retransmission time-out. */
+  uint8_t tcpstateflags; /**< TCP state and flags. */
+  uint8_t timer;         /**< The retransmission timer. */
+  uint8_t nrtx;          /**< The number of retransmissions for the last
+                              segment sent. */
+
+  uip_tcp_appstate_t appstate; /** The application state. */
+};
+
+
+/**
+ * Pointer to the current TCP connection.
+ *
+ * The uip_conn pointer can be used to access the current TCP
+ * connection.
+ */
+
+CCIF extern struct uip_conn *uip_conn;
+#if UIP_TCP
+/* The array containing all uIP connections. */
+CCIF extern struct uip_conn uip_conns[UIP_CONNS];
+#endif
+
+/**
+ * \addtogroup uiparch
+ * @{
+ */
+
+/**
+ * 4-byte array used for the 32-bit sequence number calculations.
+ */
+extern uint8_t uip_acc32[4];
+/** @} */
+
+/**
+ * Representation of a uIP UDP connection.
+ */
+struct uip_udp_conn {
+  uip_ipaddr_t ripaddr;   /**< The IP address of the remote peer. */
+  uint16_t lport;        /**< The local port number in network byte order. */
+  uint16_t rport;        /**< The remote port number in network byte order. */
+  uint8_t  ttl;          /**< Default time-to-live. */
+
+  /** The application state. */
+  uip_udp_appstate_t appstate;
+};
+
+/**
+ * The current UDP connection.
+ */
+extern struct uip_udp_conn *uip_udp_conn;
+extern struct uip_udp_conn uip_udp_conns[UIP_UDP_CONNS];
+
+struct uip_fallback_interface {
+  void (*init)(void);
+  /**
+   * \retval >=0
+   *         in case of success
+   * \retval <0
+   *         in case of failure
+   */
+  int (*output)(void);
+};
+
+#if UIP_CONF_ICMP6
+struct uip_icmp6_conn {
+  uip_icmp6_appstate_t appstate;
+};
+extern struct uip_icmp6_conn uip_icmp6_conns;
+#endif /*UIP_CONF_ICMP6*/
+
+/**
+ * The uIP TCP/IP statistics.
+ *
+ * This is the variable in which the uIP TCP/IP statistics are gathered.
+ */
+#if UIP_STATISTICS == 1
+extern struct uip_stats uip_stat;
+#define UIP_STAT(s) s
+#else
+#define UIP_STAT(s)
+#endif /* UIP_STATISTICS == 1 */
+
+/**
+ * The structure holding the TCP/IP statistics that are gathered if
+ * UIP_STATISTICS is set to 1.
+ *
+ */
+struct uip_stats {
+  struct {
+    uip_stats_t recv;     /**< Number of received packets at the IP layer. */
+    uip_stats_t sent;     /**< Number of sent packets at the IP layer. */
+    uip_stats_t forwarded;/**< Number of forwarded packets at the IP layer. */
+    uip_stats_t drop;     /**< Number of dropped packets at the IP layer. */
+    uip_stats_t vhlerr;   /**< Number of packets dropped due to wrong
+                               IP version or header length. */
+    uip_stats_t hblenerr; /**< Number of packets dropped due to wrong
+                               IP length, high byte. */
+    uip_stats_t lblenerr; /**< Number of packets dropped due to wrong
+                               IP length, low byte. */
+    uip_stats_t fragerr;  /**< Number of packets dropped because they
+                               were IP fragments. */
+    uip_stats_t chkerr;   /**< Number of packets dropped due to IP
+                               checksum errors. */
+    uip_stats_t protoerr; /**< Number of packets dropped because they
+                               were neither ICMP, UDP nor TCP. */
+  } ip;                   /**< IP statistics. */
+  struct {
+    uip_stats_t recv;     /**< Number of received ICMP packets. */
+    uip_stats_t sent;     /**< Number of sent ICMP packets. */
+    uip_stats_t drop;     /**< Number of dropped ICMP packets. */
+    uip_stats_t typeerr;  /**< Number of ICMP packets with a wrong type. */
+    uip_stats_t chkerr;   /**< Number of ICMP packets with a bad checksum. */
+  } icmp;                 /**< ICMP statistics. */
+#if UIP_TCP
+  struct {
+    uip_stats_t recv;     /**< Number of recived TCP segments. */
+    uip_stats_t sent;     /**< Number of sent TCP segments. */
+    uip_stats_t drop;     /**< Number of dropped TCP segments. */
+    uip_stats_t chkerr;   /**< Number of TCP segments with a bad checksum. */
+    uip_stats_t ackerr;   /**< Number of TCP segments with a bad ACK number. */
+    uip_stats_t rst;      /**< Number of received TCP RST (reset) segments. */
+    uip_stats_t rexmit;   /**< Number of retransmitted TCP segments. */
+    uip_stats_t syndrop;  /**< Number of dropped SYNs because too few
+                               connections were available. */
+    uip_stats_t synrst;   /**< Number of SYNs for closed ports,
+                               triggering a RST. */
+  } tcp;                  /**< TCP statistics. */
+#endif
+#if UIP_UDP
+  struct {
+    uip_stats_t drop;     /**< Number of dropped UDP segments. */
+    uip_stats_t recv;     /**< Number of recived UDP segments. */
+    uip_stats_t sent;     /**< Number of sent UDP segments. */
+    uip_stats_t chkerr;   /**< Number of UDP segments with a bad
+                               checksum. */
+  } udp;                  /**< UDP statistics. */
+#endif /* UIP_UDP */
+#if NETSTACK_CONF_WITH_IPV6
+  struct {
+    uip_stats_t drop;     /**< Number of dropped ND6 packets. */
+    uip_stats_t recv;     /**< Number of recived ND6 packets */
+    uip_stats_t sent;     /**< Number of sent ND6 packets */
+  } nd6;
+#endif /*NETSTACK_CONF_WITH_IPV6*/
+};
+
+
+/*---------------------------------------------------------------------------*/
+/* All the stuff below this point is internal to uIP and should not be
+ * used directly by an application or by a device driver.
+ */
+/*---------------------------------------------------------------------------*/
+
+
+
+/* uint8_t uip_flags:
+ *
+ * When the application is called, uip_flags will contain the flags
+ * that are defined in this file. Please read below for more
+ * information.
+ */
+CCIF extern uint8_t uip_flags;
+
+/* The following flags may be set in the global variable uip_flags
+   before calling the application callback. The UIP_ACKDATA,
+   UIP_NEWDATA, and UIP_CLOSE flags may both be set at the same time,
+   whereas the others are mutually exclusive. Note that these flags
+   should *NOT* be accessed directly, but only through the uIP
+   functions/macros. */
+
+#define UIP_ACKDATA   1     /* Signifies that the outstanding data was
+                               acked and the application should send
+                               out new data instead of retransmitting
+                               the last data. */
+#define UIP_NEWDATA   2     /* Flags the fact that the peer has sent
+                               us new data. */
+#define UIP_REXMIT    4     /* Tells the application to retransmit the
+                               data that was last sent. */
+#define UIP_POLL      8     /* Used for polling the application, to
+                               check if the application has data that
+                               it wants to send. */
+#define UIP_CLOSE     16    /* The remote host has closed the
+                               connection, thus the connection has
+                               gone away. Or the application signals
+                               that it wants to close the
+                               connection. */
+#define UIP_ABORT     32    /* The remote host has aborted the
+                               connection, thus the connection has
+                               gone away. Or the application signals
+                               that it wants to abort the
+                               connection. */
+#define UIP_CONNECTED 64    /* We have got a connection from a remote
+                               host and have set up a new connection
+                               for it, or an active connection has
+                               been successfully established. */
+
+#define UIP_TIMEDOUT  128   /* The connection has been aborted due to
+                               too many retransmissions. */
+
+
+/**
+ * \brief process the options within a hop by hop or destination option header
+ * \retval 0: nothing to send,
+ * \retval 1: drop pkt
+ * \retval 2: ICMP error message to send
+*/
+/*static uint8_t
+uip_ext_hdr_options_process(); */
+
+/* uip_process(flag):
+ *
+ * The actual uIP function which does all the work.
+ */
+void uip_process(uint8_t flag);
+
+  /* The following flags are passed as an argument to the uip_process()
+   function. They are used to distinguish between the two cases where
+   uip_process() is called. It can be called either because we have
+   incoming data that should be processed, or because the periodic
+   timer has fired. These values are never used directly, but only in
+   the macros defined in this file. */
+
+#define UIP_DATA          1     /* Tells uIP that there is incoming
+                                   data in the uip_buf buffer. The
+                                   length of the data is stored in the
+                                   global variable uip_len. */
+#define UIP_TIMER         2     /* Tells uIP that the periodic timer
+                                   has fired. */
+#define UIP_POLL_REQUEST  3     /* Tells uIP that a connection should
+                                   be polled. */
+#define UIP_UDP_SEND_CONN 4     /* Tells uIP that a UDP datagram
+                                   should be constructed in the
+                                   uip_buf buffer. */
+#if UIP_UDP
+#define UIP_UDP_TIMER     5
+#endif /* UIP_UDP */
+
+/* The TCP states used in the uip_conn->tcpstateflags. */
+#define UIP_CLOSED      0
+#define UIP_SYN_RCVD    1
+#define UIP_SYN_SENT    2
+#define UIP_ESTABLISHED 3
+#define UIP_FIN_WAIT_1  4
+#define UIP_FIN_WAIT_2  5
+#define UIP_CLOSING     6
+#define UIP_TIME_WAIT   7
+#define UIP_LAST_ACK    8
+#define UIP_TS_MASK     15
+
+#define UIP_STOPPED      16
+
+/* The TCP and IP headers. */
+struct uip_tcpip_hdr {
+#if NETSTACK_CONF_WITH_IPV6
+  /* IPv6 header. */
+  uint8_t vtc,
+    tcflow;
+  uint16_t flow;
+  uint8_t len[2];
+  uint8_t proto, ttl;
+  uip_ip6addr_t srcipaddr, destipaddr;
+#else /* NETSTACK_CONF_WITH_IPV6 */
+  /* IPv4 header. */
+  uint8_t vhl,
+    tos,
+    len[2],
+    ipid[2],
+    ipoffset[2],
+    ttl,
+    proto;
+  uint16_t ipchksum;
+  uip_ipaddr_t srcipaddr, destipaddr;
+#endif /* NETSTACK_CONF_WITH_IPV6 */
+
+  /* TCP header. */
+  uint16_t srcport,
+    destport;
+  uint8_t seqno[4],
+    ackno[4],
+    tcpoffset,
+    flags,
+    wnd[2];
+  uint16_t tcpchksum;
+  uint8_t urgp[2];
+  uint8_t optdata[4];
+};
+
+/* The ICMP and IP headers. */
+struct uip_icmpip_hdr {
+#if NETSTACK_CONF_WITH_IPV6
+  /* IPv6 header. */
+  uint8_t vtc,
+    tcf;
+  uint16_t flow;
+  uint8_t len[2];
+  uint8_t proto, ttl;
+  uip_ip6addr_t srcipaddr, destipaddr;
+#else /* NETSTACK_CONF_WITH_IPV6 */
+  /* IPv4 header. */
+  uint8_t vhl,
+    tos,
+    len[2],
+    ipid[2],
+    ipoffset[2],
+    ttl,
+    proto;
+  uint16_t ipchksum;
+  uip_ipaddr_t srcipaddr, destipaddr;
+#endif /* NETSTACK_CONF_WITH_IPV6 */
+
+  /* ICMP header. */
+  uint8_t type, icode;
+  uint16_t icmpchksum;
+#if !NETSTACK_CONF_WITH_IPV6
+  uint16_t id, seqno;
+  uint8_t payload[1];
+#endif /* !NETSTACK_CONF_WITH_IPV6 */
+};
+
+
+/* The UDP and IP headers. */
+struct uip_udpip_hdr {
+#if NETSTACK_CONF_WITH_IPV6
+  /* IPv6 header. */
+  uint8_t vtc,
+    tcf;
+  uint16_t flow;
+  uint8_t len[2];
+  uint8_t proto, ttl;
+  uip_ip6addr_t srcipaddr, destipaddr;
+#else /* NETSTACK_CONF_WITH_IPV6 */
+  /* IP header. */
+  uint8_t vhl,
+    tos,
+    len[2],
+    ipid[2],
+    ipoffset[2],
+    ttl,
+    proto;
+  uint16_t ipchksum;
+  uip_ipaddr_t srcipaddr, destipaddr;
+#endif /* NETSTACK_CONF_WITH_IPV6 */
+
+  /* UDP header. */
+  uint16_t srcport,
+    destport;
+  uint16_t udplen;
+  uint16_t udpchksum;
+};
+
+/*
+ * In IPv6 the length of the L3 headers before the transport header is
+ * not fixed, due to the possibility to include extension option headers
+ * after the IP header. hence we split here L3 and L4 headers
+ */
+/* The IP header */
+struct uip_ip_hdr {
+#if NETSTACK_CONF_WITH_IPV6
+  /* IPV6 header */
+  uint8_t vtc;
+  uint8_t tcflow;
+  uint16_t flow;
+  uint8_t len[2];
+  uint8_t proto, ttl;
+  uip_ip6addr_t srcipaddr, destipaddr;
+#else /* NETSTACK_CONF_WITH_IPV6 */
+  /* IPV4 header */
+  uint8_t vhl,
+    tos,
+    len[2],
+    ipid[2],
+    ipoffset[2],
+    ttl,
+    proto;
+  uint16_t ipchksum;
+  uip_ipaddr_t srcipaddr, destipaddr;
+#endif /* NETSTACK_CONF_WITH_IPV6 */
+};
+
+
+/*
+ * IPv6 extension option headers: we are able to process
+ * the 4 extension headers defined in RFC2460 (IPv6):
+ * - Hop by hop option header, destination option header:
+ *   These two are not used by any core IPv6 protocol, hence
+ *   we just read them and go to the next. They convey options,
+ *   the options defined in RFC2460 are Pad1 and PadN, which do
+ *   some padding, and that we do not need to read (the length
+ *   field in the header is enough)
+ * - Routing header: this one is most notably used by MIPv6,
+ *   which we do not implement, hence we just read it and go
+ *   to the next
+ * - Fragmentation header: we read this header and are able to
+ *   reassemble packets
+ *
+ * We do not offer any means to send packets with extension headers
+ *
+ * We do not implement Authentication and ESP headers, which are
+ * used in IPSec and defined in RFC4302,4303,4305,4385
+ */
+/* common header part */
+typedef struct uip_ext_hdr {
+  uint8_t next;
+  uint8_t len;
+} uip_ext_hdr;
+
+/* Hop by Hop option header */
+typedef struct uip_hbho_hdr {
+  uint8_t next;
+  uint8_t len;
+} uip_hbho_hdr;
+
+/* destination option header */
+typedef struct uip_desto_hdr {
+  uint8_t next;
+  uint8_t len;
+} uip_desto_hdr;
+
+/* We do not define structures for PAD1 and PADN options */
+
+/*
+ * routing header
+ * the routing header as 4 common bytes, then routing header type
+ * specific data there are several types of routing header. Type 0 was
+ * deprecated as per RFC5095 most notable other type is 2, used in
+ * RFC3775 (MIPv6) here we do not implement MIPv6, so we just need to
+ * parse the 4 first bytes
+ */
+typedef struct uip_routing_hdr {
+  uint8_t next;
+  uint8_t len;
+  uint8_t routing_type;
+  uint8_t seg_left;
+} uip_routing_hdr;
+
+/* RPL Source Routing Header */
+typedef struct uip_rpl_srh_hdr {
+  uint8_t cmpr; /* CmprI and CmprE */
+  uint8_t pad;
+  uint8_t reserved[2];
+} uip_rpl_srh_hdr;
+
+/* fragmentation header */
+typedef struct uip_frag_hdr {
+  uint8_t next;
+  uint8_t res;
+  uint16_t offsetresmore;
+  uint32_t id;
+} uip_frag_hdr;
+
+/*
+ * an option within the destination or hop by hop option headers
+ * it contains type an length, which is true for all options but PAD1
+ */
+typedef struct uip_ext_hdr_opt {
+  uint8_t type;
+  uint8_t len;
+} uip_ext_hdr_opt;
+
+/* PADN option */
+typedef struct uip_ext_hdr_opt_padn {
+  uint8_t opt_type;
+  uint8_t opt_len;
+} uip_ext_hdr_opt_padn;
+
+/* RPL option */
+typedef struct uip_ext_hdr_opt_rpl {
+  uint8_t opt_type;
+  uint8_t opt_len;
+  uint8_t flags;
+  uint8_t instance;
+  uint16_t senderrank;
+} uip_ext_hdr_opt_rpl;
+
+/* TCP header */
+struct uip_tcp_hdr {
+  uint16_t srcport;
+  uint16_t destport;
+  uint8_t seqno[4];
+  uint8_t ackno[4];
+  uint8_t tcpoffset;
+  uint8_t flags;
+  uint8_t  wnd[2];
+  uint16_t tcpchksum;
+  uint8_t urgp[2];
+  uint8_t optdata[4];
+};
+
+/* The ICMP headers. */
+struct uip_icmp_hdr {
+  uint8_t type, icode;
+  uint16_t icmpchksum;
+#if !NETSTACK_CONF_WITH_IPV6
+  uint16_t id, seqno;
+#endif /* !NETSTACK_CONF_WITH_IPV6 */
+};
+
+
+/* The UDP headers. */
+struct uip_udp_hdr {
+  uint16_t srcport;
+  uint16_t destport;
+  uint16_t udplen;
+  uint16_t udpchksum;
+};
+
+
+/**
+ * The buffer size available for user data in the \ref uip_buf buffer.
+ *
+ * This macro holds the available size for user data in the \ref
+ * uip_buf buffer. The macro is intended to be used for checking
+ * bounds of available user data.
+ *
+ * Example:
+ \code
+ snprintf(uip_appdata, UIP_APPDATA_SIZE, "%u\n", i);
+ \endcode
+ *
+ * \hideinitializer
+ */
+#define UIP_APPDATA_SIZE (UIP_BUFSIZE - UIP_LLH_LEN - UIP_TCPIP_HLEN)
+#define UIP_APPDATA_PTR (void *)&uip_buf[UIP_LLH_LEN + UIP_TCPIP_HLEN]
+
+#define UIP_PROTO_ICMP  1
+#define UIP_PROTO_TCP   6
+#define UIP_PROTO_UDP   17
+#define UIP_PROTO_ICMP6 58
+
+
+#if NETSTACK_CONF_WITH_IPV6
+/** @{ */
+/** \brief  extension headers types */
+#define UIP_PROTO_HBHO        0
+#define UIP_PROTO_DESTO       60
+#define UIP_PROTO_ROUTING     43
+#define UIP_PROTO_FRAG        44
+#define UIP_PROTO_NONE        59
+/** @} */
+
+/** @{ */
+/** \brief  Destination and Hop By Hop extension headers option types */
+#define UIP_EXT_HDR_OPT_PAD1  0
+#define UIP_EXT_HDR_OPT_PADN  1
+#define UIP_EXT_HDR_OPT_RPL   0x63
+
+/** @} */
+
+/** @{ */
+/**
+ * \brief Bitmaps for extension header processing
+ *
+ * When processing extension headers, we should record somehow which one we
+ * see, because you cannot have twice the same header, except for destination
+ * We store all this in one uint8_t bitmap one bit for each header expected. The
+ * order in the bitmap is the order recommended in RFC2460
+ */
+#define UIP_EXT_HDR_BITMAP_HBHO 0x01
+#define UIP_EXT_HDR_BITMAP_DESTO1 0x02
+#define UIP_EXT_HDR_BITMAP_ROUTING 0x04
+#define UIP_EXT_HDR_BITMAP_FRAG 0x08
+#define UIP_EXT_HDR_BITMAP_AH 0x10
+#define UIP_EXT_HDR_BITMAP_ESP 0x20
+#define UIP_EXT_HDR_BITMAP_DESTO2 0x40
+/** @} */
+
+
+#endif /* NETSTACK_CONF_WITH_IPV6 */
+
+
+#if UIP_FIXEDADDR
+CCIF extern const uip_ipaddr_t uip_hostaddr, uip_netmask, uip_draddr;
+#else /* UIP_FIXEDADDR */
+CCIF extern uip_ipaddr_t uip_hostaddr, uip_netmask, uip_draddr;
+#endif /* UIP_FIXEDADDR */
+CCIF extern const uip_ipaddr_t uip_broadcast_addr;
+CCIF extern const uip_ipaddr_t uip_all_zeroes_addr;
+
+#if UIP_FIXEDETHADDR
+CCIF extern const uip_lladdr_t uip_lladdr;
+#else
+CCIF extern uip_lladdr_t uip_lladdr;
+#endif
+
+
+
+
+#if NETSTACK_CONF_WITH_IPV6
+/** Length of the link local prefix */
+#define UIP_LLPREF_LEN     10
+
+/**
+ * \brief Is IPv6 address a the unspecified address
+ * a is of type uip_ipaddr_t
+ */
+#define uip_is_addr_loopback(a)                  \
+  ((((a)->u16[0]) == 0) &&                       \
+   (((a)->u16[1]) == 0) &&                       \
+   (((a)->u16[2]) == 0) &&                       \
+   (((a)->u16[3]) == 0) &&                       \
+   (((a)->u16[4]) == 0) &&                       \
+   (((a)->u16[5]) == 0) &&                       \
+   (((a)->u16[6]) == 0) &&                       \
+   (((a)->u8[14]) == 0) &&                       \
+   (((a)->u8[15]) == 0x01))
+/**
+ * \brief Is IPv6 address a the unspecified address
+ * a is of type uip_ipaddr_t
+ */
+#define uip_is_addr_unspecified(a)               \
+  ((((a)->u16[0]) == 0) &&                       \
+   (((a)->u16[1]) == 0) &&                       \
+   (((a)->u16[2]) == 0) &&                       \
+   (((a)->u16[3]) == 0) &&                       \
+   (((a)->u16[4]) == 0) &&                       \
+   (((a)->u16[5]) == 0) &&                       \
+   (((a)->u16[6]) == 0) &&                       \
+   (((a)->u16[7]) == 0))
+
+/** \brief Is IPv6 address a the link local all-nodes multicast address */
+#define uip_is_addr_linklocal_allnodes_mcast(a)     \
+  ((((a)->u8[0]) == 0xff) &&                        \
+   (((a)->u8[1]) == 0x02) &&                        \
+   (((a)->u16[1]) == 0) &&                          \
+   (((a)->u16[2]) == 0) &&                          \
+   (((a)->u16[3]) == 0) &&                          \
+   (((a)->u16[4]) == 0) &&                          \
+   (((a)->u16[5]) == 0) &&                          \
+   (((a)->u16[6]) == 0) &&                          \
+   (((a)->u8[14]) == 0) &&                          \
+   (((a)->u8[15]) == 0x01))
+
+/** \brief Is IPv6 address a the link local all-routers multicast address */
+#define uip_is_addr_linklocal_allrouters_mcast(a)     \
+  ((((a)->u8[0]) == 0xff) &&                        \
+   (((a)->u8[1]) == 0x02) &&                        \
+   (((a)->u16[1]) == 0) &&                          \
+   (((a)->u16[2]) == 0) &&                          \
+   (((a)->u16[3]) == 0) &&                          \
+   (((a)->u16[4]) == 0) &&                          \
+   (((a)->u16[5]) == 0) &&                          \
+   (((a)->u16[6]) == 0) &&                          \
+   (((a)->u8[14]) == 0) &&                          \
+   (((a)->u8[15]) == 0x02))
+
+/**
+ * \brief is addr (a) a link local unicast address, see RFC3513
+ *  i.e. is (a) on prefix FE80::/10
+ *  a is of type uip_ipaddr_t*
+ */
+#define uip_is_addr_linklocal(a)                 \
+  ((a)->u8[0] == 0xfe &&                         \
+   (a)->u8[1] == 0x80)
+
+/** \brief set IP address a to unspecified */
+#define uip_create_unspecified(a) uip_ip6addr(a, 0, 0, 0, 0, 0, 0, 0, 0)
+
+/** \brief set IP address a to the link local all-nodes multicast address */
+#define uip_create_linklocal_allnodes_mcast(a) uip_ip6addr(a, 0xff02, 0, 0, 0, 0, 0, 0, 0x0001)
+
+/** \brief set IP address a to the link local all-routers multicast address */
+#define uip_create_linklocal_allrouters_mcast(a) uip_ip6addr(a, 0xff02, 0, 0, 0, 0, 0, 0, 0x0002)
+#define uip_create_linklocal_prefix(addr) do { \
+    (addr)->u16[0] = UIP_HTONS(0xfe80);            \
+    (addr)->u16[1] = 0;                        \
+    (addr)->u16[2] = 0;                        \
+    (addr)->u16[3] = 0;                        \
+  } while(0)
+
+/**
+ * \brief  is addr (a) a solicited node multicast address, see RFC3513
+ *  a is of type uip_ipaddr_t*
+ */
+#define uip_is_addr_solicited_node(a)          \
+  ((((a)->u8[0])  == 0xFF) &&                  \
+   (((a)->u8[1])  == 0x02) &&                  \
+   (((a)->u16[1]) == 0x00) &&                  \
+   (((a)->u16[2]) == 0x00) &&                  \
+   (((a)->u16[3]) == 0x00) &&                  \
+   (((a)->u16[4]) == 0x00) &&                  \
+   (((a)->u8[10]) == 0x00) &&                  \
+   (((a)->u8[11]) == 0x01) &&                  \
+   (((a)->u8[12]) == 0xFF))
+
+/**
+ * \brief put in b the solicited node address corresponding to address a
+ * both a and b are of type uip_ipaddr_t*
+ * */
+#define uip_create_solicited_node(a, b)    \
+  (((b)->u8[0]) = 0xFF);                        \
+  (((b)->u8[1]) = 0x02);                        \
+  (((b)->u16[1]) = 0);                          \
+  (((b)->u16[2]) = 0);                          \
+  (((b)->u16[3]) = 0);                          \
+  (((b)->u16[4]) = 0);                          \
+  (((b)->u8[10]) = 0);                          \
+  (((b)->u8[11]) = 0x01);                       \
+  (((b)->u8[12]) = 0xFF);                       \
+  (((b)->u8[13]) = ((a)->u8[13]));              \
+  (((b)->u16[7]) = ((a)->u16[7]))
+
+/**
+ * \brief was addr (a) forged based on the mac address m
+ * a type is uip_ipaddr_t
+ * m type is uiplladdr_t
+ */
+#if UIP_CONF_LL_802154
+#define uip_is_addr_mac_addr_based(a, m) \
+  ((((a)->u8[8])  == (((m)->addr[0]) ^ 0x02)) &&   \
+   (((a)->u8[9])  == (m)->addr[1]) &&            \
+   (((a)->u8[10]) == (m)->addr[2]) &&            \
+   (((a)->u8[11]) == (m)->addr[3]) &&            \
+   (((a)->u8[12]) == (m)->addr[4]) &&            \
+   (((a)->u8[13]) == (m)->addr[5]) &&            \
+   (((a)->u8[14]) == (m)->addr[6]) &&            \
+   (((a)->u8[15]) == (m)->addr[7]))
+#else
+
+#define uip_is_addr_mac_addr_based(a, m) \
+  ((((a)->u8[8])  == (((m)->addr[0]) | 0x02)) &&   \
+   (((a)->u8[9])  == (m)->addr[1]) &&            \
+   (((a)->u8[10]) == (m)->addr[2]) &&            \
+   (((a)->u8[11]) == 0xff) &&            \
+   (((a)->u8[12]) == 0xfe) &&            \
+   (((a)->u8[13]) == (m)->addr[3]) &&            \
+   (((a)->u8[14]) == (m)->addr[4]) &&            \
+   (((a)->u8[15]) == (m)->addr[5]))
+
+#endif /*UIP_CONF_LL_802154*/
+
+/**
+ * \brief is address a multicast address, see RFC 3513
+ * a is of type uip_ipaddr_t*
+ * */
+#define uip_is_addr_mcast(a)                    \
+  (((a)->u8[0]) == 0xFF)
+
+/**
+ * \brief is address a global multicast address (FFxE::/16),
+ * a is of type uip_ip6addr_t*
+ * */
+#define uip_is_addr_mcast_global(a) \
+  ((((a)->u8[0]) == 0xFF) && \
+   (((a)->u8[1] & 0x0F) == 0x0E))
+
+/**
+ * \brief is address a non-routable multicast address.
+ * Scopes 1 (interface-local) and 2 (link-local) are non-routable
+ * See RFC4291 and draft-ietf-6man-multicast-scopes
+ * a is of type uip_ip6addr_t*
+ * */
+#define uip_is_addr_mcast_non_routable(a) \
+  ((((a)->u8[0]) == 0xFF) && \
+   (((a)->u8[1] & 0x0F) <= 0x02))
+
+/**
+ * \brief is address a routable multicast address.
+ * Scope 3 (Realm-Local) or higher are routable
+ * Realm-Local scope is defined in draft-ietf-6man-multicast-scopes
+ * See RFC4291 and draft-ietf-6man-multicast-scopes
+ * a is of type uip_ip6addr_t*
+ * */
+#define uip_is_addr_mcast_routable(a) \
+  ((((a)->u8[0]) == 0xFF) && \
+   (((a)->u8[1] & 0x0F) > 0x02))
+
+/**
+ * \brief is group-id of multicast address a
+ * the all nodes group-id
+ */
+#define uip_is_mcast_group_id_all_nodes(a) \
+  ((((a)->u16[1])  == 0) &&                 \
+   (((a)->u16[2])  == 0) &&                 \
+   (((a)->u16[3])  == 0) &&                 \
+   (((a)->u16[4])  == 0) &&                 \
+   (((a)->u16[5])  == 0) &&                 \
+   (((a)->u16[6])  == 0) &&                 \
+   (((a)->u8[14])  == 0) &&                 \
+   (((a)->u8[15])  == 1))
+
+/**
+ * \brief is group-id of multicast address a
+ * the all routers group-id
+ */
+#define uip_is_mcast_group_id_all_routers(a) \
+  ((((a)->u16[1])  == 0) &&                 \
+   (((a)->u16[2])  == 0) &&                 \
+   (((a)->u16[3])  == 0) &&                 \
+   (((a)->u16[4])  == 0) &&                 \
+   (((a)->u16[5])  == 0) &&                 \
+   (((a)->u16[6])  == 0) &&                 \
+   (((a)->u8[14])  == 0) &&                 \
+   (((a)->u8[15])  == 2))
+
+
+/**
+ * \brief are last three bytes of both addresses equal?
+ * This is used to compare solicited node multicast addresses
+ */
+#define uip_are_solicited_bytes_equal(a, b)             \
+  ((((a)->u8[13])  == ((b)->u8[13])) &&                 \
+   (((a)->u8[14])  == ((b)->u8[14])) &&                 \
+   (((a)->u8[15])  == ((b)->u8[15])))
+
+#endif /*NETSTACK_CONF_WITH_IPV6*/
+
+/**
+ * Calculate the Internet checksum over a buffer.
+ *
+ * The Internet checksum is the one's complement of the one's
+ * complement sum of all 16-bit words in the buffer.
+ *
+ * See RFC1071.
+ *
+ * \param data A pointer to the buffer over which the checksum is to be
+ * computed.
+ *
+ * \param len The length of the buffer over which the checksum is to
+ * be computed.
+ *
+ * \return The Internet checksum of the buffer.
+ */
+uint16_t uip_chksum(uint16_t *data, uint16_t len);
+
+/**
+ * Calculate the IP header checksum of the packet header in uip_buf.
+ *
+ * The IP header checksum is the Internet checksum of the 20 bytes of
+ * the IP header.
+ *
+ * \return The IP header checksum of the IP header in the uip_buf
+ * buffer.
+ */
+uint16_t uip_ipchksum(void);
+
+/**
+ * Calculate the TCP checksum of the packet in uip_buf and uip_appdata.
+ *
+ * The TCP checksum is the Internet checksum of data contents of the
+ * TCP segment, and a pseudo-header as defined in RFC793.
+ *
+ * \return The TCP checksum of the TCP segment in uip_buf and pointed
+ * to by uip_appdata.
+ */
+uint16_t uip_tcpchksum(void);
+
+/**
+ * Calculate the UDP checksum of the packet in uip_buf and uip_appdata.
+ *
+ * The UDP checksum is the Internet checksum of data contents of the
+ * UDP segment, and a pseudo-header as defined in RFC768.
+ *
+ * \return The UDP checksum of the UDP segment in uip_buf and pointed
+ * to by uip_appdata.
+ */
+uint16_t uip_udpchksum(void);
+
+/**
+ * Calculate the ICMP checksum of the packet in uip_buf.
+ *
+ * \return The ICMP checksum of the ICMP packet in uip_buf
+ */
+uint16_t uip_icmp6chksum(void);
+
+
+#endif /* UIP_H_ */
+
+
+/** @} */
diff --git a/Applications/netd/uip_arch.h b/Applications/netd/uip_arch.h
new file mode 100644 (file)
index 0000000..ca60c0e
--- /dev/null
@@ -0,0 +1,137 @@
+/*
+ * Copyright (c) 2001, Adam Dunkels.
+ * All rights reserved. 
+ *
+ * Redistribution and use in source and binary forms, with or without 
+ * modification, are permitted provided that the following conditions 
+ * are met: 
+ * 1. Redistributions of source code must retain the above copyright 
+ *    notice, this list of conditions and the following disclaimer. 
+ * 2. Redistributions in binary form must reproduce the above copyright 
+ *    notice, this list of conditions and the following disclaimer in the 
+ *    documentation and/or other materials provided with the distribution. 
+ * 3. The name of the author may not be used to endorse or promote
+ *    products derived from this software without specific prior
+ *    written permission.  
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
+ * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
+ * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.  
+ *
+ * This file is part of the uIP TCP/IP stack.
+ *
+ *
+ */
+
+/**
+ * \file
+ * Declarations of architecture specific functions.
+ * \author Adam Dunkels <adam@dunkels.com>
+ */
+
+/**
+ * \addtogroup uip
+ * {@
+ */
+
+/**
+ * \defgroup uiparch Architecture specific uIP functions
+ * @{
+ *
+ * The functions in the architecture specific module implement the IP
+ * check sum and 32-bit additions.
+ *
+ * The IP checksum calculation is the most computationally expensive
+ * operation in the TCP/IP stack and it therefore pays off to
+ * implement this in efficient assembler. The purpose of the uip-arch
+ * module is to let the checksum functions to be implemented in
+ * architecture specific assembler.
+ *
+ */
+
+#ifndef UIP_ARCH_H_
+#define UIP_ARCH_H_
+
+#include "uip.h"
+
+/**
+ * Carry out a 32-bit addition.
+ *
+ * Because not all architectures for which uIP is intended has native
+ * 32-bit arithmetic, uIP uses an external C function for doing the
+ * required 32-bit additions in the TCP protocol processing. This
+ * function should add the two arguments and place the result in the
+ * global variable uip_acc32.
+ *
+ * \note The 32-bit integer pointed to by the op32 parameter and the
+ * result in the uip_acc32 variable are in network byte order (big
+ * endian).
+ *
+ * \param op32 A pointer to a 4-byte array representing a 32-bit
+ * integer in network byte order (big endian).
+ *
+ * \param op16 A 16-bit integer in host byte order.
+ */
+void uip_add32(uint8_t *op32, uint16_t op16);
+
+/**
+ * Calculate the Internet checksum over a buffer.
+ *
+ * The Internet checksum is the one's complement of the one's
+ * complement sum of all 16-bit words in the buffer.
+ *
+ * See RFC1071.
+ *
+ * \note This function is not called in the current version of uIP,
+ * but future versions might make use of it.
+ *
+ * \param data A pointer to the buffer over which the checksum is to be
+ * computed.
+ *
+ * \param len The length of the buffer over which the checksum is to
+ * be computed.
+ *
+ * \return The Internet checksum of the buffer.
+ */
+uint16_t uip_chksum(uint16_t *data, uint16_t len);
+
+/**
+ * Calculate the IP header checksum of the packet header in uip_buf.
+ *
+ * The IP header checksum is the Internet checksum of the 20 bytes of
+ * the IP header.
+ *
+ * \return The IP header checksum of the IP header in the uip_buf
+ * buffer.
+ */
+uint16_t uip_ipchksum(void);
+
+/**
+ * Calculate the TCP checksum of the packet in uip_buf and uip_appdata.
+ *
+ * The TCP checksum is the Internet checksum of data contents of the
+ * TCP segment, and a pseudo-header as defined in RFC793.
+ *
+ * \note The uip_appdata pointer that points to the packet data may
+ * point anywhere in memory, so it is not possible to simply calculate
+ * the Internet checksum of the contents of the uip_buf buffer.
+ *
+ * \return The TCP checksum of the TCP segment in uip_buf and pointed
+ * to by uip_appdata.
+ */
+uint16_t uip_tcpchksum(void);
+
+uint16_t uip_udpchksum(void);
+
+/** @} */
+/** @} */
+
+#endif /* UIP_ARCH_H_ */
diff --git a/Applications/netd/uip_arp.c b/Applications/netd/uip_arp.c
new file mode 100644 (file)
index 0000000..7aa02fb
--- /dev/null
@@ -0,0 +1,440 @@
+/*
+ * Copyright (c) 2001-2003, Adam Dunkels.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote
+ *    products derived from this software without specific prior
+ *    written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
+ * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
+ * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * This file is part of the uIP TCP/IP stack.
+ *
+ *
+ */
+
+/**
+ * \file
+ * Implementation of the ARP Address Resolution Protocol.
+ * \author Adam Dunkels <adam@dunkels.com>
+ *
+ */
+
+/**
+ * \addtogroup uip
+ * @{
+ */
+
+/**
+ * \defgroup uiparp uIP Address Resolution Protocol
+ * @{
+ *
+ * The Address Resolution Protocol ARP is used for mapping between IP
+ * addresses and link level addresses such as the Ethernet MAC
+ * addresses. ARP uses broadcast queries to ask for the link level
+ * address of a known IP address and the host which is configured with
+ * the IP address for which the query was meant, will respond with its
+ * link level address.
+ *
+ * \note This ARP implementation only supports Ethernet.
+ */
+#include "uip_arp.h"
+
+#include <string.h>
+
+struct arp_hdr {
+  struct uip_eth_hdr ethhdr;
+  uint16_t hwtype;
+  uint16_t protocol;
+  uint8_t hwlen;
+  uint8_t protolen;
+  uint16_t opcode;
+  struct uip_eth_addr shwaddr;
+  uip_ipaddr_t sipaddr;
+  struct uip_eth_addr dhwaddr;
+  uip_ipaddr_t dipaddr;
+};
+
+struct ethip_hdr {
+  struct uip_eth_hdr ethhdr;
+  /* IP header. */
+  uint8_t vhl,
+    tos,
+    len[2],
+    ipid[2],
+    ipoffset[2],
+    ttl,
+    proto;
+  uint16_t ipchksum;
+  uip_ipaddr_t srcipaddr, destipaddr;
+};
+
+#define ARP_REQUEST 1
+#define ARP_REPLY   2
+
+#define ARP_HWTYPE_ETH 1
+
+struct arp_entry {
+  uip_ipaddr_t ipaddr;
+  struct uip_eth_addr ethaddr;
+  uint8_t time;
+};
+
+static const struct uip_eth_addr broadcast_ethaddr =
+  {{0xff,0xff,0xff,0xff,0xff,0xff}};
+
+static struct arp_entry arp_table[UIP_ARPTAB_SIZE];
+static uip_ipaddr_t ipaddr;
+static uint8_t i, c;
+
+static uint8_t arptime;
+static uint8_t tmpage;
+
+#define BUF   ((struct arp_hdr *)&uip_buf[0])
+#define IPBUF ((struct ethip_hdr *)&uip_buf[0])
+
+#define DEBUG 0
+#if DEBUG
+#include <stdio.h>
+#define PRINTF(...) printf(__VA_ARGS__)
+#else
+#define PRINTF(...)
+#endif
+
+/*-----------------------------------------------------------------------------------*/
+/**
+ * Initialize the ARP module.
+ *
+ */
+/*-----------------------------------------------------------------------------------*/
+void
+uip_arp_init(void)
+{
+  for(i = 0; i < UIP_ARPTAB_SIZE; ++i) {
+    memset(&arp_table[i].ipaddr, 0, 4);
+  }
+}
+/*-----------------------------------------------------------------------------------*/
+/**
+ * Periodic ARP processing function.
+ *
+ * This function performs periodic timer processing in the ARP module
+ * and should be called at regular intervals. The recommended interval
+ * is 10 seconds between the calls.
+ *
+ */
+/*-----------------------------------------------------------------------------------*/
+void
+uip_arp_timer(void)
+{
+  struct arp_entry *tabptr;
+  
+  ++arptime;
+  for(i = 0; i < UIP_ARPTAB_SIZE; ++i) {
+    tabptr = &arp_table[i];
+    if(uip_ipaddr_cmp(&tabptr->ipaddr, &uip_all_zeroes_addr) &&
+       arptime - tabptr->time >= UIP_ARP_MAXAGE) {
+      memset(&tabptr->ipaddr, 0, 4);
+    }
+  }
+
+}
+
+/*-----------------------------------------------------------------------------------*/
+static void
+uip_arp_update(uip_ipaddr_t *ipaddr, struct uip_eth_addr *ethaddr)
+{
+  register struct arp_entry *tabptr = arp_table;
+
+  /* Walk through the ARP mapping table and try to find an entry to
+     update. If none is found, the IP -> MAC address mapping is
+     inserted in the ARP table. */
+  for(i = 0; i < UIP_ARPTAB_SIZE; ++i) {
+    tabptr = &arp_table[i];
+
+    /* Only check those entries that are actually in use. */
+    if(!uip_ipaddr_cmp(&tabptr->ipaddr, &uip_all_zeroes_addr)) {
+
+      /* Check if the source IP address of the incoming packet matches
+         the IP address in this ARP table entry. */
+      if(uip_ipaddr_cmp(ipaddr, &tabptr->ipaddr)) {
+        
+       /* An old entry found, update this and return. */
+       memcpy(tabptr->ethaddr.addr, ethaddr->addr, 6);
+       tabptr->time = arptime;
+
+       return;
+      }
+    }
+       tabptr++;
+  }
+
+  /* If we get here, no existing ARP table entry was found, so we
+     create one. */
+
+  /* First, we try to find an unused entry in the ARP table. */
+  for(i = 0; i < UIP_ARPTAB_SIZE; ++i) {
+    tabptr = &arp_table[i];
+    if(uip_ipaddr_cmp(&tabptr->ipaddr, &uip_all_zeroes_addr)) {
+      break;
+    }
+  }
+
+  /* If no unused entry is found, we try to find the oldest entry and
+     throw it away. */
+  if(i == UIP_ARPTAB_SIZE) {
+    tmpage = 0;
+    c = 0;
+    for(i = 0; i < UIP_ARPTAB_SIZE; ++i) {
+      tabptr = &arp_table[i];
+      if(arptime - tabptr->time > tmpage) {
+       tmpage = arptime - tabptr->time;
+       c = i;
+      }
+    }
+    i = c;
+    tabptr = &arp_table[i];
+  }
+
+  /* Now, i is the ARP table entry which we will fill with the new
+     information. */
+  uip_ipaddr_copy(&tabptr->ipaddr, ipaddr);
+  memcpy(tabptr->ethaddr.addr, ethaddr->addr, 6);
+  tabptr->time = arptime;
+}
+/*-----------------------------------------------------------------------------------*/
+/**
+ * ARP processing for incoming IP packets
+ *
+ * This function should be called by the device driver when an IP
+ * packet has been received. The function will check if the address is
+ * in the ARP cache, and if so the ARP cache entry will be
+ * refreshed. If no ARP cache entry was found, a new one is created.
+ *
+ * This function expects an IP packet with a prepended Ethernet header
+ * in the uip_buf[] buffer, and the length of the packet in the global
+ * variable uip_len.
+ */
+/*-----------------------------------------------------------------------------------*/
+#if 0
+void
+uip_arp_ipin(void)
+{
+  uip_len -= sizeof(struct uip_eth_hdr);
+       
+  /* Only insert/update an entry if the source IP address of the
+     incoming IP packet comes from a host on the local network. */
+  if((IPBUF->srcipaddr[0] & uip_netmask[0]) !=
+     (uip_hostaddr[0] & uip_netmask[0])) {
+    return;
+  }
+  if((IPBUF->srcipaddr[1] & uip_netmask[1]) !=
+     (uip_hostaddr[1] & uip_netmask[1])) {
+    return;
+  }
+  uip_arp_update(IPBUF->srcipaddr, &(IPBUF->ethhdr.src));
+  
+  return;
+}
+#endif /* 0 */
+/*-----------------------------------------------------------------------------------*/
+/**
+ * ARP processing for incoming ARP packets.
+ *
+ * This function should be called by the device driver when an ARP
+ * packet has been received. The function will act differently
+ * depending on the ARP packet type: if it is a reply for a request
+ * that we previously sent out, the ARP cache will be filled in with
+ * the values from the ARP reply. If the incoming ARP packet is an ARP
+ * request for our IP address, an ARP reply packet is created and put
+ * into the uip_buf[] buffer.
+ *
+ * When the function returns, the value of the global variable uip_len
+ * indicates whether the device driver should send out a packet or
+ * not. If uip_len is zero, no packet should be sent. If uip_len is
+ * non-zero, it contains the length of the outbound packet that is
+ * present in the uip_buf[] buffer.
+ *
+ * This function expects an ARP packet with a prepended Ethernet
+ * header in the uip_buf[] buffer, and the length of the packet in the
+ * global variable uip_len.
+ */
+/*-----------------------------------------------------------------------------------*/
+void
+uip_arp_arpin(void)
+{
+  
+  if(uip_len < sizeof(struct arp_hdr)) {
+    uip_clear_buf();
+    return;
+  }
+  uip_clear_buf();
+  
+  switch(BUF->opcode) {
+  case UIP_HTONS(ARP_REQUEST):
+    /* ARP request. If it asked for our address, we send out a
+       reply. */
+    /*    if(BUF->dipaddr[0] == uip_hostaddr[0] &&
+         BUF->dipaddr[1] == uip_hostaddr[1]) {*/
+    PRINTF("uip_arp_arpin: request for %d.%d.%d.%d (we are %d.%d.%d.%d)\n",
+          BUF->dipaddr.u8[0], BUF->dipaddr.u8[1],
+          BUF->dipaddr.u8[2], BUF->dipaddr.u8[3],
+          uip_hostaddr.u8[0], uip_hostaddr.u8[1],
+          uip_hostaddr.u8[2], uip_hostaddr.u8[3]);
+    if(uip_ipaddr_cmp(&BUF->dipaddr, &uip_hostaddr)) {
+      /* First, we register the one who made the request in our ARP
+        table, since it is likely that we will do more communication
+        with this host in the future. */
+      uip_arp_update(&BUF->sipaddr, &BUF->shwaddr);
+      
+      BUF->opcode = UIP_HTONS(ARP_REPLY);
+
+      memcpy(BUF->dhwaddr.addr, BUF->shwaddr.addr, 6);
+      memcpy(BUF->shwaddr.addr, uip_lladdr.addr, 6);
+      memcpy(BUF->ethhdr.src.addr, uip_lladdr.addr, 6);
+      memcpy(BUF->ethhdr.dest.addr, BUF->dhwaddr.addr, 6);
+      
+      uip_ipaddr_copy(&BUF->dipaddr, &BUF->sipaddr);
+      uip_ipaddr_copy(&BUF->sipaddr, &uip_hostaddr);
+
+      BUF->ethhdr.type = UIP_HTONS(UIP_ETHTYPE_ARP);
+      uip_len = sizeof(struct arp_hdr);
+    }
+    break;
+  case UIP_HTONS(ARP_REPLY):
+    /* ARP reply. We insert or update the ARP table if it was meant
+       for us. */
+    if(uip_ipaddr_cmp(&BUF->dipaddr, &uip_hostaddr)) {
+      uip_arp_update(&BUF->sipaddr, &BUF->shwaddr);
+    }
+    break;
+  }
+
+  return;
+}
+/*-----------------------------------------------------------------------------------*/
+/**
+ * Prepend Ethernet header to an outbound IP packet and see if we need
+ * to send out an ARP request.
+ *
+ * This function should be called before sending out an IP packet. The
+ * function checks the destination IP address of the IP packet to see
+ * what Ethernet MAC address that should be used as a destination MAC
+ * address on the Ethernet.
+ *
+ * If the destination IP address is in the local network (determined
+ * by logical ANDing of netmask and our IP address), the function
+ * checks the ARP cache to see if an entry for the destination IP
+ * address is found. If so, an Ethernet header is prepended and the
+ * function returns. If no ARP cache entry is found for the
+ * destination IP address, the packet in the uip_buf[] is replaced by
+ * an ARP request packet for the IP address. The IP packet is dropped
+ * and it is assumed that they higher level protocols (e.g., TCP)
+ * eventually will retransmit the dropped packet.
+ *
+ * If the destination IP address is not on the local network, the IP
+ * address of the default router is used instead.
+ *
+ * When the function returns, a packet is present in the uip_buf[]
+ * buffer, and the length of the packet is in the global variable
+ * uip_len.
+ */
+/*-----------------------------------------------------------------------------------*/
+void
+uip_arp_out(void)
+{
+  struct arp_entry *tabptr = arp_table;
+  
+  /* Find the destination IP address in the ARP table and construct
+     the Ethernet header. If the destination IP addres isn't on the
+     local network, we use the default router's IP address instead.
+
+     If not ARP table entry is found, we overwrite the original IP
+     packet with an ARP request for the IP address. */
+
+  /* First check if destination is a local broadcast. */
+  if(uip_ipaddr_cmp(&IPBUF->destipaddr, &uip_broadcast_addr)) {
+    memcpy(IPBUF->ethhdr.dest.addr, broadcast_ethaddr.addr, 6);
+  } else if(IPBUF->destipaddr.u8[0] == 224) {
+    /* Multicast. */
+    IPBUF->ethhdr.dest.addr[0] = 0x01;
+    IPBUF->ethhdr.dest.addr[1] = 0x00;
+    IPBUF->ethhdr.dest.addr[2] = 0x5e;
+    IPBUF->ethhdr.dest.addr[3] = IPBUF->destipaddr.u8[1];
+    IPBUF->ethhdr.dest.addr[4] = IPBUF->destipaddr.u8[2];
+    IPBUF->ethhdr.dest.addr[5] = IPBUF->destipaddr.u8[3];
+  } else {
+    /* Check if the destination address is on the local network. */
+    if(!uip_ipaddr_maskcmp(&IPBUF->destipaddr, &uip_hostaddr, &uip_netmask)) {
+      /* Destination address was not on the local network, so we need to
+        use the default router's IP address instead of the destination
+        address when determining the MAC address. */
+      uip_ipaddr_copy(&ipaddr, &uip_draddr);
+    } else {
+      /* Else, we use the destination IP address. */
+      uip_ipaddr_copy(&ipaddr, &IPBUF->destipaddr);
+    }
+    for(i = 0; i < UIP_ARPTAB_SIZE; ++i) {
+      if(uip_ipaddr_cmp(&ipaddr, &tabptr->ipaddr)) {
+       break;
+      }
+         tabptr++;
+    }
+
+    if(i == UIP_ARPTAB_SIZE) {
+      /* The destination address was not in our ARP table, so we
+        overwrite the IP packet with an ARP request. */
+
+      memset(BUF->ethhdr.dest.addr, 0xff, 6);
+      memset(BUF->dhwaddr.addr, 0x00, 6);
+      memcpy(BUF->ethhdr.src.addr, uip_lladdr.addr, 6);
+      memcpy(BUF->shwaddr.addr, uip_lladdr.addr, 6);
+    
+      uip_ipaddr_copy(&BUF->dipaddr, &ipaddr);
+      uip_ipaddr_copy(&BUF->sipaddr, &uip_hostaddr);
+      BUF->opcode = UIP_HTONS(ARP_REQUEST); /* ARP request. */
+      BUF->hwtype = UIP_HTONS(ARP_HWTYPE_ETH);
+      BUF->protocol = UIP_HTONS(UIP_ETHTYPE_IP);
+      BUF->hwlen = 6;
+      BUF->protolen = 4;
+      BUF->ethhdr.type = UIP_HTONS(UIP_ETHTYPE_ARP);
+
+      uip_appdata = &uip_buf[UIP_TCPIP_HLEN + UIP_LLH_LEN];
+    
+      uip_len = sizeof(struct arp_hdr);
+      return;
+    }
+
+    /* Build an ethernet header. */
+    memcpy(IPBUF->ethhdr.dest.addr, tabptr->ethaddr.addr, 6);
+  }
+  memcpy(IPBUF->ethhdr.src.addr, uip_lladdr.addr, 6);
+  
+  IPBUF->ethhdr.type = UIP_HTONS(UIP_ETHTYPE_IP);
+
+  uip_len += sizeof(struct uip_eth_hdr);
+}
+/*-----------------------------------------------------------------------------------*/
+
+/** @} */
+/** @} */
+
diff --git a/Applications/netd/uip_arp.h b/Applications/netd/uip_arp.h
new file mode 100644 (file)
index 0000000..7ce67ad
--- /dev/null
@@ -0,0 +1,142 @@
+/*
+ * Copyright (c) 2001-2003, Adam Dunkels.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote
+ *    products derived from this software without specific prior
+ *    written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
+ * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
+ * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * This file is part of the uIP TCP/IP stack.
+ *
+ *
+ */
+
+/**
+ * \file
+ * Macros and definitions for the ARP module.
+ * \author Adam Dunkels <adam@dunkels.com>
+ */
+
+/**
+ * \addtogroup uip
+ * @{
+ */
+
+/**
+ * \addtogroup uiparp
+ * @{
+ */
+#ifndef UIP_ARP_H_
+#define UIP_ARP_H_
+
+#include "uip.h"
+
+
+
+/**
+ * The Ethernet header.
+ */
+struct uip_eth_hdr {
+  struct uip_eth_addr dest;
+  struct uip_eth_addr src;
+  uint16_t type;
+};
+
+#define UIP_ETHTYPE_ARP  0x0806
+#define UIP_ETHTYPE_IP   0x0800
+#define UIP_ETHTYPE_IPV6 0x86dd
+
+
+/* The uip_arp_init() function must be called before any of the other
+   ARP functions. */
+void uip_arp_init(void);
+
+/* The uip_arp_ipin() function should be called whenever an IP packet
+   arrives from the Ethernet. This function refreshes the ARP table or
+   inserts a new mapping if none exists. The function assumes that an
+   IP packet with an Ethernet header is present in the uip_buf buffer
+   and that the length of the packet is in the uip_len variable. */
+/*void uip_arp_ipin(void);*/
+#define uip_arp_ipin()
+
+/* The uip_arp_arpin() should be called when an ARP packet is received
+   by the Ethernet driver. This function also assumes that the
+   Ethernet frame is present in the uip_buf buffer. When the
+   uip_arp_arpin() function returns, the contents of the uip_buf
+   buffer should be sent out on the Ethernet if the uip_len variable
+   is > 0. */
+void uip_arp_arpin(void);
+
+/* The uip_arp_out() function should be called when an IP packet
+   should be sent out on the Ethernet. This function creates an
+   Ethernet header before the IP header in the uip_buf buffer. The
+   Ethernet header will have the correct Ethernet MAC destination
+   address filled in if an ARP table entry for the destination IP
+   address (or the IP address of the default router) is present. If no
+   such table entry is found, the IP packet is overwritten with an ARP
+   request and we rely on TCP to retransmit the packet that was
+   overwritten. In any case, the uip_len variable holds the length of
+   the Ethernet frame that should be transmitted. */
+void uip_arp_out(void);
+
+/* The uip_arp_timer() function should be called every ten seconds. It
+   is responsible for flushing old entries in the ARP table. */
+void uip_arp_timer(void);
+
+/** @} */
+
+/**
+ * \addtogroup uipconffunc
+ * @{
+ */
+
+
+/**
+ * Specifiy the Ethernet MAC address.
+ *
+ * The ARP code needs to know the MAC address of the Ethernet card in
+ * order to be able to respond to ARP queries and to generate working
+ * Ethernet headers.
+ *
+ * \note This macro only specifies the Ethernet MAC address to the ARP
+ * code. It cannot be used to change the MAC address of the Ethernet
+ * card.
+ *
+ * \param eaddr A pointer to a struct uip_eth_addr containing the
+ * Ethernet MAC address of the Ethernet card.
+ *
+ * \hideinitializer
+ */
+#define uip_setethaddr(eaddr) do {uip_lladdr.addr[0] = eaddr.addr[0]; \
+                              uip_lladdr.addr[1] = eaddr.addr[1];\
+                              uip_lladdr.addr[2] = eaddr.addr[2];\
+                              uip_lladdr.addr[3] = eaddr.addr[3];\
+                              uip_lladdr.addr[4] = eaddr.addr[4];\
+                              uip_lladdr.addr[5] = eaddr.addr[5];} while(0)
+
+/** @} */
+
+
+#endif /* UIP_ARP_H_ */
+/** @} */
diff --git a/Applications/netd/uiplib.c b/Applications/netd/uiplib.c
new file mode 100644 (file)
index 0000000..85be04b
--- /dev/null
@@ -0,0 +1,143 @@
+/*
+ * Copyright (c) 2004, Adam Dunkels and the Swedish Institute of
+ * Computer Science.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without 
+ * modification, are permitted provided that the following conditions 
+ * are met: 
+ * 1. Redistributions of source code must retain the above copyright 
+ *    notice, this list of conditions and the following disclaimer. 
+ * 2. Redistributions in binary form must reproduce the above copyright 
+ *    notice, this list of conditions and the following disclaimer in the 
+ *    documentation and/or other materials provided with the distribution. 
+ * 3. The name of the author may not be used to endorse or promote
+ *    products derived from this software without specific prior
+ *    written permission.  
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
+ * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
+ * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.  
+ *
+ * This file is part of the uIP TCP/IP stack and the Contiki operating system.
+ *
+ *
+ */
+
+
+#include "uip.h"
+#include "uiplib.h"
+#include <string.h>
+
+#define DEBUG DEBUG_NONE
+
+
+/*-----------------------------------------------------------------------------------*/
+#if NETSTACK_CONF_WITH_IPV6
+int
+uiplib_ip6addrconv(const char *addrstr, uip_ip6addr_t *ipaddr)
+{
+  uint16_t value;
+  int tmp, zero;
+  unsigned int len;
+  char c = 0;  //gcc warning if not initialized
+
+  value = 0;
+  zero = -1;
+  if(*addrstr == '[') addrstr++;
+
+  for(len = 0; len < sizeof(uip_ip6addr_t) - 1; addrstr++) {
+    c = *addrstr;
+    if(c == ':' || c == '\0' || c == ']' || c == '/') {
+      ipaddr->u8[len] = (value >> 8) & 0xff;
+      ipaddr->u8[len + 1] = value & 0xff;
+      len += 2;
+      value = 0;
+
+      if(c == '\0' || c == ']' || c == '/') {
+        break;
+      }
+
+      if(*(addrstr + 1) == ':') {
+        /* Zero compression */
+        if(zero < 0) {
+          zero = len;
+        }
+        addrstr++;
+      }
+    } else {
+      if(c >= '0' && c <= '9') {
+        tmp = c - '0';
+      } else if(c >= 'a' && c <= 'f') {
+        tmp = c - 'a' + 10;
+      } else if(c >= 'A' && c <= 'F') {
+        tmp = c - 'A' + 10;
+      } else {
+        PRINTF("uiplib: illegal char: '%c'\n", c);
+        return 0;
+      }
+      value = (value << 4) + (tmp & 0xf);
+    }
+  }
+  if(c != '\0' && c != ']' && c != '/') {
+    PRINTF("uiplib: too large address\n");
+    return 0;
+  }
+  if(len < sizeof(uip_ip6addr_t)) {
+    if(zero < 0) {
+      PRINTF("uiplib: too short address\n");
+      return 0;
+    }
+    memmove(&ipaddr->u8[zero + sizeof(uip_ip6addr_t) - len],
+            &ipaddr->u8[zero], len - zero);
+    memset(&ipaddr->u8[zero], 0, sizeof(uip_ip6addr_t) - len);
+  }
+
+  return 1;
+}
+#endif /* NETSTACK_CONF_WITH_IPV6 */
+/*-----------------------------------------------------------------------------------*/
+/* Parse a IPv4-address from a string. Returns the number of characters read 
+ * for the address. */
+int
+uiplib_ip4addrconv(const char *addrstr, uip_ip4addr_t *ipaddr)
+{
+  unsigned char tmp;
+  char c;
+  unsigned char i, j;
+  uint8_t charsread = 0;
+
+  tmp = 0;
+
+  for(i = 0; i < 4; ++i) {
+    j = 0;
+    do {
+      c = *addrstr;
+      ++j;
+      if(j > 4) {
+        return 0;
+      }
+      if(c == '.' || c == 0 || c == ' ') {
+        ipaddr->u8[i] = tmp;
+        tmp = 0;
+      } else if(c >= '0' && c <= '9') {
+       tmp = (tmp * 10) + (c - '0');
+      } else {
+        return 0;
+      }
+      ++addrstr;
+      ++charsread;
+    } while(c != '.' && c != 0 && c != ' ');
+
+  }
+  return charsread-1;
+}
+/*-----------------------------------------------------------------------------------*/
diff --git a/Applications/netd/uiplib.h b/Applications/netd/uiplib.h
new file mode 100644 (file)
index 0000000..0110ad2
--- /dev/null
@@ -0,0 +1,80 @@
+/*
+ * Copyright (c) 2002, Adam Dunkels.
+ * All rights reserved. 
+ *
+ * Redistribution and use in source and binary forms, with or without 
+ * modification, are permitted provided that the following conditions 
+ * are met: 
+ * 1. Redistributions of source code must retain the above copyright 
+ *    notice, this list of conditions and the following disclaimer. 
+ * 2. Redistributions in binary form must reproduce the above
+ *    copyright notice, this list of conditions and the following
+ *    disclaimer in the documentation and/or other materials provided
+ *    with the distribution. 
+ * 3. The name of the author may not be used to endorse or promote
+ *    products derived from this software without specific prior
+ *    written permission.  
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
+ * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
+ * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.  
+ *
+ * This file is part of the Contiki desktop environment for the C64.
+ *
+ *
+ */
+
+/**
+ * \file
+ * Various uIP library functions.
+ * \author
+ * Adam Dunkels <adam@sics.se>
+ *
+ */
+
+#ifndef UIPLIB_H_
+#define UIPLIB_H_
+
+#include "uip.h"
+
+/**
+ * \addtogroup uipconvfunc
+ * @{
+ */
+
+/**
+ * Convert a textual representation of an IP address to a numerical representation.
+ *
+ * This function takes a textual representation of an IP address in
+ * the form a.b.c.d for IPv4 or a:b:c:d:e:f:g:h for IPv6 and converts
+ * it into a numeric IP address representation that can be used by
+ * other uIP functions.
+ *
+ * \param addrstr A pointer to a string containing the IP address in
+ * textual form.
+ *
+ * \param addr A pointer to a uip_ip4addr_t that will be filled in with
+ * the numerical representation of the address.
+ *
+ * \retval 0 If the IP address could not be parsed.
+ * \retval Non-zero If the IP address was parsed. 
+ */
+#if NETSTACK_CONF_WITH_IPV6
+#define uiplib_ipaddrconv uiplib_ip6addrconv
+#else /* NETSTACK_CONF_WITH_IPV6 */
+#define uiplib_ipaddrconv uiplib_ip4addrconv
+#endif /* NETSTACK_CONF_WITH_IPV6 */
+
+CCIF int uiplib_ip4addrconv(const char *addrstr, uip_ip4addr_t *addr);
+CCIF int uiplib_ip6addrconv(const char *addrstr, uip_ip6addr_t *addr);
+/** @} */
+
+#endif /* UIPLIB_H_ */
diff --git a/Applications/netd/uipopt.h b/Applications/netd/uipopt.h
new file mode 100644 (file)
index 0000000..af744cf
--- /dev/null
@@ -0,0 +1,684 @@
+/*
+ * Copyright (c) 2001-2003, Adam Dunkels.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote
+ *    products derived from this software without specific prior
+ *    written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
+ * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
+ * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * This file is part of the uIP TCP/IP stack.
+ *
+ *
+ */
+
+/**
+ * \file
+ * Configuration options for uIP.
+ * \author Adam Dunkels <adam@dunkels.com>
+ *
+ * This file is used for tweaking various configuration options for
+ * uIP. You should make a copy of this file into one of your project's
+ * directories instead of editing this example "uipopt.h" file that
+ * comes with the uIP distribution.
+ */
+
+/**
+ * \addtogroup uip
+ * @{
+ */
+
+/**
+ * \defgroup uipopt Configuration options for uIP
+ * @{
+ *
+ * uIP is configured using the per-project configuration file
+ * "uipopt.h". This file contains all compile-time options for uIP and
+ * should be tweaked to match each specific project. The uIP
+ * distribution contains a documented example "uipopt.h" that can be
+ * copied and modified for each project.
+ *
+ * \note Contiki does not use the uipopt.h file to configure uIP, but
+ * uses a per-port uip-conf.h file that should be edited instead.
+ */
+
+#ifndef UIPOPT_H_
+#define UIPOPT_H_
+
+#ifndef UIP_LITTLE_ENDIAN
+#define UIP_LITTLE_ENDIAN  3412
+#endif /* UIP_LITTLE_ENDIAN */
+#ifndef UIP_BIG_ENDIAN
+#define UIP_BIG_ENDIAN     1234
+#endif /* UIP_BIG_ENDIAN */
+
+#include "fuzix-conf.h"
+
+/*------------------------------------------------------------------------------*/
+
+/**
+ * \defgroup uipoptstaticconf Static configuration options
+ * @{
+ *
+ * These configuration options can be used for setting the IP address
+ * settings statically, but only if UIP_FIXEDADDR is set to 1. The
+ * configuration options for a specific node includes IP address,
+ * netmask and default router as well as the Ethernet address. The
+ * netmask, default router and Ethernet address are applicable only
+ * if uIP should be run over Ethernet.
+ *
+ * This options are meaningful only for the IPv4 code.
+ *
+ * All of these should be changed to suit your project.
+ */
+
+/**
+ * Determines if uIP should use a fixed IP address or not.
+ *
+ * If uIP should use a fixed IP address, the settings are set in the
+ * uipopt.h file. If not, the macros uip_sethostaddr(),
+ * uip_setdraddr() and uip_setnetmask() should be used instead.
+ *
+ * \hideinitializer
+ */
+#define UIP_FIXEDADDR    0
+
+/**
+ * Ping IP address assignment.
+ *
+ * uIP uses a "ping" packets for setting its own IP address if this
+ * option is set. If so, uIP will start with an empty IP address and
+ * the destination IP address of the first incoming "ping" (ICMP echo)
+ * packet will be used for setting the hosts IP address.
+ *
+ * \note This works only if UIP_FIXEDADDR is 0.
+ *
+ * \hideinitializer
+ */
+#ifdef UIP_CONF_PINGADDRCONF
+#define UIP_PINGADDRCONF (UIP_CONF_PINGADDRCONF)
+#else /* UIP_CONF_PINGADDRCONF */
+#define UIP_PINGADDRCONF 0
+#endif /* UIP_CONF_PINGADDRCONF */
+
+
+/**
+ * Specifies if the uIP ARP module should be compiled with a fixed
+ * Ethernet MAC address or not.
+ *
+ * If this configuration option is 0, the macro uip_setethaddr() can
+ * be used to specify the Ethernet address at run-time.
+ *
+ * \hideinitializer
+ */
+#define UIP_FIXEDETHADDR 0
+
+/** @} */
+/*------------------------------------------------------------------------------*/
+
+/**
+ * \defgroup uipoptgeneral General configuration options
+ * @{
+ */
+
+/**
+ * The link level header length.
+ *
+ * This is the offset into the uip_buf where the IP header can be
+ * found. For Ethernet, this should be set to 14. For SLIP, this
+ * should be set to 0.
+ *
+ * \note we probably won't use this constant for other link layers than
+ * ethernet as they have variable header length (this is due to variable
+ * number and type of address fields and to optional security features)
+ * E.g.: 802.15.4 -> 2 + (1/2*4/8) + 0/5/6/10/14
+ *       802.11 -> 4 + (6*3/4) + 2
+ * \hideinitializer
+ */
+#ifdef UIP_CONF_LLH_LEN
+#define UIP_LLH_LEN (UIP_CONF_LLH_LEN)
+#else /* UIP_LLH_LEN */
+#define UIP_LLH_LEN     0
+#endif /* UIP_CONF_LLH_LEN */
+
+/**
+ * The size of the uIP packet buffer.
+ *
+ * The uIP packet buffer should not be smaller than 60 bytes, and does
+ * not need to be larger than 1514 bytes. Lower size results in lower
+ * TCP throughput, larger size results in higher TCP throughput.
+ *
+ * \hideinitializer
+ */
+#ifndef UIP_CONF_BUFFER_SIZE
+#define UIP_BUFSIZE (UIP_LINK_MTU + UIP_LLH_LEN)
+#else /* UIP_CONF_BUFFER_SIZE */
+#define UIP_BUFSIZE (UIP_CONF_BUFFER_SIZE)
+#endif /* UIP_CONF_BUFFER_SIZE */
+
+
+/**
+ * Determines if statistics support should be compiled in.
+ *
+ * The statistics is useful for debugging and to show the user.
+ *
+ * \hideinitializer
+ */
+#ifndef UIP_CONF_STATISTICS
+#define UIP_STATISTICS  0
+#else /* UIP_CONF_STATISTICS */
+#define UIP_STATISTICS (UIP_CONF_STATISTICS)
+#endif /* UIP_CONF_STATISTICS */
+
+/**
+ * Determines if logging of certain events should be compiled in.
+ *
+ * This is useful mostly for debugging. The function uip_log()
+ * must be implemented to suit the architecture of the project, if
+ * logging is turned on.
+ *
+ * \hideinitializer
+ */
+#ifndef UIP_CONF_LOGGING
+#define UIP_LOGGING     0
+#else /* UIP_CONF_LOGGING */
+#define UIP_LOGGING     (UIP_CONF_LOGGING)
+#endif /* UIP_CONF_LOGGING */
+
+/**
+ * Broadcast support.
+ *
+ * This flag configures IP broadcast support. This is useful only
+ * together with UDP.
+ *
+ * \hideinitializer
+ *
+ */
+#ifndef UIP_CONF_BROADCAST
+#define UIP_BROADCAST 0
+#else /* UIP_CONF_BROADCAST */
+#define UIP_BROADCAST (UIP_CONF_BROADCAST)
+#endif /* UIP_CONF_BROADCAST */
+
+/**
+ * Print out a uIP log message.
+ *
+ * This function must be implemented by the module that uses uIP, and
+ * is called by uIP whenever a log message is generated.
+ */
+void uip_log(char *msg);
+
+/** @} */
+/*------------------------------------------------------------------------------*/
+/**
+ * \defgroup uipoptip IP configuration options
+ * @{
+ *
+ */
+/**
+ * The IP TTL (time to live) of IP packets sent by uIP.
+ *
+ * This should normally not be changed.
+ */
+#ifdef UIP_CONF_TTL
+#define UIP_TTL         UIP_CONF_TTL
+#else /* UIP_CONF_TTL */
+#define UIP_TTL         64
+#endif /* UIP_CONF_TTL */
+
+/**
+ * The maximum time an IP fragment should wait in the reassembly
+ * buffer before it is dropped.
+ *
+ */
+#define UIP_REASS_MAXAGE 60 /*60s*/
+
+/**
+ * Turn on support for IP packet reassembly.
+ *
+ * uIP supports reassembly of fragmented IP packets. This features
+ * requires an additional amount of RAM to hold the reassembly buffer
+ * and the reassembly code size is approximately 700 bytes.  The
+ * reassembly buffer is of the same size as the uip_buf buffer
+ * (configured by UIP_BUFSIZE).
+ *
+ * \note IP packet reassembly is not heavily tested.
+ *
+ * \hideinitializer
+ */
+#ifdef UIP_CONF_REASSEMBLY
+#define UIP_REASSEMBLY (UIP_CONF_REASSEMBLY)
+#else /* UIP_CONF_REASSEMBLY */
+#define UIP_REASSEMBLY 0
+#endif /* UIP_CONF_REASSEMBLY */
+/** @} */
+
+/*------------------------------------------------------------------------------*/
+/**
+ * \defgroup uipoptipv6 IPv6 configuration options
+ * @{
+ *
+ */
+
+/** The maximum transmission unit at the IP Layer*/
+#define UIP_LINK_MTU 1280
+
+#ifndef NETSTACK_CONF_WITH_IPV6
+/** Do we use IPv6 or not (default: no) */
+#define NETSTACK_CONF_WITH_IPV6                 0
+#endif
+
+#ifndef UIP_CONF_IPV6_QUEUE_PKT
+/** Do we do per %neighbor queuing during address resolution (default: no) */
+#define UIP_CONF_IPV6_QUEUE_PKT       0
+#endif
+
+#ifndef UIP_CONF_IPV6_CHECKS
+/** Do we do IPv6 consistency checks (highly recommended, default: yes) */
+#define UIP_CONF_IPV6_CHECKS          1
+#endif
+
+#ifndef UIP_CONF_IPV6_REASSEMBLY
+/** Do we do IPv6 fragmentation (default: no) */
+#define UIP_CONF_IPV6_REASSEMBLY      0
+#endif
+
+#ifndef UIP_CONF_NETIF_MAX_ADDRESSES
+/** Default number of IPv6 addresses associated to the node's interface */
+#define UIP_CONF_NETIF_MAX_ADDRESSES  3
+#endif
+
+#ifndef UIP_CONF_DS6_PREFIX_NBU
+/** Default number of IPv6 prefixes associated to the node's interface */
+#define UIP_CONF_DS6_PREFIX_NBU     2
+#endif
+
+#ifndef UIP_CONF_DS6_DEFRT_NBU
+/** Minimum number of default routers */
+#define UIP_CONF_DS6_DEFRT_NBU       2
+#endif
+/** @} */
+
+/*------------------------------------------------------------------------------*/
+/**
+ * \defgroup uipoptudp UDP configuration options
+ * @{
+ *
+ * \note The UDP support in uIP is still not entirely complete; there
+ * is no support for sending or receiving broadcast or multicast
+ * packets, but it works well enough to support a number of vital
+ * applications such as DNS queries, though
+ */
+
+/**
+ * Toggles whether UDP support should be compiled in or not.
+ *
+ * \hideinitializer
+ */
+#ifdef UIP_CONF_UDP
+#define UIP_UDP UIP_CONF_UDP
+#else /* UIP_CONF_UDP */
+#define UIP_UDP           1
+#endif /* UIP_CONF_UDP */
+
+/**
+ * Toggles if UDP checksums should be used or not.
+ *
+ * \note Support for UDP checksums is currently not included in uIP,
+ * so this option has no function.
+ *
+ * \hideinitializer
+ */
+#ifdef UIP_CONF_UDP_CHECKSUMS
+#define UIP_UDP_CHECKSUMS (UIP_CONF_UDP_CHECKSUMS)
+#else
+#define UIP_UDP_CHECKSUMS (NETSTACK_CONF_WITH_IPV6)
+#endif
+
+/**
+ * The maximum amount of concurrent UDP connections.
+ *
+ * \hideinitializer
+ */
+#ifdef UIP_CONF_UDP_CONNS
+#define UIP_UDP_CONNS (UIP_CONF_UDP_CONNS)
+#else /* UIP_CONF_UDP_CONNS */
+#define UIP_UDP_CONNS    10
+#endif /* UIP_CONF_UDP_CONNS */
+
+/**
+ * The name of the function that should be called when UDP datagrams arrive.
+ *
+ * \hideinitializer
+ */
+
+
+/** @} */
+/*------------------------------------------------------------------------------*/
+/**
+ * \defgroup uipopttcp TCP configuration options
+ * @{
+ */
+
+/**
+ * Toggles whether TCP support should be compiled in or not.
+ *
+ * \hideinitializer
+ */
+#ifdef UIP_CONF_TCP
+#define UIP_TCP (UIP_CONF_TCP)
+#else /* UIP_CONF_TCP */
+#define UIP_TCP           1
+#endif /* UIP_CONF_TCP */
+
+/**
+ * Determines if support for opening connections from uIP should be
+ * compiled in.
+ *
+ * If the applications that are running on top of uIP for this project
+ * do not need to open outgoing TCP connections, this configuration
+ * option can be turned off to reduce the code size of uIP.
+ *
+ * \hideinitializer
+ */
+#ifndef UIP_CONF_ACTIVE_OPEN
+#define UIP_ACTIVE_OPEN 1
+#else /* UIP_CONF_ACTIVE_OPEN */
+#define UIP_ACTIVE_OPEN (UIP_CONF_ACTIVE_OPEN)
+#endif /* UIP_CONF_ACTIVE_OPEN */
+
+/**
+ * The maximum number of simultaneously open TCP connections.
+ *
+ * Since the TCP connections are statically allocated, turning this
+ * configuration knob down results in less RAM used. Each TCP
+ * connection requires approximately 30 bytes of memory.
+ *
+ * \hideinitializer
+ */
+#ifndef UIP_CONF_MAX_CONNECTIONS
+#define UIP_CONNS       10
+#else /* UIP_CONF_MAX_CONNECTIONS */
+#define UIP_CONNS (UIP_CONF_MAX_CONNECTIONS)
+#endif /* UIP_CONF_MAX_CONNECTIONS */
+
+
+/**
+ * The maximum number of simultaneously listening TCP ports.
+ *
+ * Each listening TCP port requires 2 bytes of memory.
+ *
+ * \hideinitializer
+ */
+#ifndef UIP_CONF_MAX_LISTENPORTS
+#define UIP_LISTENPORTS 20
+#else /* UIP_CONF_MAX_LISTENPORTS */
+#define UIP_LISTENPORTS (UIP_CONF_MAX_LISTENPORTS)
+#endif /* UIP_CONF_MAX_LISTENPORTS */
+
+/**
+ * Determines if support for TCP urgent data notification should be
+ * compiled in.
+ *
+ * Urgent data (out-of-band data) is a rarely used TCP feature that
+ * very seldom would be required.
+ *
+ * \hideinitializer
+ */
+#define UIP_URGDATA      0
+
+/**
+ * The initial retransmission timeout counted in timer pulses.
+ *
+ * This should not be changed.
+ */
+#define UIP_RTO         3
+
+/**
+ * The maximum number of times a segment should be retransmitted
+ * before the connection should be aborted.
+ *
+ * This should not be changed.
+ */
+#define UIP_MAXRTX      8
+
+/**
+ * The maximum number of times a SYN segment should be retransmitted
+ * before a connection request should be deemed to have been
+ * unsuccessful.
+ *
+ * This should not need to be changed.
+ */
+#define UIP_MAXSYNRTX      5
+
+/**
+ * The TCP maximum segment size.
+ *
+ * This is should not be to set to more than
+ * UIP_BUFSIZE - UIP_LLH_LEN - UIP_TCPIP_HLEN.
+ */
+#ifdef UIP_CONF_TCP_MSS
+#if UIP_CONF_TCP_MSS > (UIP_BUFSIZE - UIP_LLH_LEN - UIP_TCPIP_HLEN)
+#error UIP_CONF_TCP_MSS is too large for the current UIP_BUFSIZE
+#endif /* UIP_CONF_TCP_MSS > (UIP_BUFSIZE - UIP_LLH_LEN - UIP_TCPIP_HLEN) */
+#define UIP_TCP_MSS     (UIP_CONF_TCP_MSS)
+#else /* UIP_CONF_TCP_MSS */
+#define UIP_TCP_MSS     (UIP_BUFSIZE - UIP_LLH_LEN - UIP_TCPIP_HLEN)
+#endif /* UIP_CONF_TCP_MSS */
+
+/**
+ * The size of the advertised receiver's window.
+ *
+ * Should be set low (i.e., to the size of the uip_buf buffer) if the
+ * application is slow to process incoming data, or high (32768 bytes)
+ * if the application processes data quickly.
+ *
+ * \hideinitializer
+ */
+#ifndef UIP_CONF_RECEIVE_WINDOW
+#define UIP_RECEIVE_WINDOW (UIP_TCP_MSS)
+#else
+#define UIP_RECEIVE_WINDOW (UIP_CONF_RECEIVE_WINDOW)
+#endif
+
+/**
+ * How long a connection should stay in the TIME_WAIT state.
+ *
+ * This can be reduced for faster entry into power saving modes.
+ */
+#ifndef UIP_CONF_WAIT_TIMEOUT
+#define UIP_TIME_WAIT_TIMEOUT 120
+#else
+#define UIP_TIME_WAIT_TIMEOUT UIP_CONF_WAIT_TIMEOUT
+#endif
+
+/** @} */
+/*------------------------------------------------------------------------------*/
+/**
+ * \defgroup uipoptarp ARP configuration options
+ * @{
+ */
+
+/**
+ * The size of the ARP table.
+ *
+ * This option should be set to a larger value if this uIP node will
+ * have many connections from the local network.
+ *
+ * \hideinitializer
+ */
+#ifdef UIP_CONF_ARPTAB_SIZE
+#define UIP_ARPTAB_SIZE (UIP_CONF_ARPTAB_SIZE)
+#else
+#define UIP_ARPTAB_SIZE 8
+#endif
+
+/**
+ * The maximum age of ARP table entries measured in 10ths of seconds.
+ *
+ * An UIP_ARP_MAXAGE of 120 corresponds to 20 minutes (BSD
+ * default).
+ */
+#define UIP_ARP_MAXAGE 120
+
+
+/** @} */
+
+/*------------------------------------------------------------------------------*/
+
+/**
+ * \defgroup uipoptmac layer 2 options (for ipv6)
+ * @{
+ */
+
+#define UIP_DEFAULT_PREFIX_LEN 64
+
+/** @} */
+
+/*------------------------------------------------------------------------------*/
+
+/**
+ * \defgroup uipoptsics 6lowpan options (for ipv6)
+ * @{
+ */
+/**
+ * Timeout for packet reassembly at the 6lowpan layer
+ * (should be < 60s)
+ */
+#ifdef SICSLOWPAN_CONF_MAXAGE
+#define SICSLOWPAN_REASS_MAXAGE (SICSLOWPAN_CONF_MAXAGE)
+#else
+#define SICSLOWPAN_REASS_MAXAGE 20
+#endif
+
+/**
+ * Do we compress the IP header or not (default: no)
+ */
+#ifndef SICSLOWPAN_CONF_COMPRESSION
+#define SICSLOWPAN_CONF_COMPRESSION 0
+#endif
+
+/**
+ * If we use IPHC compression, how many address contexts do we support
+ */
+#ifndef SICSLOWPAN_CONF_MAX_ADDR_CONTEXTS 
+#define SICSLOWPAN_CONF_MAX_ADDR_CONTEXTS 1
+#endif
+
+/**
+ * Do we support 6lowpan fragmentation
+ */
+#ifndef SICSLOWPAN_CONF_FRAG  
+#define SICSLOWPAN_CONF_FRAG  0
+#endif
+
+/** @} */
+
+/*------------------------------------------------------------------------------*/
+/**
+ * \defgroup uipoptcpu CPU architecture configuration
+ * @{
+ *
+ * The CPU architecture configuration is where the endianess of the
+ * CPU on which uIP is to be run is specified. Most CPUs today are
+ * little endian, and the most notable exception are the Motorolas
+ * which are big endian. The BYTE_ORDER macro should be changed to
+ * reflect the CPU architecture on which uIP is to be run.
+ */
+
+/**
+ * The byte order of the CPU architecture on which uIP is to be run.
+ *
+ * This option can be either UIP_BIG_ENDIAN (Motorola byte order) or
+ * UIP_LITTLE_ENDIAN (Intel byte order).
+ *
+ * \hideinitializer
+ */
+#ifdef UIP_CONF_BYTE_ORDER
+#define UIP_BYTE_ORDER     (UIP_CONF_BYTE_ORDER)
+#else /* UIP_CONF_BYTE_ORDER */
+#define UIP_BYTE_ORDER     (UIP_LITTLE_ENDIAN)
+#endif /* UIP_CONF_BYTE_ORDER */
+
+/** @} */
+/*------------------------------------------------------------------------------*/
+
+/**
+ * \defgroup uipoptapp Application specific configurations
+ * @{
+ *
+ * An uIP application is implemented using a single application
+ * function that is called by uIP whenever a TCP/IP event occurs. The
+ * name of this function must be registered with uIP at compile time
+ * using the UIP_APPCALL definition.
+ *
+ * uIP applications can store the application state within the
+ * uip_conn structure by specifying the type of the application
+ * structure by typedef:ing the type uip_tcp_appstate_t and uip_udp_appstate_t.
+ *
+ * The file containing the definitions must be included in the
+ * uipopt.h file.
+ *
+ * The following example illustrates how this can look.
+ \code
+
+ void httpd_appcall(void);
+ #define UIP_APPCALL     httpd_appcall
+
+ struct httpd_state {
+ uint8_t state;
+ uint16_t count;
+ char *dataptr;
+ char *script;
+ };
+ typedef struct httpd_state uip_tcp_appstate_t
+ \endcode
+*/
+
+/**
+ * \var #define UIP_APPCALL
+ *
+ * The name of the application function that uIP should call in
+ * response to TCP/IP events.
+ *
+ */
+
+/**
+ * \var typedef uip_tcp_appstate_t
+ *
+ * The type of the application state that is to be stored in the
+ * uip_conn structure. This usually is typedef:ed to a struct holding
+ * application state information.
+ */
+
+/**
+ * \var typedef uip_udp_appstate_t
+ *
+ * The type of the application state that is to be stored in the
+ * uip_conn structure. This usually is typedef:ed to a struct holding
+ * application state information.
+ */
+/** @} */
+
+#endif /* UIPOPT_H_ */
+/** @} */
+/** @} */
index b7abe27..90fa953 100644 (file)
@@ -46,6 +46,7 @@ image:
        $(CROSS_CC) $(CROSS_CCOPTS) -O0 -c -o ../bank16k.o ../bank16k.c
        $(CROSS_CC) $(CROSS_CCOPTS) -O0 -c -o devtty.o devtty.c
        $(CROSS_CC) $(CROSS_CCOPTS) -O0 -c -o ../timer.o ../timer.c
+       $(CROSS_CC) $(CROSS_CCOPTS) -O0 -c -o net_native.o ../dev/net/net_native.c
        $(CROSS_CC) $(CROSS_CC_VIDEO) $(CROSS_CCOPTS) -O0 -c -o video.o video.c
        $(CROSS_CC) $(CROSS_CC_VIDEO) $(CROSS_CCOPTS) -O0 -c -o ../usermem.o ../usermem.c
        $(CROSS_LD) -o ../fuzix.bin -Map=../fuzix.map --script=fuzix.link --oformat=decb \
index 4460352..c673340 100755 (executable)
@@ -37,6 +37,10 @@ cd ../dw
 make -f Makefile.6809 TARGET=coco3 clean
 make -f Makefile.6809 TARGET=coco3
 
+cd ../netd
+make -f Makefile.6809 TARGET=coco3 clean
+make -f Makefile.6809 TARGET=coco3
+
 # build sh
 cd ../../Applications/V7/cmd/sh
 make -f Makefile.6809 TARGET=coco3 clean
index e2a24ba..45c6003 100644 (file)
@@ -11,6 +11,7 @@
 #include <dwtime.h>
 #include <netdev.h>
 
+
 struct devsw dev_tab[] =  /* The device driver switch table */
 {
 // minor    open         close        read      write       ioctl
index f4f0663..af0b957 100644 (file)
@@ -86,7 +86,6 @@ uint8_t platform_param(char *p)
        return 0;
 }
 
-
 #ifdef CONFIG_LEVEL_2
 
 /* We always use 512 byte paths so no special pathbuf needed */
diff --git a/Library/include/sys/net_native.h b/Library/include/sys/net_native.h
new file mode 100644 (file)
index 0000000..5cc82c6
--- /dev/null
@@ -0,0 +1,75 @@
+#ifndef _DEV_NET_NET_NATIVE_H
+#define _DEV_NET_NET_NATIVE_H
+
+/* These are by socket and each one is
+
+   [RX.0][RX.1]..[RX.n][TX.0][TX.1]...[TX.n]
+
+*/
+
+#define NSOCKBUF       4       /* 4 buffers per socket */
+#define RINGSIZ                (1024 * NSOCKBUF)
+
+/* The usable space will be lower once the headers are added for addressing */
+#define TXPKTSIZ       1024
+#define RXPKTSIZ       1024
+
+#define SOCKBUFOFF     (2 * RINGSIZ)
+#define RXBUFOFF       RINGSIZ
+
+/* Total size is thus 8K * sockets - typically 64K for the file */
+
+
+struct sockdata {
+       void *socket;
+       uint8_t err;
+       uint8_t ret;
+       uint8_t event;          /* Waiting events to go to user space */
+#define NEV_STATE      1
+#define NEV_READ       2
+#define NEV_WRITE      4
+#define NEV_MASK       7
+#define NEVW_STATE     128
+       uint8_t newstate;       /* Requested new state */
+       uint8_t lcn;            /* Logical channel */
+       uint16_t rlen[NSOCKBUF];        /* TCP uses 0 as total space */
+       uint16_t rbuf;
+       uint16_t rnext;
+       uint16_t tlen[NSOCKBUF];        /* Not used by TCP */
+       uint16_t tbuf;          /* Next transmit buffer (pointer for tcp) */
+       uint16_t tnext;         /* Buffers of room (bytes if TCP) */
+};
+
+struct sockmsg {
+       struct socket s;
+       struct sockdata sd;
+};
+
+#define NE_NEWSTATE    1
+#define NE_EVENT       2
+#define NE_SETADDR     3
+#define NE_INIT                4
+#define NE_ROOM                5
+#define NE_DATA                6
+#define NE_SHUTR        7
+
+struct netevent {
+       uint8_t socket;
+       uint8_t event;
+       uint8_t ret;
+       uint16_t data;
+       union {
+               uint16_t rlen[NSOCKBUF];
+               struct sockaddrs addr;
+       } info;
+};
+
+#define NET_INIT       0x4401
+
+int netdev_write(void);
+int netdev_read(uint8_t flag);
+int netdev_ioctl(uint16_t request, char *data);
+int netdev_close(void);
+
+
+#endif