]> git.sur5r.net Git - freertos/blob - FreeRTOS-Plus/Source/FreeRTOS-Plus-TCP/FreeRTOS_UDP_IP.c
commit 9f316c246baafa15c542a5aea81a94f26e3d6507
[freertos] / FreeRTOS-Plus / Source / FreeRTOS-Plus-TCP / FreeRTOS_UDP_IP.c
1 /*
2  * FreeRTOS+TCP V2.2.1
3  * Copyright (C) 2017 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 /* Standard includes. */
27 #include <stdint.h>
28 #include <stdio.h>
29
30 /* FreeRTOS includes. */
31 #include "FreeRTOS.h"
32 #include "task.h"
33 #include "queue.h"
34 #include "semphr.h"
35
36 /* FreeRTOS+TCP includes. */
37 #include "FreeRTOS_IP.h"
38 #include "FreeRTOS_Sockets.h"
39 #include "FreeRTOS_IP_Private.h"
40 #include "FreeRTOS_UDP_IP.h"
41 #include "FreeRTOS_ARP.h"
42 #include "FreeRTOS_DHCP.h"
43 #include "NetworkInterface.h"
44 #include "NetworkBufferManagement.h"
45
46 #if( ipconfigUSE_DNS == 1 )
47         #include "FreeRTOS_DNS.h"
48 #endif
49
50 /* 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
53 /* Part of the Ethernet and IP headers are always constant when sending an IPv4
54 UDP packet.  This array defines the constant parts, allowing this part of the
55 packet to be filled in using a simple memcpy() instead of individual writes. */
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 void vProcessGeneratedUDPPacket( NetworkBufferDescriptor_t * const pxNetworkBuffer )
76 {
77 UDPPacket_t *pxUDPPacket;
78 IPHeader_t *pxIPHeader;
79 eARPLookupResult_t eReturned;
80 uint32_t ulIPAddress = pxNetworkBuffer->ulIPAddress;
81 size_t uxPayloadSize;
82
83         /* Map the UDP packet onto the start of the frame. */
84         pxUDPPacket = ( UDPPacket_t * ) pxNetworkBuffer->pucEthernetBuffer;
85
86 #if ipconfigSUPPORT_OUTGOING_PINGS == 1
87         if( pxNetworkBuffer->usPort == ipPACKET_CONTAINS_ICMP_DATA )
88         {
89                 uxPayloadSize = pxNetworkBuffer->xDataLength - sizeof( ICMPPacket_t );
90         }
91         else
92 #endif
93         {
94                 uxPayloadSize = pxNetworkBuffer->xDataLength - sizeof( UDPPacket_t );
95         }
96
97         /* Determine the ARP cache status for the requested IP address. */
98         eReturned = eARPGetCacheEntry( &( ulIPAddress ), &( pxUDPPacket->xEthernetHeader.xDestinationAddress ) );
99
100         if( eReturned != eCantSendPacket )
101         {
102                 if( eReturned == eARPCacheHit )
103                 {
104                         #if( ipconfigDRIVER_INCLUDED_TX_IP_CHECKSUM == 0 )
105                                 uint8_t ucSocketOptions;
106                         #endif
107                         iptraceSENDING_UDP_PACKET( pxNetworkBuffer->ulIPAddress );
108
109                         /* Create short cuts to the data within the packet. */
110                         pxIPHeader = &( pxUDPPacket->xIPHeader );
111
112                 #if ( ipconfigSUPPORT_OUTGOING_PINGS == 1 )
113                         /* Is it possible that the packet is not actually a UDP packet
114                         after all, but an ICMP packet. */
115                         if( pxNetworkBuffer->usPort != ipPACKET_CONTAINS_ICMP_DATA )
116                 #endif /* ipconfigSUPPORT_OUTGOING_PINGS */
117                         {
118                         UDPHeader_t *pxUDPHeader;
119
120                                 pxUDPHeader = &( pxUDPPacket->xUDPHeader );
121
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
129                         /* memcpy() the constant parts of the header information into
130                         the     correct location within the packet.  This fills in:
131                                 xEthernetHeader.xSourceAddress
132                                 xEthernetHeader.usFrameType
133                                 xIPHeader.ucVersionHeaderLength
134                                 xIPHeader.ucDifferentiatedServicesCode
135                                 xIPHeader.usLength
136                                 xIPHeader.usIdentification
137                                 xIPHeader.usFragmentOffset
138                                 xIPHeader.ucTimeToLive
139                                 xIPHeader.ucProtocol
140                         and
141                                 xIPHeader.usHeaderChecksum
142                         */
143                         /* Save options now, as they will be overwritten by memcpy */
144                         #if( ipconfigDRIVER_INCLUDED_TX_IP_CHECKSUM == 0 )
145                                 ucSocketOptions = pxNetworkBuffer->pucEthernetBuffer[ ipSOCKET_OPTIONS_OFFSET ];
146                         #endif
147                         /*
148                          * Offset the memcpy by the size of a MAC address to start at the packet's
149                          * Ethernet header 'source' MAC address; the preceding 'destination' should not be altered.
150                          */
151                         char *pxUdpSrcAddrOffset = ( char *) pxUDPPacket + sizeof( MACAddress_t );
152                         memcpy( pxUdpSrcAddrOffset, xDefaultPartUDPPacketHeader.ucBytes, sizeof( xDefaultPartUDPPacketHeader ) );
153
154                 #if ipconfigSUPPORT_OUTGOING_PINGS == 1
155                         if( pxNetworkBuffer->usPort == ipPACKET_CONTAINS_ICMP_DATA )
156                         {
157                                 pxIPHeader->ucProtocol = ipPROTOCOL_ICMP;
158                                 pxIPHeader->usLength = ( uint16_t ) ( uxPayloadSize + sizeof( IPHeader_t ) + sizeof( ICMPHeader_t ) );
159                         }
160                         else
161                 #endif /* ipconfigSUPPORT_OUTGOING_PINGS */
162                         {
163                                 pxIPHeader->usLength = ( uint16_t ) ( uxPayloadSize + sizeof( IPHeader_t ) + sizeof( UDPHeader_t ) );
164                         }
165
166                         pxIPHeader->usLength = FreeRTOS_htons( pxIPHeader->usLength );
167                         /* HT:endian: changed back to network endian */
168                         pxIPHeader->ulDestinationIPAddress = pxNetworkBuffer->ulIPAddress;
169
170                         #if( ipconfigUSE_LLMNR == 1 )
171                         {
172                                 /* LLMNR messages are typically used on a LAN and they're
173                                  * not supposed to cross routers */
174                                 if( pxNetworkBuffer->ulIPAddress == ipLLMNR_IP_ADDR )
175                                 {
176                                         pxIPHeader->ucTimeToLive = 0x01;
177                                 }
178                         }
179                         #endif
180
181                         #if( ipconfigDRIVER_INCLUDED_TX_IP_CHECKSUM == 0 )
182                         {
183                                 pxIPHeader->usHeaderChecksum = 0u;
184                                 pxIPHeader->usHeaderChecksum = usGenerateChecksum( 0UL, ( uint8_t * ) &( pxIPHeader->ucVersionHeaderLength ), ipSIZE_OF_IPv4_HEADER );
185                                 pxIPHeader->usHeaderChecksum = ~FreeRTOS_htons( pxIPHeader->usHeaderChecksum );
186
187                                 if( ( ucSocketOptions & ( uint8_t ) FREERTOS_SO_UDPCKSUM_OUT ) != 0u )
188                                 {
189                                         usGenerateProtocolChecksum( (uint8_t*)pxUDPPacket, pxNetworkBuffer->xDataLength, pdTRUE );
190                                 }
191                                 else
192                                 {
193                                         pxUDPPacket->xUDPHeader.usChecksum = 0u;
194                                 }
195                         }
196                         #endif
197                 }
198                 else if( eReturned == eARPCacheMiss )
199                 {
200                         /* Add an entry to the ARP table with a null hardware address.
201                         This allows the ARP timer to know that an ARP reply is
202                         outstanding, and perform retransmissions if necessary. */
203                         vARPRefreshCacheEntry( NULL, ulIPAddress );
204
205                         /* Generate an ARP for the required IP address. */
206                         iptracePACKET_DROPPED_TO_GENERATE_ARP( pxNetworkBuffer->ulIPAddress );
207                         pxNetworkBuffer->ulIPAddress = ulIPAddress;
208                         vARPGenerateRequestPacket( pxNetworkBuffer );
209                 }
210                 else
211                 {
212                         /* The lookup indicated that an ARP request has already been
213                         sent out for the queried IP address. */
214                         eReturned = eCantSendPacket;
215                 }
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
223                 #if defined( ipconfigETHERNET_MINIMUM_PACKET_BYTES )
224                 {
225                         if( pxNetworkBuffer->xDataLength < ( size_t ) ipconfigETHERNET_MINIMUM_PACKET_BYTES )
226                         {
227                         BaseType_t xIndex;
228
229                                 for( xIndex = ( BaseType_t ) pxNetworkBuffer->xDataLength; xIndex < ( BaseType_t ) ipconfigETHERNET_MINIMUM_PACKET_BYTES; xIndex++ )
230                                 {
231                                         pxNetworkBuffer->pucEthernetBuffer[ xIndex ] = 0u;
232                                 }
233                                 pxNetworkBuffer->xDataLength = ( size_t ) ipconfigETHERNET_MINIMUM_PACKET_BYTES;
234                         }
235                 }
236                 #endif
237
238                 xNetworkInterfaceOutput( pxNetworkBuffer, pdTRUE );
239         }
240         else
241         {
242                 /* The packet can't be sent (DHCP not completed?).  Just drop the
243                 packet. */
244                 vReleaseNetworkBufferAndDescriptor( pxNetworkBuffer );
245         }
246 }
247 /*-----------------------------------------------------------*/
248
249 BaseType_t xProcessReceivedUDPPacket( NetworkBufferDescriptor_t *pxNetworkBuffer, uint16_t usPort )
250 {
251 BaseType_t xReturn = pdPASS;
252 FreeRTOS_Socket_t *pxSocket;
253 configASSERT(pxNetworkBuffer);
254 configASSERT(pxNetworkBuffer->pucEthernetBuffer);
255
256
257 UDPPacket_t *pxUDPPacket = (UDPPacket_t *) pxNetworkBuffer->pucEthernetBuffer;
258
259         /* Caller must check for minimum packet size. */
260         pxSocket = pxUDPSocketLookup( usPort );
261
262         if( pxSocket )
263         {
264
265                 /* When refreshing the ARP cache with received UDP packets we must be
266                 careful;  hundreds of broadcast messages may pass and if we're not
267                 handling them, no use to fill the ARP cache with those IP addresses. */
268                 vARPRefreshCacheEntry( &( pxUDPPacket->xEthernetHeader.xSourceAddress ), pxUDPPacket->xIPHeader.ulSourceIPAddress );
269
270                 #if( ipconfigUSE_CALLBACKS == 1 )
271                 {
272                         /* Did the owner of this socket register a reception handler ? */
273                         if( ipconfigIS_VALID_PROG_ADDRESS( pxSocket->u.xUDP.pxHandleReceive ) )
274                         {
275                                 struct freertos_sockaddr xSourceAddress, destinationAddress;
276                                 void *pcData = ( void * ) &( pxNetworkBuffer->pucEthernetBuffer[ ipUDP_PAYLOAD_OFFSET_IPv4 ] );
277                                 FOnUDPReceive_t xHandler = ( FOnUDPReceive_t ) pxSocket->u.xUDP.pxHandleReceive;
278                                 xSourceAddress.sin_port = pxNetworkBuffer->usPort;
279                                 xSourceAddress.sin_addr = pxNetworkBuffer->ulIPAddress;
280                                 destinationAddress.sin_port = usPort;
281                                 destinationAddress.sin_addr = pxUDPPacket->xIPHeader.ulDestinationIPAddress;
282
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, ( void* ) pcData, ( size_t ) ( pxNetworkBuffer->xDataLength - ipUDP_PAYLOAD_OFFSET_IPv4 ),
285                                         &xSourceAddress, &destinationAddress ) )
286                                 {
287                                         xReturn = pdFAIL; /* FAIL means that we did not consume or release the buffer */
288                                 }
289                         }
290                 }
291                 #endif /* ipconfigUSE_CALLBACKS */
292
293                 #if( ipconfigUDP_MAX_RX_PACKETS > 0 )
294                 {
295                         if( xReturn == pdPASS )
296                         {
297                                 if ( listCURRENT_LIST_LENGTH( &( pxSocket->u.xUDP.xWaitingPacketsList ) ) >= pxSocket->u.xUDP.uxMaxPackets )
298                                 {
299                                         FreeRTOS_debug_printf( ( "xProcessReceivedUDPPacket: buffer full %ld >= %ld port %u\n",
300                                                 listCURRENT_LIST_LENGTH( &( pxSocket->u.xUDP.xWaitingPacketsList ) ),
301                                                 pxSocket->u.xUDP.uxMaxPackets, pxSocket->usLocalPort ) );
302                                         xReturn = pdFAIL; /* we did not consume or release the buffer */
303                                 }
304                         }
305                 }
306                 #endif
307
308                 if( xReturn == pdPASS )
309                 {
310                         vTaskSuspendAll();
311                         {
312                                 if( xReturn == pdPASS )
313                                 {
314                                         taskENTER_CRITICAL();
315                                         {
316                                                 /* Add the network packet to the list of packets to be
317                                                 processed by the socket. */
318                                                 vListInsertEnd( &( pxSocket->u.xUDP.xWaitingPacketsList ), &( pxNetworkBuffer->xBufferListItem ) );
319                                         }
320                                         taskEXIT_CRITICAL();
321                                 }
322                         }
323                         xTaskResumeAll();
324
325                         /* Set the socket's receive event */
326                         if( pxSocket->xEventGroup != NULL )
327                         {
328                                 xEventGroupSetBits( pxSocket->xEventGroup, eSOCKET_RECEIVE );
329                         }
330
331                         #if( ipconfigSUPPORT_SELECT_FUNCTION == 1 )
332                         {
333                                 if( ( pxSocket->pxSocketSet != NULL ) && ( ( pxSocket->xSelectBits & eSELECT_READ ) != 0 ) )
334                                 {
335                                         xEventGroupSetBits( pxSocket->pxSocketSet->xSelectGroup, eSELECT_READ );
336                                 }
337                         }
338                         #endif
339
340                         #if( ipconfigSOCKET_HAS_USER_SEMAPHORE == 1 )
341                         {
342                                 if( pxSocket->pxUserSemaphore != NULL )
343                                 {
344                                         xSemaphoreGive( pxSocket->pxUserSemaphore );
345                                 }
346                         }
347                         #endif
348
349                         #if( ipconfigUSE_DHCP == 1 )
350                         {
351                                 if( xIsDHCPSocket( pxSocket ) )
352                                 {
353                                         xSendEventToIPTask( eDHCPEvent );
354                                 }
355                         }
356                         #endif
357                 }
358         }
359         else
360         {
361                 /* There is no socket listening to the target port, but still it might
362                 be for this node. */
363
364                 #if( ipconfigUSE_DNS == 1 ) && ( ipconfigDNS_USE_CALLBACKS == 1 )
365                         /* A DNS reply, check for the source port.  Although the DNS client
366                         does open a UDP socket to send a messages, this socket will be
367                         closed after a short timeout.  Messages that come late (after the
368                         socket is closed) will be treated here. */
369                         if( FreeRTOS_ntohs( pxUDPPacket->xUDPHeader.usSourcePort ) == ipDNS_PORT )
370                         {
371                                 vARPRefreshCacheEntry( &( pxUDPPacket->xEthernetHeader.xSourceAddress ), pxUDPPacket->xIPHeader.ulSourceIPAddress );
372                                 xReturn = ( BaseType_t )ulDNSHandlePacket( pxNetworkBuffer );
373                         }
374                         else
375                 #endif
376
377                 #if( ipconfigUSE_LLMNR == 1 )
378                         /* a LLMNR request, check for the destination port. */
379                         if( ( usPort == FreeRTOS_ntohs( ipLLMNR_PORT ) ) ||
380                                 ( pxUDPPacket->xUDPHeader.usSourcePort == FreeRTOS_ntohs( ipLLMNR_PORT ) ) )
381                         {
382                                 vARPRefreshCacheEntry( &( pxUDPPacket->xEthernetHeader.xSourceAddress ), pxUDPPacket->xIPHeader.ulSourceIPAddress );
383                                 xReturn = ( BaseType_t )ulDNSHandlePacket( pxNetworkBuffer );
384                         }
385                         else
386                 #endif /* ipconfigUSE_LLMNR */
387
388                 #if( ipconfigUSE_NBNS == 1 )
389                         /* a NetBIOS request, check for the destination port */
390                         if( ( usPort == FreeRTOS_ntohs( ipNBNS_PORT ) ) ||
391                                 ( pxUDPPacket->xUDPHeader.usSourcePort == FreeRTOS_ntohs( ipNBNS_PORT ) ) )
392                         {
393                                 vARPRefreshCacheEntry( &( pxUDPPacket->xEthernetHeader.xSourceAddress ), pxUDPPacket->xIPHeader.ulSourceIPAddress );
394                                 xReturn = ( BaseType_t )ulNBNSHandlePacket( pxNetworkBuffer );
395                         }
396                         else
397                 #endif /* ipconfigUSE_NBNS */
398                 {
399                         xReturn = pdFAIL;
400                 }
401         }
402
403         return xReturn;
404 }
405 /*-----------------------------------------------------------*/