Commit for the 090810 release.
[pub/USBasp.git] / Demos / Device / ClassDriver / RNDISEthernet / Lib / TCP.c
1 /*
2 LUFA Library
3 Copyright (C) Dean Camera, 2009.
4
5 dean [at] fourwalledcubicle [dot] com
6 www.fourwalledcubicle.com
7 */
8
9 /*
10 Copyright 2009 Dean Camera (dean [at] fourwalledcubicle [dot] com)
11
12 Permission to use, copy, modify, and distribute this software
13 and its documentation for any purpose and without fee is hereby
14 granted, provided that the above copyright notice appear in all
15 copies and that both that the copyright notice and this
16 permission notice and warranty disclaimer appear in supporting
17 documentation, and that the name of the author not be used in
18 advertising or publicity pertaining to distribution of the
19 software without specific, written prior permission.
20
21 The author disclaim all warranties with regard to this
22 software, including all implied warranties of merchantability
23 and fitness. In no event shall the author be liable for any
24 special, indirect or consequential damages or any damages
25 whatsoever resulting from loss of use, data or profits, whether
26 in an action of contract, negligence or other tortious action,
27 arising out of or in connection with the use or performance of
28 this software.
29 */
30
31 /** \file
32 *
33 * Transmission Control Protocol (TCP) packet handling routines. This protocol handles the reliable in-order transmission
34 * and reception of packets to and from devices on a network, to "ports" on the device. It is used in situations where data
35 * delivery must be reliable and correct, e.g. HTTP, TELNET and most other non-streaming protocols.
36 */
37
38 #define INCLUDE_FROM_TCP_C
39 #include "TCP.h"
40
41 /* Global Variables: */
42 /** Port state table array. This contains the current status of TCP ports in the device. To save on space, only open ports are
43 * stored - closed ports may be overwritten at any time, and the system will assume any ports not present in the array are closed. This
44 * allows for MAX_OPEN_TCP_PORTS to be less than the number of ports used by the application if desired.
45 */
46 TCP_PortState_t PortStateTable[MAX_OPEN_TCP_PORTS];
47
48 /** Connection state table array. This contains the current status of TCP connections in the device. To save on space, only active
49 * (non-closed) connections are stored - closed connections may be overwritten at any time, and the system will assume any connections
50 * not present in the array are closed.
51 */
52 TCP_ConnectionState_t ConnectionStateTable[MAX_TCP_CONNECTIONS];
53
54
55 /** Task to handle the calling of each registered application's callback function, to process and generate TCP packets at the application
56 * level. If an application produces a response, this task constructs the appropriate Ethernet frame and places it into the Ethernet OUT
57 * buffer for later transmission.
58 */
59 void TCP_TCPTask(USB_ClassInfo_RNDIS_Device_t* RNDISInterfaceInfo)
60 {
61 /* Run each application in sequence, to process incoming and generate outgoing packets */
62 for (uint8_t CSTableEntry = 0; CSTableEntry < MAX_TCP_CONNECTIONS; CSTableEntry++)
63 {
64 /* Find the corresponding port entry in the port table */
65 for (uint8_t PTableEntry = 0; PTableEntry < MAX_OPEN_TCP_PORTS; PTableEntry++)
66 {
67 /* Run the application handler for the port */
68 if ((PortStateTable[PTableEntry].Port == ConnectionStateTable[CSTableEntry].Port) &&
69 (PortStateTable[PTableEntry].State == TCP_Port_Open))
70 {
71 PortStateTable[PTableEntry].ApplicationHandler(&ConnectionStateTable[CSTableEntry],
72 &ConnectionStateTable[CSTableEntry].Info.Buffer);
73 }
74 }
75 }
76
77 /* Get pointer to the output frame info struct for convenience */
78 Ethernet_Frame_Info_t* FrameOUT = (Ethernet_Frame_Info_t*)&RNDISInterfaceInfo->State.FrameOUT;
79
80 /* Bail out early if there is already a frame waiting to be sent in the Ethernet OUT buffer */
81 if (FrameOUT->FrameInBuffer)
82 return;
83
84 /* Send response packets from each application as the TCP packet buffers are filled by the applications */
85 for (uint8_t CSTableEntry = 0; CSTableEntry < MAX_TCP_CONNECTIONS; CSTableEntry++)
86 {
87 /* For each completely received packet, pass it along to the listening application */
88 if ((ConnectionStateTable[CSTableEntry].Info.Buffer.Direction == TCP_PACKETDIR_OUT) &&
89 (ConnectionStateTable[CSTableEntry].Info.Buffer.Ready))
90 {
91 Ethernet_Frame_Header_t* FrameOUTHeader = (Ethernet_Frame_Header_t*)&FrameOUT->FrameData;
92 IP_Header_t* IPHeaderOUT = (IP_Header_t*)&FrameOUT->FrameData[sizeof(Ethernet_Frame_Header_t)];
93 TCP_Header_t* TCPHeaderOUT = (TCP_Header_t*)&FrameOUT->FrameData[sizeof(Ethernet_Frame_Header_t) +
94 sizeof(IP_Header_t)];
95 void* TCPDataOUT = &FrameOUT->FrameData[sizeof(Ethernet_Frame_Header_t) +
96 sizeof(IP_Header_t) +
97 sizeof(TCP_Header_t)];
98
99 uint16_t PacketSize = ConnectionStateTable[CSTableEntry].Info.Buffer.Length;
100
101 /* Fill out the TCP data */
102 TCPHeaderOUT->SourcePort = ConnectionStateTable[CSTableEntry].Port;
103 TCPHeaderOUT->DestinationPort = ConnectionStateTable[CSTableEntry].RemotePort;
104 TCPHeaderOUT->SequenceNumber = SwapEndian_32(ConnectionStateTable[CSTableEntry].Info.SequenceNumberOut);
105 TCPHeaderOUT->AcknowledgmentNumber = SwapEndian_32(ConnectionStateTable[CSTableEntry].Info.SequenceNumberIn);
106 TCPHeaderOUT->DataOffset = (sizeof(TCP_Header_t) / sizeof(uint32_t));
107 TCPHeaderOUT->WindowSize = SwapEndian_16(TCP_WINDOW_SIZE);
108
109 TCPHeaderOUT->Flags = TCP_FLAG_ACK;
110 TCPHeaderOUT->UrgentPointer = 0;
111 TCPHeaderOUT->Checksum = 0;
112 TCPHeaderOUT->Reserved = 0;
113
114 memcpy(TCPDataOUT, ConnectionStateTable[CSTableEntry].Info.Buffer.Data, PacketSize);
115
116 ConnectionStateTable[CSTableEntry].Info.SequenceNumberOut += PacketSize;
117
118 TCPHeaderOUT->Checksum = TCP_Checksum16(TCPHeaderOUT, ServerIPAddress,
119 ConnectionStateTable[CSTableEntry].RemoteAddress,
120 (sizeof(TCP_Header_t) + PacketSize));
121
122 PacketSize += sizeof(TCP_Header_t);
123
124 /* Fill out the response IP header */
125 IPHeaderOUT->TotalLength = SwapEndian_16(sizeof(IP_Header_t) + PacketSize);
126 IPHeaderOUT->TypeOfService = 0;
127 IPHeaderOUT->HeaderLength = (sizeof(IP_Header_t) / sizeof(uint32_t));
128 IPHeaderOUT->Version = 4;
129 IPHeaderOUT->Flags = 0;
130 IPHeaderOUT->FragmentOffset = 0;
131 IPHeaderOUT->Identification = 0;
132 IPHeaderOUT->HeaderChecksum = 0;
133 IPHeaderOUT->Protocol = PROTOCOL_TCP;
134 IPHeaderOUT->TTL = DEFAULT_TTL;
135 IPHeaderOUT->SourceAddress = ServerIPAddress;
136 IPHeaderOUT->DestinationAddress = ConnectionStateTable[CSTableEntry].RemoteAddress;
137
138 IPHeaderOUT->HeaderChecksum = Ethernet_Checksum16(IPHeaderOUT, sizeof(IP_Header_t));
139
140 PacketSize += sizeof(IP_Header_t);
141
142 /* Fill out the response Ethernet frame header */
143 FrameOUTHeader->Source = ServerMACAddress;
144 FrameOUTHeader->Destination = (MAC_Address_t){{0x02, 0x00, 0x02, 0x00, 0x02, 0x00}};
145 FrameOUTHeader->EtherType = SwapEndian_16(ETHERTYPE_IPV4);
146
147 PacketSize += sizeof(Ethernet_Frame_Header_t);
148
149 /* Set the response length in the buffer and indicate that a response is ready to be sent */
150 FrameOUT->FrameLength = PacketSize;
151 FrameOUT->FrameInBuffer = true;
152
153 ConnectionStateTable[CSTableEntry].Info.Buffer.Ready = false;
154
155 break;
156 }
157 }
158 }
159
160 /** Initializes the TCP protocol handler, clearing the port and connection state tables. This must be called before TCP packets are
161 * processed.
162 */
163 void TCP_Init(void)
164 {
165 /* Initialize the port state table with all CLOSED entries */
166 for (uint8_t PTableEntry = 0; PTableEntry < MAX_OPEN_TCP_PORTS; PTableEntry++)
167 PortStateTable[PTableEntry].State = TCP_Port_Closed;
168
169 /* Initialize the connection table with all CLOSED entries */
170 for (uint8_t CSTableEntry = 0; CSTableEntry < MAX_TCP_CONNECTIONS; CSTableEntry++)
171 ConnectionStateTable[CSTableEntry].State = TCP_Connection_Closed;
172 }
173
174 /** Sets the state and callback handler of the given port, specified in big endian to the given state.
175 *
176 * \param[in] Port Port whose state and callback function to set, specified in big endian
177 * \param[in] State New state of the port, a value from the TCP_PortStates_t enum
178 * \param[in] Handler Application callback handler for the port
179 *
180 * \return Boolean true if the port state was set, false otherwise (no more space in the port state table)
181 */
182 bool TCP_SetPortState(uint16_t Port, uint8_t State, void (*Handler)(TCP_ConnectionState_t*, TCP_ConnectionBuffer_t*))
183 {
184 /* Note, Port number should be specified in BIG endian to simplify network code */
185
186 /* Check to see if the port entry is already in the port state table */
187 for (uint8_t PTableEntry = 0; PTableEntry < MAX_TCP_CONNECTIONS; PTableEntry++)
188 {
189 /* Find existing entry for the port in the table, update it if found */
190 if (PortStateTable[PTableEntry].Port == Port)
191 {
192 PortStateTable[PTableEntry].State = State;
193 PortStateTable[PTableEntry].ApplicationHandler = Handler;
194 return true;
195 }
196 }
197
198 /* Check if trying to open the port -- if so we need to find an unused (closed) entry and replace it */
199 if (State == TCP_Port_Open)
200 {
201 for (uint8_t PTableEntry = 0; PTableEntry < MAX_TCP_CONNECTIONS; PTableEntry++)
202 {
203 /* Find a closed port entry in the table, change it to the given port and state */
204 if (PortStateTable[PTableEntry].State == TCP_Port_Closed)
205 {
206 PortStateTable[PTableEntry].Port = Port;
207 PortStateTable[PTableEntry].State = State;
208 PortStateTable[PTableEntry].ApplicationHandler = Handler;
209 return true;
210 }
211 }
212
213 /* Port not in table and no room to add it, return failure */
214 return false;
215 }
216 else
217 {
218 /* Port not in table but trying to close it, so operation successful */
219 return true;
220 }
221 }
222
223 /** Retrieves the current state of a given TCP port, specified in big endian.
224 *
225 * \param[in] Port TCP port whose state is to be retrieved, given in big-endian
226 *
227 * \return A value from the TCP_PortStates_t enum
228 */
229 uint8_t TCP_GetPortState(uint16_t Port)
230 {
231 /* Note, Port number should be specified in BIG endian to simplify network code */
232
233 for (uint8_t PTableEntry = 0; PTableEntry < MAX_TCP_CONNECTIONS; PTableEntry++)
234 {
235 /* Find existing entry for the port in the table, return the port status if found */
236 if (PortStateTable[PTableEntry].Port == Port)
237 return PortStateTable[PTableEntry].State;
238 }
239
240 /* Port not in table, assume closed */
241 return TCP_Port_Closed;
242 }
243
244 /** Sets the connection state of the given port, remote address and remote port to the given TCP connection state. If the
245 * connection exists in the connection state table it is updated, otherwise it is created if possible.
246 *
247 * \param[in] Port TCP port of the connection on the device, specified in big endian
248 * \param[in] RemoteAddress Remote protocol IP address of the connected device
249 * \param[in] RemotePort TCP port of the remote device in the connection, specified in big endian
250 * \param[in] State TCP connection state, a value from the TCP_ConnectionStates_t enum
251 *
252 * \return Boolean true if the connection was updated or created, false otherwise (no more space in the connection state table)
253 */
254 bool TCP_SetConnectionState(uint16_t Port, IP_Address_t RemoteAddress, uint16_t RemotePort, uint8_t State)
255 {
256 /* Note, Port number should be specified in BIG endian to simplify network code */
257
258 for (uint8_t CSTableEntry = 0; CSTableEntry < MAX_TCP_CONNECTIONS; CSTableEntry++)
259 {
260 /* Find port entry in the table */
261 if ((ConnectionStateTable[CSTableEntry].Port == Port) &&
262 IP_COMPARE(&ConnectionStateTable[CSTableEntry].RemoteAddress, &RemoteAddress) &&
263 ConnectionStateTable[CSTableEntry].RemotePort == RemotePort)
264 {
265 ConnectionStateTable[CSTableEntry].State = State;
266 return true;
267 }
268 }
269
270 for (uint8_t CSTableEntry = 0; CSTableEntry < MAX_TCP_CONNECTIONS; CSTableEntry++)
271 {
272 /* Find empty entry in the table */
273 if (ConnectionStateTable[CSTableEntry].State == TCP_Connection_Closed)
274 {
275 ConnectionStateTable[CSTableEntry].Port = Port;
276 ConnectionStateTable[CSTableEntry].RemoteAddress = RemoteAddress;
277 ConnectionStateTable[CSTableEntry].RemotePort = RemotePort;
278 ConnectionStateTable[CSTableEntry].State = State;
279 return true;
280 }
281 }
282
283 return false;
284 }
285
286 /** Retrieves the current state of a given TCP connection to a host.
287 *
288 * \param[in] Port TCP port on the device in the connection, specified in big endian
289 * \param[in] RemoteAddress Remote protocol IP address of the connected host
290 * \param[in] RemotePort Remote TCP port of the connected host, specified in big endian
291 *
292 * \return A value from the TCP_ConnectionStates_t enum
293 */
294 uint8_t TCP_GetConnectionState(uint16_t Port, IP_Address_t RemoteAddress, uint16_t RemotePort)
295 {
296 /* Note, Port number should be specified in BIG endian to simplify network code */
297
298 for (uint8_t CSTableEntry = 0; CSTableEntry < MAX_TCP_CONNECTIONS; CSTableEntry++)
299 {
300 /* Find port entry in the table */
301 if ((ConnectionStateTable[CSTableEntry].Port == Port) &&
302 IP_COMPARE(&ConnectionStateTable[CSTableEntry].RemoteAddress, &RemoteAddress) &&
303 ConnectionStateTable[CSTableEntry].RemotePort == RemotePort)
304
305 {
306 return ConnectionStateTable[CSTableEntry].State;
307 }
308 }
309
310 return TCP_Connection_Closed;
311 }
312
313 /** Retrieves the connection info structure of a given connection to a host.
314 *
315 * \param[in] Port TCP port on the device in the connection, specified in big endian
316 * \param[in] RemoteAddress Remote protocol IP address of the connected host
317 * \param[in] RemotePort Remote TCP port of the connected host, specified in big endian
318 *
319 * \return ConnectionInfo structure of the connection if found, NULL otherwise
320 */
321 TCP_ConnectionInfo_t* TCP_GetConnectionInfo(uint16_t Port, IP_Address_t RemoteAddress, uint16_t RemotePort)
322 {
323 /* Note, Port number should be specified in BIG endian to simplify network code */
324
325 for (uint8_t CSTableEntry = 0; CSTableEntry < MAX_TCP_CONNECTIONS; CSTableEntry++)
326 {
327 /* Find port entry in the table */
328 if ((ConnectionStateTable[CSTableEntry].Port == Port) &&
329 IP_COMPARE(&ConnectionStateTable[CSTableEntry].RemoteAddress, &RemoteAddress) &&
330 ConnectionStateTable[CSTableEntry].RemotePort == RemotePort)
331 {
332 return &ConnectionStateTable[CSTableEntry].Info;
333 }
334 }
335
336 return NULL;
337 }
338
339 /** Processes a TCP packet inside an Ethernet frame, and writes the appropriate response
340 * to the output Ethernet frame if one is created by a application handler.
341 *
342 * \param[in] IPHeaderInStart Pointer to the start of the incoming packet's IP header
343 * \param[in] TCPHeaderInStart Pointer to the start of the incoming packet's TCP header
344 * \param[out] TCPHeaderOutStart Pointer to the start of the outgoing packet's TCP header
345 *
346 * \return The number of bytes written to the out Ethernet frame if any, NO_RESPONSE if no
347 * response was generated, NO_PROCESS if the packet processing was deferred until the
348 * next Ethernet packet handler iteration
349 */
350 int16_t TCP_ProcessTCPPacket(void* IPHeaderInStart, void* TCPHeaderInStart, void* TCPHeaderOutStart)
351 {
352 IP_Header_t* IPHeaderIN = (IP_Header_t*)IPHeaderInStart;
353 TCP_Header_t* TCPHeaderIN = (TCP_Header_t*)TCPHeaderInStart;
354 TCP_Header_t* TCPHeaderOUT = (TCP_Header_t*)TCPHeaderOutStart;
355
356 TCP_ConnectionInfo_t* ConnectionInfo;
357
358 DecodeTCPHeader(TCPHeaderInStart);
359
360 bool PacketResponse = false;
361
362 /* Check if the destination port is open and allows incoming connections */
363 if (TCP_GetPortState(TCPHeaderIN->DestinationPort) == TCP_Port_Open)
364 {
365 /* Detect SYN from host to start a connection */
366 if (TCPHeaderIN->Flags & TCP_FLAG_SYN)
367 TCP_SetConnectionState(TCPHeaderIN->DestinationPort, IPHeaderIN->SourceAddress, TCPHeaderIN->SourcePort, TCP_Connection_Listen);
368
369 /* Detect RST from host to abort existing connection */
370 if (TCPHeaderIN->Flags & TCP_FLAG_RST)
371 {
372 if (TCP_SetConnectionState(TCPHeaderIN->DestinationPort, IPHeaderIN->SourceAddress,
373 TCPHeaderIN->SourcePort, TCP_Connection_Closed))
374 {
375 TCPHeaderOUT->Flags = (TCP_FLAG_RST | TCP_FLAG_ACK);
376 PacketResponse = true;
377 }
378 }
379 else
380 {
381 /* Process the incoming TCP packet based on the current connection state for the sender and port */
382 switch (TCP_GetConnectionState(TCPHeaderIN->DestinationPort, IPHeaderIN->SourceAddress, TCPHeaderIN->SourcePort))
383 {
384 case TCP_Connection_Listen:
385 if (TCPHeaderIN->Flags == TCP_FLAG_SYN)
386 {
387 /* SYN connection starts a connection with a peer */
388 if (TCP_SetConnectionState(TCPHeaderIN->DestinationPort, IPHeaderIN->SourceAddress,
389 TCPHeaderIN->SourcePort, TCP_Connection_SYNReceived))
390 {
391 TCPHeaderOUT->Flags = (TCP_FLAG_SYN | TCP_FLAG_ACK);
392
393 ConnectionInfo = TCP_GetConnectionInfo(TCPHeaderIN->DestinationPort, IPHeaderIN->SourceAddress, TCPHeaderIN->SourcePort);
394
395 ConnectionInfo->SequenceNumberIn = (SwapEndian_32(TCPHeaderIN->SequenceNumber) + 1);
396 ConnectionInfo->SequenceNumberOut = 0;
397 ConnectionInfo->Buffer.InUse = false;
398 }
399 else
400 {
401 TCPHeaderOUT->Flags = TCP_FLAG_RST;
402 }
403
404 PacketResponse = true;
405 }
406
407 break;
408 case TCP_Connection_SYNReceived:
409 if (TCPHeaderIN->Flags == TCP_FLAG_ACK)
410 {
411 /* ACK during the connection process completes the connection to a peer */
412
413 TCP_SetConnectionState(TCPHeaderIN->DestinationPort, IPHeaderIN->SourceAddress,
414 TCPHeaderIN->SourcePort, TCP_Connection_Established);
415
416 ConnectionInfo = TCP_GetConnectionInfo(TCPHeaderIN->DestinationPort, IPHeaderIN->SourceAddress,
417 TCPHeaderIN->SourcePort);
418
419 ConnectionInfo->SequenceNumberOut++;
420 }
421
422 break;
423 case TCP_Connection_Established:
424 if (TCPHeaderIN->Flags == (TCP_FLAG_FIN | TCP_FLAG_ACK))
425 {
426 /* FIN ACK when connected to a peer starts the finalization process */
427
428 TCPHeaderOUT->Flags = (TCP_FLAG_FIN | TCP_FLAG_ACK);
429 PacketResponse = true;
430
431 TCP_SetConnectionState(TCPHeaderIN->DestinationPort, IPHeaderIN->SourceAddress,
432 TCPHeaderIN->SourcePort, TCP_Connection_CloseWait);
433
434 ConnectionInfo = TCP_GetConnectionInfo(TCPHeaderIN->DestinationPort, IPHeaderIN->SourceAddress,
435 TCPHeaderIN->SourcePort);
436
437 ConnectionInfo->SequenceNumberIn++;
438 ConnectionInfo->SequenceNumberOut++;
439 }
440 else if ((TCPHeaderIN->Flags == TCP_FLAG_ACK) || (TCPHeaderIN->Flags == (TCP_FLAG_ACK | TCP_FLAG_PSH)))
441 {
442 ConnectionInfo = TCP_GetConnectionInfo(TCPHeaderIN->DestinationPort, IPHeaderIN->SourceAddress,
443 TCPHeaderIN->SourcePort);
444
445 /* Check if the buffer is currently in use either by a buffered data to send, or receive */
446 if ((ConnectionInfo->Buffer.InUse == false) && (ConnectionInfo->Buffer.Ready == false))
447 {
448 ConnectionInfo->Buffer.Direction = TCP_PACKETDIR_IN;
449 ConnectionInfo->Buffer.InUse = true;
450 ConnectionInfo->Buffer.Length = 0;
451 }
452
453 /* Check if the buffer has been claimed by us to read in data from the peer */
454 if ((ConnectionInfo->Buffer.Direction == TCP_PACKETDIR_IN) &&
455 (ConnectionInfo->Buffer.Length != TCP_WINDOW_SIZE))
456 {
457 uint16_t IPOffset = (IPHeaderIN->HeaderLength * sizeof(uint32_t));
458 uint16_t TCPOffset = (TCPHeaderIN->DataOffset * sizeof(uint32_t));
459 uint16_t DataLength = (SwapEndian_16(IPHeaderIN->TotalLength) - IPOffset - TCPOffset);
460
461 /* Copy the packet data into the buffer */
462 memcpy(&ConnectionInfo->Buffer.Data[ConnectionInfo->Buffer.Length],
463 &((uint8_t*)TCPHeaderInStart)[TCPOffset],
464 DataLength);
465
466 ConnectionInfo->SequenceNumberIn += DataLength;
467 ConnectionInfo->Buffer.Length += DataLength;
468
469 /* Check if the buffer is full or if the PSH flag is set, if so indicate buffer ready */
470 if ((!(TCP_WINDOW_SIZE - ConnectionInfo->Buffer.Length)) || (TCPHeaderIN->Flags & TCP_FLAG_PSH))
471 {
472 ConnectionInfo->Buffer.InUse = false;
473 ConnectionInfo->Buffer.Ready = true;
474
475 TCPHeaderOUT->Flags = TCP_FLAG_ACK;
476 PacketResponse = true;
477 }
478 }
479 else
480 {
481 /* Buffer is currently in use by the application, defer processing of the incoming packet */
482 return NO_PROCESS;
483 }
484 }
485
486 break;
487 case TCP_Connection_Closing:
488 ConnectionInfo = TCP_GetConnectionInfo(TCPHeaderIN->DestinationPort, IPHeaderIN->SourceAddress,
489 TCPHeaderIN->SourcePort);
490
491 TCPHeaderOUT->Flags = (TCP_FLAG_ACK | TCP_FLAG_FIN);
492 PacketResponse = true;
493
494 ConnectionInfo->Buffer.InUse = false;
495
496 TCP_SetConnectionState(TCPHeaderIN->DestinationPort, IPHeaderIN->SourceAddress,
497 TCPHeaderIN->SourcePort, TCP_Connection_FINWait1);
498
499 break;
500 case TCP_Connection_FINWait1:
501 if (TCPHeaderIN->Flags == (TCP_FLAG_FIN | TCP_FLAG_ACK))
502 {
503 ConnectionInfo = TCP_GetConnectionInfo(TCPHeaderIN->DestinationPort, IPHeaderIN->SourceAddress,
504 TCPHeaderIN->SourcePort);
505
506 TCPHeaderOUT->Flags = TCP_FLAG_ACK;
507 PacketResponse = true;
508
509 ConnectionInfo->SequenceNumberIn++;
510 ConnectionInfo->SequenceNumberOut++;
511
512 TCP_SetConnectionState(TCPHeaderIN->DestinationPort, IPHeaderIN->SourceAddress,
513 TCPHeaderIN->SourcePort, TCP_Connection_Closed);
514 }
515 else if (TCPHeaderIN->Flags == TCP_FLAG_ACK)
516 {
517 TCP_SetConnectionState(TCPHeaderIN->DestinationPort, IPHeaderIN->SourceAddress,
518 TCPHeaderIN->SourcePort, TCP_Connection_FINWait2);
519 }
520
521 break;
522 case TCP_Connection_FINWait2:
523 if (TCPHeaderIN->Flags == (TCP_FLAG_FIN | TCP_FLAG_ACK))
524 {
525 ConnectionInfo = TCP_GetConnectionInfo(TCPHeaderIN->DestinationPort, IPHeaderIN->SourceAddress,
526 TCPHeaderIN->SourcePort);
527
528 TCPHeaderOUT->Flags = TCP_FLAG_ACK;
529 PacketResponse = true;
530
531 ConnectionInfo->SequenceNumberIn++;
532 ConnectionInfo->SequenceNumberOut++;
533
534 TCP_SetConnectionState(TCPHeaderIN->DestinationPort, IPHeaderIN->SourceAddress,
535 TCPHeaderIN->SourcePort, TCP_Connection_Closed);
536 }
537
538 break;
539 case TCP_Connection_CloseWait:
540 if (TCPHeaderIN->Flags == TCP_FLAG_ACK)
541 {
542 TCP_SetConnectionState(TCPHeaderIN->DestinationPort, IPHeaderIN->SourceAddress,
543 TCPHeaderIN->SourcePort, TCP_Connection_Closed);
544 }
545
546 break;
547 }
548 }
549 }
550 else
551 {
552 /* Port is not open, indicate via a RST/ACK response to the sender */
553 TCPHeaderOUT->Flags = (TCP_FLAG_RST | TCP_FLAG_ACK);
554 PacketResponse = true;
555 }
556
557 /* Check if we need to respond to the sent packet */
558 if (PacketResponse)
559 {
560 ConnectionInfo = TCP_GetConnectionInfo(TCPHeaderIN->DestinationPort, IPHeaderIN->SourceAddress,
561 TCPHeaderIN->SourcePort);
562
563 TCPHeaderOUT->SourcePort = TCPHeaderIN->DestinationPort;
564 TCPHeaderOUT->DestinationPort = TCPHeaderIN->SourcePort;
565 TCPHeaderOUT->SequenceNumber = SwapEndian_32(ConnectionInfo->SequenceNumberOut);
566 TCPHeaderOUT->AcknowledgmentNumber = SwapEndian_32(ConnectionInfo->SequenceNumberIn);
567 TCPHeaderOUT->DataOffset = (sizeof(TCP_Header_t) / sizeof(uint32_t));
568
569 if (!(ConnectionInfo->Buffer.InUse))
570 TCPHeaderOUT->WindowSize = SwapEndian_16(TCP_WINDOW_SIZE);
571 else
572 TCPHeaderOUT->WindowSize = SwapEndian_16(TCP_WINDOW_SIZE - ConnectionInfo->Buffer.Length);
573
574 TCPHeaderOUT->UrgentPointer = 0;
575 TCPHeaderOUT->Checksum = 0;
576 TCPHeaderOUT->Reserved = 0;
577
578 TCPHeaderOUT->Checksum = TCP_Checksum16(TCPHeaderOUT, IPHeaderIN->DestinationAddress,
579 IPHeaderIN->SourceAddress, sizeof(TCP_Header_t));
580
581 return sizeof(TCP_Header_t);
582 }
583
584 return NO_RESPONSE;
585 }
586
587 /** Calculates the appropriate TCP checksum, consisting of the addition of the one's compliment of each word,
588 * complimented.
589 *
590 * \param[in] TCPHeaderOutStart Pointer to the start of the packet's outgoing TCP header
591 * \param[in] SourceAddress Source protocol IP address of the outgoing IP header
592 * \param[in] DestinationAddress Destination protocol IP address of the outgoing IP header
593 * \param[in] TCPOutSize Size in bytes of the TCP data header and payload
594 *
595 * \return A 16-bit TCP checksum value
596 */
597 static uint16_t TCP_Checksum16(void* TCPHeaderOutStart, IP_Address_t SourceAddress,
598 IP_Address_t DestinationAddress, uint16_t TCPOutSize)
599 {
600 uint32_t Checksum = 0;
601
602 /* TCP/IP checksums are the addition of the one's compliment of each word including the IP pseudo-header,
603 complimented */
604
605 Checksum += ((uint16_t*)&SourceAddress)[0];
606 Checksum += ((uint16_t*)&SourceAddress)[1];
607 Checksum += ((uint16_t*)&DestinationAddress)[0];
608 Checksum += ((uint16_t*)&DestinationAddress)[1];
609 Checksum += SwapEndian_16(PROTOCOL_TCP);
610 Checksum += SwapEndian_16(TCPOutSize);
611
612 for (uint8_t CurrWord = 0; CurrWord < (TCPOutSize >> 1); CurrWord++)
613 Checksum += ((uint16_t*)TCPHeaderOutStart)[CurrWord];
614
615 if (TCPOutSize & 0x01)
616 Checksum += (((uint16_t*)TCPHeaderOutStart)[TCPOutSize >> 1] & 0x00FF);
617
618 while (Checksum & 0xFFFF0000)
619 Checksum = ((Checksum & 0xFFFF) + (Checksum >> 16));
620
621 return ~Checksum;
622 }