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