Keyboard firmwares for Atmel AVR and Cortex-M
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

TCP.c 26KB

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