FreeRTOS_UDP_IP.c 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  1. /*
  2. * FreeRTOS+TCP V2.3.2 LTS Patch 1
  3. * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
  4. *
  5. * Permission is hereby granted, free of charge, to any person obtaining a copy of
  6. * this software and associated documentation files (the "Software"), to deal in
  7. * the Software without restriction, including without limitation the rights to
  8. * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
  9. * the Software, and to permit persons to whom the Software is furnished to do so,
  10. * subject to the following conditions:
  11. *
  12. * The above copyright notice and this permission notice shall be included in all
  13. * copies or substantial portions of the Software.
  14. *
  15. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
  17. * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
  18. * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
  19. * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  20. * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  21. *
  22. * http://aws.amazon.com/freertos
  23. * http://www.FreeRTOS.org
  24. */
  25. /**
  26. * @file FreeRTOS_UDP_IP.c
  27. * @brief This file has the source code for the UDP-IP functionality of the FreeRTOS+TCP
  28. * network stack.
  29. */
  30. /* Standard includes. */
  31. #include <stdint.h>
  32. #include <stdio.h>
  33. /* FreeRTOS includes. */
  34. #include "FreeRTOS.h"
  35. #include "task.h"
  36. #include "queue.h"
  37. #include "semphr.h"
  38. /* FreeRTOS+TCP includes. */
  39. #include "FreeRTOS_IP.h"
  40. #include "FreeRTOS_Sockets.h"
  41. #include "FreeRTOS_IP_Private.h"
  42. #include "FreeRTOS_UDP_IP.h"
  43. #include "FreeRTOS_ARP.h"
  44. #include "FreeRTOS_DHCP.h"
  45. #include "NetworkInterface.h"
  46. #include "NetworkBufferManagement.h"
  47. #if ( ipconfigUSE_DNS == 1 )
  48. #include "FreeRTOS_DNS.h"
  49. #endif
  50. /** @brief The expected IP version and header length coded into the IP header itself. */
  51. #define ipIP_VERSION_AND_HEADER_LENGTH_BYTE ( ( uint8_t ) 0x45 )
  52. /** @brief Part of the Ethernet and IP headers are always constant when sending an IPv4
  53. * UDP packet. This array defines the constant parts, allowing this part of the
  54. * packet to be filled in using a simple memcpy() instead of individual writes. */
  55. /*lint -e708 (Info -- union initialization). */
  56. UDPPacketHeader_t xDefaultPartUDPPacketHeader =
  57. {
  58. /* .ucBytes : */
  59. {
  60. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* Ethernet source MAC address. */
  61. 0x08, 0x00, /* Ethernet frame type. */
  62. ipIP_VERSION_AND_HEADER_LENGTH_BYTE, /* ucVersionHeaderLength. */
  63. 0x00, /* ucDifferentiatedServicesCode. */
  64. 0x00, 0x00, /* usLength. */
  65. 0x00, 0x00, /* usIdentification. */
  66. 0x00, 0x00, /* usFragmentOffset. */
  67. ipconfigUDP_TIME_TO_LIVE, /* ucTimeToLive */
  68. ipPROTOCOL_UDP, /* ucProtocol. */
  69. 0x00, 0x00, /* usHeaderChecksum. */
  70. 0x00, 0x00, 0x00, 0x00 /* Source IP address. */
  71. }
  72. };
  73. /*-----------------------------------------------------------*/
  74. /**
  75. * @brief Process the generated UDP packet and do other checks before sending the
  76. * packet such as ARP cache check and address resolution.
  77. *
  78. * @param[in] pxNetworkBuffer: The network buffer carrying the packet.
  79. */
  80. void vProcessGeneratedUDPPacket( NetworkBufferDescriptor_t * const pxNetworkBuffer )
  81. {
  82. UDPPacket_t * pxUDPPacket;
  83. IPHeader_t * pxIPHeader;
  84. eARPLookupResult_t eReturned;
  85. uint32_t ulIPAddress = pxNetworkBuffer->ulIPAddress;
  86. size_t uxPayloadSize;
  87. /* memcpy() helper variables for MISRA Rule 21.15 compliance*/
  88. const void * pvCopySource;
  89. void * pvCopyDest;
  90. /* Map the UDP packet onto the start of the frame. */
  91. pxUDPPacket = ipCAST_PTR_TO_TYPE_PTR( UDPPacket_t, pxNetworkBuffer->pucEthernetBuffer );
  92. #if ipconfigSUPPORT_OUTGOING_PINGS == 1
  93. if( pxNetworkBuffer->usPort == ( uint16_t ) ipPACKET_CONTAINS_ICMP_DATA )
  94. {
  95. uxPayloadSize = pxNetworkBuffer->xDataLength - sizeof( ICMPPacket_t );
  96. }
  97. else
  98. #endif
  99. {
  100. uxPayloadSize = pxNetworkBuffer->xDataLength - sizeof( UDPPacket_t );
  101. }
  102. /* Determine the ARP cache status for the requested IP address. */
  103. eReturned = eARPGetCacheEntry( &( ulIPAddress ), &( pxUDPPacket->xEthernetHeader.xDestinationAddress ) );
  104. if( eReturned != eCantSendPacket )
  105. {
  106. if( eReturned == eARPCacheHit )
  107. {
  108. #if ( ipconfigDRIVER_INCLUDED_TX_IP_CHECKSUM == 0 )
  109. uint8_t ucSocketOptions;
  110. #endif
  111. iptraceSENDING_UDP_PACKET( pxNetworkBuffer->ulIPAddress );
  112. /* Create short cuts to the data within the packet. */
  113. pxIPHeader = &( pxUDPPacket->xIPHeader );
  114. #if ( ipconfigSUPPORT_OUTGOING_PINGS == 1 )
  115. /* Is it possible that the packet is not actually a UDP packet
  116. * after all, but an ICMP packet. */
  117. if( pxNetworkBuffer->usPort != ( uint16_t ) ipPACKET_CONTAINS_ICMP_DATA )
  118. #endif /* ipconfigSUPPORT_OUTGOING_PINGS */
  119. {
  120. UDPHeader_t * pxUDPHeader;
  121. pxUDPHeader = &( pxUDPPacket->xUDPHeader );
  122. pxUDPHeader->usDestinationPort = pxNetworkBuffer->usPort;
  123. pxUDPHeader->usSourcePort = pxNetworkBuffer->usBoundPort;
  124. pxUDPHeader->usLength = ( uint16_t ) ( uxPayloadSize + sizeof( UDPHeader_t ) );
  125. pxUDPHeader->usLength = FreeRTOS_htons( pxUDPHeader->usLength );
  126. pxUDPHeader->usChecksum = 0U;
  127. }
  128. /* memcpy() the constant parts of the header information into
  129. * the correct location within the packet. This fills in:
  130. * xEthernetHeader.xSourceAddress
  131. * xEthernetHeader.usFrameType
  132. * xIPHeader.ucVersionHeaderLength
  133. * xIPHeader.ucDifferentiatedServicesCode
  134. * xIPHeader.usLength
  135. * xIPHeader.usIdentification
  136. * xIPHeader.usFragmentOffset
  137. * xIPHeader.ucTimeToLive
  138. * xIPHeader.ucProtocol
  139. * and
  140. * xIPHeader.usHeaderChecksum
  141. */
  142. /* Save options now, as they will be overwritten by memcpy */
  143. #if ( ipconfigDRIVER_INCLUDED_TX_IP_CHECKSUM == 0 )
  144. {
  145. ucSocketOptions = pxNetworkBuffer->pucEthernetBuffer[ ipSOCKET_OPTIONS_OFFSET ];
  146. }
  147. #endif
  148. /*
  149. * Offset the memcpy by the size of a MAC address to start at the packet's
  150. * Ethernet header 'source' MAC address; the preceding 'destination' should not be altered.
  151. */
  152. /*
  153. * Use helper variables for memcpy() to remain
  154. * compliant with MISRA Rule 21.15. These should be
  155. * optimized away.
  156. */
  157. pvCopySource = xDefaultPartUDPPacketHeader.ucBytes;
  158. /* The Ethernet source address is at offset 6. */
  159. pvCopyDest = &pxNetworkBuffer->pucEthernetBuffer[ sizeof( MACAddress_t ) ];
  160. ( void ) memcpy( pvCopyDest, pvCopySource, sizeof( xDefaultPartUDPPacketHeader ) );
  161. #if ipconfigSUPPORT_OUTGOING_PINGS == 1
  162. if( pxNetworkBuffer->usPort == ( uint16_t ) ipPACKET_CONTAINS_ICMP_DATA )
  163. {
  164. pxIPHeader->ucProtocol = ipPROTOCOL_ICMP;
  165. pxIPHeader->usLength = ( uint16_t ) ( uxPayloadSize + sizeof( IPHeader_t ) + sizeof( ICMPHeader_t ) );
  166. }
  167. else
  168. #endif /* ipconfigSUPPORT_OUTGOING_PINGS */
  169. {
  170. pxIPHeader->usLength = ( uint16_t ) ( uxPayloadSize + sizeof( IPHeader_t ) + sizeof( UDPHeader_t ) );
  171. }
  172. pxIPHeader->usLength = FreeRTOS_htons( pxIPHeader->usLength );
  173. pxIPHeader->ulDestinationIPAddress = pxNetworkBuffer->ulIPAddress;
  174. #if ( ipconfigUSE_LLMNR == 1 )
  175. {
  176. /* LLMNR messages are typically used on a LAN and they're
  177. * not supposed to cross routers */
  178. if( pxNetworkBuffer->ulIPAddress == ipLLMNR_IP_ADDR )
  179. {
  180. pxIPHeader->ucTimeToLive = 0x01;
  181. }
  182. }
  183. #endif
  184. #if ( ipconfigDRIVER_INCLUDED_TX_IP_CHECKSUM == 0 )
  185. {
  186. pxIPHeader->usHeaderChecksum = 0U;
  187. pxIPHeader->usHeaderChecksum = usGenerateChecksum( 0U, ( uint8_t * ) &( pxIPHeader->ucVersionHeaderLength ), ipSIZE_OF_IPv4_HEADER );
  188. pxIPHeader->usHeaderChecksum = ~FreeRTOS_htons( pxIPHeader->usHeaderChecksum );
  189. if( ( ucSocketOptions & ( uint8_t ) FREERTOS_SO_UDPCKSUM_OUT ) != 0U )
  190. {
  191. ( void ) usGenerateProtocolChecksum( ( uint8_t * ) pxUDPPacket, pxNetworkBuffer->xDataLength, pdTRUE );
  192. }
  193. else
  194. {
  195. pxUDPPacket->xUDPHeader.usChecksum = 0U;
  196. }
  197. }
  198. #endif /* if ( ipconfigDRIVER_INCLUDED_TX_IP_CHECKSUM == 0 ) */
  199. }
  200. else if( eReturned == eARPCacheMiss )
  201. {
  202. /* Add an entry to the ARP table with a null hardware address.
  203. * This allows the ARP timer to know that an ARP reply is
  204. * outstanding, and perform retransmissions if necessary. */
  205. vARPRefreshCacheEntry( NULL, ulIPAddress );
  206. /* Generate an ARP for the required IP address. */
  207. iptracePACKET_DROPPED_TO_GENERATE_ARP( pxNetworkBuffer->ulIPAddress );
  208. pxNetworkBuffer->ulIPAddress = ulIPAddress;
  209. vARPGenerateRequestPacket( pxNetworkBuffer );
  210. }
  211. else
  212. {
  213. /* The lookup indicated that an ARP request has already been
  214. * sent out for the queried IP address. */
  215. eReturned = eCantSendPacket;
  216. }
  217. }
  218. if( eReturned != eCantSendPacket )
  219. {
  220. /* The network driver is responsible for freeing the network buffer
  221. * after the packet has been sent. */
  222. #if defined( ipconfigETHERNET_MINIMUM_PACKET_BYTES )
  223. {
  224. if( pxNetworkBuffer->xDataLength < ( size_t ) ipconfigETHERNET_MINIMUM_PACKET_BYTES )
  225. {
  226. BaseType_t xIndex;
  227. for( xIndex = ( BaseType_t ) pxNetworkBuffer->xDataLength; xIndex < ( BaseType_t ) ipconfigETHERNET_MINIMUM_PACKET_BYTES; xIndex++ )
  228. {
  229. pxNetworkBuffer->pucEthernetBuffer[ xIndex ] = 0U;
  230. }
  231. pxNetworkBuffer->xDataLength = ( size_t ) ipconfigETHERNET_MINIMUM_PACKET_BYTES;
  232. }
  233. }
  234. #endif /* if defined( ipconfigETHERNET_MINIMUM_PACKET_BYTES ) */
  235. iptraceNETWORK_INTERFACE_OUTPUT( pxNetworkBuffer->xDataLength, pxNetworkBuffer->pucEthernetBuffer );
  236. ( void ) xNetworkInterfaceOutput( pxNetworkBuffer, pdTRUE );
  237. }
  238. else
  239. {
  240. /* The packet can't be sent (DHCP not completed?). Just drop the
  241. * packet. */
  242. vReleaseNetworkBufferAndDescriptor( pxNetworkBuffer );
  243. }
  244. }
  245. /*-----------------------------------------------------------*/
  246. /**
  247. * @brief Process the received UDP packet.
  248. *
  249. * @param[in] pxNetworkBuffer: The network buffer carrying the UDP packet.
  250. * @param[in] usPort: The port number on which this packet was received.
  251. *
  252. * @return pdPASS in case the UDP packet could be processed. Else pdFAIL is returned.
  253. */
  254. BaseType_t xProcessReceivedUDPPacket( NetworkBufferDescriptor_t * pxNetworkBuffer,
  255. uint16_t usPort )
  256. {
  257. BaseType_t xReturn = pdPASS;
  258. FreeRTOS_Socket_t * pxSocket;
  259. configASSERT( pxNetworkBuffer != NULL );
  260. configASSERT( pxNetworkBuffer->pucEthernetBuffer != NULL );
  261. /* Map the ethernet buffer to the UDPPacket_t struct for easy access to the fields. */
  262. const UDPPacket_t * pxUDPPacket = ipCAST_CONST_PTR_TO_CONST_TYPE_PTR( UDPPacket_t, pxNetworkBuffer->pucEthernetBuffer );
  263. /* Caller must check for minimum packet size. */
  264. pxSocket = pxUDPSocketLookup( usPort );
  265. if( pxSocket != NULL )
  266. {
  267. /* When refreshing the ARP cache with received UDP packets we must be
  268. * careful; hundreds of broadcast messages may pass and if we're not
  269. * handling them, no use to fill the ARP cache with those IP addresses. */
  270. vARPRefreshCacheEntry( &( pxUDPPacket->xEthernetHeader.xSourceAddress ), pxUDPPacket->xIPHeader.ulSourceIPAddress );
  271. #if ( ipconfigUSE_CALLBACKS == 1 )
  272. {
  273. /* Did the owner of this socket register a reception handler ? */
  274. if( ipconfigIS_VALID_PROG_ADDRESS( pxSocket->u.xUDP.pxHandleReceive ) )
  275. {
  276. struct freertos_sockaddr xSourceAddress, destinationAddress;
  277. void * pcData = &( pxNetworkBuffer->pucEthernetBuffer[ ipUDP_PAYLOAD_OFFSET_IPv4 ] );
  278. FOnUDPReceive_t xHandler = ( FOnUDPReceive_t ) pxSocket->u.xUDP.pxHandleReceive;
  279. xSourceAddress.sin_port = pxNetworkBuffer->usPort;
  280. xSourceAddress.sin_addr = pxNetworkBuffer->ulIPAddress;
  281. destinationAddress.sin_port = usPort;
  282. destinationAddress.sin_addr = pxUDPPacket->xIPHeader.ulDestinationIPAddress;
  283. /* The value of 'xDataLength' was proven to be at least the size of a UDP packet in prvProcessIPPacket(). */
  284. if( xHandler( ( Socket_t ) pxSocket,
  285. ( void * ) pcData,
  286. ( size_t ) ( pxNetworkBuffer->xDataLength - ipUDP_PAYLOAD_OFFSET_IPv4 ),
  287. &( xSourceAddress ),
  288. &( destinationAddress ) ) != 0 )
  289. {
  290. xReturn = pdFAIL; /* xHandler has consumed the data, do not add it to .xWaitingPacketsList'. */
  291. }
  292. }
  293. }
  294. #endif /* ipconfigUSE_CALLBACKS */
  295. #if ( ipconfigUDP_MAX_RX_PACKETS > 0U )
  296. {
  297. if( xReturn == pdPASS )
  298. {
  299. if( listCURRENT_LIST_LENGTH( &( pxSocket->u.xUDP.xWaitingPacketsList ) ) >= pxSocket->u.xUDP.uxMaxPackets )
  300. {
  301. FreeRTOS_debug_printf( ( "xProcessReceivedUDPPacket: buffer full %ld >= %ld port %u\n",
  302. listCURRENT_LIST_LENGTH( &( pxSocket->u.xUDP.xWaitingPacketsList ) ),
  303. pxSocket->u.xUDP.uxMaxPackets, pxSocket->usLocalPort ) );
  304. xReturn = pdFAIL; /* we did not consume or release the buffer */
  305. }
  306. }
  307. }
  308. #endif /* if ( ipconfigUDP_MAX_RX_PACKETS > 0U ) */
  309. #if ( ipconfigUSE_CALLBACKS == 1 ) || ( ipconfigUDP_MAX_RX_PACKETS > 0U )
  310. if( xReturn == pdPASS ) /*lint !e774: Boolean within 'if' always evaluates to True, depending on configuration. [MISRA 2012 Rule 14.3, required. */
  311. #else
  312. /* xReturn is still pdPASS. */
  313. #endif
  314. {
  315. vTaskSuspendAll();
  316. {
  317. taskENTER_CRITICAL();
  318. {
  319. /* Add the network packet to the list of packets to be
  320. * processed by the socket. */
  321. vListInsertEnd( &( pxSocket->u.xUDP.xWaitingPacketsList ), &( pxNetworkBuffer->xBufferListItem ) );
  322. }
  323. taskEXIT_CRITICAL();
  324. }
  325. ( void ) xTaskResumeAll();
  326. /* Set the socket's receive event */
  327. if( pxSocket->xEventGroup != NULL )
  328. {
  329. ( void ) xEventGroupSetBits( pxSocket->xEventGroup, ( EventBits_t ) eSOCKET_RECEIVE );
  330. }
  331. #if ( ipconfigSUPPORT_SELECT_FUNCTION == 1 )
  332. {
  333. if( ( pxSocket->pxSocketSet != NULL ) && ( ( pxSocket->xSelectBits & ( ( EventBits_t ) eSELECT_READ ) ) != 0U ) )
  334. {
  335. ( void ) xEventGroupSetBits( pxSocket->pxSocketSet->xSelectGroup, ( EventBits_t ) eSELECT_READ );
  336. }
  337. }
  338. #endif
  339. #if ( ipconfigSOCKET_HAS_USER_SEMAPHORE == 1 )
  340. {
  341. if( pxSocket->pxUserSemaphore != NULL )
  342. {
  343. ( void ) xSemaphoreGive( pxSocket->pxUserSemaphore );
  344. }
  345. }
  346. #endif
  347. #if ( ipconfigUSE_DHCP == 1 )
  348. {
  349. if( xIsDHCPSocket( pxSocket ) != 0 )
  350. {
  351. ( void ) xSendDHCPEvent();
  352. }
  353. }
  354. #endif
  355. }
  356. }
  357. else
  358. {
  359. /* There is no socket listening to the target port, but still it might
  360. * be for this node. */
  361. #if ( ipconfigUSE_DNS == 1 ) && ( ipconfigDNS_USE_CALLBACKS == 1 )
  362. /* A DNS reply, check for the source port. Although the DNS client
  363. * does open a UDP socket to send a messages, this socket will be
  364. * closed after a short timeout. Messages that come late (after the
  365. * socket is closed) will be treated here. */
  366. if( FreeRTOS_ntohs( pxUDPPacket->xUDPHeader.usSourcePort ) == ( uint16_t ) ipDNS_PORT )
  367. {
  368. vARPRefreshCacheEntry( &( pxUDPPacket->xEthernetHeader.xSourceAddress ), pxUDPPacket->xIPHeader.ulSourceIPAddress );
  369. xReturn = ( BaseType_t ) ulDNSHandlePacket( pxNetworkBuffer );
  370. }
  371. else
  372. #endif
  373. #if ( ipconfigUSE_LLMNR == 1 )
  374. /* A LLMNR request, check for the destination port. */
  375. if( ( usPort == FreeRTOS_ntohs( ipLLMNR_PORT ) ) ||
  376. ( pxUDPPacket->xUDPHeader.usSourcePort == FreeRTOS_ntohs( ipLLMNR_PORT ) ) )
  377. {
  378. vARPRefreshCacheEntry( &( pxUDPPacket->xEthernetHeader.xSourceAddress ), pxUDPPacket->xIPHeader.ulSourceIPAddress );
  379. xReturn = ( BaseType_t ) ulDNSHandlePacket( pxNetworkBuffer );
  380. }
  381. else
  382. #endif /* ipconfigUSE_LLMNR */
  383. #if ( ipconfigUSE_NBNS == 1 )
  384. /* a NetBIOS request, check for the destination port */
  385. if( ( usPort == FreeRTOS_ntohs( ipNBNS_PORT ) ) ||
  386. ( pxUDPPacket->xUDPHeader.usSourcePort == FreeRTOS_ntohs( ipNBNS_PORT ) ) )
  387. {
  388. vARPRefreshCacheEntry( &( pxUDPPacket->xEthernetHeader.xSourceAddress ), pxUDPPacket->xIPHeader.ulSourceIPAddress );
  389. xReturn = ( BaseType_t ) ulNBNSHandlePacket( pxNetworkBuffer );
  390. }
  391. else
  392. #endif /* ipconfigUSE_NBNS */
  393. {
  394. xReturn = pdFAIL;
  395. }
  396. }
  397. return xReturn;
  398. }
  399. /*-----------------------------------------------------------*/