Added support for the FTP standalone client to the c64 target.
[contiki-2.x.git] / doc / uip-doc.txt
blobd84ae09161c9c1de38576bdef07a0d2985d34f7b
1 /**
2 \addtogroup net
3 @{
4 */
6 /**
7 \defgroup uip The uIP TCP/IP stack
8 @{
10 The uIP TCP/IP stack provides Internet communication abilities to
11 Contiki.
13 \section uip-introduction uIP introduction
15 The uIP TCP/IP stack is intended to make it possible to communicate
16 using the TCP/IP protocol suite even on small 8-bit
17 micro-controllers. Despite being small and simple, uIP do not require
18 their peers to have complex, full-size stacks, but can communicate
19 with peers running a similarly light-weight stack. The code size is on
20 the order of a few kilobytes and RAM usage can be configured to be as
21 low as a few hundred bytes.
23 uIP can be found at the uIP web page: http://www.sics.se/~adam/uip/
25 \sa \ref tcpip 
26 \sa \ref uip6 and sicslowpan
27 \sa \ref uipopt "uIP Compile-time configuration options"
28 \sa \ref uipconffunc "uIP Run-time configuration functions"
29 \sa \ref uipinit "uIP initialization functions"
30 \sa \ref uipdevfunc "uIP device driver interface" and
31     \ref uipdrivervars "uIP variables used by device drivers"
32 \sa \ref uipappfunc "uIP functions called from application programs"
33 (see below) and the \ref psock "protosockets API" and their underlying
34 \ref pt "protothreads" 
36 \section uIPIntroduction Introduction
38 With the success of the Internet, the TCP/IP protocol suite has become
39 a global standard for communication. TCP/IP is the underlying protocol
40 used for web page transfers, e-mail transmissions, file transfers, and
41 peer-to-peer networking over the Internet. For embedded systems, being
42 able to run native TCP/IP makes it possible to connect the system
43 directly to an intranet or even the global Internet. Embedded devices
44 with full TCP/IP support will be first-class network citizens, thus
45 being able to fully communicate with other hosts in the network.
47 Traditional TCP/IP implementations have required far too much
48 resources both in terms of code size and memory usage to be useful in
49 small 8 or 16-bit systems. Code size of a few hundred kilobytes and
50 RAM requirements of several hundreds of kilobytes have made it
51 impossible to fit the full TCP/IP stack into systems with a few tens
52 of kilobytes of RAM and room for less than 100 kilobytes of
53 code.
55 The uIP implementation is designed to have only the absolute minimal
56 set of features needed for a full TCP/IP stack. It can only handle a
57 single network interface and contains the IP, ICMP, UDP and TCP
58 protocols. uIP is written in the C programming language.
60 Many other TCP/IP implementations for small systems assume that the
61 embedded device always will communicate with a full-scale TCP/IP
62 implementation running on a workstation-class machine. Under this
63 assumption, it is possible to remove certain TCP/IP mechanisms that
64 are very rarely used in such situations. Many of those mechanisms are
65 essential, however, if the embedded device is to communicate with
66 another equally limited device, e.g., when running distributed
67 peer-to-peer services and protocols. uIP is designed to be RFC
68 compliant in order to let the embedded devices to act as first-class
69 network citizens. The uIP TCP/IP implementation that is not tailored
70 for any specific application.
73 \section uip-tcpip TCP/IP Communication
75 The full TCP/IP suite consists of numerous protocols, ranging from low
76 level protocols such as ARP which translates IP addresses to MAC
77 addresses, to application level protocols such as SMTP that is used to
78 transfer e-mail. The uIP is mostly concerned with the TCP and IP
79 protocols and upper layer protocols will be referred to as "the
80 application". Lower layer protocols are often implemented in hardware
81 or firmware and will be referred to as "the network device" that are
82 controlled by the network device driver.
84 TCP provides a reliable byte stream to the upper layer protocols. It
85 breaks the byte stream into appropriately sized segments and each
86 segment is sent in its own IP packet. The IP packets are sent out on
87 the network by the network device driver. If the destination is not on
88 the physically connected network, the IP packet is forwarded onto
89 another network by a router that is situated between the two
90 networks. If the maximum packet size of the other network is smaller
91 than the size of the IP packet, the packet is fragmented into smaller
92 packets by the router. If possible, the size of the TCP segments are
93 chosen so that fragmentation is minimized. The final recipient of the
94 packet will have to reassemble any fragmented IP packets before they
95 can be passed to higher layers.
97 The formal requirements for the protocols in the TCP/IP stack is
98 specified in a number of RFC documents published by the Internet
99 Engineering Task Force, IETF. Each of the protocols in the stack is
100 defined in one more RFC documents and RFC1122 collects
101 all requirements and updates the previous RFCs. 
103 The RFC1122 requirements can be divided into two categories; those
104 that deal with the host to host communication and those that deal with
105 communication between the application and the networking stack. An
106 example of the first kind is "A TCP MUST be able to receive a TCP
107 option in any segment" and an example of the second kind is "There
108 MUST be a mechanism for reporting soft TCP error conditions to the
109 application." A TCP/IP implementation that violates requirements of
110 the first kind may not be able to communicate with other TCP/IP
111 implementations and may even lead to network failures. Violation of
112 the second kind of requirements will only affect the communication
113 within the system and will not affect host-to-host communication.
115 In uIP, all RFC requirements that affect host-to-host communication
116 are implemented. However, in order to reduce code size, we have
117 removed certain mechanisms in the interface between the application
118 and the stack, such as the soft error reporting mechanism and
119 dynamically configurable type-of-service bits for TCP
120 connections. Since there are only very few applications that make use
121 of those features they can be removed without loss of generality.
123 \section mainloop Main Control Loop
125 The uIP stack can be run either as a task in a multitasking system, or
126 as the main program in a singletasking system. In both cases, the main
127 control loop does two things repeatedly:
129  - Check if a packet has arrived from the network.
130  - Check if a periodic timeout has occurred.
132 If a packet has arrived, the input handler function, uip_input(),
133 should be invoked by the main control loop. The input handler function
134 will never block, but will return at once. When it returns, the stack
135 or the application for which the incoming packet was intended may have
136 produced one or more reply packets which should be sent out. If so,
137 the network device driver should be called to send out these packets.
139 Periodic timeouts are used to drive TCP mechanisms that depend on
140 timers, such as delayed acknowledgments, retransmissions and
141 round-trip time estimations. When the main control loop infers that
142 the periodic timer should fire, it should invoke the timer handler
143 function uip_periodic(). Because the TCP/IP stack may perform
144 retransmissions when dealing with a timer event, the network device
145 driver should called to send out the packets that may have been produced.
147 \section arch Architecture Specific Functions
149 uIP requires a few functions to be implemented specifically for the
150 architecture on which uIP is intended to run. These functions should
151 be hand-tuned for the particular architecture, but generic C
152 implementations are given as part of the uIP distribution.
154 \subsection checksums Checksum Calculation
156 The TCP and IP protocols implement a checksum that covers the data and
157 header portions of the TCP and IP packets. Since the calculation of
158 this checksum is made over all bytes in every packet being sent and
159 received it is important that the function that calculates the
160 checksum is efficient. Most often, this means that the checksum
161 calculation must be fine-tuned for the particular architecture on
162 which the uIP stack runs.
164 While uIP includes a generic checksum function, it also leaves it open
165 for an architecture specific implementation of the two functions
166 uip_ipchksum() and uip_tcpchksum(). The checksum calculations in those
167 functions can be written in highly optimized assembler rather than
168 generic C code.
170 \subsection longarith 32-bit Arithmetic
172 The TCP protocol uses 32-bit sequence numbers, and a TCP
173 implementation will have to do a number of 32-bit additions as part of
174 the normal protocol processing. Since 32-bit arithmetic is not
175 natively available on many of the platforms for which uIP is intended,
176 uIP leaves the 32-bit additions to be implemented by the architecture
177 specific module and does not make use of any 32-bit arithmetic in the
178 main code base.
180 While uIP implements a generic 32-bit addition, there is support for
181 having an architecture specific implementation of the uip_add32()
182 function.
185 \section memory Memory Management
187 In the architectures for which uIP is intended, RAM is the most
188 scarce resource. With only a few kilobytes of RAM available for the
189 TCP/IP stack to use, mechanisms used in traditional TCP/IP cannot be
190 directly applied.
193 The uIP stack does not use explicit dynamic memory
194 allocation. Instead, it uses a single global buffer for holding
195 packets and has a fixed table for holding connection state. The global
196 packet buffer is large enough to contain one packet of maximum
197 size. When a packet arrives from the network, the device driver places
198 it in the global buffer and calls the TCP/IP stack. If the packet
199 contains data, the TCP/IP stack will notify the corresponding
200 application. Because the data in the buffer will be overwritten by the
201 next incoming packet, the application will either have to act
202 immediately on the data or copy the data into a secondary buffer for
203 later processing. The packet buffer will not be overwritten by new
204 packets before the application has processed the data. Packets that
205 arrive when the application is processing the data must be queued,
206 either by the network device or by the device driver. Most single-chip
207 Ethernet controllers have on-chip buffers that are large enough to
208 contain at least 4 maximum sized Ethernet frames. Devices that are
209 handled by the processor, such as RS-232 ports, can copy incoming
210 bytes to a separate buffer during application processing. If the
211 buffers are full, the incoming packet is dropped. This will cause
212 performance degradation, but only when multiple connections are
213 running in parallel. This is because uIP advertises a very small
214 receiver window, which means that only a single TCP segment will be in
215 the network per connection.
217 In uIP, the same global packet buffer that is used for incoming
218 packets is also used for the TCP/IP headers of outgoing data. If the
219 application sends dynamic data, it may use the parts of the global
220 packet buffer that are not used for headers as a temporary storage
221 buffer. To send the data, the application passes a pointer to the data
222 as well as the length of the data to the stack. The TCP/IP headers are
223 written into the global buffer and once the headers have been
224 produced, the device driver sends the headers and the application data
225 out on the network. The data is not queued for
226 retransmissions. Instead, the application will have to reproduce the
227 data if a retransmission is necessary.
229 The total amount of memory usage for uIP depends heavily on the
230 applications of the particular device in which the implementations are
231 to be run. The memory configuration determines both the amount of
232 traffic the system should be able to handle and the maximum amount of
233 simultaneous connections. A device that will be sending large e-mails
234 while at the same time running a web server with highly dynamic web
235 pages and multiple simultaneous clients, will require more RAM than a
236 simple Telnet server. It is possible to run the uIP implementation
237 with as little as 200 bytes of RAM, but such a configuration will
238 provide extremely low throughput and will only allow a small number of
239 simultaneous connections.
241 \section api Application Program Interface (API)
244 The Application Program Interface (API) defines the way the
245 application program interacts with the TCP/IP stack. The most commonly
246 used API for TCP/IP is the BSD socket API which is used in most Unix
247 systems and has heavily influenced the Microsoft Windows WinSock
248 API. Because the socket API uses stop-and-wait semantics, it requires
249 support from an underlying multitasking operating system. Since the
250 overhead of task management, context switching and allocation of stack
251 space for the tasks might be too high in the intended uIP target
252 architectures, the BSD socket interface is not suitable for our
253 purposes.
255 uIP provides two APIs to programmers: protosockets, a BSD socket-like
256 API without the overhead of full multi-threading, and a "raw"
257 event-based API that is nore low-level than protosockets but uses less
258 memory.
260 \sa \ref psock
261 \sa \ref pt
264 \subsection rawapi The uIP raw API
266 The "raw" uIP API uses an event driven interface where the application is
267 invoked in response to certain events. An application running on top
268 of uIP is implemented as a C function that is called by uIP in
269 response to certain events. uIP calls the application when data is
270 received, when data has been successfully delivered to the other end
271 of the connection, when a new connection has been set up, or when data
272 has to be retransmitted. The application is also periodically polled
273 for new data. The application program provides only one callback
274 function; it is up to the application to deal with mapping different
275 network services to different ports and connections. Because the
276 application is able to act on incoming data and connection requests as
277 soon as the TCP/IP stack receives the packet, low response times can
278 be achieved even in low-end systems.
280 uIP is different from other TCP/IP stacks in that it requires help
281 from the application when doing retransmissions. Other TCP/IP stacks
282 buffer the transmitted data in memory until the data is known to be
283 successfully delivered to the remote end of the connection. If the
284 data needs to be retransmitted, the stack takes care of the
285 retransmission without notifying the application. With this approach,
286 the data has to be buffered in memory while waiting for an
287 acknowledgment even if the application might be able to quickly
288 regenerate the data if a retransmission has to be made.
290 In order to reduce memory usage, uIP utilizes the fact that the
291 application may be able to regenerate sent data and lets the
292 application take part in retransmissions. uIP does not keep track of
293 packet contents after they have been sent by the device driver, and
294 uIP requires that the application takes an active part in performing
295 the retransmission. When uIP decides that a segment should be
296 retransmitted, it calls the application with a flag set indicating
297 that a retransmission is required. The application checks the
298 retransmission flag and produces the same data that was previously
299 sent. From the application's standpoint, performing a retransmission
300 is not different from how the data originally was sent. Therefore the
301 application can be written in such a way that the same code is used
302 both for sending data and retransmitting data. Also, it is important
303 to note that even though the actual retransmission operation is
304 carried out by the application, it is the responsibility of the stack
305 to know when the retransmission should be made. Thus the complexity of
306 the application does not necessarily increase because it takes an
307 active part in doing retransmissions.
309 \subsubsection appevents Application Events
311 The application must be implemented as a C function, UIP_APPCALL(),
312 that uIP calls whenever an event occurs. Each event has a corresponding
313 test function that is used to distinguish between different
314 events. The functions are implemented as C macros that will evaluate
315 to either zero or non-zero. Note that certain events can happen in
316 conjunction with each other (i.e., new data can arrive at the same
317 time as data is acknowledged).
319 \subsubsection connstate The Connection Pointer
321 When the application is called by uIP, the global variable uip_conn is
322 set to point to the uip_conn structure for the connection that
323 currently is handled, and is called the "current connection". The
324 fields in the uip_conn structure for the current connection can be
325 used, e.g., to distinguish between different services, or to check to
326 which IP address the connection is connected. One typical use would be
327 to inspect the uip_conn->lport (the local TCP port number) to decide
328 which service the connection should provide. For instance, an
329 application might decide to act as an HTTP server if the value of
330 uip_conn->lport is equal to 80 and act as a TELNET server if the value
331 is 23. 
333 \subsubsection recvdata Receiving Data
335 If the uIP test function uip_newdata() is non-zero, the remote host of
336 the connection has sent new data. The uip_appdata pointer point to the
337 actual data. The size of the data is obtained through the uIP function
338 uip_datalen(). The data is not buffered by uIP, but will be
339 overwritten after the application function returns, and the
340 application will therefor have to either act directly on the incoming
341 data, or by itself copy the incoming data into a buffer for later
342 processing.
344 \subsubsection senddata Sending Data
346 When sending data, uIP adjusts the length of the data sent by the
347 application according to the available buffer space and the current
348 TCP window advertised by the receiver. The amount of buffer space is
349 dictated by the memory configuration. It is therefore possible that
350 all data sent from the application does not arrive at the receiver,
351 and the application may use the uip_mss() function to see how much
352 data that actually will be sent by the stack.
354 The application sends data by using the uIP function uip_send(). The
355 uip_send() function takes two arguments; a pointer to the data to be
356 sent and the length of the data. If the application needs RAM space
357 for producing the actual data that should be sent, the packet buffer
358 (pointed to by the uip_appdata pointer) can be used for this purpose.
360 The application can send only one chunk of data at a time on a
361 connection and it is not possible to call uip_send() more than once
362 per application invocation; only the data from the last call will be
363 sent.
365 \subsubsection rexmitdata Retransmitting Data
367 Retransmissions are driven by the periodic TCP timer. Every time the
368 periodic timer is invoked, the retransmission timer for each
369 connection is decremented. If the timer reaches zero, a retransmission
370 should be made. As uIP does not keep track of packet contents after they have
371 been sent by the device driver, uIP requires that the
372 application takes an active part in performing the
373 retransmission. When uIP decides that a segment should be
374 retransmitted, the application function is called with the
375 uip_rexmit() flag set, indicating that a retransmission is
376 required.
378 The application must check the uip_rexmit() flag and produce the same
379 data that was previously sent. From the application's standpoint,
380 performing a retransmission is not different from how the data
381 originally was sent. Therefor, the application can be written in such
382 a way that the same code is used both for sending data and
383 retransmitting data. Also, it is important to note that even though
384 the actual retransmission operation is carried out by the application,
385 it is the responsibility of the stack to know when the retransmission
386 should be made. Thus the complexity of the application does not
387 necessarily increase because it takes an active part in doing
388 retransmissions.
390 \subsubsection closing Closing Connections
392 The application closes the current connection by calling the
393 uip_close() during an application call. This will cause the connection
394 to be cleanly closed. In order to indicate a fatal error, the
395 application might want to abort the connection and does so by calling
396 the uip_abort() function.
398 If the connection has been closed by the remote end, the test function
399 uip_closed() is true. The application may then do any necessary
400 cleanups.
402 \subsubsection errors Reporting Errors
404 There are two fatal errors that can happen to a connection, either
405 that the connection was aborted by the remote host, or that the
406 connection retransmitted the last data too many times and has been
407 aborted. uIP reports this by calling the application function. The
408 application can use the two test functions uip_aborted() and
409 uip_timedout() to test for those error conditions.
411 \subsubsection polling Polling
413 When a connection is idle, uIP polls the application every time the
414 periodic timer fires. The application uses the test function
415 uip_poll() to check if it is being polled by uIP.
417 The polling event has two purposes. The first is to let the
418 application periodically know that a connection is idle, which allows
419 the application to close connections that have been idle for too
420 long. The other purpose is to let the application send new data that
421 has been produced. The application can only send data when invoked by
422 uIP, and therefore the poll event is the only way to send data on an
423 otherwise idle connection.
425 \subsubsection listen Listening Ports
427 uIP maintains a list of listening TCP ports. A new port is opened for
428 listening with the uip_listen() function. When a connection request
429 arrives on a listening port, uIP creates a new connection and calls
430 the application function. The test function uip_connected() is true if
431 the application was invoked because a new connection was created.
433 The application can check the lport field in the uip_conn structure to
434 check to which port the new connection was connected.
436 \subsubsection connect Opening Connections
438 New connections can be opened from within
439 uIP by the function uip_connect(). This function
440 allocates a new connection and sets a flag in the connection state
441 which will open a TCP connection to the specified IP address and port
442 the next time the connection is polled by uIP. The uip_connect()
443 function returns
444 a pointer to the uip_conn structure for the new
445 connection. If there are no free connection slots, the function
446 returns NULL. 
448 The function uip_ipaddr() may be used to pack an IP address into the
449 two element 16-bit array used by uIP to represent IP addresses.
451 Two examples of usage are shown below. The first example shows how to
452 open a connection to TCP port 8080 of the remote end of the current
453 connection. If there are not enough TCP connection slots to allow a
454 new connection to be opened, the uip_connect() function returns NULL
455 and the current connection is aborted by uip_abort(). 
457 \code
458 void connect_example1_app(void) {
459    if(uip_connect(uip_conn->ripaddr, HTONS(8080)) == NULL) {
460       uip_abort();
461    }
462 }   
463 \endcode
465 The second example shows how to open a new connection to a specific IP
466 address. No error checks are made in this example.
468 \code
469 void connect_example2(void) {
470    uip_addr_t ipaddr;
472    uip_ipaddr(ipaddr, 192,168,0,1);
473    uip_connect(ipaddr, HTONS(8080));
475 \endcode
477 \section examples Examples
479 This section presents a number of very simple uIP applications. The
480 uIP code distribution contains several more complex applications.
482 \subsection example1 A Very Simple Application
484 This first example shows a very simple application. The application
485 listens for incoming connections on port 1234. When a connection has
486 been established, the application replies to all data sent to it by
487 saying "ok"
489 The implementation of this application is shown below. The application
490 is initialized with the function called example1_init() and the uIP
491 callback function is called example1_app(). For this application, the
492 configuration variable UIP_APPCALL should be defined to be
493 example1_app().
495 \code
496 void example1_init(void) {
497    uip_listen(HTONS(1234));
500 void example1_app(void) {
501    if(uip_newdata() || uip_rexmit()) {
502       uip_send("ok\n", 3);
503    }
505 \endcode
507 The initialization function calls the uIP function uip_listen() to
508 register a listening port. The actual application function
509 example1_app() uses the test functions uip_newdata() and uip_rexmit()
510 to determine why it was called. If the application was called because
511 the remote end has sent it data, it responds with an "ok". If the
512 application function was called because data was lost in the network
513 and has to be retransmitted, it also sends an "ok".  Note that this
514 example actually shows a complete uIP application. It is not required
515 for an application to deal with all types of events such as
516 uip_connected() or uip_timedout(). 
518 \subsection example2 A More Advanced Application
520 This second example is slightly more advanced than the previous one,
521 and shows how the application state field in the uip_conn structure is
522 used.
524 This application is similar to the first application in that it
525 listens to a port for incoming connections and responds to data sent
526 to it with a single "ok". The big difference is that this application
527 prints out a welcoming "Welcome!" message when the connection has been
528 established.
530 This seemingly small change of operation makes a big difference in how
531 the application is implemented. The reason for the increase in
532 complexity is that if data should be lost in the network, the
533 application must know what data to retransmit. If the "Welcome!"
534 message was lost, the application must retransmit the welcome and if
535 one of the "ok" messages is lost, the application must send a new
536 "ok".
538 The application knows that as long as the "Welcome!" message has not
539 been acknowledged by the remote host, it might have been dropped in
540 the network. But once the remote host has sent an acknowledgment
541 back, the application can be sure that the welcome has been received
542 and knows that any lost data must be an "ok" message. Thus the
543 application can be in either of two states: either in the WELCOME-SENT
544 state where the "Welcome!" has been sent but not acknowledged, or in
545 the WELCOME-ACKED state where the "Welcome!" has been acknowledged.
547 When a remote host connects to the application, the application sends
548 the "Welcome!" message and sets it's state to WELCOME-SENT. When the
549 welcome message is acknowledged, the application moves to the
550 WELCOME-ACKED state. If the application receives any new data from the
551 remote host, it responds by sending an "ok" back.
553 If the application is requested to retransmit the last message, it
554 looks at in which state the application is. If the application is in
555 the WELCOME-SENT state, it sends a "Welcome!"  message since it
556 knows that the previous welcome message hasn't been acknowledged. If
557 the application is in the WELCOME-ACKED state, it knows that the last
558 message was an "ok" message and sends such a message.
560 The implementation of this application is seen below. This
561 configuration settings for the application is follows after its
562 implementation.
564 \code
565 struct example2_state {
566    enum {WELCOME_SENT, WELCOME_ACKED} state;
569 void example2_init(void) {
570    uip_listen(HTONS(2345));
573 void example2_app(void) {
574    struct example2_state *s;
576    s = (struct example2_state *)uip_conn->appstate;
577    
578    if(uip_connected()) {
579       s->state = WELCOME_SENT;
580       uip_send("Welcome!\n", 9);
581       return;
582    } 
584    if(uip_acked() && s->state == WELCOME_SENT) {
585       s->state = WELCOME_ACKED;
586    }
588    if(uip_newdata()) {
589       uip_send("ok\n", 3);
590    }
592    if(uip_rexmit()) {
593       switch(s->state) {
594       case WELCOME_SENT:
595          uip_send("Welcome!\n", 9);
596          break;
597       case WELCOME_ACKED:
598          uip_send("ok\n", 3);
599          break;
600       }
601    }
603 \endcode
605 The configuration for the application:
607 \code
608 #define UIP_APPCALL       example2_app
609 #define UIP_APPSTATE_SIZE sizeof(struct example2_state)
610 \endcode
612 \subsection example3 Differentiating Between Applications
614 If the system should run multiple applications, one technique to
615 differentiate between them is to use the TCP port number of either the
616 remote end or the local end of the connection. The example below shows
617 how the two examples above can be combined into one application.
619 \code
620 void example3_init(void) {
621    example1_init();
622    example2_init();   
625 void example3_app(void) {
626    switch(uip_conn->lport) {
627    case HTONS(1234):
628       example1_app();
629       break;
630    case HTONS(2345):
631       example2_app();
632       break;
633    }
635 \endcode
637 \subsection example4 Utilizing TCP Flow Control
639 This example shows a simple application that connects to a host, sends
640 an HTTP request for a file and downloads it to a slow device such a
641 disk drive. This shows how to use the flow control functions of uIP.
643 \code
644 void example4_init(void) {
645    uip_ipaddr_t ipaddr;
646    uip_ipaddr(ipaddr, 192,168,0,1);
647    uip_connect(ipaddr, HTONS(80));
650 void example4_app(void) {
651    if(uip_connected() || uip_rexmit()) {
652       uip_send("GET /file HTTP/1.0\r\nServer:192.186.0.1\r\n\r\n",
653                48);
654       return;
655    }
657    if(uip_newdata()) {
658       device_enqueue(uip_appdata, uip_datalen());
659       if(device_queue_full()) {
660          uip_stop();
661       }
662    }
664    if(uip_poll() && uip_stopped()) {
665       if(!device_queue_full()) {
666          uip_restart();
667       }
668    }
670 \endcode
672 When the connection has been established, an HTTP request is sent to
673 the server. Since this is the only data that is sent, the application
674 knows that if it needs to retransmit any data, it is that request that
675 should be retransmitted. It is therefore possible to combine these two
676 events as is done in the example.
678 When the application receives new data from the remote host, it sends
679 this data to the device by using the function device_enqueue(). It is
680 important to note that this example assumes that this function copies
681 the data into its own buffers. The data in the uip_appdata buffer will
682 be overwritten by the next incoming packet.
684 If the device's queue is full, the application stops the data from the
685 remote host by calling the uIP function uip_stop(). The application
686 can then be sure that it will not receive any new data until
687 uip_restart() is called. The application polling event is used to
688 check if the device's queue is no longer full and if so, the data flow
689 is restarted with uip_restart().
691 \subsection example5 A Simple Web Server
693 This example shows a very simple file server application that listens
694 to two ports and uses the port number to determine which file to
695 send. If the files are properly formatted, this simple application can
696 be used as a web server with static pages. The implementation follows.
698 \code
699 struct example5_state {
700    char *dataptr;
701    unsigned int dataleft;
704 void example5_init(void) {
705    uip_listen(HTONS(80));
706    uip_listen(HTONS(81));
709 void example5_app(void) {
710    struct example5_state *s;
711    s = (struct example5_state)uip_conn->appstate;
712    
713    if(uip_connected()) {
714       switch(uip_conn->lport) {
715       case HTONS(80):
716          s->dataptr = data_port_80;
717          s->dataleft = datalen_port_80;
718          break;
719       case HTONS(81):
720          s->dataptr = data_port_81;
721          s->dataleft = datalen_port_81;
722          break;
723       }
724       uip_send(s->dataptr, s->dataleft);
725       return;      
726    }
728    if(uip_acked()) {
729       if(s->dataleft < uip_mss()) {
730          uip_close();
731          return;
732       }
733       s->dataptr += uip_conn->len;
734       s->dataleft -= uip_conn->len;
735       uip_send(s->dataptr, s->dataleft);      
736    }
738 \endcode
740 The application state consists of a pointer to the data that should be
741 sent and the size of the data that is left to send. When a remote host
742 connects to the application, the local port number is used to
743 determine which file to send. The first chunk of data is sent using
744 uip_send(). uIP makes sure that no more than MSS bytes of data is
745 actually sent, even though s->dataleft may be larger than the MSS. 
747 The application is driven by incoming acknowledgments. When data has
748 been acknowledged, new data can be sent. If there is no more data to
749 send, the connection is closed using uip_close().
751 \subsection example6 Structured Application Program Design
753 When writing larger programs using uIP it is useful to be able to
754 utilize the uIP API in a structured way. The following example
755 provides a structured design that has showed itself to be useful for
756 writing larger protocol implementations than the previous examples
757 showed here. The program is divided into an uIP event handler function
758 that calls seven application handler functions that process new data,
759 act on acknowledged data, send new data, deal with connection
760 establishment or closure events and handle errors. The functions are
761 called newdata(), acked(), senddata(), connected(), closed(),
762 aborted(), and timedout(), and needs to be written specifically for
763 the protocol that is being implemented.
765 The uIP event handler function is shown below.
767 \code
768 void example6_app(void) {
769   if(uip_aborted()) {
770     aborted();
771   }
772   if(uip_timedout()) {
773     timedout();
774   }
775   if(uip_closed()) {
776     closed();
777   }
778   if(uip_connected()) {
779     connected();
780   }
781   if(uip_acked()) {
782     acked();
783   }
784   if(uip_newdata()) {
785     newdata();
786   }
787   if(uip_rexmit() ||
788      uip_newdata() ||
789      uip_acked() ||
790      uip_connected() ||
791      uip_poll()) {
792     senddata();
793   }
795 \endcode
797 The function starts with dealing with any error conditions that might
798 have happened by checking if uip_aborted() or uip_timedout() are
799 true. If so, the appropriate error function is called. Also, if the
800 connection has been closed, the closed() function is called to the it
801 deal with the event.
803 Next, the function checks if the connection has just been established
804 by checking if uip_connected() is true. The connected() function is
805 called and is supposed to do whatever needs to be done when the
806 connection is established, such as intializing the application state
807 for the connection. Since it may be the case that data should be sent
808 out, the senddata() function is called to deal with the outgoing data.
810 The following very simple application serves as an example of how the
811 application handler functions might look. This application simply
812 waits for any data to arrive on the connection, and responds to the
813 data by sending out the message "Hello world!". To illustrate how to
814 develop an application state machine, this message is sent in two
815 parts, first the "Hello" part and then the "world!" part.
817 \code
818 #define STATE_WAITING 0
819 #define STATE_HELLO   1
820 #define STATE_WORLD   2
822 struct example6_state {
823   u8_t state;
824   char *textptr;
825   int  textlen;
828 static void aborted(void) {}
829 static void timedout(void) {}
830 static void closed(void) {}
832 static void connected(void) {
833   struct example6_state *s = (struct example6_state *)uip_conn->appstate;
835   s->state   = STATE_WAITING;
836   s->textlen = 0;
839 static void newdata(void) {
840   struct example6_state *s = (struct example6_state *)uip_conn->appstate;
842   if(s->state == STATE_WAITING) {
843     s->state   = STATE_HELLO;
844     s->textptr = "Hello ";
845     s->textlen = 6;
846   }
849 static void acked(void) {
850   struct example6_state *s = (struct example6_state *)uip_conn->appstate;
851   
852   s->textlen -= uip_conn->len;
853   s->textptr += uip_conn->len;
854   if(s->textlen == 0) {
855     switch(s->state) {
856     case STATE_HELLO:
857       s->state   = STATE_WORLD;
858       s->textptr = "world!\n";
859       s->textlen = 7;
860       break;
861     case STATE_WORLD:
862       uip_close();
863       break;
864     }
865   }
868 static void senddata(void) {
869   struct example6_state *s = (struct example6_state *)uip_conn->appstate;
871   if(s->textlen > 0) {
872     uip_send(s->textptr, s->textlen);
873   }
875 \endcode
877 The application state consists of a "state" variable, a "textptr"
878 pointer to a text message and the "textlen" length of the text
879 message. The "state" variable can be either "STATE_WAITING", meaning
880 that the application is waiting for data to arrive from the network,
881 "STATE_HELLO", in which the application is sending the "Hello" part of
882 the message, or "STATE_WORLD", in which the application is sending the
883 "world!" message. 
885 The application does not handle errors or connection closing events,
886 and therefore the aborted(), timedout() and closed() functions are
887 implemented as empty functions.
889 The connected() function will be called when a connection has been
890 established, and in this case sets the "state" variable to be
891 "STATE_WAITING" and the "textlen" variable to be zero, indicating that
892 there is no message to be sent out.
894 When new data arrives from the network, the newdata() function will be
895 called by the event handler function. The newdata() function will
896 check if the connection is in the "STATE_WAITING" state, and if so
897 switches to the "STATE_HELLO" state and registers a 6 byte long "Hello
898 " message with the connection. This message will later be sent out by
899 the senddata() function.
901 The acked() function is called whenever data that previously was sent
902 has been acknowleged by the receiving host. This acked() function
903 first reduces the amount of data that is left to send, by subtracting
904 the length of the previously sent data (obtained from "uip_conn->len")
905 from the "textlen" variable, and also adjusts the "textptr" pointer
906 accordingly. It then checks if the "textlen" variable now is zero,
907 which indicates that all data now has been successfully received, and
908 if so changes application state. If the application was in the
909 "STATE_HELLO" state, it switches state to "STATE_WORLD" and sets up a
910 7 byte "world!\n" message to be sent. If the application was in the
911 "STATE_WORLD" state, it closes the connection.
913 Finally, the senddata() function takes care of actually sending the
914 data that is to be sent. It is called by the event handler function
915 when new data has been received, when data has been acknowledged, when
916 a new connection has been established, when the connection is polled
917 because of inactivity, or when a retransmission should be made. The
918 purpose of the senddata() function is to optionally format the data
919 that is to be sent, and to call the uip_send() function to actually
920 send out the data. In this particular example, the function simply
921 calls uip_send() with the appropriate arguments if data is to be sent,
922 after checking if data should be sent out or not as indicated by the
923 "textlen" variable.
925 It is important to note that the senddata() function never should
926 affect the application state; this should only be done in the acked()
927 and newdata() functions.
929 \section protoimpl Protocol Implementations
931 The protocols in the TCP/IP protocol suite are designed in a layered
932 fashion where each protocol performs a specific function and the
933 interactions between the protocol layers are strictly defined. While
934 the layered approach is a good way to design protocols, it is not
935 always the best way to implement them. In uIP, the protocol
936 implementations are tightly coupled in order to save code space.
938 This section gives detailed information on the specific protocol
939 implementations in uIP.
941 \subsection ip IP --- Internet Protocol
943 When incoming packets are processed by uIP, the IP layer is the first
944 protocol that examines the packet. The IP layer does a few simple
945 checks such as if the destination IP address of the incoming packet
946 matches any of the local IP address and verifies the IP header
947 checksum. Since there are no IP options that are strictly required and
948 because they are very uncommon, any IP options in received packets are
949 dropped.
951 \subsubsection ipreass IP Fragment Reassembly
953 IP fragment reassembly is implemented using a separate buffer that
954 holds the packet to be reassembled. An incoming fragment is copied
955 into the right place in the buffer and a bit map is used to keep track
956 of which fragments have been received. Because the first byte of an IP
957 fragment is aligned on an 8-byte boundary, the bit map requires a
958 small amount of memory. When all fragments have been reassembled, the
959 resulting IP packet is passed to the transport layer. If all fragments
960 have not been received within a specified time frame, the packet is
961 dropped.
963 The current implementation only has a single buffer for holding
964 packets to be reassembled, and therefore does not support simultaneous
965 reassembly of more than one packet. Since fragmented packets are
966 uncommon, this ought to be a reasonable decision. Extending the
967 implementation to support multiple buffers would be straightforward,
968 however.
970 \subsubsection ipbroadcast Broadcasts and Multicasts
972 IP has the ability to broadcast and multicast packets on the local
973 network. Such packets are addressed to special broadcast and multicast
974 addresses. Broadcast is used heavily in many UDP based protocols such
975 as the Microsoft Windows file-sharing SMB protocol. Multicast is
976 primarily used in protocols used for multimedia distribution such as
977 RTP. TCP is a point-to-point protocol and does not use broadcast or
978 multicast packets. uIP current supports broadcast packets as well as
979 sending multicast packets. Joining multicast groups (IGMP) and
980 receiving non-local multicast packets is not currently supported.
982 \subsection icmp ICMP --- Internet Control Message Protocol
984 The ICMP protocol is used for reporting soft error conditions and for
985 querying host parameters. Its main use is, however, the echo mechanism
986 which is used by the "ping" program.
988 The ICMP implementation in uIP is very simple as itis restricted to
989 only implement ICMP echo messages. Replies to echo messages are
990 constructed by simply swapping the source and destination IP addresses
991 of incoming echo requests and rewriting the ICMP header with the
992 Echo-Reply message type. The ICMP checksum is adjusted using standard
993 techniques (see RFC1624).
995 Since only the ICMP echo message is implemented, there is no support
996 for Path MTU discovery or ICMP redirect messages. Neither of these is
997 strictly required for interoperability; they are performance
998 enhancement mechanisms.
1000 \subsection tcp TCP --- Transmission Control Protocol
1002 The TCP implementation in uIP is driven by incoming packets and timer
1003 events. Incoming packets are parsed by TCP and if the packet contains
1004 data that is to be delivered to the application, the application is
1005 invoked by the means of the application function call. If the incoming
1006 packet acknowledges previously sent data, the connection state is
1007 updated and the application is informed, allowing it to send out new
1008 data.
1010 \subsubsection listeb Listening Connections
1012 TCP allows a connection to listen for incoming connection requests. In
1013 uIP, a listening connection is identified by the 16-bit port number
1014 and incoming connection requests are checked against the list of
1015 listening connections. This list of listening connections is dynamic
1016 and can be altered by the applications in the system.
1018 \subsubsection slidingwindow Sliding Window
1020 Most TCP implementations use a sliding window mechanism for sending
1021 data. Multiple data segments are sent in succession without waiting
1022 for an acknowledgment for each segment.
1024 The sliding window algorithm uses a lot of 32-bit operations and
1025 because 32-bit arithmetic is fairly expensive on most 8-bit CPUs, uIP
1026 does not implement it. Also, uIP does not buffer sent packets and a
1027 sliding window implementation that does not buffer sent packets will have
1028 to be supported by a complex application layer. Instead, uIP allows
1029 only a single TCP segment per connection to be unacknowledged at any
1030 given time.
1032 It is important to note that even though most TCP implementations use
1033 the sliding window algorithm, it is not required by the TCP
1034 specifications. Removing the sliding window mechanism does not affect
1035 interoperability in any way.
1037 \subsubsection rttest Round-Trip Time Estimation
1039 TCP continuously estimates the current Round-Trip Time (RTT) of every
1040 active connection in order to find a suitable value for the
1041 retransmission time-out.
1043 The RTT estimation in uIP is implemented using TCP's periodic
1044 timer. Each time the periodic timer fires, it increments a counter for
1045 each connection that has unacknowledged data in the network. When an
1046 acknowledgment is received, the current value of the counter is used
1047 as a sample of the RTT. The sample is used together with Van
1048 Jacobson's standard TCP RTT estimation function to calculate an
1049 estimate of the RTT. Karn's algorithm is used to ensure that
1050 retransmissions do not skew the estimates.
1052 \subsubsection rexmit Retransmissions
1054 Retransmissions are driven by the periodic TCP timer. Every time the
1055 periodic timer is invoked, the retransmission timer for each
1056 connection is decremented. If the timer reaches zero, a retransmission
1057 should be made.
1059 As uIP does not keep track of packet contents after they have
1060 been sent by the device driver, uIP requires that the
1061 application takes an active part in performing the
1062 retransmission. When uIP decides that a segment should be
1063 retransmitted, it calls the application with a flag set indicating
1064 that a retransmission is required. The application checks the
1065 retransmission flag and produces the same data that was previously
1066 sent. From the application's standpoint, performing a retransmission
1067 is not different from how the data originally was sent. Therefore the
1068 application can be written in such a way that the same code is used
1069 both for sending data and retransmitting data. Also, it is important
1070 to note that even though the actual retransmission operation is
1071 carried out by the application, it is the responsibility of the stack
1072 to know when the retransmission should be made. Thus the complexity of
1073 the application does not necessarily increase because it takes an
1074 active part in doing retransmissions.
1076 \subsubsection flowcontrol Flow Control
1078 The purpose of TCP's flow control mechanisms is to allow communication
1079 between hosts with wildly varying memory dimensions. In each TCP
1080 segment, the sender of the segment indicates its available buffer
1081 space. A TCP sender must not send more data than the buffer space
1082 indicated by the receiver.
1084 In uIP, the application cannot send more data than the receiving host
1085 can buffer. And application cannot send more data than the amount of
1086 bytes it is allowed to send by the receiving host. If the remote host
1087 cannot accept any data at all, the stack initiates the zero window
1088 probing mechanism.
1090 \subsubsection congestioncontrol Congestion Control
1092 The congestion control mechanisms limit the number of simultaneous TCP
1093 segments in the network. The algorithms used for congestion control
1094 are designed to be simple to implement and require only a few lines of
1095 code.
1097 Since uIP only handles one in-flight TCP segment per connection,
1098 the amount of simultaneous segments cannot be further limited, thus
1099 the congestion control mechanisms are not needed.
1101 \subsubsection urgdata Urgent Data
1103 TCP's urgent data mechanism provides an application-to-application
1104 notification mechanism, which can be used by an application to mark
1105 parts of the data stream as being more urgent than the normal
1106 stream. It is up to the receiving application to interpret the meaning
1107 of the urgent data.
1109 In many TCP implementations, including the BSD implementation, the
1110 urgent data feature increases the complexity of the implementation
1111 because it requires an asynchronous notification mechanism in an
1112 otherwise synchronous API. As uIP already use an asynchronous event
1113 based API, the implementation of the urgent data feature does not lead
1114 to increased complexity.
1116 \section performance Performance
1118 In TCP/IP implementations for high-end systems, processing time is
1119 dominated by the checksum calculation loop, the operation of copying
1120 packet data and context switching. Operating systems for high-end
1121 systems often have multiple protection domains for protecting kernel
1122 data from user processes and user processes from each other. Because
1123 the TCP/IP stack is run in the kernel, data has to be copied between
1124 the kernel space and the address space of the user processes and a
1125 context switch has to be performed once the data has been
1126 copied. Performance can be enhanced by combining the copy operation
1127 with the checksum calculation. Because high-end systems usually have
1128 numerous active connections, packet demultiplexing is also an
1129 expensive operation.
1131 A small embedded device does not have the necessary processing power
1132 to have multiple protection domains and the power to run a
1133 multitasking operating system. Therefore there is no need to copy
1134 data between the TCP/IP stack and the application program. With an
1135 event based API there is no context switch between the TCP/IP stack
1136 and the applications.
1138 In such limited systems, the TCP/IP processing overhead is dominated
1139 by the copying of packet data from the network device to host memory,
1140 and checksum calculation. Apart from the checksum calculation and
1141 copying, the TCP processing done for an incoming packet involves only
1142 updating a few counters and flags before handing the data over to the
1143 application. Thus an estimate of the CPU overhead of our TCP/IP
1144 implementations can be obtained by calculating the amount of CPU
1145 cycles needed for the checksum calculation and copying of a maximum
1146 sized packet.
1148 \subsection delack The Impact of Delayed Acknowledgments
1150 Most TCP receivers implement the delayed acknowledgment algorithm for
1151 reducing the number of pure acknowledgment packets sent. A TCP
1152 receiver using this algorithm will only send acknowledgments for every
1153 other received segment. If no segment is received within a specific
1154 time-frame, an acknowledgment is sent. The time-frame can be as high
1155 as 500 ms but typically is 200 ms.
1157 A TCP sender such as uIP that only handles a single outstanding TCP
1158 segment will interact poorly with the delayed acknowledgment
1159 algorithm. Because the receiver only receives a single segment at a
1160 time, it will wait as much as 500 ms before an acknowledgment is
1161 sent. This means that the maximum possible throughput is severely
1162 limited by the 500 ms idle time.
1164 Thus the maximum throughput equation when sending data from uIP will
1165 be $p = s / (t + t_d)$ where $s$ is the segment size and $t_d$ is the
1166 delayed acknowledgment timeout, which typically is between 200 and
1167 500 ms. With a segment size of 1000 bytes, a round-trip time of 40 ms
1168 and a delayed acknowledgment timeout of 200 ms, the maximum
1169 throughput will be 4166 bytes per second. With the delayed acknowledgment
1170 algorithm disabled at the receiver, the maximum throughput would be
1171 25000 bytes per second.
1173 It should be noted, however, that since small systems running uIP are
1174 not very likely to have large amounts of data to send, the delayed
1175 acknowledgmen t throughput degradation of uIP need not be very
1176 severe. Small amounts of data sent by such a system will not span more
1177 than a single TCP segment, and would therefore not be affected by the
1178 throughput degradation anyway.
1180 The maximum throughput when uIP acts as a receiver is not affected by
1181 the delayed acknowledgment throughput degradation.
1183 \note The \ref uipsplit module implements a hack that overcomes the
1184 problems with the delayed acknowledgment throughput degradation.
1190 /** @} */
1191 /** @} */