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