add initial Setup

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
niklasschoeningandClaude Opus 5.5 committed 2026-10-16 18:25:42 +02:00
commit bdb5db2009
1955 files changed
+1004711

No files matched your search

@@ -0,0 +1,111 @@
add_library( freertos_plus_tcp STATIC )
target_sources( freertos_plus_tcp
PRIVATE
include/FreeRTOS_ARP.h
include/FreeRTOS_BitConfig.h
include/FreeRTOS_DHCP.h
include/FreeRTOS_DHCPv6.h
include/FreeRTOS_DNS.h
include/FreeRTOS_DNS_Cache.h
include/FreeRTOS_DNS_Callback.h
include/FreeRTOS_DNS_Globals.h
include/FreeRTOS_DNS_Networking.h
include/FreeRTOS_DNS_Parser.h
include/FreeRTOS_ICMP.h
include/FreeRTOS_IP.h
include/FreeRTOS_IP_Common.h
include/FreeRTOS_IP_Private.h
include/FreeRTOS_IP_Timers.h
include/FreeRTOS_IP_Utils.h
include/FreeRTOS_IPv4.h
include/FreeRTOS_IPv4_Private.h
include/FreeRTOS_IPv4_Sockets.h
include/FreeRTOS_IPv4_Utils.h
include/FreeRTOS_IPv6.h
include/FreeRTOS_IPv6_Private.h
include/FreeRTOS_IPv6_Sockets.h
include/FreeRTOS_IPv6_Utils.h
include/FreeRTOS_ND.h
include/FreeRTOS_Routing.h
include/FreeRTOS_Sockets.h
include/FreeRTOS_Stream_Buffer.h
include/FreeRTOS_TCP_IP.h
include/FreeRTOS_TCP_Reception.h
include/FreeRTOS_TCP_State_Handling.h
include/FreeRTOS_TCP_Transmission.h
include/FreeRTOS_TCP_Utils.h
include/FreeRTOS_TCP_WIN.h
include/FreeRTOS_UDP_IP.h
include/FreeRTOSIPConfigDefaults.h
include/FreeRTOSIPDeprecatedDefinitions.h
include/IPTraceMacroDefaults.h
include/NetworkBufferManagement.h
include/NetworkInterface.h
FreeRTOS_ARP.c
FreeRTOS_BitConfig.c
FreeRTOS_DHCP.c
FreeRTOS_DHCPv6.c
FreeRTOS_DNS.c
FreeRTOS_DNS_Cache.c
FreeRTOS_DNS_Callback.c
FreeRTOS_DNS_Networking.c
FreeRTOS_DNS_Parser.c
FreeRTOS_ICMP.c
FreeRTOS_IP.c
FreeRTOS_IP_Timers.c
FreeRTOS_IP_Utils.c
FreeRTOS_IPv4.c
FreeRTOS_IPv4_Sockets.c
FreeRTOS_IPv4_Utils.c
FreeRTOS_IPv6.c
FreeRTOS_IPv6_Sockets.c
FreeRTOS_IPv6_Utils.c
FreeRTOS_ND.c
FreeRTOS_RA.c
FreeRTOS_Routing.c
FreeRTOS_Sockets.c
FreeRTOS_Stream_Buffer.c
FreeRTOS_TCP_IP.c
FreeRTOS_TCP_IP_IPv4.c
FreeRTOS_TCP_IP_IPv6.c
FreeRTOS_TCP_Reception.c
FreeRTOS_TCP_State_Handling.c
FreeRTOS_TCP_State_Handling_IPv4.c
FreeRTOS_TCP_State_Handling_IPv6.c
FreeRTOS_TCP_Transmission.c
FreeRTOS_TCP_Transmission_IPv4.c
FreeRTOS_TCP_Transmission_IPv6.c
FreeRTOS_TCP_Utils.c
FreeRTOS_TCP_Utils_IPv4.c
FreeRTOS_TCP_Utils_IPv6.c
FreeRTOS_TCP_WIN.c
FreeRTOS_Tiny_TCP.c
FreeRTOS_UDP_IP.c
FreeRTOS_UDP_IPv4.c
FreeRTOS_UDP_IPv6.c
)
target_include_directories( freertos_plus_tcp
PUBLIC
include
)
if(STANDALONE_TEST_BUILD_UNIX)
target_include_directories(freertos_plus_tcp
PUBLIC
${CMAKE_CURRENT_SOURCE_DIR}/../test/build-combination/DefaultConf )
endif()
target_link_libraries( freertos_plus_tcp
PUBLIC
freertos_config
freertos_plus_tcp_port # for pack_struct_start.h
PRIVATE
freertos_kernel
freertos_plus_tcp_network_if
freertos_plus_tcp_utilities
)
add_subdirectory(portable)
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,354 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
/**
* @file FreeRTOS_BitConfig.c
* @brief Some functions that help when analysing a binary stream of information.
* It offers an alternative to using packet structs with unaligned data members.
*/
/* Standard includes. */
#include <stdint.h>
/* FreeRTOS includes. */
#include "FreeRTOS.h"
#include "task.h"
#include "semphr.h"
/* FreeRTOS+TCP includes. */
#include "FreeRTOS_IP.h"
#include "FreeRTOS_UDP_IP.h"
#include "FreeRTOS_Sockets.h"
#include "FreeRTOS_BitConfig.h"
/*-----------------------------------------------------------*/
/**
* @brief Initialise a bit-config struct.
*
* @param[in] pxConfig The structure containing a copy of the bits.
* @param[in] pucData Not NULL if a bit-stream must be analysed, otherwise NULL.
* @param[in] uxSize The length of the binary data stream.
*
* @return pdTRUE if the malloc was OK, otherwise pdFALSE.
*/
BaseType_t xBitConfig_init( BitConfig_t * pxConfig,
const uint8_t * pucData,
size_t uxSize )
{
BaseType_t xResult = pdFALSE;
( void ) memset( ( void * ) pxConfig, 0, sizeof( *pxConfig ) );
pxConfig->ucContents = ( uint8_t * ) pvPortMalloc( uxSize );
if( pxConfig->ucContents != NULL )
{
pxConfig->uxSize = uxSize;
if( pucData != NULL )
{
( void ) memcpy( pxConfig->ucContents, pucData, uxSize );
}
else
{
( void ) memset( pxConfig->ucContents, 0, uxSize );
}
xResult = pdTRUE;
}
else
{
pxConfig->xHasError = pdTRUE;
}
return xResult;
}
/*-----------------------------------------------------------*/
/**
* @brief Read from a bit-config struct.
*
* @param[in] pxConfig The structure containing a copy of the bits.
* @param[in] pucData Not NULL if a bit-stream must be analysed, otherwise NULL.
* @param[in] uxSize The length of the binary data stream.
*
* @return pdTRUE if the malloc was OK, otherwise pdFALSE.
*/
BaseType_t xBitConfig_read_uc( BitConfig_t * pxConfig,
uint8_t * pucData,
size_t uxSize )
{
BaseType_t xResult = pdFALSE;
const size_t uxNeeded = uxSize;
if( pxConfig->xHasError == pdFALSE )
{
if( ( pxConfig->uxIndex + uxNeeded ) <= pxConfig->uxSize )
{
if( pucData != NULL )
{
( void ) memcpy( pucData, &( pxConfig->ucContents[ pxConfig->uxIndex ] ), uxNeeded );
}
else
{
/* Caller just wants to skip some bytes. */
}
pxConfig->uxIndex += uxNeeded;
xResult = pdTRUE;
}
else
{
pxConfig->xHasError = pdTRUE;
}
}
return xResult;
}
/*-----------------------------------------------------------*/
/**
* @brief Peek the last byte from a bit-config struct.
*
* @param[in] pxConfig The structure containing a copy of the bits.
* @param[in] pucData The buffer to stored peeked data.
* @param[in] uxSize The length of the binary data stream.
*
* @return pdTRUE if the malloc was OK, otherwise pdFALSE.
*/
BaseType_t pucBitConfig_peek_last_index_uc( BitConfig_t * pxConfig,
uint8_t * pucData,
size_t uxSize )
{
BaseType_t xResult = pdFALSE;
const size_t uxNeeded = uxSize;
if( pxConfig->xHasError == pdFALSE )
{
if( ( pxConfig->uxIndex >= uxNeeded ) && ( pucData != NULL ) )
{
( void ) memcpy( pucData, &( pxConfig->ucContents[ pxConfig->uxIndex - uxNeeded ] ), uxNeeded );
xResult = pdTRUE;
}
else
{
/* Not support to peek length larger than write. */
pxConfig->xHasError = pdTRUE;
}
}
return xResult;
}
/**
* @brief Read a byte from the bit stream.
*
* @param[in] pxConfig The structure containing a copy of the bits.
*
* @return A byte value. When there was not enough data, xHasError will be set.
*/
uint8_t ucBitConfig_read_8( BitConfig_t * pxConfig )
{
uint8_t ucResult = 0xffU;
const size_t uxNeeded = sizeof ucResult;
uint8_t pucData[ sizeof ucResult ];
if( xBitConfig_read_uc( pxConfig, pucData, uxNeeded ) != pdFALSE )
{
ucResult = pucData[ 0 ];
}
return ucResult;
}
/*-----------------------------------------------------------*/
/**
* @brief Read 2 bytes from the bit stream.
*
* @param[in] pxConfig The structure containing a copy of the bits.
*
* @return A 16-bit value. When there was not enough data, xHasError will be set.
*/
uint16_t usBitConfig_read_16( BitConfig_t * pxConfig )
{
uint16_t usResult = 0xffffU;
const size_t uxNeeded = sizeof usResult;
uint8_t pucData[ sizeof usResult ];
if( xBitConfig_read_uc( pxConfig, pucData, uxNeeded ) != pdFALSE )
{
usResult = ( uint16_t ) ( ( ( ( uint16_t ) pucData[ 0 ] ) << 8 ) |
( ( ( uint16_t ) pucData[ 1 ] ) ) );
}
return usResult;
}
/*-----------------------------------------------------------*/
/**
* @brief Read 4 bytes from the bit stream.
*
* @param[in] pxConfig The structure containing a copy of the bits.
*
* @return A 32-bit value. When there was not enough data, xHasError will be set.
*/
uint32_t ulBitConfig_read_32( BitConfig_t * pxConfig )
{
uint32_t ulResult = 0xffffffffU;
const size_t uxNeeded = sizeof ulResult;
uint8_t pucData[ sizeof ulResult ];
if( xBitConfig_read_uc( pxConfig, pucData, uxNeeded ) != pdFALSE )
{
ulResult = ( ( ( uint32_t ) pucData[ 0 ] ) << 24 ) |
( ( ( uint32_t ) pucData[ 1 ] ) << 16 ) |
( ( ( uint32_t ) pucData[ 2 ] ) << 8 ) |
( ( ( uint32_t ) pucData[ 3 ] ) );
}
return ulResult;
}
/*-----------------------------------------------------------*/
/**
* @brief Read any number bytes from the bit stream.
*
* @param[in] pxConfig The structure containing a copy of the bit stream.
* @param[in] pucData The binary data to be written.
* @param[in] uxSize The number of bytes to be written.
*
* There is no return value. If the operation has failed,
* the field xHasError will be set.
*/
void vBitConfig_write_uc( BitConfig_t * pxConfig,
const uint8_t * pucData,
size_t uxSize )
{
const size_t uxNeeded = uxSize;
if( pxConfig->xHasError == pdFALSE )
{
if( pxConfig->uxIndex <= ( pxConfig->uxSize - uxNeeded ) )
{
uint8_t * pucDestination = &( pxConfig->ucContents[ pxConfig->uxIndex ] );
( void ) memcpy( pucDestination, pucData, uxNeeded );
pxConfig->uxIndex += uxNeeded;
}
else
{
pxConfig->xHasError = pdTRUE;
}
}
}
/*-----------------------------------------------------------*/
/**
* @brief Write a byte to the bit stream.
*
* @param[in] pxConfig The structure containing a copy of the bits.
* @param[in] ucValue The byte to be written.
*
* There is no return value. If the operation has failed,
* the field xHasError will be set.
*/
void vBitConfig_write_8( BitConfig_t * pxConfig,
uint8_t ucValue )
{
const size_t uxNeeded = sizeof ucValue;
vBitConfig_write_uc( pxConfig, &( ucValue ), uxNeeded );
}
/*-----------------------------------------------------------*/
/**
* @brief Write a short word to the bit stream.
*
* @param[in] pxConfig The structure containing a copy of the bits.
* @param[in] usValue The 16-bit value to be written.
*
* There is no return value. If the operation has failed,
* the field xHasError will be set.
*/
void vBitConfig_write_16( BitConfig_t * pxConfig,
uint16_t usValue )
{
const size_t uxNeeded = sizeof usValue;
uint8_t pucData[ sizeof usValue ];
pucData[ 0 ] = ( uint8_t ) ( ( usValue >> 8 ) & 0xFFU );
pucData[ 1 ] = ( uint8_t ) ( usValue & 0xFFU );
vBitConfig_write_uc( pxConfig, pucData, uxNeeded );
}
/*-----------------------------------------------------------*/
/**
* @brief Write a 32-bit word to the bit stream.
*
* @param[in] pxConfig The structure containing a copy of the bits.
* @param[in] ulValue The 32-bit value to be written.
*
* There is no return value. If the operation has failed,
* the field xHasError will be set.
*/
void vBitConfig_write_32( BitConfig_t * pxConfig,
uint32_t ulValue )
{
const size_t uxNeeded = sizeof ulValue;
uint8_t pucData[ sizeof ulValue ];
pucData[ 0 ] = ( uint8_t ) ( ( ulValue >> 24 ) & 0xFFU );
pucData[ 1 ] = ( uint8_t ) ( ( ulValue >> 16 ) & 0xFFU );
pucData[ 2 ] = ( uint8_t ) ( ( ulValue >> 8 ) & 0xFFU );
pucData[ 3 ] = ( uint8_t ) ( ulValue & 0xFFU );
vBitConfig_write_uc( pxConfig, pucData, uxNeeded );
}
/*-----------------------------------------------------------*/
/**
* @brief Deallocate ( release ) the buffer, and clear the bit stream structure.
* Note that the struct must have be initialised before calling this function.
*
* @param[in] pxConfig The structure containing a copy of the bits.
*
*/
void vBitConfig_release( BitConfig_t * pxConfig )
{
if( pxConfig != NULL )
{
if( pxConfig->ucContents != NULL )
{
vPortFree( pxConfig->ucContents );
}
( void ) memset( pxConfig, 0, sizeof( BitConfig_t ) );
}
else
{
/* Nothing to free */
}
}
/*-----------------------------------------------------------*/
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,682 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
/**
* @file FreeRTOS_DNS_Cache.c
* @brief File that handles the DNS caching option
*/
/* FreeRTOS+TCP includes. */
#include "FreeRTOS_IP.h"
#include "FreeRTOS_Sockets.h"
#include "FreeRTOS_UDP_IP.h"
#include "FreeRTOS_DHCP.h"
#include "NetworkBufferManagement.h"
#include "NetworkInterface.h"
#include "FreeRTOS_DNS_Cache.h"
#include "FreeRTOS_DNS_Globals.h"
/* Standard includes. */
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#if ( ( ipconfigUSE_DNS != 0 ) && ( ipconfigUSE_DNS_CACHE == 1 ) )
/*!
* @brief DNS cache structure instantiation
*/
static DNSCacheRow_t xDNSCache[ ipconfigDNS_CACHE_ENTRIES ];
/*!
* @brief indicates the index of a free entry in the cache structure
* \a DNSCacheRow_t
*/
static UBaseType_t uxFreeEntry = 0U;
/** returns the index of the hostname entry in the dns cache. */
static BaseType_t prvFindEntryIndex( const char * pcName,
const IPv46_Address_t * pxIP,
UBaseType_t * uxResult );
/** get entry at \p index from the cache. */
static BaseType_t prvGetCacheIPEntry( UBaseType_t uxIndex,
IPv46_Address_t * pxIP,
uint32_t ulCurrentTimeSeconds,
struct freertos_addrinfo ** ppxAddressInfo );
/** update entry at \p index in the cache. */
static void prvUpdateCacheEntry( UBaseType_t uxIndex,
uint32_t ulTTL,
const IPv46_Address_t * pxIP,
uint32_t ulCurrentTimeSeconds );
/** insert entry in the cache. */
static void prvInsertCacheEntry( const char * pcName,
uint32_t ulTTL,
const IPv46_Address_t * pxIP,
uint32_t ulCurrentTimeSeconds );
/** Copy DNS cache entries at xIndex to a linked struct addrinfo. */
static void prvReadDNSCache( BaseType_t uxIndex,
struct freertos_addrinfo ** ppxAddressInfo );
/*-----------------------------------------------------------*/
#if ( ipconfigUSE_IPv4 != 0 )
/**
* @brief perform a dns lookup in the local cache
* @param pcHostName the lookup name
* @return ulIPAddress with the value from the cache else returns a zero if the
* cache is not enabled or the lookup is not successful
* @post the global structure \a xDNSCache might be modified
*/
uint32_t FreeRTOS_dnslookup( const char * pcHostName )
{
IPv46_Address_t xIPv46_Address;
/* Looking up an IPv4 address in the DNS cache. */
( void ) memset( &xIPv46_Address, 0, sizeof( xIPv46_Address ) );
( void ) FreeRTOS_ProcessDNSCache( pcHostName,
&( xIPv46_Address ),
0,
pdTRUE,
NULL );
return xIPv46_Address.xIPAddress.ulIP_IPv4;
}
/*-----------------------------------------------------------*/
#endif /* if ( ipconfigUSE_IPv4 != 0 ) */
#if ( ipconfigUSE_IPv6 != 0 )
/**
* @brief Perform a dns lookup in the local cache (IPv6)
* @param pcHostName The lookup name
* @param pxAddress_IPv6 The IPv6 address looked up from the cache if the return value is non zero.
* @return ulReturn Non zero if name is found in cache else returns a zero if the
* cache is not enabled or the lookup is not successful
* @post the global structure \a xDNSCache might be modified
*/
uint32_t FreeRTOS_dnslookup6( const char * pcHostName,
IPv6_Address_t * pxAddress_IPv6 )
{
IPv46_Address_t xIPv46_Address;
BaseType_t xResult;
uint32_t ulReturn = 0U;
/* Looking up an IPv6 address in the DNS cache. */
( void ) memset( &xIPv46_Address, 0, sizeof( xIPv46_Address ) );
/* Let FreeRTOS_ProcessDNSCache only return IPv6 addresses. */
xIPv46_Address.xIs_IPv6 = pdTRUE;
xResult = FreeRTOS_ProcessDNSCache( pcHostName, &xIPv46_Address, 0, pdTRUE, NULL );
if( xResult != pdFALSE )
{
( void ) memcpy( pxAddress_IPv6->ucBytes, xIPv46_Address.xIPAddress.xIP_IPv6.ucBytes, ipSIZE_OF_IPv6_ADDRESS );
ulReturn = 1U;
}
return ulReturn;
}
/*-----------------------------------------------------------*/
#endif /* if ( ipconfigUSE_IPv6 != 0 ) */
/**
* @brief perform a dns update in the local cache
* @param pcName the lookup name
* @param pxIP the ip value to insert/replace (IPv4/v6)
* @param ulTTL Time To live (in seconds)
* @param xLookUp Ignored
* @param ppxAddressInfo A pointer to a pointer where the find results
* will be stored.
* @return this is a dummy return, we are actually ignoring the return value
* from this function
* @post the global structure \a xDNSCache might be modified
*/
BaseType_t FreeRTOS_dns_update( const char * pcName,
IPv46_Address_t * pxIP,
uint32_t ulTTL,
BaseType_t xLookUp,
struct freertos_addrinfo ** ppxAddressInfo )
{
/* _HT_ we can as well remove the parameter 'xLookUp'. */
( void ) xLookUp;
( void ) FreeRTOS_ProcessDNSCache( pcName,
pxIP,
ulTTL,
pdFALSE,
ppxAddressInfo );
return pdTRUE;
}
/**
* @brief perform a dns clear in the local cache
* @post the global structure \a xDNSCache is modified
*/
void FreeRTOS_dnsclear( void )
{
( void ) memset( xDNSCache, 0x0, sizeof( xDNSCache ) );
uxFreeEntry = 0U;
}
/**
* @brief process a DNS Cache request (get, update, or insert)
*
* @param[in] pcName the name of the host
* @param[in,out] pxIP when doing a lookup, will be set, when doing an update,
* will be read.
* @param[in] ulTTL Time To Live (in seconds)
* @param[in] xLookUp pdTRUE if a look-up is expected, pdFALSE, when the DNS cache must
* be updated.
* @param[in,out] ppxAddressInfo A pointer to a pointer where the find results
* will be stored.
* @return whether the operation was successful
* @post the global structure \a xDNSCache might be modified
*/
BaseType_t FreeRTOS_ProcessDNSCache( const char * pcName,
IPv46_Address_t * pxIP,
uint32_t ulTTL,
BaseType_t xLookUp,
struct freertos_addrinfo ** ppxAddressInfo )
{
UBaseType_t uxIndex;
BaseType_t xResult;
/* Get the current time in clock-ticks. */
TickType_t xCurrentTickCount = xTaskGetTickCount();
/* In milliseconds. */
uint32_t ulCurrentTimeSeconds;
configASSERT( ( pcName != NULL ) );
if( xLookUp != pdFALSE )
{
pxIP->xIPAddress.ulIP_IPv4 = 0U;
}
ulCurrentTimeSeconds = ( uint32_t ) ( ( xCurrentTickCount / configTICK_RATE_HZ ) );
xResult = prvFindEntryIndex( pcName, pxIP, &uxIndex );
if( xResult == pdTRUE )
{ /* Element found */
/* Is this function called for a lookup or to add/update an IP address? */
if( xLookUp == pdTRUE )
{
/* This statement can only be reached when xResult is true; which
* implies that the entry is present and a 'get' operation will result
* in success. Therefore, it is safe to ignore the return value of the
* below function. */
( void ) prvGetCacheIPEntry( uxIndex,
pxIP,
ulCurrentTimeSeconds,
ppxAddressInfo );
}
else
{
prvUpdateCacheEntry( uxIndex,
ulTTL,
pxIP,
ulCurrentTimeSeconds );
}
}
else /* Element not Found xResult = pdFALSE */
{
if( xLookUp == pdTRUE )
{
pxIP->xIPAddress.ulIP_IPv4 = 0U;
}
else
{
prvInsertCacheEntry( pcName,
ulTTL,
pxIP,
ulCurrentTimeSeconds );
}
}
#if ( ipconfigHAS_DEBUG_PRINTF != 0 )
if( ( xLookUp == pdFALSE ) || ( pxIP->xIPAddress.ulIP_IPv4 != 0U ) )
{
char pcAddress[ 40 ];
IP_Address_t xAddress;
BaseType_t xFamily = FREERTOS_AF_INET;
switch( pxIP->xIs_IPv6 )
{
#if ( ipconfigUSE_IPv6 != 0 )
case pdTRUE:
( void ) memcpy( xAddress.xIP_IPv6.ucBytes, pxIP->xIPAddress.xIP_IPv6.ucBytes, ipSIZE_OF_IPv6_ADDRESS );
xFamily = FREERTOS_AF_INET6;
break;
#endif /* if ( ipconfigUSE_IPv6 != 0 ) */
#if ( ipconfigUSE_IPv4 != 0 )
case pdFALSE:
xAddress.ulIP_IPv4 = pxIP->xIPAddress.ulIP_IPv4;
break;
#endif /* if ( ipconfigUSE_IPv4 != 0 ) */
default:
/* MISRA 16.4 Compliance */
FreeRTOS_debug_printf( ( "FreeRTOS_ProcessDNSCache: Undefined IP Type \n" ) );
break;
}
( void ) FreeRTOS_inet_ntop( xFamily,
( const void * ) xAddress.xIP_IPv6.ucBytes,
pcAddress,
( socklen_t ) sizeof( pcAddress ) );
FreeRTOS_debug_printf( ( "FreeRTOS_ProcessDNSCache: %s: '%s' @ %s (TTL %u)\n",
( xLookUp != 0 ) ? "look-up" : "add",
pcName,
pcAddress,
( unsigned ) FreeRTOS_ntohl( ulTTL ) ) );
}
#endif /* ( ipconfigHAS_DEBUG_PRINTF != 0 ) */
return xResult;
}
/**
* @brief returns the index of the hostname entry in the dns cache.
* @param[in] pcName find it in the cache
* @param[in] pxIP ip address
* @param [out] uxResult index number
* @returns res pdTRUE if index in found else pdFALSE
*/
static BaseType_t prvFindEntryIndex( const char * pcName,
const IPv46_Address_t * pxIP,
UBaseType_t * uxResult )
{
BaseType_t xReturn = pdFALSE;
UBaseType_t uxIndex;
/* For each entry in the DNS cache table. */
for( uxIndex = 0; uxIndex < ipconfigDNS_CACHE_ENTRIES; uxIndex++ )
{
if( xDNSCache[ uxIndex ].pcName[ 0 ] == ( char ) 0 )
{ /* empty slot */
continue;
}
if( strcmp( xDNSCache[ uxIndex ].pcName, pcName ) == 0 )
{ /* hostname found */
/* IPv6 is enabled, See if the cache entry has the correct type. */
if( pxIP->xIs_IPv6 == xDNSCache[ uxIndex ].xAddresses[ 0 ].xIs_IPv6 )
{
xReturn = pdTRUE;
*uxResult = uxIndex;
break;
}
}
}
return xReturn;
}
/*-----------------------------------------------------------*/
/**
* @brief get entry at \p index from the cache
* @param[in] uxIndex index in the cache
* @param[out] pxIP fill it with the result
* @param[in] ulCurrentTimeSeconds current time
* @param[out] ppxAddressInfo Target to store the DNS entries.
* @returns \c pdTRUE if the value is valid \c pdFALSE otherwise
* @post the global structure \a xDNSCache might be modified
*
*/
static BaseType_t prvGetCacheIPEntry( UBaseType_t uxIndex,
IPv46_Address_t * pxIP,
uint32_t ulCurrentTimeSeconds,
struct freertos_addrinfo ** ppxAddressInfo )
{
BaseType_t isRead;
uint32_t ulIPAddressIndex = 0;
uint32_t ulAge = ulCurrentTimeSeconds - xDNSCache[ uxIndex ].ulTimeWhenAddedInSeconds;
/* Confirm that the record is still fresh.
* The field ulTTL was stored as network-endian. */
if( ulAge < FreeRTOS_ntohl( xDNSCache[ uxIndex ].ulTTL ) )
{
#if ( ipconfigDNS_CACHE_ADDRESSES_PER_ENTRY > 1 )
uint8_t ucIndex;
/* The ucCurrentIPAddress value increments without bound and will rollover, */
/* modulo it by the number of IP addresses to keep it in range. */
/* Also perform a final modulo by the max number of IP addresses */
/* per DNS cache entry to prevent out-of-bounds access in the event */
/* that ucNumIPAddresses has been corrupted. */
ucIndex = xDNSCache[ uxIndex ].ucCurrentIPAddress % xDNSCache[ uxIndex ].ucNumIPAddresses;
ucIndex = ucIndex % ( uint8_t ) ipconfigDNS_CACHE_ADDRESSES_PER_ENTRY;
ulIPAddressIndex = ucIndex;
xDNSCache[ uxIndex ].ucCurrentIPAddress++;
#endif /* if ( ipconfigDNS_CACHE_ADDRESSES_PER_ENTRY > 1 ) */
( void ) memcpy( pxIP, &( xDNSCache[ uxIndex ].xAddresses[ ulIPAddressIndex ] ), sizeof( *pxIP ) );
isRead = pdTRUE;
if( ppxAddressInfo != NULL )
{
/* Copy all entries from position 'uxIndex' to a linked struct addrinfo. */
prvReadDNSCache( ( BaseType_t ) uxIndex, ppxAddressInfo );
}
}
else
{
/* Age out the old cached record. */
xDNSCache[ uxIndex ].pcName[ 0 ] = ( char ) 0;
isRead = pdFALSE;
}
return isRead;
}
/*-----------------------------------------------------------*/
/**
* @brief update entry at \p index in the cache
* @param[in] uxIndex index in the cache
* @param[in] ulTTL time to live (in seconds)
* @param[in] pxIP ip to update the cache with
* @param[in] ulCurrentTimeSeconds current time
* @post the global structure \a xDNSCache is modified
*/
static void prvUpdateCacheEntry( UBaseType_t uxIndex,
uint32_t ulTTL,
const IPv46_Address_t * pxIP,
uint32_t ulCurrentTimeSeconds )
{
uint32_t ulIPAddressIndex = 0;
#if ( ipconfigDNS_CACHE_ADDRESSES_PER_ENTRY > 1 )
if( xDNSCache[ uxIndex ].ucNumIPAddresses <
( uint8_t ) ipconfigDNS_CACHE_ADDRESSES_PER_ENTRY )
{
/* If more answers exist than there are IP address storage
* slots they will overwrite entry 0 */
ulIPAddressIndex = xDNSCache[ uxIndex ].ucNumIPAddresses;
xDNSCache[ uxIndex ].ucNumIPAddresses++;
}
#endif
( void ) memcpy( &( xDNSCache[ uxIndex ].xAddresses[ ulIPAddressIndex ] ), pxIP, sizeof( *pxIP ) );
xDNSCache[ uxIndex ].ulTTL = ulTTL;
xDNSCache[ uxIndex ].ulTimeWhenAddedInSeconds = ulCurrentTimeSeconds;
}
/*-----------------------------------------------------------*/
/**
* @brief insert entry in the cache
* @param[in] pcName cache entry key
* @param[in] ulTTL time to live (in seconds)
* @param[in] pxIP ip address
* @param[in] ulCurrentTimeSeconds current time
* @post the global structure \a xDNSCache is modified
*/
static void prvInsertCacheEntry( const char * pcName,
uint32_t ulTTL,
const IPv46_Address_t * pxIP,
uint32_t ulCurrentTimeSeconds )
{
/* Add or update the item. */
if( strlen( pcName ) < ( size_t ) ipconfigDNS_CACHE_NAME_LENGTH )
{
( void ) strncpy( xDNSCache[ uxFreeEntry ].pcName, pcName, ipconfigDNS_CACHE_NAME_LENGTH );
( void ) memcpy( &( xDNSCache[ uxFreeEntry ].xAddresses[ 0 ] ), pxIP, sizeof( *pxIP ) );
xDNSCache[ uxFreeEntry ].ulTTL = ulTTL;
xDNSCache[ uxFreeEntry ].ulTimeWhenAddedInSeconds = ulCurrentTimeSeconds;
#if ( ipconfigDNS_CACHE_ADDRESSES_PER_ENTRY > 1 )
xDNSCache[ uxFreeEntry ].ucNumIPAddresses = 1;
xDNSCache[ uxFreeEntry ].ucCurrentIPAddress = 0;
/* Initialize all remaining IP addresses in this entry to 0 */
( void ) memset( &xDNSCache[ uxFreeEntry ].xAddresses[ 1 ],
0,
sizeof( xDNSCache[ uxFreeEntry ].xAddresses[ 1 ] ) *
( ( uint32_t ) ipconfigDNS_CACHE_ADDRESSES_PER_ENTRY - 1U ) );
#endif
uxFreeEntry++;
if( uxFreeEntry == ipconfigDNS_CACHE_ENTRIES )
{
uxFreeEntry = 0;
}
}
}
/*-----------------------------------------------------------*/
/**
* @brief Copy DNS cache entries at uxIndex to a linked struct addrinfo.
* @param[in] uxIndex The index from where entries must be copied.
* @param[out] ppxAddressInfo Target to store the DNS entries.
*/
static void prvReadDNSCache( BaseType_t uxIndex,
struct freertos_addrinfo ** ppxAddressInfo )
{
size_t uxIPAddressIndex;
size_t uxNumIPAddresses = 1U;
const IPv46_Address_t * pxAddresses;
struct freertos_addrinfo * pxNewAddress = NULL;
struct freertos_addrinfo ** ppxLastAddress = ppxAddressInfo;
#if ( ipconfigDNS_CACHE_ADDRESSES_PER_ENTRY > 1 )
uxNumIPAddresses = ( size_t ) xDNSCache[ uxIndex ].ucNumIPAddresses;
if( uxNumIPAddresses > ( size_t ) ipconfigDNS_CACHE_ADDRESSES_PER_ENTRY )
{
/* Make this a configASSERT()? */
uxNumIPAddresses = ipconfigDNS_CACHE_ADDRESSES_PER_ENTRY;
}
#endif /* ( ipconfigDNS_CACHE_ADDRESSES_PER_ENTRY > 1 ) */
for( uxIPAddressIndex = 0; uxIPAddressIndex < uxNumIPAddresses; uxIPAddressIndex++ )
{
pxAddresses = &( xDNSCache[ uxIndex ].xAddresses[ uxIPAddressIndex ] );
switch( pxAddresses->xIs_IPv6 ) /* LCOV_EXCL_BR_LINE - xIs_IPv6 is always either pdFALSE or pdTRUE. */
{
#if ( ipconfigUSE_IPv4 != 0 )
case pdFALSE:
{
const uint8_t * ucBytes = ( const uint8_t * ) &( pxAddresses->xIPAddress.ulIP_IPv4 );
pxNewAddress = pxNew_AddrInfo( xDNSCache[ uxIndex ].pcName, FREERTOS_AF_INET4, ucBytes );
}
break;
#endif /* ( ipconfigUSE_IPv4 != 0 ) */
#if ( ipconfigUSE_IPv6 != 0 )
case pdTRUE:
pxNewAddress = pxNew_AddrInfo( xDNSCache[ uxIndex ].pcName, FREERTOS_AF_INET6, pxAddresses->xIPAddress.xIP_IPv6.ucBytes );
break;
#endif /* ( ipconfigUSE_IPv6 != 0 ) */
default: /* LCOV_EXCL_LINE - xIs_IPv6 is always either pdFALSE or FREERTOS_AF_INET6. */
/* MISRA 16.4 Compliance */
FreeRTOS_debug_printf( ( "prvReadDNSCache: Undefined IP Type \n" ) );
break; /* LCOV_EXCL_LINE - xIs_IPv6 is always either pdFALSE or FREERTOS_AF_INET6. */
}
if( pxNewAddress == NULL )
{
/* Malloc must has failed. */
break;
}
/* Set either 'ppxAddressInfo' or 'pxNewAddress->ai_next'. */
*( ppxLastAddress ) = pxNewAddress;
ppxLastAddress = &( pxNewAddress->ai_next );
}
}
/*-----------------------------------------------------------*/
/**
* @brief Lookup the given hostname in the DNS cache
* @param[in] pcHostName THe host name to lookup
* @param[in] xFamily IP type FREERTOS_AF_INET6 / FREERTOS_AF_INET4
* @param[out] ppxAddressInfo Target to store the DNS entries.
* @returns This function returns either a valid IPv4 address, or
* in case of an IPv6 lookup, it will return a non-zero.
*/
uint32_t Prepare_CacheLookup( const char * pcHostName,
BaseType_t xFamily,
struct freertos_addrinfo ** ppxAddressInfo )
{
uint32_t ulIPAddress = 0U;
IPv46_Address_t xIPv46_Address;
switch( xFamily )
{
#if ( ipconfigUSE_IPv4 != 0 )
case FREERTOS_AF_INET:
{
BaseType_t xFound;
xIPv46_Address.xIs_IPv6 = pdFALSE;
xFound = FreeRTOS_ProcessDNSCache( pcHostName, &( xIPv46_Address ), 0, pdTRUE, ppxAddressInfo );
if( xFound != 0 )
{
if( ( ppxAddressInfo != NULL ) && ( *( ppxAddressInfo ) != NULL ) )
{
const struct freertos_sockaddr * sockaddr = ( *( ppxAddressInfo ) )->ai_addr;
ulIPAddress = sockaddr->sin_address.ulIP_IPv4;
}
}
else
{
/* prvGetHostByName will be called to start a DNS lookup. */
}
}
break;
#endif /* ( ipconfigUSE_IPv4 != 0 ) */
#if ( ipconfigUSE_IPv6 != 0 )
case FREERTOS_AF_INET6:
{
BaseType_t xFound;
xIPv46_Address.xIs_IPv6 = pdTRUE;
xFound = FreeRTOS_ProcessDNSCache( pcHostName, &( xIPv46_Address ), 0, pdTRUE, ppxAddressInfo );
if( xFound != 0 )
{
if( ( ppxAddressInfo != NULL ) && ( *( ppxAddressInfo ) != NULL ) )
{
/* This function returns either a valid IPv4 address, or
* in case of an IPv6 lookup, it will return a non-zero */
ulIPAddress = 1U;
}
}
else
{
/* prvGetHostByName will be called to start a DNS lookup. */
}
}
break;
#endif /* ( ipconfigUSE_IPv6 != 0 ) */
default:
/* MISRA 16.4 Compliance */
FreeRTOS_debug_printf( ( "Prepare_CacheLookup: Undefined xFamily \n" ) );
break;
}
return ulIPAddress;
}
/*-----------------------------------------------------------*/
#if ( ipconfigDNS_CACHE_ADDRESSES_PER_ENTRY > 1 )
/**
* @brief For debugging only: prints the contents of the DNS cache table.
*/
void vShowDNSCacheTable( void )
{
UBaseType_t xEntry;
UBaseType_t xSubEntry;
for( xEntry = 0; xEntry < ipconfigDNS_CACHE_ENTRIES; xEntry++ )
{
const DNSCacheRow_t * pxRow = &( xDNSCache[ xEntry ] );
if( pxRow->pcName[ 0 ] != ( char ) 0 )
{
FreeRTOS_printf( ( "Entry %2u: %s use %u/%u\n",
( unsigned ) xEntry,
pxRow->pcName,
( unsigned ) pxRow->ucCurrentIPAddress,
( unsigned ) pxRow->ucNumIPAddresses ) );
for( xSubEntry = 0; xSubEntry < pxRow->ucNumIPAddresses; xSubEntry++ )
{
char pcAddress[ 40 ] = "";
switch( pxRow->xAddresses[ 0 ].xIs_IPv6 )
{
/* The first entry determines the type of row:
* either IPv4 or IPv6. */
#if ( ipconfigUSE_IPv4 != 0 )
case pdFALSE:
( void ) FreeRTOS_inet_ntop( FREERTOS_AF_INET4,
( const void * ) &( pxRow->xAddresses[ xSubEntry ].xIPAddress.ulIP_IPv4 ),
pcAddress,
sizeof( pcAddress ) );
break;
#endif /* ( ipconfigUSE_IPv4 != 0 ) */
#if ( ipconfigUSE_IPv6 != 0 )
case pdTRUE:
( void ) FreeRTOS_inet_ntop( FREERTOS_AF_INET6,
( const void * ) pxRow->xAddresses[ xSubEntry ].xIPAddress.xIP_IPv6.ucBytes,
pcAddress,
sizeof( pcAddress ) );
break;
#endif /* ( ipconfigUSE_IPv6 != 0 ) */
default:
/* MISRA 16.4 Compliance */
FreeRTOS_debug_printf( ( "vShowDNSCacheTable: Undefined IP Type \n" ) );
break;
}
FreeRTOS_printf( ( " %2u: %s\n",
( unsigned ) xSubEntry,
pcAddress ) );
}
}
}
}
#endif /* if ( ipconfigDNS_CACHE_ADDRESSES_PER_ENTRY > 1 ) */
/*-----------------------------------------------------------*/
#endif /* if ( ( ipconfigUSE_DNS != 0 ) && ( ipconfigUSE_DNS_CACHE == 1 ) ) */
@@ -0,0 +1,284 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
/**
* @file FreeRTOS_DNS_Callback.c
* @brief File that handles the DNS Callback option
*/
#include "FreeRTOS_DNS_Callback.h"
#include "FreeRTOS_IP.h"
#include "FreeRTOS_IP_Private.h"
#include "FreeRTOS_DNS_Globals.h"
#include "FreeRTOS_IP_Timers.h"
#if ( ( ipconfigDNS_USE_CALLBACKS == 1 ) && ( ipconfigUSE_DNS != 0 ) )
/**
* @brief list of callbacks to send
*/
static List_t xCallbackList;
/**
* @brief A DNS reply was received, see if there is any matching entry and
* call the handler.
*
* @param[in,out] pxSet a set of variables that are shared among the helper functions.
* @param[in] pxAddress Pointer to address info ( IPv4/IPv6 ) obtained from the DNS server.
*
* @return Returns pdTRUE if uxIdentifier was recognized.
*/
BaseType_t xDNSDoCallback( ParseSet_t * pxSet,
struct freertos_addrinfo * pxAddress )
{
BaseType_t xResult = pdFALSE;
const ListItem_t * pxIterator;
const ListItem_t * pxEnd = listGET_END_MARKER( &xCallbackList );
TickType_t uxIdentifier = ( TickType_t ) pxSet->pxDNSMessageHeader->usIdentifier;
/* While iterating through the list, the scheduler is suspended.
* Remember which function shall be called once the scheduler is
* running again. */
FOnDNSEvent pCallbackFunction = NULL;
void * pvSearchID = NULL;
vTaskSuspendAll();
{
for( pxIterator = ( const ListItem_t * ) listGET_HEAD_ENTRY( &xCallbackList );
pxIterator != ( const ListItem_t * ) pxEnd;
pxIterator = ( const ListItem_t * ) listGET_NEXT( pxIterator ) )
{
BaseType_t xMatching;
DNSCallback_t * pxCallback = ( ( DNSCallback_t * ) listGET_LIST_ITEM_OWNER( pxIterator ) );
#if ( ipconfigUSE_MDNS == 1 )
/* mDNS port 5353. Host byte order comparison. */
if( pxSet->usPortNumber == ipMDNS_PORT )
{
/* In mDNS, the query ID field is ignored and the
* hostname will be compared with outstanding requests. */
xMatching = ( strcasecmp( pxCallback->pcName, pxSet->pcName ) == 0 ) ? pdTRUE : pdFALSE;
}
else
#endif /* if ( ipconfigUSE_MDNS == 1 ) */
{
xMatching = ( listGET_LIST_ITEM_VALUE( pxIterator ) == uxIdentifier ) ? pdTRUE : pdFALSE;
}
if( xMatching == pdTRUE )
{
pvSearchID = pxCallback->pvSearchID;
pCallbackFunction = pxCallback->pCallbackFunction;
( void ) uxListRemove( &pxCallback->xListItem );
vPortFree( pxCallback );
if( listLIST_IS_EMPTY( &xCallbackList ) != pdFALSE )
{
/* The list of outstanding requests is empty. No need for periodic polling. */
vIPSetDNSTimerEnableState( pdFALSE );
}
xResult = pdTRUE;
break;
}
}
}
( void ) xTaskResumeAll();
if( pCallbackFunction != NULL )
{
pCallbackFunction( pxSet->pcName, pvSearchID, pxAddress );
}
return xResult;
}
/**
* @brief FreeRTOS_gethostbyname_a() was called along with callback parameters.
* Store them in a list for later reference.
*
* @param[in] pcHostName The hostname whose IP address is being searched for.
* @param[in] pvSearchID The search ID of the DNS callback function to set.
* @param[in] pCallbackFunction The callback function pointer.
* @param[in] uxTimeout Timeout of the callback function in ms.
* @param[in] uxIdentifier Random number used as ID in the DNS message.
* @param[in] xIsIPv6 pdTRUE if the address type should be IPv6.
*/
BaseType_t xDNSSetCallBack( const char * pcHostName,
void * pvSearchID,
FOnDNSEvent pCallbackFunction,
TickType_t uxTimeout,
TickType_t uxIdentifier,
BaseType_t xIsIPv6 )
{
BaseType_t xReturn = pdPASS;
size_t lLength = strlen( pcHostName );
/* MISRA Ref 4.12.1 [Use of dynamic memory]. */
/* More details at: https://github.com/FreeRTOS/FreeRTOS-Plus-TCP/blob/main/MISRA.md#directive-412. */
/* coverity[misra_c_2012_directive_4_12_violation] */
DNSCallback_t * pxCallback = ( ( DNSCallback_t * ) pvPortMalloc( sizeof( *pxCallback ) + lLength ) );
/* Translate from ms to number of clock ticks. */
uxTimeout = pdMS_TO_TICKS( uxTimeout );
if( pxCallback != NULL )
{
if( listLIST_IS_EMPTY( &xCallbackList ) != pdFALSE )
{
/* This is the first one, start the DNS timer to check for timeouts */
vDNSTimerReload( FreeRTOS_min_uint32( 1000U, ( uint32_t ) uxTimeout ) );
}
( void ) strncpy( pxCallback->pcName, pcHostName, lLength + 1U );
pxCallback->pCallbackFunction = pCallbackFunction;
pxCallback->pvSearchID = pvSearchID;
pxCallback->uxRemainingTime = uxTimeout;
pxCallback->xIsIPv6 = xIsIPv6;
vTaskSetTimeOutState( &( pxCallback->uxTimeoutState ) );
listSET_LIST_ITEM_OWNER( &( pxCallback->xListItem ), ( void * ) pxCallback );
listSET_LIST_ITEM_VALUE( &( pxCallback->xListItem ), uxIdentifier );
vTaskSuspendAll();
{
vListInsertEnd( &xCallbackList, &pxCallback->xListItem );
}
( void ) xTaskResumeAll();
}
else
{
xReturn = pdFAIL;
FreeRTOS_debug_printf( ( " xDNSSetCallBack : Could not allocate memory: %u bytes",
( unsigned ) ( sizeof( *pxCallback ) + lLength ) ) );
}
return xReturn;
}
/*-----------------------------------------------------------*/
/**
* @brief Iterate through the list of call-back structures and remove
* old entries which have reached a timeout.
* As soon as the list has become empty, the DNS timer will be stopped.
* In case pvSearchID is supplied, the user wants to cancel a DNS request.
*
* @param[in] pvSearchID The search ID of callback function whose associated
* DNS request is being cancelled. If non-ID specific checking of
* all requests is required, then this field should be kept as NULL.
*/
void vDNSCheckCallBack( void * pvSearchID )
{
const ListItem_t * pxIterator;
const ListItem_t * pxEnd = listGET_END_MARKER( &xCallbackList );
/* When a DNS-search times out, the call-back function shall
* be called. Store theses item in a temporary list.
* Only when the scheduler is running, user functions
* shall be called. */
List_t xTempList;
vListInitialise( &xTempList );
vTaskSuspendAll();
{
for( pxIterator = ( const ListItem_t * ) listGET_HEAD_ENTRY( &xCallbackList );
pxIterator != pxEnd; )
{
DNSCallback_t * pxCallback = ( ( DNSCallback_t * ) listGET_LIST_ITEM_OWNER( pxIterator ) );
/* Move to the next item because we might remove this item */
pxIterator = ( const ListItem_t * ) listGET_NEXT( pxIterator );
if( ( pvSearchID != NULL ) && ( pvSearchID == pxCallback->pvSearchID ) )
{
( void ) uxListRemove( &( pxCallback->xListItem ) );
vPortFree( pxCallback );
}
else if( xTaskCheckForTimeOut( &pxCallback->uxTimeoutState, &( pxCallback->uxRemainingTime ) ) != pdFALSE )
{
/* A time-out occurred in the asynchronous search.
* Remove it from xCallbackList. */
( void ) uxListRemove( &( pxCallback->xListItem ) );
/* Insert it in a temporary list. The function will be called
* once the scheduler is resumed. */
vListInsertEnd( &( xTempList ), &pxCallback->xListItem );
}
else
{
/* This call-back is still waiting for a reply or a time-out. */
}
}
}
( void ) xTaskResumeAll();
if( listLIST_IS_EMPTY( &xTempList ) == pdFALSE )
{
/* There is at least one item in xTempList which must be removed and deleted. */
pxEnd = listGET_END_MARKER( &xTempList );
for( pxIterator = ( const ListItem_t * ) listGET_HEAD_ENTRY( &xTempList );
pxIterator != pxEnd;
)
{
DNSCallback_t * pxCallback = ( ( DNSCallback_t * ) listGET_LIST_ITEM_OWNER( pxIterator ) );
/* Move to the next item because we might remove this item */
pxIterator = ( const ListItem_t * ) listGET_NEXT( pxIterator );
/* A time-out occurred in the asynchronous search.
* Call the application hook with the proper information. */
if( pxCallback->xIsIPv6 != 0 )
{
pxCallback->pCallbackFunction( pxCallback->pcName, pxCallback->pvSearchID, NULL );
}
else
{
pxCallback->pCallbackFunction( pxCallback->pcName, pxCallback->pvSearchID, 0U );
}
/* Remove it from 'xTempList' and free the memory. */
( void ) uxListRemove( &( pxCallback->xListItem ) );
vPortFree( pxCallback );
}
}
if( listLIST_IS_EMPTY( &xCallbackList ) != pdFALSE )
{
vIPSetDNSTimerEnableState( pdFALSE );
}
}
/*-----------------------------------------------------------*/
/**
* @brief initialize the cache
* @post will modify global list xCallbackList
*/
void vDNSCallbackInitialise()
{
vListInitialise( &xCallbackList );
}
#endif /* if ( ipconfigDNS_USE_CALLBACKS == 1 ) */
@@ -0,0 +1,173 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
/**
* @file FreeRTOS_DNS_Networking.c
* @brief Implements the Domain Name System Networking
* for the FreeRTOS+TCP network stack.
*/
#include "FreeRTOS.h"
#include "FreeRTOS_DNS_Networking.h"
#if ( ipconfigUSE_DNS != 0 )
/**
* @brief Bind the socket to a port number.
* @param[in] xSocket the socket that must be bound.
* @param[in] usPort the port number to bind to.
* @return The created socket - or NULL if the socket could not be created or could not be bound.
*/
BaseType_t DNS_BindSocket( Socket_t xSocket,
uint16_t usPort )
{
struct freertos_sockaddr xAddress;
BaseType_t xReturn;
( void ) memset( &( xAddress ), 0, sizeof( xAddress ) );
xAddress.sin_family = FREERTOS_AF_INET;
xAddress.sin_port = usPort;
xReturn = FreeRTOS_bind( xSocket, &xAddress, ( socklen_t ) sizeof( xAddress ) );
return xReturn;
}
/**
* @brief Create a socket and bind it to the standard DNS port number.
*
* @return The created socket - or NULL if the socket could not be created or could not be bound.
*/
Socket_t DNS_CreateSocket( TickType_t uxReadTimeOut_ticks )
{
Socket_t xSocket;
TickType_t uxWriteTimeOut_ticks = ipconfigDNS_SEND_BLOCK_TIME_TICKS;
/* This must be the first time this function has been called. Create
* the socket. */
xSocket = FreeRTOS_socket( FREERTOS_AF_INET, FREERTOS_SOCK_DGRAM, FREERTOS_IPPROTO_UDP );
if( xSocketValid( xSocket ) == pdFALSE )
{
/* There was an error, return NULL. */
xSocket = NULL;
}
else
{
/* Ideally we should check for the return value. But since we are passing
* correct parameters, and xSocket is != NULL, the return value is
* going to be '0' i.e. success. Thus, return value is discarded */
( void ) FreeRTOS_setsockopt( xSocket, 0, FREERTOS_SO_SNDTIMEO, &( uxWriteTimeOut_ticks ), sizeof( TickType_t ) );
( void ) FreeRTOS_setsockopt( xSocket, 0, FREERTOS_SO_RCVTIMEO, &( uxReadTimeOut_ticks ), sizeof( TickType_t ) );
}
return xSocket;
}
/**
* @brief perform a DNS network request
* @param xDNSSocket Created socket
* @param xAddress address structure (ip, port etc)
* @param pxDNSBuf buffer to send
* @return xReturn: true if the message could be sent
* false otherwise
*
*/
BaseType_t DNS_SendRequest( Socket_t xDNSSocket,
const struct freertos_sockaddr * xAddress,
const struct xDNSBuffer * pxDNSBuf )
{
BaseType_t xReturn = pdFALSE;
BaseType_t xSent;
iptraceSENDING_DNS_REQUEST();
/* Send the DNS message. */
xSent = FreeRTOS_sendto( xDNSSocket,
pxDNSBuf->pucPayloadBuffer,
pxDNSBuf->uxPayloadLength,
FREERTOS_ZERO_COPY,
xAddress,
( socklen_t ) sizeof( *xAddress ) );
if( xSent == ( BaseType_t ) pxDNSBuf->uxPayloadLength )
{
xReturn = pdPASS;
}
else
{
/* The message was not sent so the stack will not be
* releasing the zero copy - it must be released here. */
xReturn = pdFAIL;
}
return xReturn;
}
/*-----------------------------------------------------------*/
/**
* @brief perform a DNS network read
* @param xDNSSocket socket
* @param xAddress address to read from
* @param pxReceiveBuffer buffer to fill with received data
*/
BaseType_t DNS_ReadReply( ConstSocket_t xDNSSocket,
struct freertos_sockaddr * xAddress,
struct xDNSBuffer * pxReceiveBuffer )
{
BaseType_t xReturn;
uint32_t ulAddressLength = ( uint32_t ) sizeof( struct freertos_sockaddr );
/* Wait for the reply. */
xReturn = FreeRTOS_recvfrom( xDNSSocket,
&pxReceiveBuffer->pucPayloadBuffer,
0,
FREERTOS_ZERO_COPY,
xAddress,
&ulAddressLength );
if( xReturn <= 0 )
{
/* 'pdFREERTOS_ERRNO_EWOULDBLOCK' is returned in case of a timeout. */
FreeRTOS_printf( ( "DNS_ReadReply returns %d\n", ( int ) xReturn ) );
}
return xReturn;
}
/*-----------------------------------------------------------*/
/**
* @brief perform a DNS network close
* @param xDNSSocket the DNS socket to close
*/
void DNS_CloseSocket( Socket_t xDNSSocket )
{
( void ) FreeRTOS_closesocket( xDNSSocket );
}
#endif /* if ( ipconfigUSE_DNS != 0 ) */
/*-----------------------------------------------------------*/
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,268 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
/**
* @file FreeRTOS_ICMP.c
* @brief Implements the Internet Control Message Protocol for the FreeRTOS+TCP network stack.
*/
/* Standard includes. */
#include <stdint.h>
#include <stdio.h>
#include <string.h>
/* FreeRTOS includes. */
#include "FreeRTOS.h"
#include "task.h"
#include "queue.h"
#include "semphr.h"
/* FreeRTOS+TCP includes. */
#include "FreeRTOS_IP.h"
#include "FreeRTOS_IP_Private.h"
#include "FreeRTOS_ICMP.h"
#include "FreeRTOS_Sockets.h"
#include "FreeRTOS_UDP_IP.h"
#include "FreeRTOS_DHCP.h"
#include "NetworkInterface.h"
#include "NetworkBufferManagement.h"
#include "FreeRTOS_DNS.h"
/*
* Turns around an incoming ping request to convert it into a ping reply.
*/
#if ( ipconfigREPLY_TO_INCOMING_PINGS == 1 )
static eFrameProcessingResult_t prvProcessICMPEchoRequest( ICMPPacket_t * const pxICMPPacket,
const NetworkBufferDescriptor_t * const pxNetworkBuffer );
#endif /* ipconfigREPLY_TO_INCOMING_PINGS */
/*
* Processes incoming ping replies. The application callback function
* vApplicationPingReplyHook() is called with the results.
*/
#if ( ipconfigSUPPORT_OUTGOING_PINGS == 1 )
static void prvProcessICMPEchoReply( const NetworkBufferDescriptor_t * const pxNetworkBuffer );
#endif /* ipconfigSUPPORT_OUTGOING_PINGS */
#if ( ipconfigREPLY_TO_INCOMING_PINGS == 1 ) || ( ipconfigSUPPORT_OUTGOING_PINGS == 1 )
/**
* @brief Process an ICMP packet. Only echo requests and echo replies are recognised and handled.
*
* @param[in,out] pxNetworkBuffer The pointer to the network buffer descriptor
* that contains the ICMP message.
*
* @return eReleaseBuffer when the message buffer should be released, or eReturnEthernetFrame
* when the packet should be returned.
*/
eFrameProcessingResult_t ProcessICMPPacket( const NetworkBufferDescriptor_t * const pxNetworkBuffer )
{
eFrameProcessingResult_t eReturn = eReleaseBuffer;
iptraceICMP_PACKET_RECEIVED();
configASSERT( pxNetworkBuffer->xDataLength >= sizeof( ICMPPacket_t ) );
if( pxNetworkBuffer->xDataLength >= sizeof( ICMPPacket_t ) )
{
/* Map the buffer onto a ICMP-Packet struct to easily access the
* fields of ICMP packet. */
/* MISRA Ref 11.3.1 [Misaligned access] */
/* More details at: https://github.com/FreeRTOS/FreeRTOS-Plus-TCP/blob/main/MISRA.md#rule-113 */
/* coverity[misra_c_2012_rule_11_3_violation] */
ICMPPacket_t * pxICMPPacket = ( ( ICMPPacket_t * ) pxNetworkBuffer->pucEthernetBuffer );
switch( pxICMPPacket->xICMPHeader.ucTypeOfMessage )
{
case ipICMP_ECHO_REQUEST:
#if ( ipconfigREPLY_TO_INCOMING_PINGS == 1 )
{
eReturn = prvProcessICMPEchoRequest( pxICMPPacket, pxNetworkBuffer );
}
#endif /* ( ipconfigREPLY_TO_INCOMING_PINGS == 1 ) */
break;
case ipICMP_ECHO_REPLY:
#if ( ipconfigSUPPORT_OUTGOING_PINGS == 1 )
{
prvProcessICMPEchoReply( pxNetworkBuffer );
}
#endif /* ipconfigSUPPORT_OUTGOING_PINGS */
break;
default:
/* Only ICMP echo packets are handled. */
break;
}
}
return eReturn;
}
#endif /* ( ipconfigREPLY_TO_INCOMING_PINGS == 1 ) || ( ipconfigSUPPORT_OUTGOING_PINGS == 1 ) */
/*-----------------------------------------------------------*/
#if ( ipconfigREPLY_TO_INCOMING_PINGS == 1 )
/**
* @brief Process an ICMP echo request.
*
* @param[in,out] pxICMPPacket The IP packet that contains the ICMP message.
* @param pxNetworkBuffer Pointer to the network buffer containing the ICMP packet.
* @returns Function returns eReturnEthernetFrame.
*/
static eFrameProcessingResult_t prvProcessICMPEchoRequest( ICMPPacket_t * const pxICMPPacket,
const NetworkBufferDescriptor_t * const pxNetworkBuffer )
{
ICMPHeader_t * pxICMPHeader;
IPHeader_t * pxIPHeader;
uint32_t ulIPAddress;
pxICMPHeader = &( pxICMPPacket->xICMPHeader );
pxIPHeader = &( pxICMPPacket->xIPHeader );
/* HT:endian: changed back */
iptraceSENDING_PING_REPLY( pxIPHeader->ulSourceIPAddress );
/* The checksum can be checked here - but a ping reply should be
* returned even if the checksum is incorrect so the other end can
* tell that the ping was received - even if the ping reply contains
* invalid data. */
pxICMPHeader->ucTypeOfMessage = ( uint8_t ) ipICMP_ECHO_REPLY;
ulIPAddress = pxIPHeader->ulDestinationIPAddress;
pxIPHeader->ulDestinationIPAddress = pxIPHeader->ulSourceIPAddress;
pxIPHeader->ulSourceIPAddress = ulIPAddress;
/* Update the TTL field. */
pxIPHeader->ucTimeToLive = ipconfigICMP_TIME_TO_LIVE;
/* The stack doesn't support fragments, so the fragment offset field must always be zero.
* The header was never memset to zero, so set both the fragment offset and fragmentation flags in one go.
*/
#if ( ipconfigFORCE_IP_DONT_FRAGMENT != 0 )
pxIPHeader->usFragmentOffset = ipFRAGMENT_FLAGS_DONT_FRAGMENT;
#else
pxIPHeader->usFragmentOffset = 0U;
#endif
#if ( ipconfigDRIVER_INCLUDED_TX_IP_CHECKSUM == 0 )
{
/* calculate the IP header checksum, in case the driver won't do that. */
pxIPHeader->usHeaderChecksum = 0x00U;
pxIPHeader->usHeaderChecksum = usGenerateChecksum( 0U, ( uint8_t * ) &( pxIPHeader->ucVersionHeaderLength ), uxIPHeaderSizePacket( pxNetworkBuffer ) );
pxIPHeader->usHeaderChecksum = ( uint16_t ) ~FreeRTOS_htons( pxIPHeader->usHeaderChecksum );
/* calculate the ICMP checksum for an outgoing packet. */
( void ) usGenerateProtocolChecksum( ( uint8_t * ) pxICMPPacket, pxNetworkBuffer->xDataLength, pdTRUE );
}
#else
{
/* Just to prevent compiler warnings about unused parameters. */
( void ) pxNetworkBuffer;
/* Many EMAC peripherals will only calculate the ICMP checksum
* correctly if the field is nulled beforehand. */
pxICMPHeader->usChecksum = 0U;
}
#endif /* if ( ipconfigDRIVER_INCLUDED_TX_IP_CHECKSUM == 0 ) */
return eReturnEthernetFrame;
}
#endif /* ipconfigREPLY_TO_INCOMING_PINGS == 1 */
/*-----------------------------------------------------------*/
#if ( ipconfigSUPPORT_OUTGOING_PINGS == 1 )
/**
* @brief Process an ICMP echo reply.
*
* @param[in] pxNetworkBuffer The network buffer descriptor containing the ICMP packet.
*/
static void prvProcessICMPEchoReply( const NetworkBufferDescriptor_t * const pxNetworkBuffer )
{
/* The packet contained an ICMPv4 frame. */
/* MISRA Ref 11.3.1 [Misaligned access] */
/* More details at: https://github.com/FreeRTOS/FreeRTOS-Plus-TCP/blob/main/MISRA.md#rule-113 */
/* coverity[misra_c_2012_rule_11_3_violation] */
ICMPPacket_t * pxICMPPacket = ( ICMPPacket_t * ) pxNetworkBuffer->pucEthernetBuffer;
ePingReplyStatus_t eStatus = eSuccess;
uint16_t usDataLength, usByteCount, usCount;
size_t usByteAvail;
uint8_t * pucByte;
/* Find the total length of the IP packet. */
usDataLength = pxICMPPacket->xIPHeader.usLength;
usByteCount = FreeRTOS_ntohs( usDataLength );
usByteAvail = pxNetworkBuffer->xDataLength;
if( usByteAvail >= ( ipSIZE_OF_ETH_HEADER + ipSIZE_OF_IPv4_HEADER + ipSIZE_OF_ICMPv4_HEADER ) )
{
usByteAvail = usByteAvail - ( ipSIZE_OF_ETH_HEADER + ipSIZE_OF_IPv4_HEADER + ipSIZE_OF_ICMPv4_HEADER );
if( usByteCount >= ( ipSIZE_OF_IPv4_HEADER + ipSIZE_OF_ICMPv4_HEADER ) )
{
usByteCount = ( uint16_t ) ( usByteCount - ( ipSIZE_OF_IPv4_HEADER + ipSIZE_OF_ICMPv4_HEADER ) );
if( usByteCount <= usByteAvail )
{
/* Checksum has already been checked before in prvProcessIPPacket */
/* Find the first byte of the data within the ICMP packet. */
pucByte = ( uint8_t * ) pxICMPPacket;
/* Add an offset of 14 + 20 + 8. */
pucByte = &( pucByte[ sizeof( ICMPPacket_t ) ] );
/* Check each byte. */
for( usCount = 0; usCount < usByteCount; usCount++ )
{
if( *pucByte != ( uint8_t ) ipECHO_DATA_FILL_BYTE )
{
eStatus = eInvalidData;
break;
}
pucByte++;
}
/* Call back into the application to pass it the result. */
vApplicationPingReplyHook( eStatus, pxICMPPacket->xICMPHeader.usIdentifier );
}
}
else
{
/* usByteCount too small, drop. */
}
}
else
{
/* Buffer too small, drop. */
}
}
#endif /* if ( ipconfigSUPPORT_OUTGOING_PINGS == 1 ) */
/*-----------------------------------------------------------*/
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,741 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
/**
* @file FreeRTOS_IP_Timers.c
* @brief Implements the Internet Control Message Protocol for the FreeRTOS+TCP network stack.
*/
/* Standard includes. */
#include <stdint.h>
#include <stdio.h>
#include <string.h>
/* FreeRTOS includes. */
#include "FreeRTOS.h"
#include "task.h"
#include "queue.h"
#include "semphr.h"
/* FreeRTOS+TCP includes. */
#include "FreeRTOS_IP.h"
#include "FreeRTOS_IP_Timers.h"
#include "FreeRTOS_IP_Utils.h"
#include "FreeRTOS_Sockets.h"
#include "FreeRTOS_IP_Private.h"
#include "FreeRTOS_UDP_IP.h"
#include "FreeRTOS_DHCP.h"
#include "FreeRTOS_ARP.h"
#include "FreeRTOS_ND.h"
#include "NetworkInterface.h"
#include "NetworkBufferManagement.h"
#include "FreeRTOS_Routing.h"
#include "FreeRTOS_DNS.h"
/*-----------------------------------------------------------*/
/** @brief 'xAllNetworksUp' becomes pdTRUE when all network interfaces are initialised
* and becomes pdFALSE when any network interface goes down. */
/* MISRA Ref 8.9.1 [File scoped variables] */
/* More details at: https://github.com/FreeRTOS/FreeRTOS-Plus-TCP/blob/main/MISRA.md#rule-89 */
/* coverity[misra_c_2012_rule_8_9_violation] */
static BaseType_t xAllNetworksUp = pdFALSE;
/*-----------------------------------------------------------*/
/*
* Utility functions for the light weight IP timers.
*/
/**
* Start an IP timer. The IP-task has its own implementation of a timer
* called 'IPTimer_t', which is based on the FreeRTOS 'TimeOut_t'.
*/
static void prvIPTimerStart( IPTimer_t * pxTimer,
TickType_t xTime );
/**
* Check the IP timer to see whether an IP event should be processed or not.
*/
static BaseType_t prvIPTimerCheck( IPTimer_t * pxTimer );
/**
* Sets the reload time of an IP timer and restarts it.
*/
static void prvIPTimerReload( IPTimer_t * pxTimer,
TickType_t xTime );
/*-----------------------------------------------------------*/
/*
* A timer for each of the following processes, all of which need attention on a
* regular basis
*/
#if ipconfigIS_ENABLED( ipconfigUSE_IPv4 )
/** @brief Timer to limit the maximum time a packet should be stored while
* awaiting an ARP resolution. */
static IPTimer_t xARPResolutionTimer;
/** @brief ARP timer, to check its table entries. */
static IPTimer_t xARPTimer;
#endif
#if ipconfigIS_ENABLED( ipconfigUSE_IPv6 )
/** @brief Timer to limit the maximum time a packet should be stored while
* awaiting an ND resolution. */
static IPTimer_t xNDResolutionTimer;
/** @brief ND timer, to check its table entries. */
static IPTimer_t xNDTimer;
#endif
#if ( ipconfigUSE_TCP != 0 )
/** @brief TCP timer, to check for timeouts, resends. */
static IPTimer_t xTCPTimer;
#endif
#if ( ipconfigDNS_USE_CALLBACKS != 0 )
/** @brief DNS timer, to check for timeouts when looking-up a domain. */
static IPTimer_t xDNSTimer;
#endif
/** @brief As long as not all networks are up, repeat initialisation by calling the
* xNetworkInterfaceInitialise() function of the interfaces that are not ready. */
/* MISRA Ref 8.9.1 [File scoped variables] */
/* More details at: https://github.com/FreeRTOS/FreeRTOS-Plus-TCP/blob/main/MISRA.md#rule-89 */
/* coverity[misra_c_2012_rule_8_9_violation] */
static IPTimer_t xNetworkTimer;
struct xNetworkEndpoint;
/*-----------------------------------------------------------*/
/**
* @brief Calculate the maximum sleep time remaining. It will go through all
* timers to see which timer will expire first. That will be the amount
* of time to block in the next call to xQueueReceive().
*
* @return The maximum sleep time or ipconfigMAX_IP_TASK_SLEEP_TIME,
* whichever is smaller.
*/
TickType_t xCalculateSleepTime( void )
{
TickType_t uxMaximumSleepTime;
/* Start with the maximum sleep time, then check this against the remaining
* time in any other timers that are active. */
uxMaximumSleepTime = ipconfigMAX_IP_TASK_SLEEP_TIME;
#if ipconfigIS_ENABLED( ipconfigUSE_IPv4 )
if( xARPTimer.bActive != pdFALSE_UNSIGNED )
{
if( xARPTimer.ulRemainingTime < uxMaximumSleepTime )
{
uxMaximumSleepTime = xARPTimer.ulRemainingTime;
}
}
#endif
#if ipconfigIS_ENABLED( ipconfigUSE_IPv6 )
if( xNDTimer.bActive != pdFALSE_UNSIGNED )
{
if( xNDTimer.ulRemainingTime < uxMaximumSleepTime )
{
uxMaximumSleepTime = xNDTimer.ulRemainingTime;
}
}
#endif
#if ( ipconfigUSE_DHCP == 1 ) || ( ipconfigUSE_RA == 1 )
{
const NetworkEndPoint_t * pxEndPoint = pxNetworkEndPoints;
while( pxEndPoint != NULL )
{
if( pxEndPoint->xDHCP_RATimer.bActive != pdFALSE_UNSIGNED )
{
if( pxEndPoint->xDHCP_RATimer.ulRemainingTime < uxMaximumSleepTime )
{
uxMaximumSleepTime = pxEndPoint->xDHCP_RATimer.ulRemainingTime;
}
}
pxEndPoint = pxEndPoint->pxNext;
}
}
#endif /* ipconfigUSE_DHCP */
#if ( ipconfigUSE_TCP == 1 )
{
if( xTCPTimer.bActive != pdFALSE_UNSIGNED )
{
if( xTCPTimer.ulRemainingTime < uxMaximumSleepTime )
{
uxMaximumSleepTime = xTCPTimer.ulRemainingTime;
}
}
}
#endif
#if ( ipconfigDNS_USE_CALLBACKS != 0 )
{
if( xDNSTimer.bActive != pdFALSE_UNSIGNED )
{
if( xDNSTimer.ulRemainingTime < uxMaximumSleepTime )
{
uxMaximumSleepTime = xDNSTimer.ulRemainingTime;
}
}
}
#endif
return uxMaximumSleepTime;
}
/*-----------------------------------------------------------*/
/**
* @brief Check the network timers (ARP/ND/DHCP/DNS/TCP) and if they are
* expired, send an event to the IP-Task.
*/
/* MISRA Ref 8.9.1 [File scoped variables] */
/* More details at: https://github.com/FreeRTOS/FreeRTOS-Plus-TCP/blob/main/MISRA.md#rule-89 */
/* coverity[misra_c_2012_rule_8_9_violation] */
/* coverity[single_use] */
void vCheckNetworkTimers( void )
{
NetworkInterface_t * pxInterface;
#if ipconfigIS_ENABLED( ipconfigUSE_IPv4 )
/* Is it time for ARP processing? */
if( prvIPTimerCheck( &xARPTimer ) != pdFALSE )
{
( void ) xSendEventToIPTask( eARPTimerEvent );
}
/* Is the ARP resolution timer expired? */
if( prvIPTimerCheck( &xARPResolutionTimer ) != pdFALSE )
{
if( pxARPWaitingNetworkBuffer != NULL )
{
/* Disable the ARP resolution timer. */
vIPSetARPResolutionTimerEnableState( pdFALSE );
/* We have waited long enough for the ARP response. Now, free the network
* buffer. */
vReleaseNetworkBufferAndDescriptor( pxARPWaitingNetworkBuffer );
/* Clear the pointer. */
pxARPWaitingNetworkBuffer = NULL;
iptraceDELAYED_ARP_TIMER_EXPIRED();
}
}
#endif /* if ipconfigIS_ENABLED( ipconfigUSE_IPv4 ) */
#if ipconfigIS_ENABLED( ipconfigUSE_IPv6 )
/* Is it time for ND processing? */
if( prvIPTimerCheck( &xNDTimer ) != pdFALSE )
{
( void ) xSendEventToIPTask( eNDTimerEvent );
}
/* Is the ND resolution timer expired? */
if( prvIPTimerCheck( &xNDResolutionTimer ) != pdFALSE )
{
if( pxNDWaitingNetworkBuffer != NULL )
{
/* Disable the ND resolution timer. */
vIPSetNDResolutionTimerEnableState( pdFALSE );
/* We have waited long enough for the ND response. Now, free the network
* buffer. */
vReleaseNetworkBufferAndDescriptor( pxNDWaitingNetworkBuffer );
/* Clear the pointer. */
pxNDWaitingNetworkBuffer = NULL;
iptraceDELAYED_ND_TIMER_EXPIRED();
}
}
#endif /* if ipconfigIS_ENABLED( ipconfigUSE_IPv6 ) */
#if ( ipconfigUSE_DHCP == 1 ) || ( ipconfigUSE_RA == 1 )
{
/* Is it time for DHCP processing? */
NetworkEndPoint_t * pxEndPoint = pxNetworkEndPoints;
while( pxEndPoint != NULL )
{
if( prvIPTimerCheck( &( pxEndPoint->xDHCP_RATimer ) ) != pdFALSE )
{
#if ( ipconfigUSE_DHCP == 1 )
if( END_POINT_USES_DHCP( pxEndPoint ) )
{
( void ) xSendDHCPEvent( pxEndPoint );
}
#endif /* ( ipconfigUSE_DHCP == 1 ) */
#if ( ( ipconfigUSE_RA != 0 ) && ( ipconfigUSE_IPv6 != 0 ) )
if( END_POINT_USES_RA( pxEndPoint ) )
{
vRAProcess( pdFALSE, pxEndPoint );
}
#endif /* ( ipconfigUSE_RA != 0 ) */
}
pxEndPoint = pxEndPoint->pxNext;
}
}
#endif /* ( ipconfigUSE_DHCP == 1 ) || ( ipconfigUSE_RA != 0 ) */
#if ( ipconfigDNS_USE_CALLBACKS != 0 )
{
/* Is it time for DNS processing? */
if( prvIPTimerCheck( &xDNSTimer ) != pdFALSE )
{
vDNSCheckCallBack( NULL );
}
}
#endif /* ipconfigDNS_USE_CALLBACKS */
#if ( ipconfigUSE_TCP == 1 )
{
BaseType_t xWillSleep;
TickType_t xNextTime;
BaseType_t xCheckTCPSockets;
/* If the IP task has messages waiting to be processed then
* it will not sleep in any case. */
if( uxQueueMessagesWaiting( xNetworkEventQueue ) == 0U )
{
xWillSleep = pdTRUE;
}
else
{
xWillSleep = pdFALSE;
}
/* Sockets need to be checked if the TCP timer has expired. */
xCheckTCPSockets = prvIPTimerCheck( &xTCPTimer );
/* Sockets will also be checked if there are TCP messages but the
* message queue is empty (indicated by xWillSleep being true). */
if( xWillSleep != pdFALSE )
{
xCheckTCPSockets = pdTRUE;
}
if( xCheckTCPSockets != pdFALSE )
{
/* Attend to the sockets, returning the period after which the
* check must be repeated. */
xNextTime = xTCPTimerCheck( xWillSleep );
prvIPTimerStart( &xTCPTimer, xNextTime );
}
}
/* See if any socket was planned to be closed. */
vSocketCloseNextTime( NULL );
/* See if any reusable socket needs to go back to 'eTCP_LISTEN' state. */
vSocketListenNextTime( NULL );
#endif /* ipconfigUSE_TCP == 1 */
/* Is it time to trigger the repeated NetworkDown events? */
if( xAllNetworksUp == pdFALSE )
{
if( prvIPTimerCheck( &( xNetworkTimer ) ) != pdFALSE )
{
BaseType_t xUp = pdTRUE;
for( pxInterface = pxNetworkInterfaces; pxInterface != NULL; pxInterface = pxInterface->pxNext )
{
if( pxInterface->bits.bInterfaceUp == pdFALSE_UNSIGNED )
{
xUp = pdFALSE;
FreeRTOS_NetworkDown( pxInterface );
}
}
vSetAllNetworksUp( xUp );
}
}
}
/*-----------------------------------------------------------*/
/**
* @brief Start an IP timer. The IP-task has its own implementation of a timer
* called 'IPTimer_t', which is based on the FreeRTOS 'TimeOut_t'.
*
* @param[in] pxTimer Pointer to the IP timer. When zero, the timer is marked
* as expired.
* @param[in] xTime Time to be loaded into the IP timer.
*/
static void prvIPTimerStart( IPTimer_t * pxTimer,
TickType_t xTime )
{
vTaskSetTimeOutState( &pxTimer->xTimeOut );
pxTimer->ulRemainingTime = xTime;
if( xTime == ( TickType_t ) 0 )
{
pxTimer->bExpired = ipTRUE_BOOL;
}
else
{
pxTimer->bExpired = ipFALSE_BOOL;
}
pxTimer->bActive = ipTRUE_BOOL;
}
/*-----------------------------------------------------------*/
#if ipconfigIS_ENABLED( ipconfigUSE_IPv4 )
/**
* @brief Start an ARP Resolution timer.
*
* @param[in] xTime Time to be loaded into the ARP Resolution timer.
*/
void vIPTimerStartARPResolution( TickType_t xTime )
{
prvIPTimerStart( &( xARPResolutionTimer ), xTime );
}
#endif
/*-----------------------------------------------------------*/
#if ipconfigIS_ENABLED( ipconfigUSE_IPv6 )
/**
* @brief Start an ND Resolution timer.
*
* @param[in] xTime Time to be loaded into the ND Resolution timer.
*/
void vIPTimerStartNDResolution( TickType_t xTime )
{
prvIPTimerStart( &( xNDResolutionTimer ), xTime );
}
#endif
/*-----------------------------------------------------------*/
/**
* @brief Sets the reload time of an IP timer and restarts it.
*
* @param[in] pxTimer Pointer to the IP timer.
* @param[in] xTime Time to be reloaded into the IP timer.
*/
static void prvIPTimerReload( IPTimer_t * pxTimer,
TickType_t xTime )
{
pxTimer->ulReloadTime = xTime;
prvIPTimerStart( pxTimer, xTime );
}
/*-----------------------------------------------------------*/
#if ( ipconfigUSE_TCP == 1 )
/**
* @brief Sets the reload time of the TCP timer and restarts it.
*
* @param[in] xTime Time to be reloaded into the TCP timer.
*/
void vTCPTimerReload( TickType_t xTime )
{
prvIPTimerReload( &xTCPTimer, xTime );
}
#endif
/*-----------------------------------------------------------*/
#if ipconfigIS_ENABLED( ipconfigUSE_IPv4 )
/**
* @brief Sets the reload time of the ARP timer and restarts it.
*
* @param[in] xTime Time to be reloaded into the ARP timer.
*/
void vARPTimerReload( TickType_t xTime )
{
prvIPTimerReload( &xARPTimer, xTime );
}
#endif
/*-----------------------------------------------------------*/
#if ipconfigIS_ENABLED( ipconfigUSE_IPv6 )
/**
* @brief Sets the reload time of the ND timer and restarts it.
*
* @param[in] xTime Time to be reloaded into the ND timer.
*/
void vNDTimerReload( TickType_t xTime )
{
prvIPTimerReload( &xNDTimer, xTime );
}
#endif
/*-----------------------------------------------------------*/
#if ( ipconfigDNS_USE_CALLBACKS != 0 )
/**
* @brief Reload the DNS timer.
*
* @param[in] ulCheckTime The reload value.
*/
void vDNSTimerReload( uint32_t ulCheckTime )
{
prvIPTimerReload( &xDNSTimer, ulCheckTime );
}
#endif /* ipconfigDNS_USE_CALLBACKS != 0 */
/*-----------------------------------------------------------*/
#if ( ipconfigUSE_DHCP == 1 ) || ( ipconfigUSE_RA == 1 )
/**
* @brief Set the reload time of the DHCP/DHCPv6/RA timer.
*
* @param[in] pxEndPoint The end-point that needs to acquire an IP-address.
* @param[in] uxClockTicks The number of clock-ticks after which the timer should expire.
*/
void vDHCP_RATimerReload( NetworkEndPoint_t * pxEndPoint,
TickType_t uxClockTicks )
{
FreeRTOS_printf( ( "vDHCP_RATimerReload: %lu\n", ( unsigned long ) uxClockTicks ) );
prvIPTimerReload( &( pxEndPoint->xDHCP_RATimer ), uxClockTicks );
}
#endif /* ( ipconfigUSE_DHCP == 1 ) || ( ipconfigUSE_RA == 1 ) */
/*-----------------------------------------------------------*/
/**
* @brief Reload the Network timer.
*
* @param[in] xTime Time to be reloaded into the Network timer.
*/
void vNetworkTimerReload( TickType_t xTime )
{
prvIPTimerReload( &xNetworkTimer, xTime );
}
/*-----------------------------------------------------------*/
/**
* @brief Check the IP timer to see whether an IP event should be processed or not.
*
* @param[in] pxTimer Pointer to the IP timer.
*
* @return If the timer is expired then pdTRUE is returned. Else pdFALSE.
*/
static BaseType_t prvIPTimerCheck( IPTimer_t * pxTimer )
{
BaseType_t xReturn;
if( pxTimer->bActive == pdFALSE_UNSIGNED )
{
/* The timer is not enabled. */
xReturn = pdFALSE;
}
else
{
/* The timer might have set the bExpired flag already, if not, check the
* value of xTimeOut against ulRemainingTime. */
if( pxTimer->bExpired == ipFALSE_BOOL )
{
if( xTaskCheckForTimeOut( &( pxTimer->xTimeOut ), &( pxTimer->ulRemainingTime ) ) != pdFALSE )
{
pxTimer->bExpired = ipTRUE_BOOL;
}
}
if( pxTimer->bExpired != ipFALSE_BOOL )
{
prvIPTimerStart( pxTimer, pxTimer->ulReloadTime );
xReturn = pdTRUE;
}
else
{
xReturn = pdFALSE;
}
}
return xReturn;
}
/*-----------------------------------------------------------*/
#if ( ipconfigUSE_TCP == 1 )
/**
* @brief Enable/disable the TCP timer.
*
* @param[in] xExpiredState pdTRUE - set as expired; pdFALSE - set as non-expired.
*/
void vIPSetTCPTimerExpiredState( BaseType_t xExpiredState )
{
xTCPTimer.bActive = ipTRUE_BOOL;
if( xExpiredState != pdFALSE )
{
xTCPTimer.bExpired = ipTRUE_BOOL;
}
else
{
xTCPTimer.bExpired = ipFALSE_BOOL;
}
}
#endif /* if ( ipconfigUSE_TCP == 1 ) */
/*-----------------------------------------------------------*/
#if ipconfigIS_ENABLED( ipconfigUSE_IPv4 )
/**
* @brief Enable/disable the ARP timer.
*
* @param[in] xEnableState pdTRUE - enable timer; pdFALSE - disable timer.
*/
void vIPSetARPTimerEnableState( BaseType_t xEnableState )
{
if( xEnableState != pdFALSE )
{
xARPTimer.bActive = ipTRUE_BOOL;
}
else
{
xARPTimer.bActive = ipFALSE_BOOL;
}
}
/*-----------------------------------------------------------*/
/**
* @brief Enable or disable the ARP resolution timer.
*
* @param[in] xEnableState pdTRUE if the timer must be enabled, pdFALSE otherwise.
*/
void vIPSetARPResolutionTimerEnableState( BaseType_t xEnableState )
{
if( xEnableState != pdFALSE )
{
xARPResolutionTimer.bActive = ipTRUE_BOOL;
}
else
{
xARPResolutionTimer.bActive = ipFALSE_BOOL;
}
}
#endif /* if ipconfigIS_ENABLED( ipconfigUSE_IPv4 ) */
/*-----------------------------------------------------------*/
#if ipconfigIS_ENABLED( ipconfigUSE_IPv6 )
/**
* @brief Enable/disable the ND timer.
*
* @param[in] xEnableState pdTRUE - enable timer; pdFALSE - disable timer.
*/
void vIPSetNDTimerEnableState( BaseType_t xEnableState )
{
if( xEnableState != pdFALSE )
{
xNDTimer.bActive = ipTRUE_BOOL;
}
else
{
xNDTimer.bActive = ipFALSE_BOOL;
}
}
/*-----------------------------------------------------------*/
/**
* @brief Enable or disable the ND resolution timer.
*
* @param[in] xEnableState pdTRUE if the timer must be enabled, pdFALSE otherwise.
*/
void vIPSetNDResolutionTimerEnableState( BaseType_t xEnableState )
{
if( xEnableState != pdFALSE )
{
xNDResolutionTimer.bActive = ipTRUE_BOOL;
}
else
{
xNDResolutionTimer.bActive = ipFALSE_BOOL;
}
}
#endif /* if ipconfigIS_ENABLED( ipconfigUSE_IPv6 ) */
/*-----------------------------------------------------------*/
#if ( ipconfigUSE_DHCP == 1 ) || ( ipconfigUSE_RA == 1 ) || ( ipconfigUSE_DHCPv6 == 1 )
/**
* @brief Enable or disable the DHCP/DHCPv6/RA timer.
*
* @param[in] pxEndPoint The end-point that needs to acquire an IP-address.
* @param[in] xEnableState pdTRUE if the timer must be enabled, pdFALSE otherwise.
*/
void vIPSetDHCP_RATimerEnableState( NetworkEndPoint_t * pxEndPoint,
BaseType_t xEnableState )
{
FreeRTOS_printf( ( "vIPSetDHCP_RATimerEnableState: %s\n", ( xEnableState != 0 ) ? "On" : "Off" ) );
/* 'xDHCP_RATimer' is shared between DHCP (IPv4) and RA/SLAAC (IPv6). */
if( xEnableState != 0 )
{
pxEndPoint->xDHCP_RATimer.bActive = ipTRUE_BOOL;
}
else
{
pxEndPoint->xDHCP_RATimer.bActive = ipFALSE_BOOL;
}
}
#endif /* if ( ipconfigUSE_DHCP == 1 ) || ( ipconfigUSE_RA == 1 ) || ( ipconfigUSE_DHCPv6 == 1 ) */
/*-----------------------------------------------------------*/
#if ( ipconfigDNS_USE_CALLBACKS == 1 )
/**
* @brief Enable/disable the DNS timer.
*
* @param[in] xEnableState pdTRUE - enable timer; pdFALSE - disable timer.
*/
void vIPSetDNSTimerEnableState( BaseType_t xEnableState )
{
if( xEnableState != 0 )
{
xDNSTimer.bActive = ipTRUE_BOOL;
}
else
{
xDNSTimer.bActive = ipFALSE_BOOL;
}
}
#endif /* ipconfigDNS_USE_CALLBACKS == 1 */
/*-----------------------------------------------------------*/
/**
* @brief Mark whether all interfaces are up or at least one interface is down.
* If all interfaces are up, the 'xNetworkTimer' will not be checked.
*/
void vSetAllNetworksUp( BaseType_t xIsAllNetworksUp )
{
xAllNetworksUp = xIsAllNetworksUp;
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,644 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
/**
* @file FreeRTOS_IPv4.c
* @brief Implements the basic functionality for the FreeRTOS+TCP network stack.
*/
/* Standard includes. */
#include <stdint.h>
#include <stdio.h>
#include <string.h>
/* FreeRTOS includes. */
#include "FreeRTOS.h"
/* FreeRTOS+TCP includes. */
#include "FreeRTOS_IP.h"
#include "FreeRTOS_IPv4.h"
/* IPv4 multi-cast addresses range from 224.0.0.0.0 to 240.0.0.0. */
#define ipFIRST_MULTI_CAST_IPv4 0xE0000000U /**< Lower bound of the IPv4 multicast address. */
#define ipLAST_MULTI_CAST_IPv4 0xF0000000U /**< Higher bound of the IPv4 multicast address. */
/* Just make sure the contents doesn't get compiled if IPv4 is not enabled. */
/* *INDENT-OFF* */
#if( ipconfigUSE_IPv4 != 0 )
/* *INDENT-ON* */
#if ( ipconfigDRIVER_INCLUDED_RX_IP_CHECKSUM == 1 )
/* Check IPv4 packet length. */
static BaseType_t xCheckIPv4SizeFields( const void * const pvEthernetBuffer,
size_t uxBufferLength );
#endif /* ( ipconfigDRIVER_INCLUDED_RX_IP_CHECKSUM == 1 ) */
#if ( ipconfigDRIVER_INCLUDED_RX_IP_CHECKSUM == 1 )
/**
* @brief Check IPv4 packet length.
*
* @param[in] pvEthernetBuffer The Ethernet packet received.
* @param[in] uxBufferLength The total number of bytes received.
*
* @return pdPASS when the length fields in the packet OK, pdFAIL when the packet
* should be dropped.
*/
static BaseType_t xCheckIPv4SizeFields( const void * const pvEthernetBuffer,
size_t uxBufferLength )
{
size_t uxLength;
UBaseType_t uxIPHeaderLength;
uint8_t ucProtocol;
uint16_t usLength;
uint16_t ucVersionHeaderLength;
size_t uxMinimumLength;
BaseType_t xResult = pdFAIL;
/* Map the buffer onto a IP-Packet struct to easily access the
* fields of the IP packet. */
const IPPacket_t * const pxIPPacket = ( ( const IPPacket_t * ) pvEthernetBuffer );
DEBUG_DECLARE_TRACE_VARIABLE( BaseType_t, xLocation, 0 );
do
{
/* Check for minimum packet size: Ethernet header and an IP-header, 34 bytes */
if( uxBufferLength < sizeof( IPPacket_t ) )
{
DEBUG_SET_TRACE_VARIABLE( xLocation, 1 );
break;
}
ucVersionHeaderLength = pxIPPacket->xIPHeader.ucVersionHeaderLength;
/* Test if the length of the IP-header is between 20 and 60 bytes,
* and if the IP-version is 4. */
if( ( ucVersionHeaderLength < ipIPV4_VERSION_HEADER_LENGTH_MIN ) ||
( ucVersionHeaderLength > ipIPV4_VERSION_HEADER_LENGTH_MAX ) )
{
DEBUG_SET_TRACE_VARIABLE( xLocation, 2 );
break;
}
ucVersionHeaderLength = ( uint16_t ) ( ( ucVersionHeaderLength & ( uint8_t ) 0x0FU ) << 2U );
uxIPHeaderLength = ( UBaseType_t ) ucVersionHeaderLength;
/* Check if the complete IP-header is transferred. */
if( uxBufferLength < ( ipSIZE_OF_ETH_HEADER + uxIPHeaderLength ) )
{
DEBUG_SET_TRACE_VARIABLE( xLocation, 3 );
break;
}
/* Check if the complete IP-header plus protocol data have been transferred: */
usLength = pxIPPacket->xIPHeader.usLength;
usLength = FreeRTOS_ntohs( usLength );
if( uxBufferLength < ( size_t ) ( ipSIZE_OF_ETH_HEADER + ( size_t ) usLength ) )
{
DEBUG_SET_TRACE_VARIABLE( xLocation, 4 );
break;
}
/* Identify the next protocol. */
ucProtocol = pxIPPacket->xIPHeader.ucProtocol;
/* Switch on the Layer 3/4 protocol. */
if( ucProtocol == ( uint8_t ) ipPROTOCOL_UDP )
{
/* Expect at least a complete UDP header. */
uxMinimumLength = uxIPHeaderLength + ipSIZE_OF_ETH_HEADER + ipSIZE_OF_UDP_HEADER;
}
else if( ucProtocol == ( uint8_t ) ipPROTOCOL_TCP )
{
uxMinimumLength = uxIPHeaderLength + ipSIZE_OF_ETH_HEADER + ipSIZE_OF_TCP_HEADER;
}
else if( ( ucProtocol == ( uint8_t ) ipPROTOCOL_ICMP ) ||
( ucProtocol == ( uint8_t ) ipPROTOCOL_IGMP ) )
{
uxMinimumLength = uxIPHeaderLength + ipSIZE_OF_ETH_HEADER + ipSIZE_OF_ICMPv4_HEADER;
}
else
{
/* Unhandled protocol, other than ICMP, IGMP, UDP, or TCP. */
DEBUG_SET_TRACE_VARIABLE( xLocation, 5 );
break;
}
if( uxBufferLength < uxMinimumLength )
{
DEBUG_SET_TRACE_VARIABLE( xLocation, 6 );
break;
}
uxLength = ( size_t ) usLength;
uxLength -= ( ( uint16_t ) uxIPHeaderLength ); /* normally, minus 20. */
if( ( uxLength < ( ( size_t ) sizeof( UDPHeader_t ) ) ) ||
( uxLength > ( ( size_t ) ipconfigNETWORK_MTU - ( size_t ) uxIPHeaderLength ) ) )
{
/* For incoming packets, the length is out of bound: either
* too short or too long. For outgoing packets, there is a
* serious problem with the format/length. */
DEBUG_SET_TRACE_VARIABLE( xLocation, 7 );
break;
}
xResult = pdPASS;
} while( ipFALSE_BOOL );
if( xResult != pdPASS )
{
/* NOP if ipconfigHAS_PRINTF != 1 */
FreeRTOS_printf( ( "xCheckIPv4SizeFields: location %ld\n", xLocation ) );
}
return xResult;
}
#endif /* ( ipconfigDRIVER_INCLUDED_RX_IP_CHECKSUM == 1 ) */
/*-----------------------------------------------------------*/
/**
* @brief Is the IP address an IPv4 multicast address.
*
* @param[in] ulIPAddress The IP address being checked.
*
* @return pdTRUE if the IP address is a multicast address or else, pdFALSE.
*/
BaseType_t xIsIPv4Multicast( uint32_t ulIPAddress )
{
BaseType_t xReturn;
uint32_t ulIP = FreeRTOS_ntohl( ulIPAddress );
if( ( ulIP >= ipFIRST_MULTI_CAST_IPv4 ) && ( ulIP < ipLAST_MULTI_CAST_IPv4 ) )
{
xReturn = pdTRUE;
}
else
{
xReturn = pdFALSE;
}
return xReturn;
}
/*-----------------------------------------------------------*/
/**
* @brief Checks if the IP address matches the global 255.255.255.255 broadcast address or
* the broadcast address for any of our IPv4 endpoints.
*
* @param[in] ulIPAddress The IP address being checked.
*
* @param[out] ppxEndPoint Pointer to an end-point where we store the endpoint whose broadcast address we matched. Or NULL if no IPv4 endpoints were found.
*
* @return pdTRUE if the IP address is a broadcast address or else, pdFALSE.
*/
BaseType_t xIsIPv4Broadcast( uint32_t ulIPAddress,
struct xNetworkEndPoint ** ppxEndPoint )
{
BaseType_t xIsBroadcast;
NetworkEndPoint_t * pxEndPoint;
/* Assign a default answer based on the "global" broadcast. This way
* we can still return the correct result even if there are no endpoints. */
xIsBroadcast = ( ulIPAddress == FREERTOS_INADDR_BROADCAST ) ? pdTRUE : pdFALSE;
for( pxEndPoint = FreeRTOS_FirstEndPoint( NULL );
pxEndPoint != NULL;
pxEndPoint = FreeRTOS_NextEndPoint( NULL, pxEndPoint ) )
{
#if ( ipconfigUSE_IPv6 == ipconfigENABLE )
/* Skip over any IPv6 endpoints. */
if( pxEndPoint->bits.bIPv6 == ipTRUE_BOOL )
{
continue;
}
#endif /* ( ipconfigUSE_IPv6 == ipconfigENABLE ) */
/* If we already know if ulIPAddress is a broadcast,
* simply return this first matching IPv4 endpoint. */
if( xIsBroadcast == pdTRUE )
{
break;
}
else if( ulIPAddress == pxEndPoint->ipv4_settings.ulBroadcastAddress )
{
xIsBroadcast = pdTRUE;
break;
}
else
{
/* do nothing, coverity happy */
}
}
/* If the caller wants to know the corresponding endpoint, copy the result.
* Note that this may be null if ulIPAddress is 255.255.255.255 AND there are
* no IPv4 endpoints.
* Also, when ulIPAddress is 255.255.255.255, we will
* return the first IPv4 endpoint that we run across. */
if( ( xIsBroadcast == pdTRUE ) && ( ppxEndPoint != NULL ) )
{
*ppxEndPoint = pxEndPoint;
}
return xIsBroadcast;
}
/*-----------------------------------------------------------*/
/**
* @brief Check if the packet is an illegal loopback packet.
*
* @param[in] pxIPHeader The IP-header being checked.
*
* @return Returns pdTRUE if the packet should be stopped, because either the source
* or the target address is a loopback address.
*/
BaseType_t xBadIPv4Loopback( const IPHeader_t * const pxIPHeader )
{
BaseType_t xReturn = pdFALSE;
BaseType_t x1 = ( xIsIPv4Loopback( pxIPHeader->ulDestinationIPAddress ) != 0 ) ? pdTRUE : pdFALSE;
BaseType_t x2 = ( xIsIPv4Loopback( pxIPHeader->ulSourceIPAddress ) != 0 ) ? pdTRUE : pdFALSE;
if( x1 != x2 )
{
/* Either the source or the destination address is an IPv4 loopback address. */
xReturn = pdTRUE;
}
return xReturn;
}
/*-----------------------------------------------------------*/
/**
* @brief Is the IP address an IPv4 loopback address.
*
* @param[in] ulAddress The IP address being checked.
*
* @return pdTRUE if the IP address is a loopback address or else, pdFALSE.
*/
BaseType_t xIsIPv4Loopback( uint32_t ulAddress )
{
BaseType_t xReturn = pdFALSE;
uint32_t ulIP = FreeRTOS_ntohl( ulAddress );
if( ( ulIP >= ipFIRST_LOOPBACK_IPv4 ) &&
( ulIP < ipLAST_LOOPBACK_IPv4 ) )
{
xReturn = pdTRUE;
}
return xReturn;
}
/*-----------------------------------------------------------*/
/**
* @brief Check whether this IPv4 packet is to be allowed or to be dropped.
*
* @param[in] pxIPPacket The IP packet under consideration.
* @param[in] pxNetworkBuffer The whole network buffer.
* @param[in] uxHeaderLength The length of the header.
*
* @return Whether the packet should be processed or dropped.
*/
enum eFrameProcessingResult prvAllowIPPacketIPv4( const struct xIP_PACKET * const pxIPPacket,
const struct xNETWORK_BUFFER * const pxNetworkBuffer,
UBaseType_t uxHeaderLength )
{
eFrameProcessingResult_t eReturn = eProcessBuffer;
#if ( ( ipconfigETHERNET_DRIVER_FILTERS_PACKETS == 0 ) || ( ipconfigDRIVER_INCLUDED_RX_IP_CHECKSUM == 0 ) )
const IPHeader_t * pxIPHeader = &( pxIPPacket->xIPHeader );
#else
/* or else, the parameter won't be used and the function will be optimised
* away */
( void ) pxIPPacket;
#endif
#if ( ipconfigETHERNET_DRIVER_FILTERS_PACKETS == 0 )
{
/* In systems with a very small amount of RAM, it might be advantageous
* to have incoming messages checked earlier, by the network card driver.
* This method may decrease the usage of scarce network buffers. */
uint32_t ulDestinationIPAddress = pxIPHeader->ulDestinationIPAddress;
uint32_t ulSourceIPAddress = pxIPHeader->ulSourceIPAddress;
/* Get a reference to the endpoint that the packet was assigned to during pxEasyFit() */
const NetworkEndPoint_t * pxEndPoint = pxNetworkBuffer->pxEndPoint;
/* Ensure that the incoming packet is not fragmented because the stack
* doesn't not support IP fragmentation. All but the last fragment coming in will have their
* "more fragments" flag set and the last fragment will have a non-zero offset.
* We need to drop the packet in either of those cases. */
if( ( ( pxIPHeader->usFragmentOffset & ipFRAGMENT_OFFSET_BIT_MASK ) != 0U ) || ( ( pxIPHeader->usFragmentOffset & ipFRAGMENT_FLAGS_MORE_FRAGMENTS ) != 0U ) )
{
/* Can not handle, fragmented packet. */
eReturn = eReleaseBuffer;
}
/* Test if the length of the IP-header is between 20 and 60 bytes,
* and if the IP-version is 4. */
else if( ( pxIPHeader->ucVersionHeaderLength < ipIPV4_VERSION_HEADER_LENGTH_MIN ) ||
( pxIPHeader->ucVersionHeaderLength > ipIPV4_VERSION_HEADER_LENGTH_MAX ) )
{
/* Can not handle, unknown or invalid header version. */
eReturn = eReleaseBuffer;
}
else if( ( xIsIPv4Loopback( ulDestinationIPAddress ) == pdTRUE ) ||
( xIsIPv4Loopback( ulSourceIPAddress ) == pdTRUE ) )
{
/* source OR destination is a loopback address. Make sure they BOTH are. */
if( xBadIPv4Loopback( &( pxIPPacket->xIPHeader ) ) == pdTRUE )
{
/* The local loopback addresses must never appear outside a host. See RFC 1122
* section 3.2.1.3. */
eReturn = eReleaseBuffer;
}
}
else if( memcmp( xBroadcastMACAddress.ucBytes,
pxIPPacket->xEthernetHeader.xSourceAddress.ucBytes,
sizeof( MACAddress_t ) ) == 0 )
{
/* Ethernet source is a broadcast address. Drop the packet. */
eReturn = eReleaseBuffer;
}
else if( xIsIPv4Multicast( ulSourceIPAddress ) == pdTRUE )
{
/* Source is a multicast IP address. Drop the packet in conformity with RFC 1112 section 7.2. */
eReturn = eReleaseBuffer;
}
/* Use ipv4_settings for filtering only after the endpoint is up,
* so that DHCP packets that are exchanged for DHCP (example, DHCP unicast offers)
* are not dropped/filtered. */
else if( FreeRTOS_IsEndPointUp( pxEndPoint ) != pdFALSE )
{
if(
/* Not destined for the assigned endpoint IPv4 address? */
( ulDestinationIPAddress != pxEndPoint->ipv4_settings.ulIPAddress ) &&
/* Also not an IPv4 broadcast address ? */
( ulDestinationIPAddress != pxEndPoint->ipv4_settings.ulBroadcastAddress ) &&
( ulDestinationIPAddress != FREERTOS_INADDR_BROADCAST ) &&
/* And not an IPv4 multicast address ? */
( xIsIPv4Multicast( ulDestinationIPAddress ) == pdFALSE ) )
{
/* Packet is not for this node, release it */
eReturn = eReleaseBuffer;
}
/* Is the source address correct? */
else if( ( ulSourceIPAddress == pxEndPoint->ipv4_settings.ulBroadcastAddress ) ||
( ulSourceIPAddress == FREERTOS_INADDR_BROADCAST ) )
{
/* The source address cannot be broadcast address. Replying to this
* packet may cause network storms. Drop the packet. */
eReturn = eReleaseBuffer;
}
else if( ( memcmp( xBroadcastMACAddress.ucBytes,
pxIPPacket->xEthernetHeader.xDestinationAddress.ucBytes,
sizeof( MACAddress_t ) ) == 0 ) &&
( ulDestinationIPAddress != pxEndPoint->ipv4_settings.ulBroadcastAddress ) && ( ulDestinationIPAddress != FREERTOS_INADDR_BROADCAST ) )
{
/* Ethernet address is a broadcast address, but the IP address is not a
* broadcast address. */
eReturn = eReleaseBuffer;
}
else
{
/* Packet is not fragmented, destination is this device, source IP and MAC
* addresses are correct. */
}
}
else
{
/* Endpoint is down */
/* Check if the destination MAC address is a broadcast MAC address. */
if( memcmp( xBroadcastMACAddress.ucBytes,
pxIPPacket->xEthernetHeader.xDestinationAddress.ucBytes,
sizeof( MACAddress_t ) ) == 0 )
{
if( ulDestinationIPAddress != FREERTOS_INADDR_BROADCAST )
{
/* Ethernet address is a broadcast address, but the IP address is not a
* broadcast address. */
eReturn = eReleaseBuffer;
}
else
{
/* Accept valid broadcast packet. */
}
}
/* RFC 2131: https://datatracker.ietf.org/doc/html/rfc2131#autoid-8
* The TCP/IP software SHOULD accept and
* forward to the IP layer any IP packets delivered to the client's
* hardware address before the IP address is configured; DHCP servers
* and BOOTP relay agents may not be able to deliver DHCP messages to
* clients that cannot accept hardware unicast datagrams before the
* TCP/IP software is configured. */
else if( ( memcmp( pxEndPoint->xMACAddress.ucBytes,
pxIPPacket->xEthernetHeader.xDestinationAddress.ucBytes,
sizeof( MACAddress_t ) ) != 0 ) )
{
/* The endpoint is not up, and the destination MAC address of the
* packet is not matching the endpoint's MAC address nor broadcast
* MAC address. Drop the packet. */
eReturn = eReleaseBuffer;
}
else
{
/* Endpoint is down, but the hardware address matches. Accept the
* packet as per RFC 2131 */
}
}
}
#endif /* ipconfigETHERNET_DRIVER_FILTERS_PACKETS */
#if ( ipconfigDRIVER_INCLUDED_RX_IP_CHECKSUM == 0 )
{
/* Some drivers of NIC's with checksum-offloading will enable the above
* define, so that the checksum won't be checked again here */
if( eReturn == eProcessBuffer )
{
/* Is the IP header checksum correct?
*
* NOTE: When the checksum of IP header is calculated while not omitting
* the checksum field, the resulting value of the checksum always is 0xffff
* which is denoted by ipCORRECT_CRC. See this wiki for more information:
* https://en.wikipedia.org/wiki/IPv4_header_checksum#Verifying_the_IPv4_header_checksum
* and this RFC: https://tools.ietf.org/html/rfc1624#page-4
*/
if( usGenerateChecksum( 0U, ( const uint8_t * ) &( pxIPHeader->ucVersionHeaderLength ), ( size_t ) uxHeaderLength ) != ipCORRECT_CRC )
{
/* Check sum in IP-header not correct. */
eReturn = eReleaseBuffer;
}
/* Is the upper-layer checksum (TCP/UDP/ICMP) correct? */
else if( usGenerateProtocolChecksum( ( uint8_t * ) ( pxNetworkBuffer->pucEthernetBuffer ), pxNetworkBuffer->xDataLength, pdFALSE ) != ipCORRECT_CRC )
{
/* Protocol checksum not accepted. */
eReturn = eReleaseBuffer;
}
else
{
/* The checksum of the received packet is OK. */
}
}
}
#else /* if ( ipconfigDRIVER_INCLUDED_RX_IP_CHECKSUM == 0 ) */
{
if( eReturn == eProcessBuffer )
{
if( xCheckIPv4SizeFields( pxNetworkBuffer->pucEthernetBuffer, pxNetworkBuffer->xDataLength ) != pdPASS )
{
/* Some of the length checks were not successful. */
eReturn = eReleaseBuffer;
}
}
#if ( ipconfigUDP_PASS_ZERO_CHECKSUM_PACKETS == 0 )
{
/* Check if this is a UDP packet without a checksum. */
if( eReturn == eProcessBuffer )
{
uint8_t ucProtocol;
const ProtocolHeaders_t * pxProtocolHeaders;
/* ipconfigUDP_PASS_ZERO_CHECKSUM_PACKETS is defined as 0,
* and so UDP packets carrying a protocol checksum of 0, will
* be dropped. */
ucProtocol = pxIPPacket->xIPHeader.ucProtocol;
/* MISRA Ref 11.3.1 [Misaligned access] */
/* More details at: https://github.com/FreeRTOS/FreeRTOS-Plus-TCP/blob/main/MISRA.md#rule-113 */
/* coverity[misra_c_2012_rule_11_3_violation] */
pxProtocolHeaders = ( ( ProtocolHeaders_t * ) &( pxNetworkBuffer->pucEthernetBuffer[ ipSIZE_OF_ETH_HEADER + ( size_t ) ipSIZE_OF_IPv4_HEADER ] ) );
/* Identify the next protocol. */
if( ucProtocol == ( uint8_t ) ipPROTOCOL_UDP )
{
if( pxProtocolHeaders->xUDPHeader.usChecksum == ( uint16_t ) 0U )
{
#if ( ipconfigHAS_PRINTF != 0 )
{
static BaseType_t xCount = 0;
/* Exclude this from branch coverage as this is only used for debugging. */
if( xCount < 5 ) /* LCOV_EXCL_BR_LINE */
{
FreeRTOS_printf( ( "prvAllowIPPacket: UDP packet from %lxip without CRC dropped\n",
( unsigned long ) FreeRTOS_ntohl( pxIPPacket->xIPHeader.ulSourceIPAddress ) ) );
xCount++;
}
}
#endif /* ( ipconfigHAS_PRINTF != 0 ) */
/* Protocol checksum not accepted. */
eReturn = eReleaseBuffer;
}
}
}
}
#endif /* ( ipconfigUDP_PASS_ZERO_CHECKSUM_PACKETS == 0 ) */
/* to avoid warning unused parameters */
( void ) pxNetworkBuffer;
( void ) uxHeaderLength;
}
#endif /* ipconfigDRIVER_INCLUDED_RX_IP_CHECKSUM == 0 */
return eReturn;
}
/*-----------------------------------------------------------*/
/** @brief Check if the IP-header is carrying options.
* @param[in] pxNetworkBuffer the network buffer that contains the packet.
*
* @return Either 'eProcessBuffer' or 'eReleaseBuffer'
*/
enum eFrameProcessingResult prvCheckIP4HeaderOptions( struct xNETWORK_BUFFER * const pxNetworkBuffer )
{
eFrameProcessingResult_t eReturn = eProcessBuffer;
/* This function is only called for IPv4 packets, with an IP-header
* which is larger than 20 bytes. The extra space is used for IP-options.
* The options will either be removed, or the packet shall be dropped,
* depending on a user define. */
#if ( ipconfigIP_PASS_PACKETS_WITH_IP_OPTIONS != 0 )
{
/* MISRA Ref 11.3.1 [Misaligned access] */
/* More details at: https://github.com/FreeRTOS/FreeRTOS-Plus-TCP/blob/main/MISRA.md#rule-113 */
/* coverity[misra_c_2012_rule_11_3_violation] */
IPHeader_t * pxIPHeader = ( ( IPHeader_t * ) &( pxNetworkBuffer->pucEthernetBuffer[ ipSIZE_OF_ETH_HEADER ] ) );
/* All structs of headers expect a IP header size of 20 bytes
* IP header options were included, we'll ignore them and cut them out. */
size_t uxLength = ( size_t ) pxIPHeader->ucVersionHeaderLength;
/* Check if the IP headers are acceptable and if it has our destination.
* The lowest four bits of 'ucVersionHeaderLength' indicate the IP-header
* length in multiples of 4. */
size_t uxHeaderLength = ( size_t ) ( ( uxLength & 0x0FU ) << 2 );
/* Number of bytes contained in IPv4 header options. */
const size_t optlen = ( ( size_t ) uxHeaderLength ) - ipSIZE_OF_IPv4_HEADER;
/* From: the previous start of UDP/ICMP/TCP data. */
const uint8_t * pucSource = ( const uint8_t * ) &( pxNetworkBuffer->pucEthernetBuffer[ sizeof( EthernetHeader_t ) + uxHeaderLength ] );
/* To: the usual start of UDP/ICMP/TCP data at offset 20 (decimal ) from IP header. */
uint8_t * pucTarget = ( uint8_t * ) &( pxNetworkBuffer->pucEthernetBuffer[ sizeof( EthernetHeader_t ) + ipSIZE_OF_IPv4_HEADER ] );
/* How many: total length minus the options and the lower headers. */
const size_t xMoveLen = pxNetworkBuffer->xDataLength - ( optlen + ipSIZE_OF_IPv4_HEADER + ipSIZE_OF_ETH_HEADER );
( void ) memmove( pucTarget, pucSource, xMoveLen );
pxNetworkBuffer->xDataLength -= optlen;
/* Update the total length of the IP packet after removing options. */
pxIPHeader->usLength = FreeRTOS_htons( FreeRTOS_ntohs( pxIPHeader->usLength ) - optlen );
/* Rewrite the Version/IHL byte to indicate that this packet has no IP options. */
pxIPHeader->ucVersionHeaderLength = ( uint8_t ) ( ( pxIPHeader->ucVersionHeaderLength & 0xF0U ) | /* High nibble is the version. */
( ( ipSIZE_OF_IPv4_HEADER >> 2 ) & 0x0FU ) );
}
#else /* if ( ipconfigIP_PASS_PACKETS_WITH_IP_OPTIONS != 0 ) */
{
/* 'ipconfigIP_PASS_PACKETS_WITH_IP_OPTIONS' is not set, so packets carrying
* IP-options will be dropped. */
eReturn = eReleaseBuffer;
}
#endif /* if ( ipconfigIP_PASS_PACKETS_WITH_IP_OPTIONS != 0 ) */
return eReturn;
}
/*-----------------------------------------------------------*/
/* *INDENT-OFF* */
#endif /* ipconfigUSE_IPv4 != 0 ) */
/* *INDENT-ON* */
@@ -0,0 +1,277 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
/**
* @file FreeRTOS_IPv4_Sockets.c
* @brief Implements the Sockets API based on Berkeley sockets for the FreeRTOS+TCP network stack.
* Sockets are used by the application processes to interact with the IP-task which in turn
* interacts with the hardware.
*/
/* Standard includes. */
#include <stdint.h>
#include <stdio.h>
/* FreeRTOS includes. */
#include "FreeRTOS.h"
#include "task.h"
#include "queue.h"
#include "semphr.h"
/* FreeRTOS+TCP includes. */
#include "FreeRTOS_UDP_IP.h"
#include "FreeRTOS_IP.h"
#include "FreeRTOS_IPv4_Sockets.h"
/** @brief The number of octets that make up an IP address. */
#define socketMAX_IP_ADDRESS_OCTETS ( 4U )
/* Just make sure the contents doesn't get compiled if IPv4 is not enabled. */
/* *INDENT-OFF* */
#if( ipconfigUSE_IPv4 != 0 )
/* *INDENT-ON* */
/**
* @brief This function converts the character string pcSource into a network address
* structure, then copies the network address structure to pvDestination.
* pvDestination is written in network byte order.
*
* @param[in] pcSource The character string in holding the IP address.
* @param[out] pvDestination The returned network address in 32-bit network-endian format.
*
* @return pdPASS if the translation was successful or else pdFAIL.
*/
BaseType_t FreeRTOS_inet_pton4( const char * pcSource,
void * pvDestination )
{
const uint32_t ulDecimalBase = 10U;
uint8_t ucOctet[ socketMAX_IP_ADDRESS_OCTETS ];
uint32_t ulReturn = 0U, ulValue;
UBaseType_t uxOctetNumber;
BaseType_t xResult = pdPASS;
const char * pcIPAddress = pcSource;
const void * pvCopySource;
( void ) memset( pvDestination, 0, sizeof( ulReturn ) );
/* Translate "192.168.2.100" to a 32-bit number, network-endian. */
for( uxOctetNumber = 0U; uxOctetNumber < socketMAX_IP_ADDRESS_OCTETS; uxOctetNumber++ )
{
ulValue = 0U;
if( pcIPAddress[ 0 ] == '0' )
{
/* Test for the sequence "0[0-9]", which would make it an octal representation. */
if( ( pcIPAddress[ 1 ] >= '0' ) && ( pcIPAddress[ 1 ] <= '9' ) )
{
FreeRTOS_printf( ( "Octal representation of IP-addresses is not supported." ) );
/* Don't support octal numbers. */
xResult = pdFAIL;
break;
}
}
while( ( *pcIPAddress >= '0' ) && ( *pcIPAddress <= '9' ) )
{
BaseType_t xChar;
/* Move previous read characters into the next decimal
* position. */
ulValue *= ulDecimalBase;
/* Add the binary value of the ascii character. */
xChar = ( BaseType_t ) pcIPAddress[ 0 ];
xChar = xChar - ( BaseType_t ) '0';
ulValue += ( uint32_t ) xChar;
/* Move to next character in the string. */
pcIPAddress++;
}
/* Check characters were read. */
if( pcIPAddress == pcSource )
{
xResult = pdFAIL;
}
/* Check the value fits in an 8-bit number. */
if( ulValue > 0xffU )
{
xResult = pdFAIL;
}
else
{
ucOctet[ uxOctetNumber ] = ( uint8_t ) ulValue;
/* Check the next character is as expected. */
if( uxOctetNumber < ( socketMAX_IP_ADDRESS_OCTETS - 1U ) )
{
if( *pcIPAddress != '.' )
{
xResult = pdFAIL;
}
else
{
/* Move past the dot. */
pcIPAddress++;
}
}
}
if( xResult == pdFAIL )
{
/* No point going on. */
break;
}
}
if( *pcIPAddress != ( char ) 0 )
{
/* Expected the end of the string. */
xResult = pdFAIL;
}
if( uxOctetNumber != socketMAX_IP_ADDRESS_OCTETS )
{
/* Didn't read enough octets. */
xResult = pdFAIL;
}
if( xResult == pdPASS )
{
/* lint: ucOctet has been set because xResult == pdPASS. */
ulReturn = FreeRTOS_inet_addr_quick( ucOctet[ 0 ], ucOctet[ 1 ], ucOctet[ 2 ], ucOctet[ 3 ] );
}
else
{
ulReturn = 0U;
}
if( xResult == pdPASS )
{
pvCopySource = ( const void * ) &ulReturn;
( void ) memcpy( pvDestination, pvCopySource, sizeof( ulReturn ) );
}
return xResult;
}
/*-----------------------------------------------------------*/
/**
* @brief Convert the 32-bit representation of the IP-address to the dotted decimal format.
*
* @param[in] pvSource The pointer to the 32-bit representation of the IP-address.
* @param[out] pcDestination The pointer to a character array where the string of the
* dotted decimal IP format.
* @param[in] uxSize Size of the character array. This value makes sure that the code
* doesn't write beyond it's bounds.
*
* @return The pointer to the string holding the dotted decimal format of the IP-address. If
* everything passes correctly, then the pointer being returned is the same as
* pcDestination, else a NULL is returned.
*/
const char * FreeRTOS_inet_ntop4( const void * pvSource,
char * pcDestination,
socklen_t uxSize )
{
uint32_t ulIPAddress;
void * pvCopyDest;
const char * pcReturn;
if( uxSize < 16U )
{
/* There must be space for "255.255.255.255". */
pcReturn = NULL;
}
else
{
pvCopyDest = ( void * ) &ulIPAddress;
( void ) memcpy( pvCopyDest, pvSource, sizeof( ulIPAddress ) );
( void ) FreeRTOS_inet_ntoa( ulIPAddress, pcDestination );
pcReturn = pcDestination;
}
return pcReturn;
}
/**
* @brief Called by prvSendUDPPacket(), this function will UDP packet
* fields and IPv4 address for the packet to be send.
* @param[in] pxNetworkBuffer The packet to be sent.
* @param[in] pxDestinationAddress The IPv4 socket address.
* @return Returns NULL, always.
*/
void * xSend_UDP_Update_IPv4( NetworkBufferDescriptor_t * pxNetworkBuffer,
const struct freertos_sockaddr * pxDestinationAddress )
{
UDPPacket_t * pxUDPPacket;
if( ( pxNetworkBuffer != NULL ) && ( pxDestinationAddress != NULL ) )
{
/* MISRA Ref 11.3.1 [Misaligned access] */
/* More details at: https://github.com/FreeRTOS/FreeRTOS-Plus-TCP/blob/main/MISRA.md#rule-113 */
/* coverity[misra_c_2012_rule_11_3_violation] */
pxUDPPacket = ( ( UDPPacket_t * ) pxNetworkBuffer->pucEthernetBuffer );
pxNetworkBuffer->xIPAddress.ulIP_IPv4 = pxDestinationAddress->sin_address.ulIP_IPv4;
/* Map the UDP packet onto the start of the frame. */
pxUDPPacket->xEthernetHeader.usFrameType = ipIPv4_FRAME_TYPE;
}
return NULL;
}
/**
* @brief Called by FreeRTOS_recvfrom(), this function will update socket
* address with IPv4 address from the packet received.
* @param[in] pxNetworkBuffer The packet received.
* @param[in] pxSourceAddress The IPv4 socket address.
* @return The Payload Offset.
*/
size_t xRecv_Update_IPv4( const NetworkBufferDescriptor_t * pxNetworkBuffer,
struct freertos_sockaddr * pxSourceAddress )
{
size_t uxPayloadOffset = 0;
if( ( pxNetworkBuffer != NULL ) && ( pxSourceAddress != NULL ) )
{
pxSourceAddress->sin_family = ( uint8_t ) FREERTOS_AF_INET;
pxSourceAddress->sin_address.ulIP_IPv4 = pxNetworkBuffer->xIPAddress.ulIP_IPv4;
pxSourceAddress->sin_port = pxNetworkBuffer->usPort;
}
uxPayloadOffset = ipUDP_PAYLOAD_OFFSET_IPv4;
return uxPayloadOffset;
}
/*-----------------------------------------------------------*/
/* *INDENT-OFF* */
#endif /* ipconfigUSE_IPv4 != 0 ) */
/* *INDENT-ON* */
@@ -0,0 +1,160 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
/**
* @file FreeRTOS_IPv4_Utils.c
* @brief Implements the basic functionality for the FreeRTOS+TCP network stack functions for IPv4.
*/
/* Standard includes. */
#include <stdint.h>
#include <stdio.h>
/* FreeRTOS includes. */
#include "FreeRTOS.h"
/* FreeRTOS+TCP includes. */
#include "FreeRTOS_IP.h"
/* Just make sure the contents doesn't get compiled if IPv4 is not enabled. */
/* *INDENT-OFF* */
#if( ipconfigUSE_IPv4 != 0 )
/* *INDENT-ON* */
/*-----------------------------------------------------------*/
/**
* @brief Set multicast MAC address.
*
* @param[in] ulIPAddress IP address.
* @param[out] pxMACAddress Pointer to MAC address.
*/
void vSetMultiCastIPv4MacAddress( uint32_t ulIPAddress,
MACAddress_t * pxMACAddress )
{
uint32_t ulIP = FreeRTOS_ntohl( ulIPAddress );
pxMACAddress->ucBytes[ 0 ] = ( uint8_t ) ipMULTICAST_MAC_ADDRESS_IPv4_0;
pxMACAddress->ucBytes[ 1 ] = ( uint8_t ) ipMULTICAST_MAC_ADDRESS_IPv4_1;
pxMACAddress->ucBytes[ 2 ] = ( uint8_t ) ipMULTICAST_MAC_ADDRESS_IPv4_2;
pxMACAddress->ucBytes[ 3 ] = ( uint8_t ) ( ( ulIP >> 16 ) & 0x7fU ); /* Use 7 bits. */
pxMACAddress->ucBytes[ 4 ] = ( uint8_t ) ( ( ulIP >> 8 ) & 0xffU ); /* Use 8 bits. */
pxMACAddress->ucBytes[ 5 ] = ( uint8_t ) ( ( ulIP ) & 0xffU ); /* Use 8 bits. */
}
/*-----------------------------------------------------------*/
/** @brief Do the first IPv4 length checks at the IP-header level.
* @param[in] pucEthernetBuffer The buffer containing the packet.
* @param[in] uxBufferLength The number of bytes to be sent or received.
* @param[in] pxSet A struct describing this packet.
*
* @return Non-zero in case of an error.
*/
BaseType_t prvChecksumIPv4Checks( uint8_t * pucEthernetBuffer,
size_t uxBufferLength,
struct xPacketSummary * pxSet )
{
BaseType_t xReturn = 0;
uint8_t ucVersion;
uint16_t usLength;
pxSet->xIsIPv6 = pdFALSE;
usLength = pxSet->pxIPPacket->xIPHeader.usLength;
usLength = FreeRTOS_ntohs( usLength );
/* IPv4 : the lower nibble in 'ucVersionHeaderLength' indicates the length
* of the IP-header, expressed in number of 4-byte words. Usually 5 words.
*/
ucVersion = pxSet->pxIPPacket->xIPHeader.ucVersionHeaderLength & ( uint8_t ) 0x0FU;
pxSet->uxIPHeaderLength = ( size_t ) ucVersion;
pxSet->uxIPHeaderLength *= 4U;
if( usLength < pxSet->uxIPHeaderLength )
{
pxSet->usChecksum = ipINVALID_LENGTH;
xReturn = 3;
}
/* Check for minimum packet size. */
if( xReturn == 0 )
{
if( uxBufferLength < sizeof( IPPacket_t ) )
{
pxSet->usChecksum = ipINVALID_LENGTH;
xReturn = 4;
}
}
if( xReturn == 0 )
{
/* Check for minimum packet size. */
if( uxBufferLength < ( ipSIZE_OF_ETH_HEADER + pxSet->uxIPHeaderLength ) )
{
/* The packet does not contain the full IP-headers so drop it. */
pxSet->usChecksum = ipINVALID_LENGTH;
xReturn = 5;
}
}
if( xReturn == 0 )
{
size_t uxNeeded;
/* xIPHeader.usLength is the total length, minus the Ethernet header. */
pxSet->usPayloadLength = FreeRTOS_ntohs( pxSet->pxIPPacket->xIPHeader.usLength );
uxNeeded = pxSet->usPayloadLength;
uxNeeded += ipSIZE_OF_ETH_HEADER;
if( uxBufferLength < uxNeeded )
{
/* The payload is longer than the packet appears to contain. */
pxSet->usChecksum = ipINVALID_LENGTH;
xReturn = 6;
}
}
if( xReturn == 0 )
{
/* Identify the next protocol. */
pxSet->ucProtocol = pxSet->pxIPPacket->xIPHeader.ucProtocol;
/* MISRA Ref 11.3.1 [Misaligned access] */
/* More details at: https://github.com/FreeRTOS/FreeRTOS-Plus-TCP/blob/main/MISRA.md#rule-113 */
/* coverity[misra_c_2012_rule_11_3_violation] */
pxSet->pxProtocolHeaders = ( ( ProtocolHeaders_t * ) &( pucEthernetBuffer[ pxSet->uxIPHeaderLength + ipSIZE_OF_ETH_HEADER ] ) );
/* For IPv4, the number of bytes in IP-header + the protocol is indicated. */
pxSet->usProtocolBytes = ( uint16_t ) ( pxSet->usPayloadLength - pxSet->uxIPHeaderLength );
}
return xReturn;
}
/*-----------------------------------------------------------*/
/* *INDENT-OFF* */
#endif /* ipconfigUSE_IPv4 != 0 ) */
/* *INDENT-ON* */
@@ -0,0 +1,709 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
/**
* @file FreeRTOS_IPv6.c
* @brief Implements the basic functionality for the FreeRTOS+TCP network stack.
*/
/* Standard includes. */
#include <stdint.h>
#include <stdio.h>
#include <string.h>
/* FreeRTOS includes. */
#include "FreeRTOS.h"
/* FreeRTOS+TCP includes. */
#include "FreeRTOS_IP.h"
/* *INDENT-OFF* */
#if( ipconfigUSE_IPv6 != 0 )
/* *INDENT-ON* */
/** @brief Get the scope field in IPv6 multicast address. */
#define IPv6MC_GET_SCOPE_VALUE( pxIPv6Address ) ( ( ( pxIPv6Address )->ucBytes[ 1 ] ) & 0x0FU )
/** @brief Get the flags field in IPv6 multicast address. */
#define IPv6MC_GET_FLAGS_VALUE( pxIPv6Address ) ( ( ( pxIPv6Address )->ucBytes[ 1 ] ) & 0xF0U )
/** @brief Get the group ID field in IPv6 multicast address. */
#define IPv6MC_GET_GROUP_ID( pxIPv6Address, pxReturnGroupID ) ( xGetIPv6MulticastGroupID( pxIPv6Address, pxReturnGroupID ) )
/**
* This variable is initialized by the system to contain the wildcard IPv6 address.
*/
const struct xIPv6_Address FreeRTOS_in6addr_any = { 0 };
/**
* This variable is initialized by the system to contain the loopback IPv6 address.
*/
/* MISRA Ref 8.9.1 [File scoped variables] */
/* More details at: https://github.com/FreeRTOS/FreeRTOS-Plus-TCP/blob/main/MISRA.md#rule-89 */
/* coverity[misra_c_2012_rule_8_9_violation] */
const struct xIPv6_Address FreeRTOS_in6addr_loopback = { { 0U, 0U, 0U, 0U, 0U, 0U, 0U, 0U, 0U, 0U, 0U, 0U, 0U, 0U, 0U, 1U } };
#if ( ipconfigDRIVER_INCLUDED_RX_IP_CHECKSUM == 1 )
/* Check IPv6 packet length. */
static BaseType_t xCheckIPv6SizeFields( const void * const pvEthernetBuffer,
size_t uxBufferLength );
#endif /* ( ipconfigDRIVER_INCLUDED_RX_IP_CHECKSUM == 1 ) */
#if ( ipconfigDRIVER_INCLUDED_RX_IP_CHECKSUM == 1 )
/* Check if ucNextHeader is an extension header. */
static BaseType_t xIsExtHeader( uint8_t ucNextHeader );
#endif /* ( ipconfigDRIVER_INCLUDED_RX_IP_CHECKSUM == 1 ) */
#if ( ipconfigDRIVER_INCLUDED_RX_IP_CHECKSUM == 1 )
/**
* @brief Check IPv6 packet length.
*
* @param[in] pvEthernetBuffer The Ethernet packet received.
* @param[in] uxBufferLength The total number of bytes received.
*
* @return pdPASS when the length fields in the packet OK, pdFAIL when the packet
* should be dropped.
*/
static BaseType_t xCheckIPv6SizeFields( const void * const pvEthernetBuffer,
size_t uxBufferLength )
{
BaseType_t xResult = pdFAIL;
uint16_t usPayloadLength;
uint8_t ucNextHeader;
size_t uxMinimumLength;
size_t uxExtHeaderLength = 0;
const IPExtHeader_IPv6_t * pxExtHeader = NULL;
const uint8_t * const pucEthernetBuffer = ( const uint8_t * ) pvEthernetBuffer;
/* Map the buffer onto a IPv6-Packet struct to easily access the
* fields of the IPv6 packet. */
const IPPacket_IPv6_t * const pxIPv6Packet = ( const IPPacket_IPv6_t * ) pucEthernetBuffer;
DEBUG_DECLARE_TRACE_VARIABLE( BaseType_t, xLocation, 0 );
do
{
/* Check for minimum packet size: Ethernet header and an IPv6-header, 54 bytes */
if( uxBufferLength < sizeof( IPHeader_IPv6_t ) )
{
DEBUG_SET_TRACE_VARIABLE( xLocation, 1 );
break;
}
/* Check if the IPv6-header is transferred. */
if( uxBufferLength < ( ipSIZE_OF_ETH_HEADER + ipSIZE_OF_IPv6_HEADER ) )
{
DEBUG_SET_TRACE_VARIABLE( xLocation, 3 );
break;
}
/* Check if the complete IPv6-header plus protocol data have been transferred: */
usPayloadLength = FreeRTOS_ntohs( pxIPv6Packet->xIPHeader.usPayloadLength );
if( uxBufferLength < ( size_t ) ( ipSIZE_OF_ETH_HEADER + ipSIZE_OF_IPv6_HEADER + ( size_t ) usPayloadLength ) )
{
DEBUG_SET_TRACE_VARIABLE( xLocation, 4 );
break;
}
/* Identify the next protocol. */
ucNextHeader = pxIPv6Packet->xIPHeader.ucNextHeader;
while( xIsExtHeader( ucNextHeader ) )
{
pxExtHeader = ( const IPExtHeader_IPv6_t * ) ( &( pucEthernetBuffer[ ipSIZE_OF_ETH_HEADER + ipSIZE_OF_IPv6_HEADER + uxExtHeaderLength ] ) );
/* The definition of length in extension header - Length of this header in 8-octet units, not including the first 8 octets. */
uxExtHeaderLength += ( size_t ) ( ( 8 * pxExtHeader->ucHeaderExtLength ) + 8 );
ucNextHeader = pxExtHeader->ucNextHeader;
if( ipSIZE_OF_ETH_HEADER + ipSIZE_OF_IPv6_HEADER + uxExtHeaderLength >= uxBufferLength )
{
break;
}
}
if( ipSIZE_OF_ETH_HEADER + ipSIZE_OF_IPv6_HEADER + uxExtHeaderLength >= uxBufferLength )
{
DEBUG_SET_TRACE_VARIABLE( xLocation, 7 );
break;
}
/* Switch on the Layer 3/4 protocol. */
if( ucNextHeader == ( uint8_t ) ipPROTOCOL_UDP )
{
/* Expect at least a complete UDP header. */
uxMinimumLength = ipSIZE_OF_ETH_HEADER + ipSIZE_OF_IPv6_HEADER + uxExtHeaderLength + ipSIZE_OF_UDP_HEADER;
}
else if( ucNextHeader == ( uint8_t ) ipPROTOCOL_TCP )
{
uxMinimumLength = ipSIZE_OF_ETH_HEADER + ipSIZE_OF_IPv6_HEADER + uxExtHeaderLength + ipSIZE_OF_TCP_HEADER;
}
else if( ucNextHeader == ( uint8_t ) ipPROTOCOL_ICMP_IPv6 )
{
uint8_t ucTypeOfMessage;
uxMinimumLength = ipSIZE_OF_ETH_HEADER + ipSIZE_OF_IPv6_HEADER + uxExtHeaderLength;
ucTypeOfMessage = pucEthernetBuffer[ uxMinimumLength ];
if( ( ucTypeOfMessage == ipICMP_PING_REQUEST_IPv6 ) ||
( ucTypeOfMessage == ipICMP_PING_REPLY_IPv6 ) )
{
uxMinimumLength += sizeof( ICMPEcho_IPv6_t );
}
else if( ucTypeOfMessage == ipICMP_ROUTER_SOLICITATION_IPv6 )
{
uxMinimumLength += sizeof( ICMPRouterSolicitation_IPv6_t );
}
else if( ucTypeOfMessage == ipICMP_ROUTER_ADVERTISEMENT_IPv6 )
{
uxMinimumLength += sizeof( ICMPRouterAdvertisement_IPv6_t );
}
else
{
uxMinimumLength += ipSIZE_OF_ICMPv6_HEADER;
}
}
else
{
/* Unhandled protocol, other than ICMP, IGMP, UDP, or TCP. */
DEBUG_SET_TRACE_VARIABLE( xLocation, 5 );
break;
}
if( uxBufferLength < uxMinimumLength )
{
DEBUG_SET_TRACE_VARIABLE( xLocation, 6 );
break;
}
xResult = pdPASS;
} while( ipFALSE_BOOL );
if( xResult != pdPASS )
{
/* NOP if ipconfigHAS_PRINTF != 1 */
FreeRTOS_printf( ( "xCheckIPv6SizeFields: location %ld\n", xLocation ) );
}
return xResult;
}
#endif /* ( ipconfigDRIVER_INCLUDED_RX_IP_CHECKSUM == 1 ) */
/*-----------------------------------------------------------*/
#if ( ipconfigDRIVER_INCLUDED_RX_IP_CHECKSUM == 1 )
/**
* @brief Check if ucNextHeader is an extension header.
*
* @param[in] ucNextHeader Next header, such as ipIPv6_EXT_HEADER_HOP_BY_HOP.
*
* @return pdTRUE if it's extension header, otherwise pdFALSE.
*/
static BaseType_t xIsExtHeader( uint8_t ucNextHeader )
{
BaseType_t xReturn = pdFALSE;
switch( ucNextHeader )
{
case ipIPv6_EXT_HEADER_HOP_BY_HOP:
case ipIPv6_EXT_HEADER_ROUTING_HEADER:
case ipIPv6_EXT_HEADER_FRAGMENT_HEADER:
case ipIPv6_EXT_HEADER_SECURE_PAYLOAD:
case ipIPv6_EXT_HEADER_AUTHEN_HEADER:
case ipIPv6_EXT_HEADER_DESTINATION_OPTIONS:
case ipIPv6_EXT_HEADER_MOBILITY_HEADER:
xReturn = pdTRUE;
}
return xReturn;
}
#endif /* ( ipconfigDRIVER_INCLUDED_RX_IP_CHECKSUM == 1 ) */
/*-----------------------------------------------------------*/
/**
* @brief Get the group ID and stored into IPv6_Address_t.
*
* @param[in] pxIPv6Address The multicast address to filter group ID.
* @param[out] pxReturnGroupID The buffer to store group ID.
*/
static void xGetIPv6MulticastGroupID( const IPv6_Address_t * pxIPv6Address,
IPv6_Address_t * pxReturnGroupID )
{
configASSERT( pxIPv6Address != NULL );
configASSERT( pxReturnGroupID != NULL );
pxReturnGroupID->ucBytes[ 0 ] = 0U;
pxReturnGroupID->ucBytes[ 1 ] = 0U;
( void ) memcpy( &( pxReturnGroupID->ucBytes[ 2 ] ), &( pxIPv6Address->ucBytes[ 2 ] ), 14 );
}
/*-----------------------------------------------------------*/
/**
* @brief Check if the IP-address is an IPv6 loopback address.
*
* @param[in] pxAddress The IP-address being checked.
*
* @return pdTRUE if the IP-address is a loopback address or else, pdFALSE.
*/
BaseType_t xIsIPv6Loopback( const IPv6_Address_t * pxAddress )
{
BaseType_t xReturn = pdFALSE;
if( memcmp( pxAddress->ucBytes, FreeRTOS_in6addr_loopback.ucBytes, ipSIZE_OF_IPv6_ADDRESS ) == 0 )
{
xReturn = pdTRUE;
}
return xReturn;
}
#if ( ipconfigETHERNET_DRIVER_FILTERS_PACKETS == 0 )
/**
* @brief Check if the packet is an illegal loopback packet.
*
* @param[in] pxIPv6Header The IP-header of the packet.
*
* @return Returns pdTRUE if the packet should be stopped, because either the source
* or the target address is a loopback address.
*/
/* MISRA Ref 8.9.1 [File scoped variables] */
/* More details at: https://github.com/FreeRTOS/FreeRTOS-Plus-TCP/blob/main/MISRA.md#rule-89 */
/* coverity[misra_c_2012_rule_8_9_violation] */
/* coverity[single_use] */
BaseType_t xBadIPv6Loopback( const IPHeader_IPv6_t * const pxIPv6Header )
{
BaseType_t xReturn = pdFALSE;
const NetworkEndPoint_t * pxEndPoint = FreeRTOS_FindEndPointOnIP_IPv6( &( pxIPv6Header->xSourceAddress ) );
/* Allow loopback packets from this node itself only. */
if( pxEndPoint != NULL )
{
BaseType_t x1 = ( xIsIPv6Loopback( &( pxIPv6Header->xDestinationAddress ) ) != 0 ) ? pdTRUE : pdFALSE;
BaseType_t x2 = ( xIsIPv6Loopback( &( pxIPv6Header->xSourceAddress ) ) != 0 ) ? pdTRUE : pdFALSE;
if( x1 != x2 )
{
/* Either source or the destination address is a loopback address. */
xReturn = pdTRUE;
}
}
return xReturn;
}
#endif /* ipconfigETHERNET_DRIVER_FILTERS_PACKETS == 0 */
/*-----------------------------------------------------------*/
/**
* @brief Check whether this IPv6 address is an allowed multicast address or not.
*
* @param[in] pxIPAddress The IP address to be checked.
*
* @return Returns pdTRUE if pxIPAddress is an allowed multicast address, pdFALSE if not.
*/
BaseType_t xIsIPv6AllowedMulticast( const IPv6_Address_t * pxIPAddress )
{
BaseType_t xReturn = pdFALSE;
IPv6_Address_t xGroupIDAddress;
if( pxIPAddress->ucBytes[ 0 ] == 0xffU )
{
IPv6MC_GET_GROUP_ID( pxIPAddress, &xGroupIDAddress );
/* From RFC4291 - sec 2.7, packets from multicast address whose scope field is 0
* should be silently dropped. */
if( IPv6MC_GET_SCOPE_VALUE( pxIPAddress ) == 0U )
{
xReturn = pdFALSE;
}
/* From RFC4291 - sec 2.7.1, packets from predefined multicast address should never be used.
* - 0xFF00::
* - 0xFF01::
* - ..
* - 0xFF0F:: */
else if( ( IPv6MC_GET_FLAGS_VALUE( pxIPAddress ) == 0U ) &&
( memcmp( xGroupIDAddress.ucBytes, FreeRTOS_in6addr_any.ucBytes, sizeof( IPv6_Address_t ) ) == 0 ) )
{
xReturn = pdFALSE;
}
else
{
xReturn = pdTRUE;
}
}
return xReturn;
}
/*-----------------------------------------------------------*/
/**
* @brief Compares 2 IPv6 addresses and checks if the one
* on the left can handle the one on right. Note that 'xCompareIPv6_Address' will also check if 'pxRight' is
* the special unicast address: ff02::1:ffnn:nnnn, where nn:nnnn are
* the last 3 bytes of the IPv6 address.
*
* @param[in] pxLeft First IP address.
* @param[in] pxRight Second IP address.
* @param[in] uxPrefixLength The IP address prefix length in bits.
*
* @return Returns 0 if it can handle it, else non zero .
*/
BaseType_t xCompareIPv6_Address( const IPv6_Address_t * pxLeft,
const IPv6_Address_t * pxRight,
size_t uxPrefixLength )
{
BaseType_t xResult;
/* This variable is initialized by the system to contain the IPv6 multicast address for all nodes. */
static const struct xIPv6_Address FreeRTOS_in6addr_allnodes = { { 0xff, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01 } };
/* 0 2 4 6 8 10 12 14 */
/* ff02:0000:0000:0000:0000:0001:ff66:4a81 */
if( ( pxRight->ucBytes[ 0 ] == 0xffU ) &&
( pxRight->ucBytes[ 1 ] == 0x02U ) &&
( pxRight->ucBytes[ 12 ] == 0xffU ) )
{
/* This is an LLMNR address. */
xResult = memcmp( &( pxLeft->ucBytes[ 13 ] ), &( pxRight->ucBytes[ 13 ] ), 3 );
}
else
if( memcmp( pxRight->ucBytes, FreeRTOS_in6addr_allnodes.ucBytes, sizeof( IPv6_Address_t ) ) == 0 )
{
/* FF02::1 is all node address to reach out all nodes in the same link. */
xResult = 0;
}
else
if( ( pxRight->ucBytes[ 0 ] == 0xfeU ) &&
( pxRight->ucBytes[ 1 ] == 0x80U ) &&
( pxLeft->ucBytes[ 0 ] == 0xfeU ) &&
( pxLeft->ucBytes[ 1 ] == 0x80U ) )
{
/* Both are local addresses. */
xResult = 0;
}
else
{
if( uxPrefixLength == 0U )
{
xResult = 0;
}
else if( uxPrefixLength == ( 8U * ipSIZE_OF_IPv6_ADDRESS ) )
{
xResult = memcmp( pxLeft->ucBytes, pxRight->ucBytes, ipSIZE_OF_IPv6_ADDRESS );
}
else
{
size_t uxLength = uxPrefixLength / 8U;
xResult = 0;
if( uxLength > 0U )
{
xResult = memcmp( pxLeft->ucBytes, pxRight->ucBytes, uxLength );
}
if( ( xResult == 0 ) && ( ( uxPrefixLength % 8U ) != 0U ) )
{
/* One byte has both a network- and a host-address. */
size_t uxBits = uxPrefixLength % 8U;
size_t uxHostLen = 8U - uxBits;
uint32_t uxHostMask = ( ( ( uint32_t ) 1U ) << uxHostLen ) - 1U;
uint8_t ucNetMask = ( uint8_t ) ~( uxHostMask );
if( ( pxLeft->ucBytes[ uxLength ] & ucNetMask ) != ( pxRight->ucBytes[ uxLength ] & ucNetMask ) )
{
xResult = 1;
}
}
}
}
return xResult;
}
/*-----------------------------------------------------------*/
/**
* @brief Check whether this IPv6 packet is to be allowed or to be dropped.
*
* @param[in] pxIPv6Header The IP packet under consideration.
* @param[in] pxNetworkBuffer The whole network buffer.
* @param[in] uxHeaderLength The length of the header.
*
* @return Whether the packet should be processed or dropped.
*/
eFrameProcessingResult_t prvAllowIPPacketIPv6( const IPHeader_IPv6_t * const pxIPv6Header,
const NetworkBufferDescriptor_t * const pxNetworkBuffer,
UBaseType_t uxHeaderLength )
{
eFrameProcessingResult_t eReturn;
#if ( ipconfigETHERNET_DRIVER_FILTERS_PACKETS == 0 )
{
/* In systems with a very small amount of RAM, it might be advantageous
* to have incoming messages checked earlier, by the network card driver.
* This method may decrease the usage of sparse network buffers. */
const IPv6_Address_t * pxDestinationIPAddress = &( pxIPv6Header->xDestinationAddress );
const IPv6_Address_t * pxSourceIPAddress = &( pxIPv6Header->xSourceAddress );
BaseType_t xHasUnspecifiedAddress = pdFALSE;
uint16_t ucVersionTrafficClass = pxIPv6Header->ucVersionTrafficClass;
/* Drop if packet has unspecified IPv6 address (defined in RFC4291 - sec 2.5.2)
* either in source or destination address. */
if( ( memcmp( pxDestinationIPAddress->ucBytes, FreeRTOS_in6addr_any.ucBytes, sizeof( IPv6_Address_t ) ) == 0 ) ||
( memcmp( pxSourceIPAddress->ucBytes, FreeRTOS_in6addr_any.ucBytes, sizeof( IPv6_Address_t ) ) == 0 ) )
{
xHasUnspecifiedAddress = pdTRUE;
}
/* Test if the IP-version is 6. */
if( ( ( ucVersionTrafficClass & ( uint8_t ) 0xF0U ) >> 4 ) != 6U )
{
/* Can not handle, unknown or invalid header version. */
eReturn = eReleaseBuffer;
FreeRTOS_printf( ( "prvAllowIPPacketIPv6: drop packet, invalid header version: %u\n", ( ucVersionTrafficClass & ( uint8_t ) 0xF0U ) >> 4 ) );
}
/* Is the packet for this IP address? */
else if( ( xHasUnspecifiedAddress == pdFALSE ) &&
( pxNetworkBuffer->pxEndPoint != NULL ) &&
( memcmp( pxDestinationIPAddress->ucBytes, pxNetworkBuffer->pxEndPoint->ipv6_settings.xIPAddress.ucBytes, sizeof( IPv6_Address_t ) ) == 0 ) )
{
eReturn = eProcessBuffer;
}
/* Is it the legal multicast address? */
else if( ( ( xHasUnspecifiedAddress == pdFALSE ) &&
( xBadIPv6Loopback( pxIPv6Header ) == pdFALSE ) ) &&
( ( xIsIPv6AllowedMulticast( pxDestinationIPAddress ) != pdFALSE ) ||
/* Or (during DHCP negotiation) we have no IP-address yet? */
( FreeRTOS_IsNetworkUp() == 0 ) ) )
{
eReturn = eProcessBuffer;
}
else
{
/* Packet is not for this node, or the network is still not up,
* release it */
eReturn = eReleaseBuffer;
FreeRTOS_printf( ( "prvAllowIPPacketIPv6: drop %pip (from %pip)\n", pxDestinationIPAddress->ucBytes, pxIPv6Header->xSourceAddress.ucBytes ) );
}
}
#else /* if ( ipconfigETHERNET_DRIVER_FILTERS_PACKETS == 0 ) */
{
( void ) pxIPv6Header;
/* The packet has been checked by the network interface. */
eReturn = eProcessBuffer;
}
#endif /* ipconfigETHERNET_DRIVER_FILTERS_PACKETS */
#if ( ipconfigDRIVER_INCLUDED_RX_IP_CHECKSUM == 0 )
{
/* Some drivers of NIC's with checksum-offloading will enable the above
* define, so that the checksum won't be checked again here */
if( eReturn == eProcessBuffer )
{
/* IPv6 does not have a separate checksum in the IP-header */
/* Is the upper-layer checksum (TCP/UDP/ICMP) correct? */
if( usGenerateProtocolChecksum( ( uint8_t * ) ( pxNetworkBuffer->pucEthernetBuffer ), pxNetworkBuffer->xDataLength, pdFALSE ) != ipCORRECT_CRC )
{
/* Protocol checksum not accepted. */
eReturn = eReleaseBuffer;
}
}
}
#else /* if ( ipconfigDRIVER_INCLUDED_RX_IP_CHECKSUM == 0 ) */
{
if( eReturn == eProcessBuffer )
{
if( xCheckIPv6SizeFields( pxNetworkBuffer->pucEthernetBuffer, pxNetworkBuffer->xDataLength ) != pdPASS )
{
/* Some of the length checks were not successful. */
eReturn = eReleaseBuffer;
}
}
/* to avoid warning unused parameters */
( void ) pxNetworkBuffer;
}
#endif /* ipconfigDRIVER_INCLUDED_RX_IP_CHECKSUM == 0 */
( void ) uxHeaderLength;
return eReturn;
}
/*-----------------------------------------------------------*/
/**
* @brief Check extension header and next header and return their order.
*
* @param[in] ucProtocol Extension header ID.
* @param[in] ucNextHeader Next header ID.
*
* @return Extension header order in the packet.
*/
BaseType_t xGetExtensionOrder( uint8_t ucProtocol,
uint8_t ucNextHeader )
{
BaseType_t xReturn;
switch( ucProtocol )
{
case ipIPv6_EXT_HEADER_HOP_BY_HOP:
xReturn = 1;
break;
case ipIPv6_EXT_HEADER_DESTINATION_OPTIONS:
xReturn = 7;
if( ucNextHeader == ipIPv6_EXT_HEADER_ROUTING_HEADER )
{
xReturn = 2;
}
break;
case ipIPv6_EXT_HEADER_ROUTING_HEADER:
xReturn = 3;
break;
case ipIPv6_EXT_HEADER_FRAGMENT_HEADER:
xReturn = 4;
break;
case ipIPv6_EXT_HEADER_AUTHEN_HEADER:
xReturn = 5;
break;
case ipIPv6_EXT_HEADER_SECURE_PAYLOAD:
xReturn = 6;
break;
/* Destination options may follow here in case there are no routing options. */
case ipIPv6_EXT_HEADER_MOBILITY_HEADER:
xReturn = 8;
break;
default:
xReturn = -1;
break;
}
return xReturn;
}
/*-----------------------------------------------------------*/
/**
* @brief Handle the IPv6 extension headers.
*
* @param[in,out] pxNetworkBuffer The received packet that contains IPv6 extension headers.
* @param[in] xDoRemove Function removes the extension header if xDoRemove is set to pdTRUE.
*
* @return eProcessBuffer in case the options are removed successfully, otherwise
* eReleaseBuffer.
*/
eFrameProcessingResult_t eHandleIPv6ExtensionHeaders( NetworkBufferDescriptor_t * const pxNetworkBuffer,
BaseType_t xDoRemove )
{
eFrameProcessingResult_t eResult = eReleaseBuffer;
const size_t uxMaxLength = pxNetworkBuffer->xDataLength;
/* MISRA Ref 11.3.1 [Misaligned access] */
/* More details at: https://github.com/FreeRTOS/FreeRTOS-Plus-TCP/blob/main/MISRA.md#rule-113 */
/* coverity[misra_c_2012_rule_11_3_violation] */
IPPacket_IPv6_t * pxIPPacket_IPv6 = ( ( IPPacket_IPv6_t * ) pxNetworkBuffer->pucEthernetBuffer );
size_t xMoveLen = 0U;
size_t uxRemovedBytes = 0U;
uint8_t ucNextHeader = 0U;
size_t uxIndex = 0U;
uxRemovedBytes = usGetExtensionHeaderLength( pxNetworkBuffer->pucEthernetBuffer, pxNetworkBuffer->xDataLength, &ucNextHeader );
uxIndex = ipSIZE_OF_ETH_HEADER + ipSIZE_OF_IPv6_HEADER + uxRemovedBytes;
if( uxIndex < uxMaxLength )
{
uint8_t * pucTo;
const uint8_t * pucFrom;
uint16_t usPayloadLength = FreeRTOS_ntohs( pxIPPacket_IPv6->xIPHeader.usPayloadLength );
if( uxRemovedBytes >= ( size_t ) usPayloadLength )
{
/* Can not remove more bytes than the payload length. */
}
else if( xDoRemove == pdTRUE )
{
pxIPPacket_IPv6->xIPHeader.ucNextHeader = ucNextHeader;
pucTo = &( pxNetworkBuffer->pucEthernetBuffer[ ipSIZE_OF_ETH_HEADER + ipSIZE_OF_IPv6_HEADER ] );
pucFrom = &( pxNetworkBuffer->pucEthernetBuffer[ uxIndex ] );
xMoveLen = uxMaxLength - uxIndex;
( void ) memmove( pucTo, pucFrom, xMoveLen );
pxNetworkBuffer->xDataLength -= uxRemovedBytes;
usPayloadLength = ( uint16_t ) ( usPayloadLength - uxRemovedBytes );
pxIPPacket_IPv6->xIPHeader.usPayloadLength = FreeRTOS_htons( usPayloadLength );
eResult = eProcessBuffer;
}
else
{
/* xDoRemove is false, so the function is not supposed to
* remove extension headers. */
}
}
FreeRTOS_printf( ( "Extension headers : %s Truncated %u bytes. Removed %u, Payload %u xDataLength now %u\n",
( eResult == eProcessBuffer ) ? "good" : "bad",
( unsigned ) xMoveLen,
( unsigned ) uxRemovedBytes,
FreeRTOS_ntohs( pxIPPacket_IPv6->xIPHeader.usPayloadLength ),
( unsigned ) pxNetworkBuffer->xDataLength ) );
return eResult;
}
/*-----------------------------------------------------------*/
/* *INDENT-OFF* */
#endif /* ( ipconfigUSE_IPv6 != 0 ) */
/* *INDENT-ON* */
@@ -0,0 +1,660 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
/**
* @file FreeRTOS_IPv6_Sockets.c
* @brief Implements the Sockets API based on Berkeley sockets for the FreeRTOS+TCP network stack.
* Sockets are used by the application processes to interact with the IP-task which in turn
* interacts with the hardware.
*/
/* Standard includes. */
#include <stdint.h>
#include <stdio.h>
/* FreeRTOS includes. */
#include "FreeRTOS.h"
/* FreeRTOS+TCP includes. */
#include "FreeRTOS_IP.h"
#include "FreeRTOS_IPv6_Sockets.h"
/* *INDENT-OFF* */
#if( ipconfigUSE_IPv6 != 0 )
/* *INDENT-ON* */
#if ( ipconfigUSE_TCP == 1 )
/**
* @brief Called by pxTCPSocketLookup(), this function will check if a socket
* is connected to a remote IP-address. It will be called from a loop
* iterating through all sockets.
* @param[in] pxSocket The socket to be inspected.
* @param[in] pxAddress The IPv4/IPv6 address.
* @return The socket in case it is connected to the remote IP-address.
*/
FreeRTOS_Socket_t * pxTCPSocketLookup_IPv6( FreeRTOS_Socket_t * pxSocket,
const IPv46_Address_t * pxAddress )
{
FreeRTOS_Socket_t * pxResult = NULL;
if( ( pxSocket != NULL ) && ( pxAddress != NULL ) )
{
if( pxSocket->bits.bIsIPv6 != pdFALSE_UNSIGNED )
{
if( pxAddress->xIs_IPv6 != pdFALSE )
{
if( memcmp( pxSocket->u.xTCP.xRemoteIP.xIP_IPv6.ucBytes, pxAddress->xIPAddress.xIP_IPv6.ucBytes, ipSIZE_OF_IPv6_ADDRESS ) == 0 )
{
/* For sockets not in listening mode, find a match with
* uxLocalPort, ulRemoteIP AND uxRemotePort. */
pxResult = pxSocket;
}
}
}
else
{
if( pxAddress->xIs_IPv6 == pdFALSE )
{
if( pxSocket->u.xTCP.xRemoteIP.ulIP_IPv4 == pxAddress->xIPAddress.ulIP_IPv4 )
{
/* For sockets not in listening mode, find a match with
* uxLocalPort, ulRemoteIP AND uxRemotePort. */
pxResult = pxSocket;
}
}
}
}
return pxResult;
}
#endif /* if ( ( ipconfigUSE_TCP == 1 ) */
/**
* @brief Called by prvSendUDPPacket(), this function will UDP packet
* fields and IPv6 address for the packet to be send.
* @param[in] pxNetworkBuffer The packet to be sent.
* @param[in] pxDestinationAddress The IPv4 socket address.
* @return Returns NULL, always.
*/
void * xSend_UDP_Update_IPv6( NetworkBufferDescriptor_t * pxNetworkBuffer,
const struct freertos_sockaddr * pxDestinationAddress )
{
/* MISRA Ref 11.3.1 [Misaligned access] */
/* More details at: https://github.com/FreeRTOS/FreeRTOS-Plus-TCP/blob/main/MISRA.md#rule-113 */
/* coverity[misra_c_2012_rule_11_3_violation] */
UDPPacket_IPv6_t * pxUDPPacket_IPv6 = ( ( UDPPacket_IPv6_t * ) pxNetworkBuffer->pucEthernetBuffer );
pxNetworkBuffer->xIPAddress.ulIP_IPv4 = 0U;
configASSERT( pxDestinationAddress != NULL );
( void ) memcpy( pxUDPPacket_IPv6->xIPHeader.xDestinationAddress.ucBytes, pxDestinationAddress->sin_address.xIP_IPv6.ucBytes, ipSIZE_OF_IPv6_ADDRESS );
( void ) memcpy( pxNetworkBuffer->xIPAddress.xIP_IPv6.ucBytes, pxDestinationAddress->sin_address.xIP_IPv6.ucBytes, ipSIZE_OF_IPv6_ADDRESS );
pxUDPPacket_IPv6->xEthernetHeader.usFrameType = ipIPv6_FRAME_TYPE;
return NULL;
}
/**
* @brief Called by FreeRTOS_recvfrom(), this function will update socket
* address with IPv6 address from the packet received.
* @param[in] pxNetworkBuffer The packet received.
* @param[in] pxSourceAddress The IPv4 socket address.
* @return The Payload Offset.
*/
size_t xRecv_Update_IPv6( const NetworkBufferDescriptor_t * pxNetworkBuffer,
struct freertos_sockaddr * pxSourceAddress )
{
/* MISRA Ref 11.3.1 [Misaligned access] */
/* More details at: https://github.com/FreeRTOS/FreeRTOS-Plus-TCP/blob/main/MISRA.md#rule-113 */
/* coverity[misra_c_2012_rule_11_3_violation] */
const UDPPacket_IPv6_t * pxUDPPacketV6 = ( ( const UDPPacket_IPv6_t * ) pxNetworkBuffer->pucEthernetBuffer );
size_t uxPayloadOffset = 0;
if( pxUDPPacketV6->xEthernetHeader.usFrameType == ipIPv6_FRAME_TYPE )
{
if( pxSourceAddress != NULL )
{
( void ) memcpy( ( void * ) pxSourceAddress->sin_address.xIP_IPv6.ucBytes,
( const void * ) pxUDPPacketV6->xIPHeader.xSourceAddress.ucBytes,
ipSIZE_OF_IPv6_ADDRESS );
pxSourceAddress->sin_family = ( uint8_t ) FREERTOS_AF_INET6;
pxSourceAddress->sin_port = pxNetworkBuffer->usPort;
}
uxPayloadOffset = ipUDP_PAYLOAD_OFFSET_IPv6;
}
return uxPayloadOffset;
}
/**
* @brief Converts a 4 bit (nibble) value to a readable hex character, e.g. 14 becomes 'e'.
* @param usValue The value to be converted, must be between 0 and 15.
* @return The character, between '0' and '9', or between 'a' and 'f'.
*/
char cHexToChar( uint16_t usValue )
{
char cReturn = '0';
if( usValue <= 9U )
{
cReturn = ( char ) ( cReturn + usValue );
}
else if( usValue <= 15U )
{
cReturn = 'a';
cReturn = ( char ) ( cReturn + ( usValue - ( uint16_t ) 10 ) );
}
else
{
/* The value passed to 'usValue' has been and-ed with 0x0f,
* so this else clause should never be reached. */
configASSERT( 0 == 1 );
}
return cReturn;
}
/*-----------------------------------------------------------*/
/**
* @brief Convert a short numeric value to a hex string of at most 4 characters.
* The resulting string is **not** null-terminated. The resulting string
* will not have leading zero's, except when 'usValue' equals zero.
* @param[in] pcBuffer The buffer to which the string is written.
* @param[in] uxBufferSize The size of the buffer pointed to by 'pcBuffer'.
* @param[in] usValue The 16-bit value to be converted.
* @return The number of bytes written to 'pcBuffer'.
*/
socklen_t uxHexPrintShort( char * pcBuffer,
size_t uxBufferSize,
uint16_t usValue )
{
const size_t uxNibbleCount = 4U;
size_t uxNibble;
socklen_t uxIndex = 0U;
uint16_t usShifter = usValue;
BaseType_t xHadNonZero = pdFALSE;
for( uxNibble = 0; uxNibble < uxNibbleCount; uxNibble++ )
{
uint16_t usNibble = ( usShifter >> 12 ) & 0x0FU;
if( usNibble != 0U )
{
xHadNonZero = pdTRUE;
}
if( ( xHadNonZero != pdFALSE ) || ( uxNibble == ( uxNibbleCount - 1U ) ) )
{
if( uxIndex >= ( uxBufferSize - 1U ) )
{
break;
}
pcBuffer[ uxIndex ] = cHexToChar( usNibble );
uxIndex++;
}
usShifter = ( uint16_t ) ( usShifter << 4 );
}
return uxIndex;
}
/*-----------------------------------------------------------*/
/**
* @brief Scan the binary IPv6 address and find the longest train of consecutive zero's.
* The result of this search will be stored in 'xZeroStart' and 'xZeroLength'.
* @param pxSet the set of parameters as used by FreeRTOS_inet_ntop6().
*/
void prv_ntop6_search_zeros( struct sNTOP6_Set * pxSet )
{
BaseType_t xIndex = 0; /* The index in the IPv6 address: 0..7. */
BaseType_t xCurStart = 0; /* The position of the first zero found so far. */
BaseType_t xCurLength = 0; /* The number of zero's seen so far. */
const BaseType_t xShortCount = 8; /* An IPv6 address consists of 8 shorts. */
/* Default: when xZeroStart is negative, it won't match with any xIndex. */
pxSet->xZeroStart = -1;
/* Look for the longest train of zero's 0:0:0:... */
for( ; xIndex < xShortCount; xIndex++ )
{
uint16_t usValue = pxSet->pusAddress[ xIndex ];
if( usValue == 0U )
{
if( xCurLength == 0 )
{
/* Remember the position of the first zero. */
xCurStart = xIndex;
}
/* Count consecutive zeros. */
xCurLength++;
}
if( ( usValue != 0U ) || ( xIndex == ( xShortCount - 1 ) ) )
{
/* Has a longer train of zero's been found? */
if( ( xCurLength > 1 ) && ( pxSet->xZeroLength < xCurLength ) )
{
/* Remember the number of consecutive zeros. */
pxSet->xZeroLength = xCurLength;
/* Remember the index of the first zero found. */
pxSet->xZeroStart = xCurStart;
}
/* Reset the counter of consecutive zeros. */
xCurLength = 0;
}
}
}
/*-----------------------------------------------------------*/
/**
* @brief The location is now at the longest train of zero's. Two colons have to
* be printed without a numeric value, e.g. "ff02::1".
* @param pcDestination the output buffer where the colons will be printed.
* @param uxSize the remaining length of the output buffer.
* @param pxSet the set of parameters as used by FreeRTOS_inet_ntop6().
* @return pdPASS in case the output buffer is big enough to contain the colons.
* @note uxSize must be at least 2, enough to print "::". The string will get
* null-terminated later on.
*/
static BaseType_t prv_ntop6_write_zeros( char * pcDestination,
size_t uxSize,
struct sNTOP6_Set * pxSet )
{
BaseType_t xReturn = pdPASS;
const BaseType_t xShortCount = 8; /* An IPv6 address consists of 8 shorts. */
if( pxSet->uxTargetIndex <= ( uxSize - 1U ) )
{
pcDestination[ pxSet->uxTargetIndex ] = ':';
pxSet->uxTargetIndex++;
if( ( pxSet->xIndex + pxSet->xZeroLength ) == xShortCount )
{
/* Reached the last index, write a second ":". */
if( pxSet->uxTargetIndex <= ( uxSize - 1U ) )
{
pcDestination[ pxSet->uxTargetIndex ] = ':';
pxSet->uxTargetIndex++;
}
else
{
/* Can not write the second colon. */
xReturn = pdFAIL;
}
}
else
{
/* Otherwise the function prv_ntop6_write_short() will places the second colon. */
}
}
else
{
/* Can not write the first colon. */
xReturn = pdFAIL;
}
return xReturn;
}
/*-----------------------------------------------------------*/
/**
* @brief Write a short value, as a hex number with at most 4 characters. E.g. the
* value 15 will be printed as "f".
* @param pcDestination the output buffer where the hex number is to be printed.
* @param uxSize the remaining length of the output buffer.
* @param pxSet the set of parameters as used by FreeRTOS_inet_ntop6().
* @return pdPASS in case the output buffer is big enough to contain the string.
* @note uxSize must be at least 4, enough to print "abcd". The string will get
* null-terminated later on.
*/
static BaseType_t prv_ntop6_write_short( char * pcDestination,
size_t uxSize,
struct sNTOP6_Set * pxSet )
{
socklen_t uxLength;
BaseType_t xReturn = pdPASS;
const size_t uxBytesPerShortValue = 4U;
if( pxSet->xIndex > 0 )
{
if( pxSet->uxTargetIndex >= ( uxSize - 1U ) )
{
xReturn = pdFAIL;
}
else
{
pcDestination[ pxSet->uxTargetIndex ] = ':';
pxSet->uxTargetIndex++;
}
}
if( xReturn == pdPASS )
{
/* If there is enough space to write a short. */
if( pxSet->uxTargetIndex <= ( uxSize - uxBytesPerShortValue ) )
{
/* Write hex value of short. at most 4 + 1 bytes. */
uxLength = uxHexPrintShort( &( pcDestination[ pxSet->uxTargetIndex ] ),
uxBytesPerShortValue + 1U,
FreeRTOS_ntohs( pxSet->pusAddress[ pxSet->xIndex ] ) );
/* uxLength will be non zero and positive always. */
pxSet->uxTargetIndex += uxLength;
}
else
{
xReturn = pdFAIL;
}
}
return xReturn;
}
/*-----------------------------------------------------------*/
/**
* @brief This function converts a binary IPv6 address to a human readable notation.
*
* @param[in] pvSource The binary address, 16 bytes long..
* @param[out] pcDestination The human-readable ( hexadecimal ) notation of the
* address.
* @param[in] uxSize The size of pvDestination. A value of 40 is recommended.
*
* @return pdPASS if the translation was successful or else pdFAIL.
*/
const char * FreeRTOS_inet_ntop6( const void * pvSource,
char * pcDestination,
socklen_t uxSize )
{
const char * pcReturn; /* The return value, which is either 'pcDestination' or NULL. */
struct sNTOP6_Set xSet; /* A set of values for easy exchange with the helper functions prv_ntop6_xxx(). */
( void ) memset( &( xSet ), 0, sizeof( xSet ) );
xSet.pusAddress = pvSource;
if( uxSize < 3U )
{
/* Can not even print :: */
}
else
{
prv_ntop6_search_zeros( &( xSet ) );
while( xSet.xIndex < 8 )
{
if( xSet.xIndex == xSet.xZeroStart )
{
if( prv_ntop6_write_zeros( pcDestination, uxSize, &( xSet ) ) == pdFAIL )
{
break;
}
xSet.xIndex += xSet.xZeroLength;
}
else
{
if( prv_ntop6_write_short( pcDestination, uxSize, &( xSet ) ) == pdFAIL )
{
break;
}
xSet.xIndex++;
}
}
}
if( xSet.xIndex < 8 )
{
/* Didn't reach the last nibble: clear the string. */
pcReturn = NULL;
}
else
{
pcDestination[ xSet.uxTargetIndex ] = '\0';
pcReturn = pcDestination;
}
return pcReturn;
}
/*-----------------------------------------------------------*/
/**
* @brief Converting a readable IPv6 address to its binary form, add one nibble.
*
* @param[in] pxSet A set of variables describing the conversion.
* @param[in] ucNew The hex value, between 0 and 15
* @param[in] ch The character, such as '5', 'f', or ':'.
*
* @return pdTRUE when the nibble was added, otherwise pdFALSE.
*/
static BaseType_t prv_inet_pton6_add_nibble( struct sPTON6_Set * pxSet,
uint8_t ucNew,
char ch )
{
BaseType_t xReturn = pdPASS;
if( ucNew != ( uint8_t ) socketINVALID_HEX_CHAR )
{
/* Shift in 4 bits. */
pxSet->ulValue <<= 4;
pxSet->ulValue |= ( uint32_t ) ucNew;
/* Remember that ulValue is valid now. */
pxSet->xHadDigit = pdTRUE;
/* Check if the number is not becoming larger than 16 bits. */
if( pxSet->ulValue > 0xffffU )
{
/* The highest nibble has already been set,
* an overflow would occur. Break out of the for-loop. */
xReturn = pdFAIL;
}
}
else if( ch == ':' )
{
if( pxSet->xHadDigit == pdFALSE )
{
/* A "::" sequence has been received. Check if it is not a third colon. */
if( pxSet->xColon >= 0 )
{
xReturn = pdFAIL;
}
else
{
/* Two or more zero's are expected, starting at position 'xColon'. */
pxSet->xColon = pxSet->xTargetIndex;
}
}
else
{
if( pxSet->xTargetIndex <= pxSet->xHighestIndex )
{
/* Store a short value at position 'xTargetIndex'. */
pxSet->pucTarget[ pxSet->xTargetIndex ] = ( uint8_t ) ( ( pxSet->ulValue >> 8 ) & 0xffU );
pxSet->pucTarget[ pxSet->xTargetIndex + 1 ] = ( uint8_t ) ( pxSet->ulValue & 0xffU );
pxSet->xTargetIndex += 2;
pxSet->xHadDigit = pdFALSE;
pxSet->ulValue = 0U;
}
else
{
xReturn = pdFAIL;
}
}
}
else
{
/* When an IPv4 address or rubbish is provided, this statement will be reached. */
xReturn = pdFAIL;
}
return xReturn;
}
/*-----------------------------------------------------------*/
/**
* @brief Convert an ASCII character to its corresponding hexadecimal value.
* A :: block was found, now fill in the zero's.
* @param[in] pxSet A set of variables describing the conversion.
*/
static void prv_inet_pton6_set_zeros( struct sPTON6_Set * pxSet )
{
/* The number of bytes that were written after the :: */
const BaseType_t xCount = pxSet->xTargetIndex - pxSet->xColon;
const BaseType_t xTopIndex = ( BaseType_t ) ipSIZE_OF_IPv6_ADDRESS;
BaseType_t xIndex;
BaseType_t xTarget = xTopIndex - 1;
BaseType_t xSource = pxSet->xColon + ( xCount - 1 );
/* Inserting 'xCount' zero's. */
for( xIndex = 0; xIndex < xCount; xIndex++ )
{
pxSet->pucTarget[ xTarget ] = pxSet->pucTarget[ xSource ];
pxSet->pucTarget[ xSource ] = 0;
xTarget--;
xSource--;
}
pxSet->xTargetIndex = ( BaseType_t ) ipSIZE_OF_IPv6_ADDRESS;
}
/*-----------------------------------------------------------*/
/**
* @brief Convert an IPv6 address in hexadecimal notation to a binary format of 16 bytes.
*
* @param[in] pcSource The address in hexadecimal notation.
* @param[out] pvDestination The address in binary format, 16 bytes long.
*
* @return The 32-bit representation of IP(v4) address.
*/
BaseType_t FreeRTOS_inet_pton6( const char * pcSource,
void * pvDestination )
{
char ch;
uint8_t ucNew;
BaseType_t xResult;
struct sPTON6_Set xSet;
const char * pcIterator = pcSource;
( void ) memset( &( xSet ), 0, sizeof( xSet ) );
xSet.xColon = -1;
xSet.pucTarget = pvDestination;
( void ) memset( xSet.pucTarget, 0, ipSIZE_OF_IPv6_ADDRESS );
xResult = 0;
/* Leading :: requires some special handling. */
if( strcmp( pcIterator, "::" ) == 0 )
{
xResult = 1;
}
else
{
if( pcIterator[ 0 ] == ':' )
{
pcIterator++;
}
/* The last bytes will be written at position 14 and 15. */
xSet.xHighestIndex = ( BaseType_t ) ipSIZE_OF_IPv6_ADDRESS;
xSet.xHighestIndex -= ( BaseType_t ) sizeof( uint16_t );
/* The value in ulValue is not yet valid. */
xSet.xHadDigit = pdFALSE;
xSet.ulValue = 0U;
for( ; ; )
{
ch = *( pcIterator );
pcIterator++;
if( ch == ( char ) '\0' )
{
/* The string is parsed now.
* Store the last short, if present. */
if( ( xSet.xHadDigit != pdFALSE ) &&
( xSet.xTargetIndex <= xSet.xHighestIndex ) )
{
/* Add the last value seen, network byte order ( MSB first ). */
xSet.pucTarget[ xSet.xTargetIndex ] = ( uint8_t ) ( ( xSet.ulValue >> 8 ) & 0xffU );
xSet.pucTarget[ xSet.xTargetIndex + 1 ] = ( uint8_t ) ( xSet.ulValue & 0xffU );
xSet.xTargetIndex += 2;
}
/* Break out of the for-ever loop. */
break;
}
/* Convert from a readable character to a hex value. */
ucNew = ucASCIIToHex( ch );
/* See if this is a digit or a colon. */
xResult = prv_inet_pton6_add_nibble( &( xSet ), ucNew, ch );
if( xResult == pdFALSE )
{
/* The new character was not accepted. */
break;
}
} /* for( ;; ) */
if( xSet.xColon >= 0 )
{
/* The address contains a block of zero. */
prv_inet_pton6_set_zeros( &( xSet ) );
}
if( xSet.xTargetIndex == ( BaseType_t ) ipSIZE_OF_IPv6_ADDRESS )
{
xResult = 1;
}
}
if( xResult != 1 )
{
xSet.pucTarget = ( uint8_t * ) pvDestination;
( void ) memset( xSet.pucTarget, 0, ipSIZE_OF_IPv6_ADDRESS );
}
return xResult;
}
/*-----------------------------------------------------------*/
/* *INDENT-OFF* */
#endif /* ipconfigUSE_IPv6 != 0 */
/* *INDENT-ON* */
@@ -0,0 +1,367 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
/**
* @file FreeRTOS_IPv6_Utils.c
* @brief Implements the basic functionality for the FreeRTOS+TCP network stack functions for IPv6.
*/
/* Standard includes. */
#include <stdint.h>
#include <stdio.h>
/* FreeRTOS includes. */
#include "FreeRTOS.h"
/* FreeRTOS+TCP includes. */
#include "FreeRTOS_IP.h"
/*-----------------------------------------------------------*/
/* *INDENT-OFF* */
#if( ipconfigUSE_IPv6 != 0 )
/* *INDENT-ON* */
/**
* @brief Set multicast MAC address.
*
* @param[in] pxAddress IPv6 address.
* @param[out] pxMACAddress Pointer to MAC address.
*/
void vSetMultiCastIPv6MacAddress( const IPv6_Address_t * pxAddress,
MACAddress_t * pxMACAddress )
{
pxMACAddress->ucBytes[ 0 ] = ipMULTICAST_MAC_ADDRESS_IPv6_0;
pxMACAddress->ucBytes[ 1 ] = ipMULTICAST_MAC_ADDRESS_IPv6_1;
pxMACAddress->ucBytes[ 2 ] = pxAddress->ucBytes[ 12 ];
pxMACAddress->ucBytes[ 3 ] = pxAddress->ucBytes[ 13 ];
pxMACAddress->ucBytes[ 4 ] = pxAddress->ucBytes[ 14 ];
pxMACAddress->ucBytes[ 5 ] = pxAddress->ucBytes[ 15 ];
}
/*-----------------------------------------------------------*/
/** @brief Do the first IPv6 length checks at the IP-header level.
* @param[in] pucEthernetBuffer The buffer containing the packet.
* @param[in] uxBufferLength The number of bytes to be sent or received.
* @param[in] pxSet A struct describing this packet.
*
* @return Non-zero in case of an error.
*/
BaseType_t prvChecksumIPv6Checks( uint8_t * pucEthernetBuffer,
size_t uxBufferLength,
struct xPacketSummary * pxSet )
{
BaseType_t xReturn = 0;
size_t uxExtensionHeaderLength = 0;
pxSet->xIsIPv6 = pdTRUE;
pxSet->uxIPHeaderLength = ipSIZE_OF_IPv6_HEADER;
/* Check for minimum packet size: ipSIZE_OF_ETH_HEADER + ipSIZE_OF_IPv6_HEADER (54 bytes) */
if( uxBufferLength < sizeof( IPPacket_IPv6_t ) )
{
pxSet->usChecksum = ipINVALID_LENGTH;
xReturn = 1;
}
else
{
uxExtensionHeaderLength = usGetExtensionHeaderLength( pucEthernetBuffer, uxBufferLength, &pxSet->ucProtocol );
if( ( ipSIZE_OF_ETH_HEADER + ipSIZE_OF_IPv6_HEADER + uxExtensionHeaderLength ) >= uxBufferLength )
{
/* Error detected when parsing extension header. */
pxSet->usChecksum = ipINVALID_LENGTH;
xReturn = 3;
}
else
{
size_t uxNeeded;
/* MISRA Ref 11.3.1 [Misaligned access] */
/* More details at: https://github.com/FreeRTOS/FreeRTOS-Plus-TCP/blob/main/MISRA.md#rule-113 */
/* coverity[misra_c_2012_rule_11_3_violation] */
pxSet->pxProtocolHeaders = ( ( ProtocolHeaders_t * ) &( pucEthernetBuffer[ ipSIZE_OF_ETH_HEADER + ipSIZE_OF_IPv6_HEADER + uxExtensionHeaderLength ] ) );
pxSet->usPayloadLength = FreeRTOS_ntohs( pxSet->pxIPPacket_IPv6->usPayloadLength );
/* For IPv6, the number of bytes in the protocol is indicated. */
if( pxSet->usPayloadLength < uxExtensionHeaderLength )
{
/* Invalid payload length - extension headers exceed payload. */
pxSet->usChecksum = ipINVALID_LENGTH;
xReturn = 4;
}
else
{
pxSet->usProtocolBytes = ( uint16_t ) ( pxSet->usPayloadLength - uxExtensionHeaderLength );
}
uxNeeded = ( size_t ) pxSet->usPayloadLength;
uxNeeded += ipSIZE_OF_ETH_HEADER + ipSIZE_OF_IPv6_HEADER;
if( uxBufferLength < uxNeeded )
{
/* The packet does not contain a complete IPv6 packet. */
pxSet->usChecksum = ipINVALID_LENGTH;
xReturn = 2;
}
}
}
return xReturn;
}
/*-----------------------------------------------------------*/
/**
* @brief Check the buffer lengths of an ICMPv6 packet.
* @param[in] uxBufferLength The total length of the packet.
* @param[in] pxSet A struct describing this packet.
* @return Non-zero in case of an error.
*/
BaseType_t prvChecksumICMPv6Checks( size_t uxBufferLength,
struct xPacketSummary * pxSet )
{
BaseType_t xReturn = 0;
size_t xICMPLength;
switch( pxSet->pxProtocolHeaders->xICMPHeaderIPv6.ucTypeOfMessage )
{
case ipICMP_PING_REQUEST_IPv6:
case ipICMP_PING_REPLY_IPv6:
xICMPLength = sizeof( ICMPEcho_IPv6_t );
break;
case ipICMP_ROUTER_SOLICITATION_IPv6:
xICMPLength = sizeof( ICMPRouterSolicitation_IPv6_t );
break;
default:
xICMPLength = ipSIZE_OF_ICMPv6_HEADER;
break;
}
if( uxBufferLength < ( ipSIZE_OF_ETH_HEADER + pxSet->uxIPHeaderLength + xICMPLength ) )
{
pxSet->usChecksum = ipINVALID_LENGTH;
xReturn = 10;
}
if( xReturn == 0 )
{
pxSet->uxProtocolHeaderLength = xICMPLength;
#if ( ipconfigHAS_DEBUG_PRINTF != 0 )
{
pxSet->pcType = "ICMP_IPv6";
}
#endif /* ipconfigHAS_DEBUG_PRINTF != 0 */
}
return xReturn;
}
/*-----------------------------------------------------------*/
/**
* @brief Get total length of all extension headers in IPv6 packet.
*
* @param[in] pucEthernetBuffer The buffer containing the packet.
* @param[in] uxBufferLength The number of bytes to be sent or received.
* @param[out] pucProtocol The L4 protocol, such as TCP/UDP/ICMPv6.
*
* @return The total length of all extension headers, or whole buffer length when error detected.
*/
size_t usGetExtensionHeaderLength( const uint8_t * pucEthernetBuffer,
size_t uxBufferLength,
uint8_t * pucProtocol )
{
uint8_t ucCurrentHeader;
const IPPacket_IPv6_t * pxIPPacket_IPv6;
uint8_t ucNextHeader = 0U;
size_t uxIndex = ipSIZE_OF_ETH_HEADER + ipSIZE_OF_IPv6_HEADER;
size_t uxHopSize = 0U;
BaseType_t xCurrentOrder = 0;
BaseType_t xNextOrder = 0;
size_t uxReturn = uxBufferLength;
if( ( pucEthernetBuffer != NULL ) && ( pucProtocol != NULL ) )
{
/* MISRA Ref 11.3.1 [Misaligned access] */
/* More details at: https://github.com/FreeRTOS/FreeRTOS-Plus-TCP/blob/main/MISRA.md#rule-113 */
/* coverity[misra_c_2012_rule_11_3_violation] */
pxIPPacket_IPv6 = ( ( const IPPacket_IPv6_t * ) pucEthernetBuffer );
ucCurrentHeader = pxIPPacket_IPv6->xIPHeader.ucNextHeader;
/* Check if packet has extension header. */
if( xGetExtensionOrder( ucCurrentHeader, 0U ) > 0 )
{
while( ( uxIndex + 8U ) < uxBufferLength )
{
ucNextHeader = pucEthernetBuffer[ uxIndex ];
xCurrentOrder = xGetExtensionOrder( ucCurrentHeader, ucNextHeader );
/* To avoid compile warning if debug print is disabled. */
( void ) xCurrentOrder;
/* Read the length expressed in number of octets. */
uxHopSize = ( size_t ) pucEthernetBuffer[ uxIndex + 1U ];
/* And multiply by 8 and add the minimum size of 8. */
uxHopSize = ( uxHopSize * 8U ) + 8U;
if( ( uxIndex + uxHopSize ) >= uxBufferLength )
{
FreeRTOS_debug_printf( ( "The length %u + %u of extension header is larger than buffer size %u \n", ( unsigned ) uxIndex, ( unsigned ) uxHopSize, ( unsigned ) uxBufferLength ) );
break;
}
uxIndex = uxIndex + uxHopSize;
if( ( ucNextHeader == ipPROTOCOL_TCP ) ||
( ucNextHeader == ipPROTOCOL_UDP ) ||
( ucNextHeader == ipPROTOCOL_ICMP_IPv6 ) )
{
FreeRTOS_debug_printf( ( "Stop at header %u\n", ucNextHeader ) );
uxReturn = uxIndex - ( ipSIZE_OF_ETH_HEADER + ipSIZE_OF_IPv6_HEADER );
*pucProtocol = ucNextHeader;
break;
}
xNextOrder = xGetExtensionOrder( ucNextHeader, pucEthernetBuffer[ uxIndex ] );
FreeRTOS_debug_printf( ( "Going from header %2u (%d) to %2u (%d)\n",
ucCurrentHeader,
( int ) xCurrentOrder,
ucNextHeader,
( int ) xNextOrder ) );
/*
* IPv6 nodes must accept and attempt to process extension headers in
* any order and occurring any number of times in the same packet,
* except for the Hop-by-Hop Options header which is restricted to
* appear immediately after an IPv6 header only. Outlined
* by RFC 2460 section 4.1 Extension Header Order.
*/
if( xNextOrder == 1 ) /* ipIPv6_EXT_HEADER_HOP_BY_HOP */
{
FreeRTOS_printf( ( "Wrong order. Hop-by-Hop Options header restricted to appear immediately after an IPv6 header\n" ) );
break;
}
else if( xNextOrder < 0 )
{
FreeRTOS_printf( ( "Invalid extension header detected\n" ) );
break;
}
else
{
/* Do nothing, coverity happy. */
}
ucCurrentHeader = ucNextHeader;
}
}
else
{
/* No extension headers. */
*pucProtocol = ucCurrentHeader;
uxReturn = 0;
}
}
return uxReturn;
}
/*-----------------------------------------------------------*/
/**
* @brief Every IPv6 end-point has a solicited node multicast address and a corresponding
* multicast MAC address. The IPv6 solicited node address also has an MLD reports associated
* with it. This function manages both the MAC address and the MLD report associated with
* the end-point's solicited-node address. On network UP, this function registers the MAC address
* with the network driver's filter and creates and MLD report for the UPv6 multicast address.
* On network DOWN, the function unregisters the MAC address and removes the MLD report.
* This is a "convenience" function that keeps all these tasks under one roof for easier maintenance.
*
* @param[in] pxEndPoint The end-point for which a network up/down event is being handled.
* @param[in] xNetworkGoingUp pdTRUE when the network goes UP, pdFALSE when the network goes DOWN.
*/
void vManageSolicitedNodeAddress( const struct xNetworkEndPoint * pxEndPoint,
BaseType_t xNetworkGoingUp )
{
IPv6_Type_t xAddressType;
MACAddress_t xMACAddress;
configASSERT( pxEndPoint != NULL );
configASSERT( pxEndPoint->pxNetworkInterface != NULL );
/* do{}while(0) to allow for the use of break statements */
do
{
/* During the very first network DOWN event, pxEndPoint->ipv6_settings does not yet hold the proper address and
* therefore the calculated MAC address will be incorrect. Nothing bad will happen though, because the address
* type check below will kick us out before the call to pfRemoveAllowedMAC(). Without the check below, the network
* driver ends up being called once to register 33:33:FF:00:00:00 and that MAC never gets unregistered. */
/* Solicited-node multicast addresses only apply to normal unicast non-loopback addresses. */
xAddressType = xIPv6_GetIPType( &( pxEndPoint->ipv6_settings.xIPAddress ) );
if( ( xAddressType != eIPv6_LinkLocal ) && ( xAddressType != eIPv6_SiteLocal ) && ( xAddressType != eIPv6_Global ) )
{
/* The address of this end-point is something other than a normal unicast address... Maybe it's the
* loopback address or maybe this is an error scenario. In any case, there is no corresponding
* solicited-node multicast address that we need to manage. Do nothing.*/
break;
}
/* Calculate the multicast MAC that corresponds to this endpoint's IPv6 address. */
xMACAddress.ucBytes[ 0 ] = ipMULTICAST_MAC_ADDRESS_IPv6_0;
xMACAddress.ucBytes[ 1 ] = ipMULTICAST_MAC_ADDRESS_IPv6_0;
xMACAddress.ucBytes[ 2 ] = 0xFFU;
xMACAddress.ucBytes[ 3 ] = pxEndPoint->ipv6_settings.xIPAddress.ucBytes[ 13 ];
xMACAddress.ucBytes[ 4 ] = pxEndPoint->ipv6_settings.xIPAddress.ucBytes[ 14 ];
xMACAddress.ucBytes[ 5 ] = pxEndPoint->ipv6_settings.xIPAddress.ucBytes[ 15 ];
/* Update the network driver filter */
if( xNetworkGoingUp == pdTRUE )
{
if( pxEndPoint->pxNetworkInterface->pfAddAllowedMAC != NULL )
{
pxEndPoint->pxNetworkInterface->pfAddAllowedMAC( pxEndPoint->pxNetworkInterface, xMACAddress.ucBytes );
}
}
else
{
if( pxEndPoint->pxNetworkInterface->pfRemoveAllowedMAC != NULL )
{
pxEndPoint->pxNetworkInterface->pfRemoveAllowedMAC( pxEndPoint->pxNetworkInterface, xMACAddress.ucBytes );
}
}
} while( ipFALSE_BOOL );
}
/*-----------------------------------------------------------*/
/* *INDENT-OFF* */
#endif /* ( ipconfigUSE_IPv6 != 0 ) */
/* *INDENT-ON* */
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,723 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
/**
* @file FreeRTOS_RA.c
* @brief A client implementation of Router advertisement protocol.
*/
/* Standard includes. */
#include <stdint.h>
#include <stdio.h>
/* FreeRTOS includes. */
#include "FreeRTOS.h"
#include "task.h"
/* FreeRTOS+TCP includes. */
#include "FreeRTOS_IP.h"
#include "FreeRTOS_Sockets.h"
#include "FreeRTOS_IP_Private.h"
#include "FreeRTOS_IP_Timers.h"
#include "FreeRTOS_UDP_IP.h"
#include "FreeRTOS_Routing.h"
#include "FreeRTOS_ND.h"
#if ( ipconfigUSE_LLMNR == 1 )
#include "FreeRTOS_DNS.h"
#endif /* ipconfigUSE_LLMNR */
#include "NetworkBufferManagement.h"
/* This define may exclude the entire source file. */
#if ( ipconfigUSE_IPv6 != 0 ) && ( ipconfigUSE_RA != 0 )
/*-----------------------------------------------------------*/
/** A block time of 0 simply means "don't block". */
#define raDONT_BLOCK ( ( TickType_t ) 0 )
/** The default value for the IPv6-field 'ucVersionTrafficClass'. */
#define raDEFAULT_VERSION_TRAFFIC_CLASS 0x60U
/** The default value for the IPv6-field 'ucHopLimit'. */
#define raDEFAULT_HOP_LIMIT 255U
/*-----------------------------------------------------------*/
/* Initialise the Router Advertisement process for a given end-point. */
static void vRAProcessInit( NetworkEndPoint_t * pxEndPoint );
/* Find a link-local address that is bound to a given interface. */
static BaseType_t xGetLinkLocalAddress( const NetworkInterface_t * pxInterface,
IPv6_Address_t * pxAddress );
/* Read the reply received from the RA server. */
static ICMPPrefixOption_IPv6_t * vReceiveRA_ReadReply( const NetworkBufferDescriptor_t * pxNetworkBuffer );
/* Handle the states that are limited by a timer. See if any of the timers has expired. */
static TickType_t xRAProcess_HandleWaitStates( NetworkEndPoint_t * pxEndPoint,
TickType_t uxReloadTime );
/* Handle the other states. */
static TickType_t xRAProcess_HandleOtherStates( NetworkEndPoint_t * pxEndPoint,
TickType_t uxReloadTime );
/*-----------------------------------------------------------*/
/**
* @brief Find a link-local address that is bound to a given interface.
*
* @param[in] pxInterface The interface for which a link-local address is looked up.
* @param[out] pxAddress The IP address will be copied to this parameter.
*
* @return pdPASS in case a link-local address was found, otherwise pdFAIL.
*/
static BaseType_t xGetLinkLocalAddress( const NetworkInterface_t * pxInterface,
IPv6_Address_t * pxAddress )
{
BaseType_t xResult = pdFAIL;
NetworkEndPoint_t * pxEndPoint;
for( pxEndPoint = FreeRTOS_FirstEndPoint( pxInterface );
pxEndPoint != NULL;
pxEndPoint = FreeRTOS_NextEndPoint( pxInterface, pxEndPoint ) )
{
/* Check if it has the link-local prefix FE80::/10 */
if( ( pxEndPoint->ipv6_settings.xIPAddress.ucBytes[ 0 ] == 0xfeU ) &&
( ( pxEndPoint->ipv6_settings.xIPAddress.ucBytes[ 1 ] & 0xc0U ) == 0x80U ) )
{
( void ) memcpy( pxAddress->ucBytes, pxEndPoint->ipv6_settings.xIPAddress.ucBytes, ipSIZE_OF_IPv6_ADDRESS );
xResult = pdPASS;
break;
}
}
return xResult;
}
/*-----------------------------------------------------------*/
/**
* @brief Send an ICMPv6 message of the type: Router Solicitation.
*
* @param[in] pxNetworkBuffer The network buffer which can be used for this.
* @param[in] pxIPAddress The target address, normally ff02::2
*
*/
void vNDSendRouterSolicitation( NetworkBufferDescriptor_t * pxNetworkBuffer,
IPv6_Address_t * pxIPAddress )
{
ICMPPacket_IPv6_t * pxICMPPacket;
ICMPRouterSolicitation_IPv6_t * xRASolicitationRequest;
const NetworkEndPoint_t * pxEndPoint = pxNetworkBuffer->pxEndPoint;
const size_t uxNeededSize = ipSIZE_OF_ETH_HEADER + ipSIZE_OF_IPv6_HEADER + sizeof( ICMPRouterSolicitation_IPv6_t );
MACAddress_t xMultiCastMacAddress;
NetworkBufferDescriptor_t * pxDescriptor = pxNetworkBuffer;
IPv6_Address_t xSourceAddress;
BaseType_t xHasLocal;
NetworkBufferDescriptor_t * pxNewDescriptor = NULL;
configASSERT( pxEndPoint != NULL );
configASSERT( pxEndPoint->bits.bIPv6 != ipFALSE_BOOL );
xHasLocal = xGetLinkLocalAddress( pxEndPoint->pxNetworkInterface, &( xSourceAddress ) );
if( xHasLocal == pdFAIL )
{
FreeRTOS_printf( ( "RA: can not find a Link-local address\n" ) );
( void ) memset( xSourceAddress.ucBytes, 0, ipSIZE_OF_IPv6_ADDRESS );
}
else
{
FreeRTOS_printf( ( "RA: source %pip\n", ( void * ) xSourceAddress.ucBytes ) );
}
if( pxDescriptor->xDataLength < uxNeededSize )
{
pxNewDescriptor = pxDuplicateNetworkBufferWithDescriptor( pxDescriptor, uxNeededSize );
vReleaseNetworkBufferAndDescriptor( pxDescriptor );
pxDescriptor = pxNewDescriptor;
}
if( pxDescriptor != NULL )
{
/* MISRA Ref 11.3.1 [Misaligned access] */
/* More details at: https://github.com/FreeRTOS/FreeRTOS-Plus-TCP/blob/main/MISRA.md#rule-113 */
/* coverity[misra_c_2012_rule_11_3_violation] */
pxICMPPacket = ( ( ICMPPacket_IPv6_t * ) pxDescriptor->pucEthernetBuffer );
/* MISRA Ref 11.3.1 [Misaligned access] */
/* More details at: https://github.com/FreeRTOS/FreeRTOS-Plus-TCP/blob/main/MISRA.md#rule-113 */
/* coverity[misra_c_2012_rule_11_3_violation] */
xRASolicitationRequest = ( ( ICMPRouterSolicitation_IPv6_t * ) &( pxICMPPacket->xICMPHeaderIPv6 ) );
pxDescriptor->xDataLength = uxNeededSize;
( void ) eNDGetCacheEntry( pxIPAddress, &( xMultiCastMacAddress ), NULL );
/* Set Ethernet header. Will be swapped. */
( void ) memcpy( pxICMPPacket->xEthernetHeader.xSourceAddress.ucBytes, xMultiCastMacAddress.ucBytes, ipMAC_ADDRESS_LENGTH_BYTES );
( void ) memcpy( pxICMPPacket->xEthernetHeader.xDestinationAddress.ucBytes, pxEndPoint->xMACAddress.ucBytes, ipMAC_ADDRESS_LENGTH_BYTES );
pxICMPPacket->xEthernetHeader.usFrameType = ipIPv6_FRAME_TYPE;
/* Set IP-header. */
pxICMPPacket->xIPHeader.ucVersionTrafficClass = raDEFAULT_VERSION_TRAFFIC_CLASS;
pxICMPPacket->xIPHeader.ucTrafficClassFlow = 0U;
pxICMPPacket->xIPHeader.usFlowLabel = 0U;
pxICMPPacket->xIPHeader.usPayloadLength = FreeRTOS_htons( sizeof( ICMPRouterSolicitation_IPv6_t ) );
pxICMPPacket->xIPHeader.ucNextHeader = ipPROTOCOL_ICMP_IPv6;
pxICMPPacket->xIPHeader.ucHopLimit = raDEFAULT_HOP_LIMIT;
/* Normally, the source address is set as 'ipv6_settings.xIPAddress'.
* But is some routers will not accept a public IP-address, the original
* default address will be used. It must be a link-local address. */
( void ) memcpy( pxICMPPacket->xIPHeader.xSourceAddress.ucBytes, xSourceAddress.ucBytes, ipSIZE_OF_IPv6_ADDRESS );
( void ) memcpy( pxICMPPacket->xIPHeader.xDestinationAddress.ucBytes, pxIPAddress->ucBytes, ipSIZE_OF_IPv6_ADDRESS );
/* Set ICMP header. */
( void ) memset( xRASolicitationRequest, 0, sizeof( *xRASolicitationRequest ) );
xRASolicitationRequest->ucTypeOfMessage = ipICMP_ROUTER_SOLICITATION_IPv6;
/* __XX__ revisit on why commented out
* xRASolicitationRequest->ucOptionType = ndICMP_SOURCE_LINK_LAYER_ADDRESS;
* xRASolicitationRequest->ucOptionLength = 1;
* ( void ) memcpy( xRASolicitationRequest->ucOptionBytes, pxEndPoint->xMACAddress.ucBytes, ipMAC_ADDRESS_LENGTH_BYTES );
*/
/* Checksums. */
#if ( ipconfigDRIVER_INCLUDED_TX_IP_CHECKSUM == 0 )
{
/* calculate the ICMPv6 checksum for outgoing package */
( void ) usGenerateProtocolChecksum( pxDescriptor->pucEthernetBuffer, pxDescriptor->xDataLength, pdTRUE );
}
#else
{
/* Many EMAC peripherals will only calculate the ICMP checksum
* correctly if the field is nulled beforehand. */
xRASolicitationRequest->usChecksum = 0U;
}
#endif
/* This function will fill in the eth addresses and send the packet */
vReturnEthernetFrame( pxDescriptor, pdTRUE );
}
}
/*-----------------------------------------------------------*/
/**
* @brief Receive a NA ( Neighbour Advertisement ) message to see if a chosen IP-address is already in use.
*
* @param[in] pxNetworkBuffer The buffer that contains the message.
*/
void vReceiveNA( const NetworkBufferDescriptor_t * pxNetworkBuffer )
{
const NetworkInterface_t * pxInterface = pxNetworkBuffer->pxInterface;
NetworkEndPoint_t * pxPoint;
/* MISRA Ref 11.3.1 [Misaligned access] */
/* More details at: https://github.com/FreeRTOS/FreeRTOS-Plus-TCP/blob/main/MISRA.md#rule-113 */
/* coverity[misra_c_2012_rule_11_3_violation] */
const ICMPPacket_IPv6_t * pxICMPPacket = ( ( const ICMPPacket_IPv6_t * ) pxNetworkBuffer->pucEthernetBuffer );
const ICMPHeader_IPv6_t * pxICMPHeader_IPv6 = ( ( const ICMPHeader_IPv6_t * ) &( pxICMPPacket->xICMPHeaderIPv6 ) );
for( pxPoint = FreeRTOS_FirstEndPoint( pxInterface );
pxPoint != NULL;
pxPoint = FreeRTOS_NextEndPoint( pxInterface, pxPoint ) )
{
if( ( pxPoint->bits.bWantRA != ipFALSE_BOOL ) && ( pxPoint->xRAData.eRAState == eRAStateIPWait ) )
{
if( memcmp( pxPoint->ipv6_settings.xIPAddress.ucBytes, pxICMPHeader_IPv6->xIPv6Address.ucBytes, ipSIZE_OF_IPv6_ADDRESS ) == 0 )
{
pxPoint->xRAData.bits.bIPAddressInUse = ipTRUE_BOOL;
vDHCP_RATimerReload( pxPoint, 100U );
}
}
}
}
/*-----------------------------------------------------------*/
/**
* @brief Read a received RA reply and return the prefix option from the packet.
*
* @param[in] pxNetworkBuffer The buffer that contains the message.
*
* @returns Returns the ICMP prefix option pointer, pointing to its location in the
* input RA reply message buffer.
*/
static ICMPPrefixOption_IPv6_t * vReceiveRA_ReadReply( const NetworkBufferDescriptor_t * pxNetworkBuffer )
{
size_t uxIndex = 0U;
const size_t uxICMPSize = sizeof( ICMPRouterAdvertisement_IPv6_t );
const size_t uxNeededSize = ipSIZE_OF_ETH_HEADER + ipSIZE_OF_IPv6_HEADER + uxICMPSize;
/* uxLast points to the first byte after the buffer. */
const size_t uxLast = pxNetworkBuffer->xDataLength - uxNeededSize;
uint8_t * pucBytes = &( pxNetworkBuffer->pucEthernetBuffer[ uxNeededSize ] );
ICMPPrefixOption_IPv6_t * pxPrefixOption = NULL;
BaseType_t xMalformed = pdFALSE;
while( ( uxIndex + 1U ) < uxLast )
{
uint8_t ucType = pucBytes[ uxIndex ];
size_t uxPrefixLength = ( size_t ) pucBytes[ uxIndex + 1U ];
size_t uxLength = uxPrefixLength * 8U;
if( uxPrefixLength == 0U )
{
/* According to RFC 4861, length of the option value 0 is invalid. Hence returning from here */
FreeRTOS_printf( ( "RA: Invalid length of the option value as zero. " ) );
break;
}
if( uxLast < ( uxIndex + uxLength ) )
{
FreeRTOS_printf( ( "RA: Not enough bytes ( %u > %u )\n", ( unsigned ) ( uxIndex + uxLength ), ( unsigned ) uxLast ) );
break;
}
switch( ucType )
{
case ndICMP_SOURCE_LINK_LAYER_ADDRESS: /* 1 */
FreeRTOS_printf( ( "RA: Source = %02x-%02x-%02x-%02x-%02x-%02x\n",
pucBytes[ uxIndex + 2U ],
pucBytes[ uxIndex + 3U ],
pucBytes[ uxIndex + 4U ],
pucBytes[ uxIndex + 5U ],
pucBytes[ uxIndex + 6U ],
pucBytes[ uxIndex + 7U ] ) );
break;
case ndICMP_TARGET_LINK_LAYER_ADDRESS: /* 2 */
break;
case ndICMP_PREFIX_INFORMATION: /* 3 */
if( uxLength < sizeof( ICMPPrefixOption_IPv6_t ) )
{
FreeRTOS_printf(
( "RA: Prefix option too short ( %u < %u )\n",
( unsigned ) uxLength,
( unsigned ) sizeof( ICMPPrefixOption_IPv6_t ) ) );
xMalformed = pdTRUE;
}
else
{
/* MISRA Ref 11.3.1 [Misaligned access] */
/* More details at: https://github.com/FreeRTOS/FreeRTOS-Plus-TCP/blob/main/MISRA.md#rule-113 */
/* coverity[misra_c_2012_rule_11_3_violation] */
pxPrefixOption = ( ( ICMPPrefixOption_IPv6_t * ) &( pucBytes[ uxIndex ] ) );
FreeRTOS_printf( ( "RA: Prefix len %d Life %u, %u (%pip)\n",
pxPrefixOption->ucPrefixLength,
( unsigned ) FreeRTOS_ntohl( pxPrefixOption->ulValidLifeTime ),
( unsigned ) FreeRTOS_ntohl( pxPrefixOption->ulPreferredLifeTime ),
( void * ) pxPrefixOption->ucPrefix ) );
}
break;
case ndICMP_REDIRECTED_HEADER: /* 4 */
break;
case ndICMP_MTU_OPTION: /* 5 */
{
#if ipconfigHAS_PRINTF == 1
uint32_t ulMTU;
( void ) ulMTU;
/* ulChar2u32 returns host-endian numbers. */
ulMTU = ulChar2u32( &( pucBytes[ uxIndex + 4U ] ) );
FreeRTOS_printf( ( "RA: MTU = %u\n", ( unsigned int ) ulMTU ) );
#endif /* ipconfigHAS_PRINTF == 1 */
}
break;
default:
FreeRTOS_printf( ( "RA: Type 0x%02x not implemented\n", ucType ) );
break;
}
if( xMalformed != pdFALSE )
{
FreeRTOS_printf( ( "RA: Malformed packet.\n" ) );
break;
}
uxIndex = uxIndex + uxLength;
} /* while( ( uxIndex + 1 ) < uxLast ) */
return pxPrefixOption;
}
/*-----------------------------------------------------------*/
/**
* @brief Receive and analyse a RA ( Router Advertisement ) message.
* If the reply is satisfactory, the end-point will do SLAAC: choose an IP-address using the
* prefix offered, and completed with random bits. It will start testing if another device
* already exists that uses the same IP-address.
*
* @param[in] pxNetworkBuffer The buffer that contains the message.
*/
void vReceiveRA( const NetworkBufferDescriptor_t * pxNetworkBuffer )
{
/* MISRA Ref 11.3.1 [Misaligned access] */
/* More details at: https://github.com/FreeRTOS/FreeRTOS-Plus-TCP/blob/main/MISRA.md#rule-113 */
/* coverity[misra_c_2012_rule_11_3_violation] */
const ICMPPacket_IPv6_t * pxICMPPacket = ( ( const ICMPPacket_IPv6_t * ) pxNetworkBuffer->pucEthernetBuffer );
const ICMPPrefixOption_IPv6_t * pxPrefixOption = NULL;
const size_t uxICMPSize = sizeof( ICMPRouterAdvertisement_IPv6_t );
const size_t uxNeededSize = ipSIZE_OF_ETH_HEADER + ipSIZE_OF_IPv6_HEADER + uxICMPSize;
/* A Router Advertisement was received, handle it here. */
if( uxNeededSize > pxNetworkBuffer->xDataLength )
{
FreeRTOS_printf( ( "vReceiveRA: The buffer provided is too small\n" ) );
}
else
{
/* MISRA Ref 11.3.1 [Misaligned access] */
/* More details at: https://github.com/FreeRTOS/FreeRTOS-Plus-TCP/blob/main/MISRA.md#rule-113 */
/* coverity[misra_c_2012_rule_11_3_violation] */
const ICMPRouterAdvertisement_IPv6_t * pxAdvertisement = ( ( const ICMPRouterAdvertisement_IPv6_t * ) &( pxICMPPacket->xICMPHeaderIPv6 ) );
FreeRTOS_printf( ( "RA: Type %02x Srv %02x Checksum %04x Hops %d Flags %02x Life %d\n",
pxAdvertisement->ucTypeOfMessage,
pxAdvertisement->ucTypeOfService,
FreeRTOS_ntohs( pxAdvertisement->usChecksum ),
pxAdvertisement->ucHopLimit,
pxAdvertisement->ucFlags,
FreeRTOS_ntohs( pxAdvertisement->usLifetime ) ) );
if( pxAdvertisement->usLifetime != 0U )
{
pxPrefixOption = vReceiveRA_ReadReply( pxNetworkBuffer );
configASSERT( pxNetworkBuffer->pxInterface != NULL );
if( pxPrefixOption != NULL )
{
NetworkEndPoint_t * pxEndPoint;
for( pxEndPoint = FreeRTOS_FirstEndPoint( pxNetworkBuffer->pxInterface );
pxEndPoint != NULL;
pxEndPoint = FreeRTOS_NextEndPoint( pxNetworkBuffer->pxInterface, pxEndPoint ) )
{
if( ( pxEndPoint->bits.bWantRA != ipFALSE_BOOL ) && ( pxEndPoint->xRAData.eRAState == eRAStateWait ) )
{
if( ( pxPrefixOption->ucPrefixLength == 0U ) ||
( pxPrefixOption->ucPrefixLength > ( 8U * ipSIZE_OF_IPv6_ADDRESS ) ) )
{
FreeRTOS_printf( ( "vReceiveRA: The prefix length "
"is invalid\n" ) );
break;
}
pxEndPoint->ipv6_settings.uxPrefixLength = pxPrefixOption->ucPrefixLength;
( void ) memcpy( pxEndPoint->ipv6_settings.xPrefix.ucBytes, pxPrefixOption->ucPrefix, ipSIZE_OF_IPv6_ADDRESS );
( void ) memcpy( pxEndPoint->ipv6_settings.xGatewayAddress.ucBytes, pxICMPPacket->xIPHeader.xSourceAddress.ucBytes, ipSIZE_OF_IPv6_ADDRESS );
pxEndPoint->xRAData.bits.bRouterReplied = ipTRUE_BOOL;
pxEndPoint->xRAData.uxRetryCount = 0U;
pxEndPoint->xRAData.ulPreferredLifeTime = FreeRTOS_ntohl( pxPrefixOption->ulPreferredLifeTime );
/* Force taking a new random IP-address. */
pxEndPoint->xRAData.bits.bIPAddressInUse = ipTRUE_BOOL;
pxEndPoint->xRAData.eRAState = eRAStateIPTest;
vRAProcess( pdFALSE, pxEndPoint );
}
}
}
}
else
{
/* The life-time field contains zero. */
}
}
}
/*-----------------------------------------------------------*/
/**
* @brief Handles the RA wait state and calculates the new timer reload value
* based on the wait state. Also checks if any timer has expired. If its found that
* there is no other device using the same IP-address vIPNetworkUpCalls() is called
* to send the network up event.
*
* @param[in] pxEndPoint The end point for which RA assignment is required.
* @param[out] uxReloadTime Timer reload value in ticks.
*
* @return New timer reload value.
*/
static TickType_t xRAProcess_HandleWaitStates( NetworkEndPoint_t * pxEndPoint,
TickType_t uxReloadTime )
{
TickType_t uxNewReloadTime = uxReloadTime;
if( pxEndPoint->xRAData.eRAState == eRAStateWait )
{
/* A Router Solicitation has been sent, waited for a reply, but no came.
* All replies will be handled in the function vReceiveRA(). */
pxEndPoint->xRAData.uxRetryCount++;
if( pxEndPoint->xRAData.uxRetryCount < ( UBaseType_t ) ipconfigRA_SEARCH_COUNT )
{
pxEndPoint->xRAData.eRAState = eRAStateApply;
}
else
{
FreeRTOS_printf( ( "RA: Giving up waiting for a Router.\n" ) );
( void ) memcpy( &( pxEndPoint->ipv6_settings ), &( pxEndPoint->ipv6_defaults ), sizeof( pxEndPoint->ipv6_settings ) );
pxEndPoint->xRAData.bits.bRouterReplied = ipFALSE_BOOL;
pxEndPoint->xRAData.uxRetryCount = 0U;
/* Force taking a new random IP-address. */
pxEndPoint->xRAData.bits.bIPAddressInUse = ipTRUE_BOOL;
pxEndPoint->xRAData.eRAState = eRAStateIPTest;
}
}
else if( pxEndPoint->xRAData.eRAState == eRAStateIPWait )
{
/* A Neighbour Solicitation has been sent, waited for a reply.
* Repeat this 'ipconfigRA_IP_TEST_COUNT' times to be sure. */
if( pxEndPoint->xRAData.bits.bIPAddressInUse != ipFALSE_BOOL )
{
/* Another device has responded with the same IPv4 address. */
pxEndPoint->xRAData.uxRetryCount = 0U;
pxEndPoint->xRAData.eRAState = eRAStateIPTest;
uxNewReloadTime = pdMS_TO_TICKS( ipconfigRA_IP_TEST_TIME_OUT_MSEC );
}
else if( pxEndPoint->xRAData.uxRetryCount < ( UBaseType_t ) ipconfigRA_IP_TEST_COUNT )
{
/* Try again. */
pxEndPoint->xRAData.uxRetryCount++;
pxEndPoint->xRAData.eRAState = eRAStateIPTest;
uxNewReloadTime = pdMS_TO_TICKS( ipconfigRA_IP_TEST_TIME_OUT_MSEC );
}
else
{
/* Now it is assumed that there is no other device using the same IP-address. */
if( pxEndPoint->xRAData.bits.bRouterReplied != ipFALSE_BOOL )
{
/* Obtained configuration from a router. */
uxNewReloadTime = pdMS_TO_TICKS( ( 1000U * ( uint64_t ) pxEndPoint->xRAData.ulPreferredLifeTime ) );
pxEndPoint->xRAData.eRAState = eRAStatePreLease;
iptraceRA_SUCCEEDED( &( pxEndPoint->ipv6_settings.xIPAddress ) );
FreeRTOS_printf( ( "RA: succeeded, using IP address %pip Reload after %u seconds\n",
( void * ) pxEndPoint->ipv6_settings.xIPAddress.ucBytes,
( unsigned ) pxEndPoint->xRAData.ulPreferredLifeTime ) );
}
else
{
/* Using the default network parameters. */
pxEndPoint->xRAData.eRAState = eRAStateFailed;
iptraceRA_REQUESTS_FAILED_USING_DEFAULT_IP_ADDRESS( &( pxEndPoint->ipv6_settings.xIPAddress ) );
FreeRTOS_printf( ( "RA: failed, using default parameters and IP address %pip\n", ( void * ) pxEndPoint->ipv6_settings.xIPAddress.ucBytes ) );
/* Disable the timer. */
uxNewReloadTime = 0U;
}
/* Now call vIPNetworkUpCalls() to send the network-up event and
* start the Resolution timer. */
vIPNetworkUpCalls( pxEndPoint );
}
}
else
{
/* Do nothing */
}
return uxNewReloadTime;
}
/*-----------------------------------------------------------*/
/**
* @brief Handles the RA states other than the wait states.
*
* @param[in] pxEndPoint The end point for which RA assignment is required.
* @param[out] uxReloadTime Timer reload value in ticks.
*
* @return New timer reload value.
*/
static TickType_t xRAProcess_HandleOtherStates( NetworkEndPoint_t * pxEndPoint,
TickType_t uxReloadTime )
{
TickType_t uxNewReloadTime = uxReloadTime;
switch( pxEndPoint->xRAData.eRAState )
{
case eRAStateApply:
{
IPv6_Address_t xIPAddress;
size_t uxNeededSize;
NetworkBufferDescriptor_t * pxNetworkBuffer;
/* Send a Router Solicitation to ff02::2 */
( void ) memset( xIPAddress.ucBytes, 0, sizeof( xIPAddress.ucBytes ) );
xIPAddress.ucBytes[ 0 ] = 0xffU;
xIPAddress.ucBytes[ 1 ] = 0x02U;
xIPAddress.ucBytes[ 15 ] = 0x02U;
uxNeededSize = ipSIZE_OF_ETH_HEADER + ipSIZE_OF_IPv6_HEADER + sizeof( ICMPRouterSolicitation_IPv6_t );
pxNetworkBuffer = pxGetNetworkBufferWithDescriptor( uxNeededSize, raDONT_BLOCK );
if( pxNetworkBuffer != NULL )
{
pxNetworkBuffer->pxEndPoint = pxEndPoint;
vNDSendRouterSolicitation( pxNetworkBuffer, &( xIPAddress ) );
}
FreeRTOS_printf( ( "vRAProcess: Router Solicitation, attempt %lu/%u\n",
pxEndPoint->xRAData.uxRetryCount + 1U,
ipconfigRA_SEARCH_COUNT ) );
/* Wait a configurable time for a router advertisement. */
uxNewReloadTime = pdMS_TO_TICKS( ipconfigRA_SEARCH_TIME_OUT_MSEC );
pxEndPoint->xRAData.eRAState = eRAStateWait;
}
break;
case eRAStateIPTest: /* Assuming an IP address, test if another device is using it already. */
{
size_t uxNeededSize;
NetworkBufferDescriptor_t * pxNetworkBuffer;
/* Get an IP-address, using the network prefix and a random host address. */
if( pxEndPoint->xRAData.bits.bIPAddressInUse != ipFALSE_BOOL )
{
pxEndPoint->xRAData.bits.bIPAddressInUse = ipFALSE_BOOL;
( void ) FreeRTOS_CreateIPv6Address( &pxEndPoint->ipv6_settings.xIPAddress, &pxEndPoint->ipv6_settings.xPrefix, pxEndPoint->ipv6_settings.uxPrefixLength, pdTRUE );
FreeRTOS_printf( ( "RA: Creating a random IP-address\n" ) );
}
FreeRTOS_printf( ( "RA: Neighbour solicitation for %pip\n", ( void * ) pxEndPoint->ipv6_settings.xIPAddress.ucBytes ) );
uxNeededSize = ipSIZE_OF_ETH_HEADER + ipSIZE_OF_IPv6_HEADER + sizeof( ICMPHeader_IPv6_t );
pxNetworkBuffer = pxGetNetworkBufferWithDescriptor( uxNeededSize, raDONT_BLOCK );
if( pxNetworkBuffer != NULL )
{
pxNetworkBuffer->pxEndPoint = pxEndPoint;
vNDSendNeighbourSolicitation( pxNetworkBuffer, &( pxEndPoint->ipv6_settings.xIPAddress ) );
}
uxNewReloadTime = pdMS_TO_TICKS( 1000U );
pxEndPoint->xRAData.eRAState = eRAStateIPWait;
}
break;
case eRAStatePreLease:
pxEndPoint->xRAData.eRAState = eRAStateLease;
break;
case eRAStateLease:
vRAProcessInit( pxEndPoint );
uxNewReloadTime = pdMS_TO_TICKS( 1000U );
break;
case eRAStateFailed:
break;
default:
/* All states were handled. */
break;
}
return uxNewReloadTime;
}
/*-----------------------------------------------------------*/
/**
* @brief Initialise the RA state machine.
*
* @param[in] pxEndPoint The end-point for which Router Advertisement is required.
*/
static void vRAProcessInit( NetworkEndPoint_t * pxEndPoint )
{
pxEndPoint->xRAData.uxRetryCount = 0U;
pxEndPoint->xRAData.eRAState = eRAStateApply;
}
/**
* @brief Do a single cycle of the RA state machine.
*
* @param[in] xDoReset pdTRUE if the state machine must be reset.
* @param[in] pxEndPoint The end-point for which a RA assignment is required.
*/
void vRAProcess( BaseType_t xDoReset,
NetworkEndPoint_t * pxEndPoint )
{
TickType_t uxReloadTime = pdMS_TO_TICKS( 5000U );
#if ( ipconfigHAS_PRINTF == 1 )
eRAState_t eRAState;
#endif
configASSERT( pxEndPoint != NULL );
#if ( ipconfigHAS_PRINTF == 1 )
/* Remember the initial state, just for logging. */
eRAState = pxEndPoint->xRAData.eRAState;
#endif
if( xDoReset != pdFALSE )
{
vRAProcessInit( pxEndPoint );
}
/* First handle the states that are limited by a timer. See if some
* timer has expired. */
uxReloadTime = xRAProcess_HandleWaitStates( pxEndPoint, uxReloadTime );
/* Now handle the other states. */
uxReloadTime = xRAProcess_HandleOtherStates( pxEndPoint, uxReloadTime );
#if ( ipconfigHAS_PRINTF == 1 )
{
FreeRTOS_printf( ( "vRAProcess( %ld, %pip) bRouterReplied=%d bIPAddressInUse=%d state %d -> %d\n",
xDoReset,
( void * ) pxEndPoint->ipv6_defaults.xIPAddress.ucBytes,
pxEndPoint->xRAData.bits.bRouterReplied,
pxEndPoint->xRAData.bits.bIPAddressInUse,
eRAState,
pxEndPoint->xRAData.eRAState ) );
}
#endif /* ( ipconfigHAS_PRINTF == 1 ) */
if( uxReloadTime != 0U )
{
FreeRTOS_printf( ( "RA: Reload %u seconds\n", ( unsigned ) ( uxReloadTime / 1000U ) ) );
vDHCP_RATimerReload( pxEndPoint, uxReloadTime );
}
else
{
/* Disable the timer, this function vRAProcess() won't be called anymore for this end-point. */
FreeRTOS_printf( ( "RA: Disabled timer.\n" ) );
vIPSetDHCP_RATimerEnableState( pxEndPoint, pdFALSE );
}
}
/*-----------------------------------------------------------*/
#endif /* ( ipconfigUSE_IPv6 != 0 ) && ( ipconfigUSE_RA != 0 ) */
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,425 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
/**
* @file FreeRTOS_Stream_Buffer.c
* @brief Provides the API for managing/creating the stream buffers in the FreeRTOS+TCP network stack.
*/
/* Standard includes. */
#include <stdint.h>
#include <string.h>
/* FreeRTOS includes. */
#include "FreeRTOS.h"
#include "task.h"
/* FreeRTOS+TCP includes. */
#include "FreeRTOS_IP.h"
/**
* @brief Get the space between lower and upper value provided to the function.
* @param[in] pxBuffer The circular stream buffer.
* @param[in] uxLower The lower value.
* @param[in] uxUpper The upper value.
* @return The space between uxLower and uxUpper, which equals to the distance
* minus 1.
*/
size_t uxStreamBufferSpace( const StreamBuffer_t * const pxBuffer,
size_t uxLower,
size_t uxUpper )
{
const size_t uxLength = pxBuffer->LENGTH;
size_t uxCount = uxLength + uxUpper - uxLower - 1U;
if( uxCount >= uxLength )
{
uxCount -= uxLength;
}
return uxCount;
}
/*-----------------------------------------------------------*/
/**
* @brief Get the distance between lower and upper value provided to the function.
* @param[in] pxBuffer The circular stream buffer.
* @param[in] uxLower The lower value.
* @param[in] uxUpper The upper value.
* @return The distance between uxLower and uxUpper.
*/
size_t uxStreamBufferDistance( const StreamBuffer_t * const pxBuffer,
size_t uxLower,
size_t uxUpper )
{
const size_t uxLength = pxBuffer->LENGTH;
size_t uxCount = uxLength + uxUpper - uxLower;
if( uxCount >= uxLength )
{
uxCount -= uxLength;
}
return uxCount;
}
/*-----------------------------------------------------------*/
/**
* @brief Get the number of items which can be added to the buffer at
* the head before reaching the tail.
* @param[in] pxBuffer The circular stream buffer.
* @return The number of items which can still be added to uxHead
* before hitting on uxTail
*/
size_t uxStreamBufferGetSpace( const StreamBuffer_t * const pxBuffer )
{
return uxStreamBufferSpace( pxBuffer, pxBuffer->uxHead, pxBuffer->uxTail );
}
/*-----------------------------------------------------------*/
/**
* @brief Get the distance between the pointer in free space and the tail.
* @param[in] pxBuffer The circular stream buffer.
* @return Distance between uxFront and uxTail or the number of items
* which can still be added to uxFront, before hitting on uxTail.
*/
size_t uxStreamBufferFrontSpace( const StreamBuffer_t * const pxBuffer )
{
return uxStreamBufferSpace( pxBuffer, pxBuffer->uxFront, pxBuffer->uxTail );
}
/*-----------------------------------------------------------*/
/**
* @brief Get the number of items which can be read from the tail before
* reaching the head.
* @param[in] pxBuffer The circular stream buffer.
* @return The number of items which can be read from the tail before
* reaching the head.
*/
size_t uxStreamBufferGetSize( const StreamBuffer_t * const pxBuffer )
{
return uxStreamBufferDistance( pxBuffer, pxBuffer->uxTail, pxBuffer->uxHead );
}
/*-----------------------------------------------------------*/
/**
* @brief Get the space between the mid pointer and the head in the stream
* buffer.
* @param[in] pxBuffer The circular stream buffer.
* @return The space between the mid pointer and the head.
*/
size_t uxStreamBufferMidSpace( const StreamBuffer_t * const pxBuffer )
{
return uxStreamBufferDistance( pxBuffer, pxBuffer->uxMid, pxBuffer->uxHead );
}
/*-----------------------------------------------------------*/
/**
* @brief Clear the stream buffer.
* @param[in] pxBuffer The circular stream buffer.
*/
void vStreamBufferClear( StreamBuffer_t * const pxBuffer )
{
/* Make the circular buffer empty */
pxBuffer->uxHead = 0U;
pxBuffer->uxTail = 0U;
pxBuffer->uxFront = 0U;
pxBuffer->uxMid = 0U;
}
/*-----------------------------------------------------------*/
/**
* @brief Move the mid pointer forward by given byte count
* @param[in] pxBuffer The circular stream buffer.
* @param[in] uxCount The byte count by which the mid pointer is to be moved.
*/
void vStreamBufferMoveMid( StreamBuffer_t * const pxBuffer,
const size_t uxCount )
{
/* Increment uxMid, but no further than uxHead */
const size_t uxLength = pxBuffer->LENGTH;
const size_t uxSize = uxStreamBufferMidSpace( pxBuffer );
size_t uxMid = pxBuffer->uxMid;
size_t uxMoveCount = uxCount;
if( uxMoveCount > uxSize )
{
uxMoveCount = uxSize;
}
uxMid += uxMoveCount;
if( uxMid >= uxLength )
{
uxMid -= uxLength;
}
pxBuffer->uxMid = uxMid;
}
/*-----------------------------------------------------------*/
/**
* @brief Check whether the value in left is less than or equal to the
* value in right from the perspective of the circular stream
* buffer.
* @param[in] pxBuffer The circular stream buffer.
* @param[in] uxLeft The left pointer in the stream buffer.
* @param[in] uxRight The right value pointer in the stream buffer.
* @return pdTRUE if uxLeft <= uxRight, else pdFALSE.
*/
BaseType_t xStreamBufferLessThenEqual( const StreamBuffer_t * const pxBuffer,
size_t uxLeft,
size_t uxRight )
{
BaseType_t xReturn = pdFALSE;
const size_t uxTail = pxBuffer->uxTail;
if( ( uxLeft - uxTail ) <= ( uxRight - uxTail ) )
{
xReturn = pdTRUE;
}
return xReturn;
}
/*-----------------------------------------------------------*/
/**
* @brief Get the pointer to data and the amount of data which can be read in one go.
*
* @param[in] pxBuffer The circular stream buffer.
* @param[out] ppucData Pointer to the data pointer which will point to the
* data which can be read.
*
* @return The number of bytes which can be read in one go (which might be less than
* actual number of available bytes since this is a circular buffer and tail
* can loop back to the start of the buffer).
*/
size_t uxStreamBufferGetPtr( StreamBuffer_t * const pxBuffer,
uint8_t ** const ppucData )
{
const size_t uxNextTail = pxBuffer->uxTail;
const size_t uxSize = uxStreamBufferGetSize( pxBuffer );
/* MISRA Ref 18.4.1 [Usage of +, -, += and -= operators on expression of pointer type]. */
/* More details at: https://github.com/FreeRTOS/FreeRTOS-Plus-TCP/blob/main/MISRA.md#rule-184. */
/* coverity[misra_c_2012_rule_18_4_violation] */
*ppucData = pxBuffer->ucArray + uxNextTail;
return FreeRTOS_min_size_t( uxSize, pxBuffer->LENGTH - uxNextTail );
}
/*-----------------------------------------------------------*/
/**
* @brief Adds data to a stream buffer.
*
* @param[in,out] pxBuffer The buffer to which the bytes will be added.
* @param[in] uxOffset If uxOffset > 0, data will be written at an offset from uxHead
* while uxHead will not be moved yet.
* @param[in] pucData A pointer to the data to be added. If 'pucData' equals NULL,
* the function is called to advance the 'Head' only.
* @param[in] uxByteCount The number of bytes to add.
*
* @return The number of bytes added to the buffer.
*/
size_t uxStreamBufferAdd( StreamBuffer_t * const pxBuffer,
size_t uxOffset,
const uint8_t * const pucData,
size_t uxByteCount )
{
size_t uxCount;
size_t uxSpace = uxStreamBufferGetSpace( pxBuffer );
/* If uxOffset > 0, items can be placed in front of uxHead */
if( uxSpace > uxOffset )
{
uxSpace -= uxOffset;
}
else
{
uxSpace = 0U;
}
/* The number of bytes that can be written is the minimum of the number of
* bytes requested and the number available. */
uxCount = FreeRTOS_min_size_t( uxSpace, uxByteCount );
if( uxCount != 0U )
{
const size_t uxLength = pxBuffer->LENGTH;
size_t uxNextHead = pxBuffer->uxHead;
if( uxOffset != 0U )
{
/* ( uxOffset > 0 ) means: write in front if the uxHead marker */
uxNextHead += uxOffset;
if( uxNextHead >= uxLength )
{
uxNextHead -= uxLength;
}
}
if( pucData != NULL )
{
/* Calculate the number of bytes that can be added in the first
* write - which may be less than the total number of bytes that need
* to be added if the buffer will wrap back to the beginning. */
const size_t uxFirst = FreeRTOS_min_size_t( uxLength - uxNextHead, uxCount );
/* Write as many bytes as can be written in the first write. */
( void ) pvPortMemCpyStreamBuffer( &( pxBuffer->ucArray[ uxNextHead ] ), pucData, uxFirst );
/* If the number of bytes written was less than the number that
* could be written in the first write... */
if( uxCount > uxFirst )
{
/* ...then write the remaining bytes to the start of the
* buffer. */
( void ) pvPortMemCpyStreamBuffer( pxBuffer->ucArray, &( pucData[ uxFirst ] ), uxCount - uxFirst );
}
}
/* The below update to the stream buffer members must happen
* atomically. */
taskENTER_CRITICAL();
{
if( uxOffset == 0U )
{
/* ( uxOffset == 0 ) means: write at uxHead position */
uxNextHead += uxCount;
if( uxNextHead >= uxLength )
{
uxNextHead -= uxLength;
}
pxBuffer->uxHead = uxNextHead;
}
if( xStreamBufferLessThenEqual( pxBuffer, pxBuffer->uxFront, uxNextHead ) != pdFALSE )
{
/* Advance the front pointer */
pxBuffer->uxFront = uxNextHead;
}
}
taskEXIT_CRITICAL();
}
return uxCount;
}
/*-----------------------------------------------------------*/
/**
* @brief Read bytes from stream buffer.
*
* @param[in] pxBuffer The buffer from which the bytes will be read.
* @param[in] uxOffset can be used to read data located at a certain offset from 'lTail'.
* @param[in,out] pucData If 'pucData' equals NULL, the function is called to advance 'lTail' only.
* @param[in] uxMaxCount The number of bytes to read.
* @param[in] xPeek if 'xPeek' is pdTRUE, or if 'uxOffset' is non-zero, the 'lTail' pointer will
* not be advanced.
*
* @return The count of the bytes read.
*/
size_t uxStreamBufferGet( StreamBuffer_t * const pxBuffer,
size_t uxOffset,
uint8_t * const pucData,
size_t uxMaxCount,
BaseType_t xPeek )
{
size_t uxCount;
/* How much data is available? */
size_t uxSize = uxStreamBufferGetSize( pxBuffer );
if( uxSize > uxOffset )
{
uxSize -= uxOffset;
}
else
{
uxSize = 0U;
}
/* Use the minimum of the wanted bytes and the available bytes. */
uxCount = FreeRTOS_min_size_t( uxSize, uxMaxCount );
if( uxCount != 0U )
{
const size_t uxLength = pxBuffer->LENGTH;
size_t uxNextTail = pxBuffer->uxTail;
if( uxOffset != 0U )
{
uxNextTail += uxOffset;
if( uxNextTail >= uxLength )
{
uxNextTail -= uxLength;
}
}
if( pucData != NULL )
{
/* Calculate the number of bytes that can be read - which may be
* less than the number wanted if the data wraps around to the start of
* the buffer. */
const size_t uxFirst = FreeRTOS_min_size_t( uxLength - uxNextTail, uxCount );
/* Obtain the number of bytes it is possible to obtain in the first
* read. */
( void ) pvPortMemCpyStreamBuffer( pucData, &( pxBuffer->ucArray[ uxNextTail ] ), uxFirst );
/* If the total number of wanted bytes is greater than the number
* that could be read in the first read... */
if( uxCount > uxFirst )
{
/* ...then read the remaining bytes from the start of the buffer. */
( void ) pvPortMemCpyStreamBuffer( &( pucData[ uxFirst ] ), pxBuffer->ucArray, uxCount - uxFirst );
}
}
if( ( xPeek == pdFALSE ) && ( uxOffset == 0U ) )
{
/* Move the tail pointer to effectively remove the data read from
* the buffer. */
uxNextTail += uxCount;
if( uxNextTail >= uxLength )
{
uxNextTail -= uxLength;
}
pxBuffer->uxTail = uxNextTail;
}
}
return uxCount;
}
/*-----------------------------------------------------------*/
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,81 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
/**
* @file FreeRTOS_TCP_IP_IPv4.c
* @brief Module which handles the TCP connections for FreeRTOS+TCP.
* It depends on FreeRTOS_TCP_WIN.c, which handles the TCP windowing
* schemes.
*
* Endianness: in this module all ports and IP addresses are stored in
* host byte-order, except fields in the IP-packets
*/
/* Standard includes. */
#include <stdint.h>
#include <stdio.h>
/* FreeRTOS includes. */
#include "FreeRTOS.h"
#include "task.h"
#include "queue.h"
#include "semphr.h"
/* FreeRTOS+TCP includes. */
#include "FreeRTOS_IP.h"
#include "FreeRTOS_Sockets.h"
#include "FreeRTOS_IP_Private.h"
#include "FreeRTOS_UDP_IP.h"
#include "FreeRTOS_DHCP.h"
#include "NetworkInterface.h"
#include "NetworkBufferManagement.h"
#include "FreeRTOS_TCP_Reception.h"
#include "FreeRTOS_TCP_Transmission.h"
#include "FreeRTOS_TCP_State_Handling.h"
#include "FreeRTOS_TCP_Utils.h"
/* Just make sure the contents doesn't get compiled if TCP is not enabled. */
/* *INDENT-OFF* */
#if( ipconfigUSE_IPv4 != 0 ) && ( ipconfigUSE_TCP == 1 )
/* *INDENT-ON* */
/* *INDENT-OFF* */
#endif /* ( ipconfigUSE_IPv4 != 0 ) && ( ipconfigUSE_TCP == 1 ) */
/* *INDENT-ON* */
/* Provide access to private members for testing. */
#ifdef FREERTOS_ENABLE_UNIT_TESTS
#include "freertos_tcp_test_access_tcp_define.h"
#endif
/* Provide access to private members for verification. */
#ifdef FREERTOS_TCP_ENABLE_VERIFICATION
#include "aws_freertos_tcp_verification_access_tcp_define.h"
#endif
@@ -0,0 +1,81 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
/**
* @file FreeRTOS_TCP_IP_IPv6.c
* @brief Module which handles the TCP connections for FreeRTOS+TCP.
* It depends on FreeRTOS_TCP_WIN.c, which handles the TCP windowing
* schemes.
*
* Endianness: in this module all ports and IP addresses are stored in
* host byte-order, except fields in the IP-packets
*/
/* Standard includes. */
#include <stdint.h>
#include <stdio.h>
/* FreeRTOS includes. */
#include "FreeRTOS.h"
#include "task.h"
#include "queue.h"
#include "semphr.h"
/* FreeRTOS+TCP includes. */
#include "FreeRTOS_IP.h"
#include "FreeRTOS_Sockets.h"
#include "FreeRTOS_IP_Private.h"
#include "FreeRTOS_UDP_IP.h"
#include "FreeRTOS_DHCP.h"
#include "NetworkInterface.h"
#include "NetworkBufferManagement.h"
#include "FreeRTOS_TCP_Reception.h"
#include "FreeRTOS_TCP_Transmission.h"
#include "FreeRTOS_TCP_State_Handling.h"
#include "FreeRTOS_TCP_Utils.h"
/* Just make sure the contents doesn't get compiled if TCP is not enabled. */
/* *INDENT-OFF* */
#if( ipconfigUSE_IPv6 != 0 ) && ( ipconfigUSE_TCP == 1 )
/* *INDENT-ON* */
/* Provide access to private members for testing. */
#ifdef FREERTOS_ENABLE_UNIT_TESTS
#include "freertos_tcp_test_access_tcp_define.h"
#endif
/* Provide access to private members for verification. */
#ifdef FREERTOS_TCP_ENABLE_VERIFICATION
#include "aws_freertos_tcp_verification_access_tcp_define.h"
#endif
/* *INDENT-OFF* */
#endif /* ( ipconfigUSE_IPv6 != 0 ) && ( ipconfigUSE_TCP == 1 ) */
/* *INDENT-ON* */
@@ -0,0 +1,664 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
/**
* @file FreeRTOS_TCP_Reception.c
* @brief Module which processes the packet received from a socket for FreeRTOS+TCP.
*
* Endianness: in this module all ports and IP addresses are stored in
* host byte-order, except fields in the IP-packets
*/
/* Standard includes. */
#include <stdint.h>
#include <stdio.h>
/* FreeRTOS includes. */
#include "FreeRTOS.h"
#include "task.h"
#include "queue.h"
#include "semphr.h"
/* FreeRTOS+TCP includes. */
#include "FreeRTOS_IP.h"
#include "FreeRTOS_Sockets.h"
#include "FreeRTOS_IP_Private.h"
#include "FreeRTOS_UDP_IP.h"
#include "FreeRTOS_DHCP.h"
#include "NetworkInterface.h"
#include "NetworkBufferManagement.h"
#include "FreeRTOS_TCP_Transmission.h"
#include "FreeRTOS_TCP_Reception.h"
/* Just make sure the contents doesn't get compiled if TCP is not enabled. */
#if ipconfigUSE_TCP == 1
/*
* Identify and deal with a single TCP header option, advancing the pointer to
* the header. This function returns pdTRUE or pdFALSE depending on whether the
* caller should continue to parse more header options or break the loop.
*/
static int32_t prvSingleStepTCPHeaderOptions( const uint8_t * const pucPtr,
size_t uxTotalLength,
FreeRTOS_Socket_t * const pxSocket,
BaseType_t xHasSYNFlag );
#if ( ipconfigUSE_TCP_WIN == 1 )
/*
* Skip past TCP header options when doing Selective ACK, until there are no
* more options left.
*/
static void prvReadSackOption( const uint8_t * const pucPtr,
size_t uxIndex,
FreeRTOS_Socket_t * const pxSocket );
#endif /* ( ipconfigUSE_TCP_WIN == 1 ) */
/**
* @brief Parse the TCP option(s) received, if present.
*
* @param[in] pxSocket The socket handling the connection.
* @param[in] pxNetworkBuffer The network buffer containing the TCP
* packet.
*
* @return: If the options are well formed and processed successfully
* then pdPASS is returned; else a pdFAIL is returned.
*
* @note It has already been verified that:
* ((pxTCPHeader->ucTCPOffset & 0xf0) > 0x50), meaning that
* the TP header is longer than the usual 20 (5 x 4) bytes.
*/
BaseType_t prvCheckOptions( FreeRTOS_Socket_t * pxSocket,
const NetworkBufferDescriptor_t * pxNetworkBuffer )
{
size_t uxTCPHeaderOffset = ipSIZE_OF_ETH_HEADER + uxIPHeaderSizePacket( pxNetworkBuffer );
/* MISRA Ref 11.3.1 [Misaligned access] */
/* More details at: https://github.com/FreeRTOS/FreeRTOS-Plus-TCP/blob/main/MISRA.md#rule-113 */
/* coverity[misra_c_2012_rule_11_3_violation] */
const ProtocolHeaders_t * pxProtocolHeaders = ( ( ProtocolHeaders_t * )
&( pxNetworkBuffer->pucEthernetBuffer[ uxTCPHeaderOffset ] ) );
const TCPHeader_t * pxTCPHeader;
const uint8_t * pucPtr;
BaseType_t xHasSYNFlag;
BaseType_t xReturn = pdPASS;
/* Offset in the network packet where the first option byte is stored. */
size_t uxOptionOffset = uxTCPHeaderOffset + ipSIZE_OF_TCP_HEADER;
size_t uxOptionsLength;
int32_t lResult;
uint8_t ucLength;
pxTCPHeader = &( pxProtocolHeaders->xTCPHeader );
/* A character pointer to iterate through the option data */
pucPtr = pxTCPHeader->ucOptdata;
if( pxTCPHeader->ucTCPOffset <= ( 5U << 4U ) )
{
/* Avoid integer underflow in computation of ucLength. */
}
else
{
ucLength = ( uint8_t ) ( ( ( pxTCPHeader->ucTCPOffset >> 4U ) - 5U ) << 2U );
uxOptionsLength = ( size_t ) ucLength;
if( pxNetworkBuffer->xDataLength > uxOptionOffset )
{
/* Validate options size calculation. */
if( uxOptionsLength <= ( pxNetworkBuffer->xDataLength - uxOptionOffset ) )
{
if( ( pxTCPHeader->ucTCPFlags & tcpTCP_FLAG_SYN ) != ( uint8_t ) 0U )
{
xHasSYNFlag = pdTRUE;
}
else
{
xHasSYNFlag = pdFALSE;
}
/* The length check is only necessary in case the option data are
* corrupted, we don't like to run into invalid memory and crash. */
for( ; ; )
{
if( uxOptionsLength == 0U )
{
/* coverity[break_stmt] : Break statement terminating the loop */
break;
}
lResult = prvSingleStepTCPHeaderOptions( pucPtr, uxOptionsLength, pxSocket, xHasSYNFlag );
if( lResult < 0 )
{
xReturn = pdFAIL;
break;
}
if( lResult == 0 )
{
break;
}
uxOptionsLength -= ( size_t ) lResult;
pucPtr = &( pucPtr[ lResult ] );
}
}
}
}
return xReturn;
}
/*-----------------------------------------------------------*/
/**
* @brief Identify and deal with a single TCP header option, advancing the pointer to
* the header.
*
* @param[in] pucPtr Pointer to the TCP packet options.
* @param[in] uxTotalLength Length of the TCP packet options.
* @param[in] pxSocket Socket handling the connection.
* @param[in] xHasSYNFlag Whether the header has SYN flag or not.
*
* @return This function returns index of the next option if the current option is
* successfully processed and it is not the end of options whereafter the caller
* should continue to process more options.
* If the options have ended, this function will return a zero whereafter the
* caller should stop parsing options and continue further processing.
* If the current option has erroneous value, then the function returns a
* negative value wherein the calling function should not process this packet any
* further and drop it.
*/
static int32_t prvSingleStepTCPHeaderOptions( const uint8_t * const pucPtr,
size_t uxTotalLength,
FreeRTOS_Socket_t * const pxSocket,
BaseType_t xHasSYNFlag )
{
UBaseType_t uxNewMSS;
size_t uxRemainingOptionsBytes = uxTotalLength;
uint8_t ucLen;
int32_t lIndex = 0;
TCPWindow_t * pxTCPWindow = &( pxSocket->u.xTCP.xTCPWindow );
BaseType_t xReturn = pdFALSE;
if( pucPtr[ 0U ] == tcpTCP_OPT_END )
{
/* End of options. */
lIndex = 0;
}
else if( pucPtr[ 0U ] == tcpTCP_OPT_NOOP )
{
/* NOP option, inserted to make the length a multiple of 4. */
lIndex = 1;
}
else if( uxRemainingOptionsBytes < 2U )
{
/* Any other well-formed option must be at least two bytes: the option
* type byte followed by a length byte. */
lIndex = -1;
}
#if ( ipconfigUSE_TCP_WIN != 0 )
else if( pucPtr[ 0 ] == tcpTCP_OPT_WSOPT )
{
/* The TCP Window Scale Option. */
/* Confirm that the option fits in the remaining buffer space. */
if( ( uxRemainingOptionsBytes < tcpTCP_OPT_WSOPT_LEN ) || ( pucPtr[ 1 ] != tcpTCP_OPT_WSOPT_LEN ) )
{
lIndex = -1;
}
else
{
/* Option is only valid in SYN phase. */
if( xHasSYNFlag != 0 )
{
/* From RFC7323 - section 2.3, we should limit the WSopt not larger than 14. */
if( pucPtr[ 2 ] > tcpTCP_OPT_WSOPT_MAXIMUM_VALUE )
{
FreeRTOS_debug_printf( ( "The WSopt(%u) from SYN packet is larger than maximum value.", pucPtr[ 2 ] ) );
pxSocket->u.xTCP.ucPeerWinScaleFactor = tcpTCP_OPT_WSOPT_MAXIMUM_VALUE;
}
else
{
pxSocket->u.xTCP.ucPeerWinScaleFactor = pucPtr[ 2 ];
}
pxSocket->u.xTCP.bits.bWinScaling = ipTRUE_BOOL;
}
lIndex = ( int32_t ) tcpTCP_OPT_WSOPT_LEN;
}
}
#endif /* ipconfigUSE_TCP_WIN */
else if( pucPtr[ 0 ] == tcpTCP_OPT_MSS )
{
/* Confirm that the option fits in the remaining buffer space. */
if( ( uxRemainingOptionsBytes < tcpTCP_OPT_MSS_LEN ) || ( pucPtr[ 1 ] != tcpTCP_OPT_MSS_LEN ) )
{
lIndex = -1;
}
else
{
/* An MSS option with the correct option length. FreeRTOS_htons()
* is not needed here because usChar2u16() already returns a host
* endian number. */
uxNewMSS = usChar2u16( &( pucPtr[ 2 ] ) );
if( pxSocket->u.xTCP.usMSS != uxNewMSS )
{
/* Perform a basic check on the the new MSS. */
if( uxNewMSS == 0U )
{
lIndex = -1;
/* Return Condition found. */
xReturn = pdTRUE;
}
else
{
FreeRTOS_debug_printf( ( "MSS change %u -> %u\n", pxSocket->u.xTCP.usMSS, ( unsigned ) uxNewMSS ) );
}
}
/* If a 'return' condition has not been found. */
if( xReturn == pdFALSE )
{
/* Restrict the minimum value of segment length to the ( Minimum IP MTU (576) - IP header(20) - TCP Header(20) ).
* See "RFC 791 section 3.1 Total Length" for more details. */
if( uxNewMSS < tcpMINIMUM_SEGMENT_LENGTH )
{
uxNewMSS = tcpMINIMUM_SEGMENT_LENGTH;
}
if( pxSocket->u.xTCP.usMSS > uxNewMSS )
{
/* our MSS was bigger than the MSS of the other party: adapt it. */
pxSocket->u.xTCP.bits.bMssChange = ipTRUE_BOOL;
if( pxSocket->u.xTCP.usMSS > uxNewMSS )
{
/* The peer advertises a smaller MSS than this socket was
* using. Use that as well. */
FreeRTOS_debug_printf( ( "Change mss %d => %u\n", pxSocket->u.xTCP.usMSS, ( unsigned ) uxNewMSS ) );
}
pxTCPWindow->xSize.ulRxWindowLength = ( ( uint32_t ) uxNewMSS ) * ( pxTCPWindow->xSize.ulRxWindowLength / ( ( uint32_t ) uxNewMSS ) );
pxTCPWindow->usMSSInit = ( uint16_t ) uxNewMSS;
pxTCPWindow->usMSS = ( uint16_t ) uxNewMSS;
pxSocket->u.xTCP.usMSS = ( uint16_t ) uxNewMSS;
}
lIndex = ( int32_t ) tcpTCP_OPT_MSS_LEN;
}
}
}
else
{
/* All other options have a length field, so that we easily
* can skip past them. */
ucLen = pucPtr[ 1 ];
lIndex = 0;
if( ( ucLen < ( uint8_t ) 2U ) || ( uxRemainingOptionsBytes < ( size_t ) ucLen ) )
{
/* If the length field is too small or too big, the options are
* malformed, don't process them further.
*/
lIndex = -1;
}
else
{
#if ( ipconfigUSE_TCP_WIN == 1 )
{
/* Selective ACK: the peer has received a packet but it is missing
* earlier packets. At least this packet does not need retransmission
* anymore. ulTCPWindowTxSack( ) takes care of this administration.
*/
if( pucPtr[ 0U ] == tcpTCP_OPT_SACK_A )
{
ucLen = ( uint8_t ) ( ucLen - 2U );
lIndex += 2;
while( ucLen >= ( uint8_t ) 8U )
{
prvReadSackOption( pucPtr, ( size_t ) lIndex, pxSocket );
lIndex += 8;
ucLen = ( uint8_t ) ( ucLen - 8U );
}
/* ucLen should be 0 by now. */
}
}
#endif /* ipconfigUSE_TCP_WIN == 1 */
lIndex += ( int32_t ) ucLen;
}
}
#if ( ipconfigUSE_TCP_WIN == 0 )
/* Avoid compiler warnings when TCP window is not used. */
( void ) xHasSYNFlag;
#endif
return lIndex;
}
/*-----------------------------------------------------------*/
#if ( ipconfigUSE_TCP_WIN == 1 )
/**
* @brief Skip past TCP header options when doing Selective ACK, until there are no
* more options left.
*
* @param[in] pucPtr Pointer to the TCP packet options.
* @param[in] uxIndex Index of options in the TCP packet options.
* @param[in] pxSocket Socket handling the TCP connection.
*/
static void prvReadSackOption( const uint8_t * const pucPtr,
size_t uxIndex,
FreeRTOS_Socket_t * const pxSocket )
{
uint32_t ulFirst = ulChar2u32( &( pucPtr[ uxIndex ] ) );
uint32_t ulLast = ulChar2u32( &( pucPtr[ uxIndex + 4U ] ) );
uint32_t ulCount = ulTCPWindowTxSack( &( pxSocket->u.xTCP.xTCPWindow ), ulFirst, ulLast );
/* ulTCPWindowTxSack( ) returns the number of bytes which have been acked
* starting from the head position. Advance the tail pointer in txStream.
*/
if( ( pxSocket->u.xTCP.txStream != NULL ) && ( ulCount > 0U ) )
{
/* Just advancing the tail index, 'ulCount' bytes have been confirmed. */
( void ) uxStreamBufferGet( pxSocket->u.xTCP.txStream, 0, NULL, ( size_t ) ulCount, pdFALSE );
pxSocket->xEventBits |= ( EventBits_t ) eSOCKET_SEND;
#if ipconfigSUPPORT_SELECT_FUNCTION == 1
{
if( ( pxSocket->xSelectBits & ( EventBits_t ) eSELECT_WRITE ) != 0U )
{
/* The field 'xEventBits' is used to store regular socket events
* (at most 8), as well as 'select events', which will be left-shifted.
*/
pxSocket->xEventBits |= ( ( EventBits_t ) eSELECT_WRITE ) << SOCKET_EVENT_BIT_COUNT;
}
}
#endif
/* In case the socket owner has installed an OnSent handler,
* call it now. */
#if ( ipconfigUSE_CALLBACKS == 1 )
{
if( ipconfigIS_VALID_PROG_ADDRESS( pxSocket->u.xTCP.pxHandleSent ) )
{
pxSocket->u.xTCP.pxHandleSent( pxSocket, ulCount );
}
}
#endif /* ipconfigUSE_CALLBACKS == 1 */
}
}
#endif /* ( ipconfigUSE_TCP_WIN != 0 ) */
/*-----------------------------------------------------------*/
/**
* @brief prvCheckRxData(): called from prvTCPHandleState(). The
* first thing that will be done is find the TCP payload data
* and check the length of this data.
*
* @param[in] pxNetworkBuffer The network buffer holding the received data.
* @param[out] ppucRecvData It will point to first byte of the TCP payload.
*
* @return Length of the received buffer.
*/
BaseType_t prvCheckRxData( const NetworkBufferDescriptor_t * pxNetworkBuffer,
uint8_t ** ppucRecvData )
{
/* Map the ethernet buffer onto the ProtocolHeader_t struct for easy access to the fields. */
/* MISRA Ref 11.3.1 [Misaligned access] */
/* More details at: https://github.com/FreeRTOS/FreeRTOS-Plus-TCP/blob/main/MISRA.md#rule-113 */
/* coverity[misra_c_2012_rule_11_3_violation] */
const ProtocolHeaders_t * pxProtocolHeaders = ( ( ProtocolHeaders_t * )
&( pxNetworkBuffer->pucEthernetBuffer[ ( size_t ) ipSIZE_OF_ETH_HEADER + uxIPHeaderSizePacket( pxNetworkBuffer ) ] ) );
const TCPHeader_t * pxTCPHeader = &( pxProtocolHeaders->xTCPHeader );
int32_t lLength, lTCPHeaderLength, lReceiveLength, lUrgentLength;
/* Map the buffer onto an IPHeader_t struct for easy access to fields. */
const size_t xIPHeaderLength = uxIPHeaderSizePacket( pxNetworkBuffer );
uint16_t usLength;
uint8_t ucIntermediateResult = 0;
/* Determine the length and the offset of the user-data sent to this
* node.
*
* The size of the TCP header is given in a multiple of 4-byte words (single
* byte, needs no ntoh() translation). A shift-right 2: is the same as
* (offset >> 4) * 4. */
ucIntermediateResult = ( pxTCPHeader->ucTCPOffset & tcpVALID_BITS_IN_TCP_OFFSET_BYTE ) >> 2;
lTCPHeaderLength = ( int32_t ) ucIntermediateResult;
/* Let pucRecvData point to the first byte received. */
*ppucRecvData = &( pxNetworkBuffer->pucEthernetBuffer[ ( size_t ) ipSIZE_OF_ETH_HEADER + xIPHeaderLength + ( size_t ) lTCPHeaderLength ] );
/* Calculate lReceiveLength - the length of the TCP data received. This is
* equal to the total packet length minus:
* ( LinkLayer length (14) + IP header length (20) + size of TCP header(20 +) ).*/
lReceiveLength = ( int32_t ) pxNetworkBuffer->xDataLength;
lReceiveLength -= ( int32_t ) ipSIZE_OF_ETH_HEADER;
/* MISRA Ref 11.3.1 [Misaligned access] */
/* More details at: https://github.com/FreeRTOS/FreeRTOS-Plus-TCP/blob/main/MISRA.md#rule-113 */
/* coverity[misra_c_2012_rule_11_3_violation] */
switch( ( ( EthernetHeader_t * ) pxNetworkBuffer->pucEthernetBuffer )->usFrameType )
{
#if ( ipconfigUSE_IPv4 != 0 )
case ipIPv4_FRAME_TYPE:
{
/* MISRA Ref 11.3.1 [Misaligned access] */
/* More details at: https://github.com/FreeRTOS/FreeRTOS-Plus-TCP/blob/main/MISRA.md#rule-113 */
/* coverity[misra_c_2012_rule_11_3_violation] */
const IPHeader_t * pxIPHeader = ( ( IPHeader_t * ) &( pxNetworkBuffer->pucEthernetBuffer[ ipSIZE_OF_ETH_HEADER ] ) );
usLength = FreeRTOS_htons( pxIPHeader->usLength );
lLength = ( int32_t ) usLength;
}
break;
#endif /* ( ipconfigUSE_IPv4 != 0 ) */
#if ( ipconfigUSE_IPv6 != 0 )
case ipIPv6_FRAME_TYPE:
{
/* MISRA Ref 11.3.1 [Misaligned access] */
/* More details at: https://github.com/FreeRTOS/FreeRTOS-Plus-TCP/blob/main/MISRA.md#rule-113 */
/* coverity[misra_c_2012_rule_11_3_violation] */
const IPHeader_IPv6_t * pxIPHeader = ( ( IPHeader_IPv6_t * ) &( pxNetworkBuffer->pucEthernetBuffer[ ipSIZE_OF_ETH_HEADER ] ) );
/* For Coverity: conversion and cast in 2 steps. */
usLength = FreeRTOS_htons( pxIPHeader->usPayloadLength );
lLength = ( int32_t ) usLength;
/* Add the length of the TCP-header, because that was not included in 'usPayloadLength'. */
lLength += ( int32_t ) sizeof( IPHeader_IPv6_t );
}
break;
#endif /* ( ipconfigUSE_IPv6 != 0 ) */
default:
/* Shouldn't reach here */
lLength = 0;
break;
}
if( lReceiveLength > lLength )
{
/* More bytes were received than the reported length, often because of
* padding bytes at the end. */
lReceiveLength = lLength;
}
/* Subtract the size of the TCP and IP headers and the actual data size is
* known. */
if( lReceiveLength > ( lTCPHeaderLength + ( int32_t ) xIPHeaderLength ) )
{
lReceiveLength -= ( lTCPHeaderLength + ( int32_t ) xIPHeaderLength );
}
else
{
lReceiveLength = 0;
}
/* Urgent Pointer:
* This field communicates the current value of the urgent pointer as a
* positive offset from the sequence number in this segment. The urgent
* pointer points to the sequence number of the octet following the urgent
* data. This field is only be interpreted in segments with the URG control
* bit set. */
if( ( pxTCPHeader->ucTCPFlags & tcpTCP_FLAG_URG ) != 0U )
{
/* Although we ignore the urgent data, we have to skip it. */
lUrgentLength = ( int32_t ) FreeRTOS_htons( pxTCPHeader->usUrgent );
/* MISRA Ref 18.4.1 [Usage of +, -, += and -= operators on expression of pointer type]. */
/* More details at: https://github.com/FreeRTOS/FreeRTOS-Plus-TCP/blob/main/MISRA.md#rule-184. */
/* coverity[misra_c_2012_rule_18_4_violation] */
*ppucRecvData += lUrgentLength;
lReceiveLength -= FreeRTOS_min_int32( lReceiveLength, lUrgentLength );
}
return ( BaseType_t ) lReceiveLength;
}
/*-----------------------------------------------------------*/
/**
* @brief prvStoreRxData(): called from prvTCPHandleState().
* The second thing is to do is check if the payload data may
* be accepted. If so, they will be added to the reception queue.
*
* @param[in] pxSocket The socket owning the connection.
* @param[in] pucRecvData Pointer to received data.
* @param[in] pxNetworkBuffer The network buffer descriptor.
* @param[in] ulReceiveLength The length of the received data.
*
* @return 0 on success, -1 on failure of storing data.
*/
BaseType_t prvStoreRxData( FreeRTOS_Socket_t * pxSocket,
const uint8_t * pucRecvData,
NetworkBufferDescriptor_t * pxNetworkBuffer,
uint32_t ulReceiveLength )
{
/* Map the ethernet buffer onto the ProtocolHeader_t struct for easy access to the fields. */
size_t uxIPOffset = uxIPHeaderSizePacket( pxNetworkBuffer );
/* MISRA Ref 11.3.1 [Misaligned access] */
/* More details at: https://github.com/FreeRTOS/FreeRTOS-Plus-TCP/blob/main/MISRA.md#rule-113 */
/* coverity[misra_c_2012_rule_11_3_violation] */
const ProtocolHeaders_t * pxProtocolHeaders = ( ( const ProtocolHeaders_t * )
&( pxNetworkBuffer->pucEthernetBuffer[ ipSIZE_OF_ETH_HEADER + uxIPOffset ] ) );
const TCPHeader_t * pxTCPHeader = &pxProtocolHeaders->xTCPHeader;
TCPWindow_t * pxTCPWindow = &pxSocket->u.xTCP.xTCPWindow;
uint32_t ulSequenceNumber, ulSpace;
int32_t lOffset, lStored;
BaseType_t xResult = 0;
uint32_t ulRxLength = ulReceiveLength;
const uint8_t * pucRxBuffer = &( pucRecvData[ 0 ] );
ulSequenceNumber = FreeRTOS_ntohl( pxTCPHeader->ulSequenceNumber );
if( ( ulRxLength > 0U ) && ( pxSocket->u.xTCP.eTCPState >= eSYN_RECEIVED ) )
{
uint32_t ulSkipCount = 0;
/* See if way may accept the data contents and forward it to the socket
* owner.
*
* If it can't be "accept"ed it may have to be stored and send a selective
* ack (SACK) option to confirm it. In that case, lTCPAddRxdata() will be
* called later to store an out-of-order packet (in case lOffset is
* negative). */
if( pxSocket->u.xTCP.rxStream != NULL )
{
ulSpace = ( uint32_t ) uxStreamBufferGetSpace( pxSocket->u.xTCP.rxStream );
}
else
{
ulSpace = ( uint32_t ) pxSocket->u.xTCP.uxRxStreamSize;
}
lOffset = lTCPWindowRxCheck( pxTCPWindow, ulSequenceNumber, ulRxLength, ulSpace, &( ulSkipCount ) );
if( lOffset >= 0 )
{
/* New data has arrived and may be made available to the user. See
* if the head marker in rxStream may be advanced, only if lOffset == 0.
* In case the low-water mark is reached, bLowWater will be set
* "low-water" here stands for "little space". */
if( ulSkipCount != 0U )
{
/* A packet was received that starts before 'ulCurrentSequenceNumber',
* and that ends after it. The first 'ulSkipCount' bytes shall be
* skipped. */
ulRxLength -= ulSkipCount;
pucRxBuffer = &( pucRecvData[ ulSkipCount ] );
}
lStored = lTCPAddRxdata( pxSocket, ( uint32_t ) lOffset, pucRxBuffer, ulRxLength );
if( lStored != ( int32_t ) ulRxLength )
{
FreeRTOS_debug_printf( ( "lTCPAddRxdata: stored %d / %u bytes? ?\n", ( int ) lStored, ( unsigned ) ulRxLength ) );
/* Received data could not be stored. The socket's flag
* bMallocError has been set. The socket now has the status
* eCLOSE_WAIT and a RST packet will be sent back. */
( void ) prvTCPSendReset( pxNetworkBuffer );
xResult = -1;
}
}
/* After a missing packet has come in, higher packets may be passed to
* the user. */
#if ( ipconfigUSE_TCP_WIN == 1 )
{
/* Now lTCPAddRxdata() will move the rxHead pointer forward
* so data becomes available to the user immediately
* In case the low-water mark is reached, bLowWater will be set. */
if( ( xResult == 0 ) && ( pxTCPWindow->ulUserDataLength > 0U ) )
{
( void ) lTCPAddRxdata( pxSocket, 0U, NULL, pxTCPWindow->ulUserDataLength );
pxTCPWindow->ulUserDataLength = 0;
}
}
#endif /* ipconfigUSE_TCP_WIN */
}
else
{
pxTCPWindow->ucOptionLength = 0U;
}
return xResult;
}
/*-----------------------------------------------------------*/
#endif /* ipconfigUSE_TCP == 1 */
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,234 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
/**
* @file FreeRTOS_TCP_State_Handling_IPv4.c
* @brief Module which handles the TCP protocol state transition for FreeRTOS+TCP.
*
* Endianness: in this module all ports and IP addresses are stored in
* host byte-order, except fields in the IP-packets
*/
/* Standard includes. */
#include <stdint.h>
#include <stdio.h>
/* FreeRTOS includes. */
#include "FreeRTOS.h"
#include "task.h"
#include "queue.h"
#include "semphr.h"
/* FreeRTOS+TCP includes. */
#include "FreeRTOS_IP.h"
#include "FreeRTOS_Sockets.h"
#include "FreeRTOS_IP_Private.h"
#include "FreeRTOS_UDP_IP.h"
#include "FreeRTOS_DHCP.h"
#include "NetworkInterface.h"
#include "NetworkBufferManagement.h"
#include "FreeRTOS_TCP_Reception.h"
#include "FreeRTOS_TCP_Transmission.h"
#include "FreeRTOS_TCP_State_Handling.h"
#include "FreeRTOS_TCP_Utils.h"
/* Just make sure the contents doesn't get compiled if TCP is not enabled. */
/* *INDENT-OFF* */
#if( ipconfigUSE_IPv4 != 0 ) && ( ipconfigUSE_TCP == 1 )
/* *INDENT-ON* */
/**
* @brief Handle 'listen' event on the given socket.
*
* @param[in] pxSocket The socket on which the listen occurred.
* @param[in] pxNetworkBuffer The network buffer carrying the packet.
*
* @return If a new socket/duplicate socket is created, then the pointer to
* that socket is returned or else, a NULL pointer is returned.
*/
FreeRTOS_Socket_t * prvHandleListen_IPV4( FreeRTOS_Socket_t * pxSocket,
NetworkBufferDescriptor_t * pxNetworkBuffer )
{
/* Map the ethernet buffer onto a TCPPacket_t struct for easy access to the fields. */
const TCPPacket_t * pxTCPPacket = NULL;
FreeRTOS_Socket_t * pxReturn = NULL;
uint32_t ulInitialSequenceNumber = 0U;
const NetworkEndPoint_t * pxEndpoint = NULL;
BaseType_t xIsNewSocket = pdFALSE;
if( ( pxSocket != NULL ) && ( pxNetworkBuffer != NULL ) )
{
/* Initialize pointers if inputs are valid. */
/* MISRA Ref 11.3.1 [Misaligned access] */
/* More details at: https://github.com/FreeRTOS/FreeRTOS-Plus-TCP/blob/main/MISRA.md#rule-113 */
/* coverity[misra_c_2012_rule_11_3_violation] */
pxTCPPacket = ( ( const TCPPacket_t * ) pxNetworkBuffer->pucEthernetBuffer );
pxEndpoint = pxNetworkBuffer->pxEndPoint;
}
/* Silently discard a SYN packet which was not specifically sent for this node. */
if( ( pxEndpoint != NULL ) && ( pxTCPPacket->xIPHeader.ulDestinationIPAddress == pxEndpoint->ipv4_settings.ulIPAddress ) )
{
/* Assume that a new Initial Sequence Number will be required. Request
* it now in order to fail out if necessary. */
ulInitialSequenceNumber = ulApplicationGetNextSequenceNumber( pxTCPPacket->xIPHeader.ulDestinationIPAddress,
pxSocket->usLocalPort,
pxTCPPacket->xIPHeader.ulSourceIPAddress,
pxTCPPacket->xTCPHeader.usSourcePort );
}
else
{
/* Set the sequence number to 0 to avoid further processing. */
ulInitialSequenceNumber = 0U;
}
/* A pure SYN (without ACK) has come in, create a new socket to answer
* it. */
if( ulInitialSequenceNumber != 0U )
{
if( pxSocket->u.xTCP.bits.bReuseSocket != ipFALSE_BOOL )
{
/* The flag bReuseSocket indicates that the same instance of the
* listening socket should be used for the connection. */
pxReturn = pxSocket;
pxSocket->u.xTCP.bits.bPassQueued = ipTRUE_BOOL;
pxSocket->u.xTCP.pxPeerSocket = pxSocket;
}
else
{
/* The socket does not have the bReuseSocket flag set meaning create a
* new socket when a connection comes in. */
pxReturn = NULL;
if( pxSocket->u.xTCP.usChildCount >= pxSocket->u.xTCP.usBacklog )
{
FreeRTOS_printf( ( "Check: Socket %u already has %u / %u child%s\n",
pxSocket->usLocalPort,
pxSocket->u.xTCP.usChildCount,
pxSocket->u.xTCP.usBacklog,
( pxSocket->u.xTCP.usChildCount == 1U ) ? "" : "ren" ) );
( void ) prvTCPSendReset( pxNetworkBuffer );
}
else
{
FreeRTOS_Socket_t * pxNewSocket = ( FreeRTOS_Socket_t * )
FreeRTOS_socket( FREERTOS_AF_INET, FREERTOS_SOCK_STREAM, FREERTOS_IPPROTO_TCP );
/* MISRA Ref 11.4.1 [Socket error and integer to pointer conversion] */
/* More details at: https://github.com/FreeRTOS/FreeRTOS-Plus-TCP/blob/main/MISRA.md#rule-114 */
/* coverity[misra_c_2012_rule_11_4_violation] */
if( ( pxNewSocket == NULL ) || ( pxNewSocket == FREERTOS_INVALID_SOCKET ) )
{
FreeRTOS_debug_printf( ( "TCP: Listen: new socket failed\n" ) );
( void ) prvTCPSendReset( pxNetworkBuffer );
}
else if( prvTCPSocketCopy( pxNewSocket, pxSocket ) != pdFALSE )
{
/* The socket will be connected immediately, no time for the
* owner to setsockopt's, therefore copy properties of the server
* socket to the new socket. Only the binding might fail (due to
* lack of resources). */
pxReturn = pxNewSocket;
xIsNewSocket = pdTRUE;
}
else
{
/* Copying failed somehow. */
}
}
}
}
if( ( ulInitialSequenceNumber != 0U ) && ( pxReturn != NULL ) )
{
do
{
size_t xCopyLength;
BaseType_t xReturnCreateWindow;
/* Map the byte stream onto the ProtocolHeaders_t for easy access to the fields. */
/* MISRA Ref 11.3.1 [Misaligned access] */
/* More details at: https://github.com/FreeRTOS/FreeRTOS-Plus-TCP/blob/main/MISRA.md#rule-113 */
/* coverity[misra_c_2012_rule_11_3_violation] */
const ProtocolHeaders_t * pxProtocolHeaders = ( ( const ProtocolHeaders_t * )
&( pxNetworkBuffer->pucEthernetBuffer[ ipSIZE_OF_ETH_HEADER + uxIPHeaderSizePacket( pxNetworkBuffer ) ] ) );
/* The endpoint in network buffer must be valid in this condition. */
pxReturn->pxEndPoint = pxNetworkBuffer->pxEndPoint;
pxReturn->bits.bIsIPv6 = ipFALSE_BOOL;
pxReturn->u.xTCP.usRemotePort = FreeRTOS_htons( pxTCPPacket->xTCPHeader.usSourcePort );
pxReturn->u.xTCP.xRemoteIP.ulIP_IPv4 = FreeRTOS_htonl( pxTCPPacket->xIPHeader.ulSourceIPAddress );
pxReturn->u.xTCP.xTCPWindow.ulOurSequenceNumber = ulInitialSequenceNumber;
/* Here is the SYN action. */
pxReturn->u.xTCP.xTCPWindow.rx.ulCurrentSequenceNumber = FreeRTOS_ntohl( pxProtocolHeaders->xTCPHeader.ulSequenceNumber );
prvSocketSetMSS( pxReturn );
xReturnCreateWindow = prvTCPCreateWindow( pxReturn );
/* Did allocating TCP sectors fail? */
if( xReturnCreateWindow != pdPASS )
{
/* Close the socket if it was newly created. */
if( xIsNewSocket == pdTRUE )
{
( void ) vSocketClose( pxReturn );
}
pxReturn = NULL;
break;
}
vTCPStateChange( pxReturn, eSYN_FIRST );
/* Make a copy of the header up to the TCP header. It is needed later
* on, whenever data must be sent to the peer. */
if( pxNetworkBuffer->xDataLength > sizeof( pxReturn->u.xTCP.xPacket.u.ucLastPacket ) )
{
xCopyLength = sizeof( pxReturn->u.xTCP.xPacket.u.ucLastPacket );
}
else
{
xCopyLength = pxNetworkBuffer->xDataLength;
}
( void ) memcpy( ( void * ) pxReturn->u.xTCP.xPacket.u.ucLastPacket,
( const void * ) pxNetworkBuffer->pucEthernetBuffer,
xCopyLength );
} while( ipFALSE_BOOL );
}
return pxReturn;
}
/*-----------------------------------------------------------*/
/* *INDENT-OFF* */
#endif /* ( ipconfigUSE_IPv4 != 0 ) && ( ipconfigUSE_TCP == 1 ) */
/* *INDENT-ON* */
@@ -0,0 +1,234 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
/**
* @file FreeRTOS_TCP_State_Handling_IPv6.c
* @brief Module which handles the TCP protocol state transition for FreeRTOS+TCP.
*
* Endianness: in this module all ports and IP addresses are stored in
* host byte-order, except fields in the IP-packets
*/
/* Standard includes. */
#include <stdint.h>
#include <stdio.h>
/* FreeRTOS includes. */
#include "FreeRTOS.h"
#include "task.h"
#include "queue.h"
#include "semphr.h"
/* FreeRTOS+TCP includes. */
#include "FreeRTOS_IP.h"
#include "FreeRTOS_Sockets.h"
#include "FreeRTOS_IP_Private.h"
#include "FreeRTOS_UDP_IP.h"
#include "FreeRTOS_DHCP.h"
#include "NetworkInterface.h"
#include "NetworkBufferManagement.h"
#include "FreeRTOS_TCP_Reception.h"
#include "FreeRTOS_TCP_Transmission.h"
#include "FreeRTOS_TCP_State_Handling.h"
#include "FreeRTOS_TCP_Utils.h"
/* Just make sure the contents doesn't get compiled if TCP is not enabled. */
/* *INDENT-OFF* */
#if( ipconfigUSE_IPv6 != 0 ) && ( ipconfigUSE_TCP == 1 )
/* *INDENT-ON* */
/**
* @brief Handle 'listen' event on the given socket.
*
* @param[in] pxSocket The socket on which the listen occurred.
* @param[in] pxNetworkBuffer The network buffer carrying the packet.
*
* @return If a new socket/duplicate socket is created, then the pointer to
* that socket is returned or else, a NULL pointer is returned.
*/
FreeRTOS_Socket_t * prvHandleListen_IPV6( FreeRTOS_Socket_t * pxSocket,
NetworkBufferDescriptor_t * pxNetworkBuffer )
{
const TCPPacket_IPv6_t * pxTCPPacket = NULL;
FreeRTOS_Socket_t * pxReturn = NULL;
uint32_t ulInitialSequenceNumber = 0;
BaseType_t xHasSequence = pdFALSE;
BaseType_t xIsNewSocket = pdFALSE;
if( ( pxSocket != NULL ) && ( pxNetworkBuffer != NULL ) )
{
/* Map the ethernet buffer onto a TCPPacket_IPv6_t struct for easy access to the fields. */
/* MISRA Ref 11.3.1 [Misaligned access] */
/* More details at: https://github.com/FreeRTOS/FreeRTOS-Plus-TCP/blob/main/MISRA.md#rule-113 */
/* coverity[misra_c_2012_rule_11_3_violation] */
pxTCPPacket = ( ( const TCPPacket_IPv6_t * ) pxNetworkBuffer->pucEthernetBuffer );
configASSERT( pxNetworkBuffer->pxEndPoint != NULL );
/* Silently discard a SYN packet which was not specifically sent for this node. */
if( memcmp( pxTCPPacket->xIPHeader.xDestinationAddress.ucBytes, pxNetworkBuffer->pxEndPoint->ipv6_settings.xIPAddress.ucBytes, ipSIZE_OF_IPv6_ADDRESS ) == 0 )
{
/* Assume that a new Initial Sequence Number will be required. Request
* it now in order to fail out if necessary. */
if( xApplicationGetRandomNumber( &ulInitialSequenceNumber ) == pdPASS )
{
xHasSequence = pdTRUE;
}
}
}
/* A pure SYN (without ACK) has come in, create a new socket to answer
* it. */
if( xHasSequence != pdFALSE )
{
if( pxSocket->u.xTCP.bits.bReuseSocket != ipFALSE_BOOL )
{
/* The flag bReuseSocket indicates that the same instance of the
* listening socket should be used for the connection. */
pxReturn = pxSocket;
pxSocket->u.xTCP.bits.bPassQueued = ipTRUE_BOOL;
pxSocket->u.xTCP.pxPeerSocket = pxSocket;
}
else
{
/* The socket does not have the bReuseSocket flag set meaning create a
* new socket when a connection comes in. */
pxReturn = NULL;
if( pxSocket->u.xTCP.usChildCount >= pxSocket->u.xTCP.usBacklog )
{
FreeRTOS_printf( ( "Check: Socket %u already has %u / %u child%s\n",
pxSocket->usLocalPort,
pxSocket->u.xTCP.usChildCount,
pxSocket->u.xTCP.usBacklog,
( pxSocket->u.xTCP.usChildCount == 1U ) ? "" : "ren" ) );
( void ) prvTCPSendReset( pxNetworkBuffer );
}
else
{
FreeRTOS_Socket_t * pxNewSocket = ( FreeRTOS_Socket_t * )
FreeRTOS_socket( FREERTOS_AF_INET6, FREERTOS_SOCK_STREAM, FREERTOS_IPPROTO_TCP );
/* MISRA Ref 11.4.1 [Socket error and integer to pointer conversion] */
/* More details at: https://github.com/FreeRTOS/FreeRTOS-Plus-TCP/blob/main/MISRA.md#rule-114 */
/* coverity[misra_c_2012_rule_11_4_violation] */
if( ( pxNewSocket == NULL ) || ( pxNewSocket == FREERTOS_INVALID_SOCKET ) )
{
FreeRTOS_debug_printf( ( "TCP: Listen: new socket failed\n" ) );
( void ) prvTCPSendReset( pxNetworkBuffer );
}
else if( prvTCPSocketCopy( pxNewSocket, pxSocket ) != pdFALSE )
{
/* The socket will be connected immediately, no time for the
* owner to setsockopt's, therefore copy properties of the server
* socket to the new socket. Only the binding might fail (due to
* lack of resources). */
pxReturn = pxNewSocket;
xIsNewSocket = pdTRUE;
}
else
{
/* Copying failed somehow. */
}
}
}
}
if( ( xHasSequence != pdFALSE ) && ( pxReturn != NULL ) )
{
do
{
size_t xCopyLength;
const IPHeader_IPv6_t * pxIPHeader_IPv6;
BaseType_t xReturnCreateWindow;
/* Map the byte stream onto the ProtocolHeaders_t for easy access to the fields. */
/* MISRA Ref 11.3.1 [Misaligned access] */
/* More details at: https://github.com/FreeRTOS/FreeRTOS-Plus-TCP/blob/main/MISRA.md#rule-113 */
/* coverity[misra_c_2012_rule_11_3_violation] */
const ProtocolHeaders_t * pxProtocolHeaders = ( ( const ProtocolHeaders_t * )
&( pxNetworkBuffer->pucEthernetBuffer[ ipSIZE_OF_ETH_HEADER + uxIPHeaderSizePacket( pxNetworkBuffer ) ] ) );
pxReturn->pxEndPoint = pxNetworkBuffer->pxEndPoint;
pxReturn->bits.bIsIPv6 = ipTRUE_BOOL;
/* MISRA Ref 11.3.1 [Misaligned access] */
/* More details at: https://github.com/FreeRTOS/FreeRTOS-Plus-TCP/blob/main/MISRA.md#rule-113 */
/* coverity[misra_c_2012_rule_11_3_violation] */
pxIPHeader_IPv6 = ( ( const IPHeader_IPv6_t * ) &( pxNetworkBuffer->pucEthernetBuffer[ ipSIZE_OF_ETH_HEADER ] ) );
pxReturn->u.xTCP.usRemotePort = FreeRTOS_ntohs( pxTCPPacket->xTCPHeader.usSourcePort );
( void ) memcpy( pxReturn->u.xTCP.xRemoteIP.xIP_IPv6.ucBytes, pxIPHeader_IPv6->xSourceAddress.ucBytes, ipSIZE_OF_IPv6_ADDRESS );
pxReturn->u.xTCP.xTCPWindow.ulOurSequenceNumber = ulInitialSequenceNumber;
/* Here is the SYN action. */
pxReturn->u.xTCP.xTCPWindow.rx.ulCurrentSequenceNumber = FreeRTOS_ntohl( pxProtocolHeaders->xTCPHeader.ulSequenceNumber );
prvSocketSetMSS( pxReturn );
xReturnCreateWindow = prvTCPCreateWindow( pxReturn );
/* Did allocating TCP sectors fail? */
if( xReturnCreateWindow != pdPASS )
{
/* Close the socket if it was newly created. */
if( xIsNewSocket == pdTRUE )
{
( void ) vSocketClose( pxReturn );
}
pxReturn = NULL;
break;
}
vTCPStateChange( pxReturn, eSYN_FIRST );
/* Make a copy of the header up to the TCP header. It is needed later
* on, whenever data must be sent to the peer. */
if( pxNetworkBuffer->xDataLength > sizeof( pxReturn->u.xTCP.xPacket.u.ucLastPacket ) )
{
xCopyLength = sizeof( pxReturn->u.xTCP.xPacket.u.ucLastPacket );
}
else
{
xCopyLength = pxNetworkBuffer->xDataLength;
}
( void ) memcpy( ( void * ) pxReturn->u.xTCP.xPacket.u.ucLastPacket,
( const void * ) pxNetworkBuffer->pucEthernetBuffer,
xCopyLength );
} while( ipFALSE_BOOL );
}
return pxReturn;
}
/*-----------------------------------------------------------*/
/* *INDENT-OFF* */
#endif /* ( ipconfigUSE_IPv6 != 0 ) && ( ipconfigUSE_TCP == 1 ) */
/* *INDENT-ON* */
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,523 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
/**
* @file FreeRTOS_TCP_Transmission_IPv4.c
* @brief Module which prepares the packet to be sent through
* a socket for FreeRTOS+TCP.
* It depends on FreeRTOS_TCP_WIN.c, which handles the TCP windowing
* schemes.
*
* Endianness: in this module all ports and IP addresses are stored in
* host byte-order, except fields in the IP-packets
*/
/* Standard includes. */
#include <stdint.h>
#include <stdio.h>
/* FreeRTOS includes. */
#include "FreeRTOS.h"
#include "task.h"
#include "queue.h"
#include "semphr.h"
/* FreeRTOS+TCP includes. */
#include "FreeRTOS_IP.h"
#include "FreeRTOS_Sockets.h"
#include "FreeRTOS_IP_Private.h"
#include "NetworkInterface.h"
#include "NetworkBufferManagement.h"
#include "FreeRTOS_ARP.h"
#include "FreeRTOSIPConfigDefaults.h"
#include "FreeRTOS_TCP_IP.h"
#include "FreeRTOS_TCP_Reception.h"
#include "FreeRTOS_TCP_Transmission.h"
#include "FreeRTOS_TCP_State_Handling.h"
#include "FreeRTOS_TCP_Utils.h"
/* Just make sure the contents doesn't get compiled if TCP is not enabled. */
/* *INDENT-OFF* */
#if( ipconfigUSE_IPv4 != 0 ) && ( ipconfigUSE_TCP == 1 )
/* *INDENT-ON* */
/*------------------------------------------------------------------------*/
/**
* @brief Return (or send) a packet to the peer. The data is stored in pxBuffer,
* which may either point to a real network buffer or to a TCP socket field
* called 'xTCP.xPacket'. A temporary xNetworkBuffer will be used to pass
* the data to the NIC.
*
* @param[in] pxSocket The socket owning the connection.
* @param[in] pxDescriptor The network buffer descriptor carrying the packet.
* @param[in] ulLen Length of the packet being sent.
* @param[in] xReleaseAfterSend pdTRUE if the ownership of the descriptor is
* transferred to the network interface.
*/
void prvTCPReturnPacket_IPV4( FreeRTOS_Socket_t * pxSocket,
NetworkBufferDescriptor_t * pxDescriptor,
uint32_t ulLen,
BaseType_t xReleaseAfterSend )
{
TCPPacket_t * pxTCPPacket = NULL;
ProtocolHeaders_t * pxProtocolHeaders = NULL;
IPHeader_t * pxIPHeader = NULL;
BaseType_t xDoRelease = xReleaseAfterSend;
EthernetHeader_t * pxEthernetHeader = NULL;
NetworkBufferDescriptor_t * pxNetworkBuffer = pxDescriptor;
NetworkBufferDescriptor_t xTempBuffer;
/* memcpy() helper variables for MISRA Rule 21.15 compliance*/
MACAddress_t xMACAddress;
const void * pvCopySource = NULL;
void * pvCopyDest = NULL;
const size_t uxIPHeaderSize = ipSIZE_OF_IPv4_HEADER;
uint32_t ulDestinationIPAddress;
eResolutionLookupResult_t eResult;
NetworkEndPoint_t * pxEndPoint = NULL;
do
{
/* For sending, a pseudo network buffer will be used, as explained above. */
if( pxNetworkBuffer == NULL )
{
pxNetworkBuffer = &xTempBuffer;
( void ) memset( &xTempBuffer, 0, sizeof( xTempBuffer ) );
#if ( ipconfigUSE_LINKED_RX_MESSAGES != 0 )
{
pxNetworkBuffer->pxNextBuffer = NULL;
}
#endif
pxNetworkBuffer->pucEthernetBuffer = pxSocket->u.xTCP.xPacket.u.ucLastPacket;
pxNetworkBuffer->xDataLength = sizeof( pxSocket->u.xTCP.xPacket.u.ucLastPacket );
xDoRelease = pdFALSE;
}
#if ( ipconfigZERO_COPY_TX_DRIVER != 0 )
{
if( xDoRelease == pdFALSE )
{
/* A zero-copy network driver wants to pass the packet buffer
* to DMA, so a new buffer must be created. */
pxNetworkBuffer = pxDuplicateNetworkBufferWithDescriptor( pxNetworkBuffer, ( size_t ) pxNetworkBuffer->xDataLength );
if( pxNetworkBuffer != NULL )
{
xDoRelease = pdTRUE;
}
else
{
FreeRTOS_debug_printf( ( "prvTCPReturnPacket: duplicate failed\n" ) );
}
}
}
#endif /* ipconfigZERO_COPY_TX_DRIVER */
#ifndef __COVERITY__
if( pxNetworkBuffer != NULL ) /* LCOV_EXCL_BR_LINE the 2nd branch will never be reached */
#endif
{
NetworkInterface_t * pxInterface;
/* MISRA Ref 11.3.1 [Misaligned access] */
/* More details at: https://github.com/FreeRTOS/FreeRTOS-Plus-TCP/blob/main/MISRA.md#rule-113 */
/* coverity[misra_c_2012_rule_11_3_violation] */
pxIPHeader = ( ( IPHeader_t * ) &( pxNetworkBuffer->pucEthernetBuffer[ ipSIZE_OF_ETH_HEADER ] ) );
/* Map the Ethernet buffer onto a TCPPacket_t struct for easy access to the fields. */
/* MISRA Ref 11.3.1 [Misaligned access] */
/* More details at: https://github.com/FreeRTOS/FreeRTOS-Plus-TCP/blob/main/MISRA.md#rule-113 */
/* coverity[misra_c_2012_rule_11_3_violation] */
pxTCPPacket = ( TCPPacket_t * ) pxNetworkBuffer->pucEthernetBuffer;
pxEthernetHeader = ( EthernetHeader_t * ) &( pxTCPPacket->xEthernetHeader );
/* MISRA Ref 11.3.1 [Misaligned access] */
/* More details at: https://github.com/FreeRTOS/FreeRTOS-Plus-TCP/blob/main/MISRA.md#rule-113 */
/* coverity[misra_c_2012_rule_11_3_violation] */
pxProtocolHeaders = ( ProtocolHeaders_t * ) &( pxNetworkBuffer->pucEthernetBuffer[ ipSIZE_OF_ETH_HEADER + uxIPHeaderSize ] );
if( pxNetworkBuffer->pxEndPoint == NULL )
{
prvTCPReturn_SetEndPoint( pxSocket, pxNetworkBuffer, uxIPHeaderSize );
if( pxNetworkBuffer->pxEndPoint == NULL )
{
break;
}
}
/* Fill the packet, using hton translations. */
if( pxSocket != NULL )
{
prvTCPReturn_CheckTCPWindow( pxSocket, pxNetworkBuffer, uxIPHeaderSize );
prvTCPReturn_SetSequenceNumber( pxSocket, pxNetworkBuffer, uxIPHeaderSize, ulLen );
pxIPHeader->ulDestinationIPAddress = FreeRTOS_htonl( pxSocket->u.xTCP.xRemoteIP.ulIP_IPv4 );
pxIPHeader->ulSourceIPAddress = pxNetworkBuffer->pxEndPoint->ipv4_settings.ulIPAddress;
}
else
{
/* Sending data without a socket, probably replying with a RST flag
* Just swap the two sequence numbers. */
vFlip_32( pxProtocolHeaders->xTCPHeader.ulSequenceNumber, pxProtocolHeaders->xTCPHeader.ulAckNr );
vFlip_32( pxIPHeader->ulDestinationIPAddress, pxIPHeader->ulSourceIPAddress );
}
pxIPHeader->ucTimeToLive = ( uint8_t ) ipconfigTCP_TIME_TO_LIVE;
pxIPHeader->usLength = FreeRTOS_htons( ulLen );
/* Just an increasing number. */
pxIPHeader->usIdentification = FreeRTOS_htons( usPacketIdentifier );
usPacketIdentifier++;
/* The stack doesn't support fragments, so the fragment offset field must always be zero.
* The header was never memset to zero, so set both the fragment offset and fragmentation flags in one go.
*/
#if ( ipconfigFORCE_IP_DONT_FRAGMENT != 0 )
pxIPHeader->usFragmentOffset = ipFRAGMENT_FLAGS_DONT_FRAGMENT;
#else
pxIPHeader->usFragmentOffset = 0U;
#endif
#if ( ipconfigDRIVER_INCLUDED_TX_IP_CHECKSUM == 0 )
{
/* calculate the IP header checksum, in case the driver won't do that. */
pxIPHeader->usHeaderChecksum = 0x00U;
pxIPHeader->usHeaderChecksum = usGenerateChecksum( 0U, ( uint8_t * ) &( pxIPHeader->ucVersionHeaderLength ), uxIPHeaderSize );
pxIPHeader->usHeaderChecksum = ( uint16_t ) ~FreeRTOS_htons( pxIPHeader->usHeaderChecksum );
/* calculate the TCP checksum for an outgoing packet. */
( void ) usGenerateProtocolChecksum( ( uint8_t * ) pxTCPPacket, pxNetworkBuffer->xDataLength, pdTRUE );
}
#endif /* if ( ipconfigDRIVER_INCLUDED_TX_IP_CHECKSUM == 0 ) */
vFlip_16( pxProtocolHeaders->xTCPHeader.usSourcePort, pxProtocolHeaders->xTCPHeader.usDestinationPort );
/* Important: tell NIC driver how many bytes must be sent. */
pxNetworkBuffer->xDataLength = ( size_t ) ulLen;
pxNetworkBuffer->xDataLength += ipSIZE_OF_ETH_HEADER;
#if ( ipconfigUSE_LINKED_RX_MESSAGES != 0 )
{
pxNetworkBuffer->pxNextBuffer = NULL;
}
#endif
pvCopySource = &pxEthernetHeader->xSourceAddress;
ulDestinationIPAddress = pxIPHeader->ulDestinationIPAddress;
eResult = eARPGetCacheEntry( &ulDestinationIPAddress, &xMACAddress, &pxEndPoint );
if( eResult == eResolutionCacheHit )
{
pvCopySource = &xMACAddress;
pxNetworkBuffer->pxEndPoint = pxEndPoint;
}
else
{
pvCopySource = &pxEthernetHeader->xSourceAddress;
}
if( pxNetworkBuffer->pxEndPoint == NULL )
{
break;
}
/* Fill in the destination MAC addresses. */
pvCopyDest = &pxEthernetHeader->xDestinationAddress;
( void ) memcpy( pvCopyDest, pvCopySource, sizeof( pxEthernetHeader->xDestinationAddress ) );
/*
* Use helper variables for memcpy() to remain
* compliant with MISRA Rule 21.15. These should be
* optimized away.
*/
pvCopySource = pxNetworkBuffer->pxEndPoint->xMACAddress.ucBytes;
pvCopyDest = &pxEthernetHeader->xSourceAddress;
( void ) memcpy( pvCopyDest, pvCopySource, ( size_t ) ipMAC_ADDRESS_LENGTH_BYTES );
#if ( ipconfigETHERNET_MINIMUM_PACKET_BYTES > 0 )
{
if( pxNetworkBuffer->xDataLength < ( size_t ) ipconfigETHERNET_MINIMUM_PACKET_BYTES )
{
BaseType_t xIndex;
for( xIndex = ( BaseType_t ) pxNetworkBuffer->xDataLength; xIndex < ( BaseType_t ) ipconfigETHERNET_MINIMUM_PACKET_BYTES; xIndex++ )
{
pxNetworkBuffer->pucEthernetBuffer[ xIndex ] = 0U;
}
pxNetworkBuffer->xDataLength = ( size_t ) ipconfigETHERNET_MINIMUM_PACKET_BYTES;
}
}
#endif /* if( ipconfigETHERNET_MINIMUM_PACKET_BYTES > 0 ) */
/* Send! */
iptraceNETWORK_INTERFACE_OUTPUT( pxNetworkBuffer->xDataLength, pxNetworkBuffer->pucEthernetBuffer );
configASSERT( pxNetworkBuffer->pxEndPoint->pxNetworkInterface != NULL );
configASSERT( pxNetworkBuffer->pxEndPoint->pxNetworkInterface->pfOutput != NULL );
pxInterface = pxNetworkBuffer->pxEndPoint->pxNetworkInterface;
( void ) pxInterface->pfOutput( pxInterface, pxNetworkBuffer, xDoRelease );
if( xDoRelease == pdFALSE )
{
/* Swap-back some fields, as pxBuffer probably points to a socket field
* containing the packet header. */
vFlip_16( pxTCPPacket->xTCPHeader.usSourcePort, pxTCPPacket->xTCPHeader.usDestinationPort );
pxIPHeader->ulSourceIPAddress = pxIPHeader->ulDestinationIPAddress;
( void ) memcpy( pxEthernetHeader->xSourceAddress.ucBytes, pxEthernetHeader->xDestinationAddress.ucBytes, ( size_t ) ipMAC_ADDRESS_LENGTH_BYTES );
}
else
{
xDoRelease = pdFALSE;
/* The buffer has been passed to DMA and will be released after use */
}
} /* if( pxNetworkBuffer != NULL ) */
} while( ipFALSE_BOOL );
if( xDoRelease == pdTRUE )
{
vReleaseNetworkBufferAndDescriptor( pxNetworkBuffer );
}
}
/*-----------------------------------------------------------*/
/**
* @brief Let ARP look-up the MAC-address of the peer and initialise the first SYN
* packet.
*
* @param[in] pxSocket The socket owning the TCP connection. The first packet shall
* be created in this socket.
*
* @return pdTRUE: if the packet was successfully created and the first SYN can be sent.
* Else pdFALSE.
*
* @note Connecting sockets have a special state: eCONNECT_SYN. In this phase,
* the Ethernet address of the target will be found using ARP. In case the
* target IP address is not within the netmask, the hardware address of the
* gateway will be used.
*/
BaseType_t prvTCPPrepareConnect_IPV4( FreeRTOS_Socket_t * pxSocket )
{
TCPPacket_t * pxTCPPacket;
IPHeader_t * pxIPHeader;
eResolutionLookupResult_t eReturned;
uint32_t ulRemoteIP;
MACAddress_t xEthAddress;
BaseType_t xReturn = pdTRUE;
uint32_t ulInitialSequenceNumber = 0;
#if ( ipconfigHAS_PRINTF != 0 )
{
/* Only necessary for nicer logging. */
( void ) memset( xEthAddress.ucBytes, 0, sizeof( xEthAddress.ucBytes ) );
}
#endif /* ipconfigHAS_PRINTF != 0 */
ulRemoteIP = FreeRTOS_htonl( pxSocket->u.xTCP.xRemoteIP.ulIP_IPv4 );
/* Determine the ARP cache status for the requested IP address. */
eReturned = eARPGetCacheEntry( &( ulRemoteIP ), &( xEthAddress ), &( pxSocket->pxEndPoint ) );
switch( eReturned )
{
case eResolutionCacheHit: /* An ARP table lookup found a valid entry. */
break; /* We can now prepare the SYN packet. */
case eResolutionCacheMiss: /* An ARP table lookup did not find a valid entry. */
case eResolutionFailed: /* There is no IP address, or an ARP is still in progress. */
default:
/* Count the number of times it could not find the ARP address. */
pxSocket->u.xTCP.ucRepCount++;
FreeRTOS_debug_printf( ( "ARP for %xip (using %xip): rc=%d %02x-%02x-%02x-%02x-%02x-%02x\n",
( unsigned ) pxSocket->u.xTCP.xRemoteIP.ulIP_IPv4,
( unsigned ) FreeRTOS_htonl( ulRemoteIP ),
eReturned,
xEthAddress.ucBytes[ 0 ],
xEthAddress.ucBytes[ 1 ],
xEthAddress.ucBytes[ 2 ],
xEthAddress.ucBytes[ 3 ],
xEthAddress.ucBytes[ 4 ],
xEthAddress.ucBytes[ 5 ] ) );
/* And issue a (new) ARP request */
FreeRTOS_OutputARPRequest( ulRemoteIP );
xReturn = pdFALSE;
break;
}
if( xReturn != pdFALSE )
{
/* Get a difficult-to-predict initial sequence number for this 4-tuple. */
ulInitialSequenceNumber = ulApplicationGetNextSequenceNumber( pxSocket->xLocalAddress.ulIP_IPv4,
pxSocket->usLocalPort,
pxSocket->u.xTCP.xRemoteIP.ulIP_IPv4,
pxSocket->u.xTCP.usRemotePort );
/* Check for a random number generation error. */
if( ulInitialSequenceNumber == 0U )
{
xReturn = pdFALSE;
}
}
if( xReturn != pdFALSE )
{
uint16_t usLength;
/* The MAC-address of the peer (or gateway) has been found,
* now prepare the initial TCP packet and some fields in the socket. Map
* the buffer onto the TCPPacket_t struct to easily access it's field. */
/* MISRA Ref 11.3.1 [Misaligned access] */
/* More details at: https://github.com/FreeRTOS/FreeRTOS-Plus-TCP/blob/main/MISRA.md#rule-113 */
/* coverity[misra_c_2012_rule_11_3_violation] */
pxTCPPacket = ( ( TCPPacket_t * ) pxSocket->u.xTCP.xPacket.u.ucLastPacket );
pxIPHeader = &pxTCPPacket->xIPHeader;
/* reset the retry counter to zero. */
pxSocket->u.xTCP.ucRepCount = 0U;
/* And remember that the connect/SYN data are prepared. */
pxSocket->u.xTCP.bits.bConnPrepared = ipTRUE_BOOL;
/* Now that the Ethernet address is known, the initial packet can be
* prepared. */
( void ) memset( pxSocket->u.xTCP.xPacket.u.ucLastPacket, 0, sizeof( pxSocket->u.xTCP.xPacket.u.ucLastPacket ) );
/* Write the Ethernet address in Source, because it will be swapped by
* prvTCPReturnPacket(). */
( void ) memcpy( ( void * ) ( &pxTCPPacket->xEthernetHeader.xSourceAddress ), ( const void * ) ( &xEthAddress ), sizeof( xEthAddress ) );
/* 'ipIPv4_FRAME_TYPE' is already in network-byte-order. */
pxTCPPacket->xEthernetHeader.usFrameType = ipIPv4_FRAME_TYPE;
pxIPHeader->ucVersionHeaderLength = 0x45U;
usLength = ( uint16_t ) ( sizeof( TCPPacket_t ) - sizeof( pxTCPPacket->xEthernetHeader ) );
pxIPHeader->usLength = FreeRTOS_htons( usLength );
pxIPHeader->ucTimeToLive = ( uint8_t ) ipconfigTCP_TIME_TO_LIVE;
pxIPHeader->ucProtocol = ( uint8_t ) ipPROTOCOL_TCP;
/* Addresses and ports will be stored swapped because prvTCPReturnPacket
* will swap them back while replying. */
pxIPHeader->ulSourceIPAddress = FreeRTOS_htonl( pxSocket->u.xTCP.xRemoteIP.ulIP_IPv4 );
pxTCPPacket->xTCPHeader.usSourcePort = FreeRTOS_htons( pxSocket->u.xTCP.usRemotePort );
pxTCPPacket->xTCPHeader.usDestinationPort = FreeRTOS_htons( pxSocket->usLocalPort );
/* We are actively connecting, so the peer's Initial Sequence Number (ISN)
* isn't known yet. */
pxSocket->u.xTCP.xTCPWindow.rx.ulCurrentSequenceNumber = 0U;
/* Start with ISN (Initial Sequence Number). */
pxSocket->u.xTCP.xTCPWindow.ulOurSequenceNumber = ulInitialSequenceNumber;
/* The TCP header size is 20 bytes, divided by 4 equals 5, which is put in
* the high nibble of the TCP offset field. */
pxTCPPacket->xTCPHeader.ucTCPOffset = 0x50U;
/* Only set the SYN flag. */
pxTCPPacket->xTCPHeader.ucTCPFlags = tcpTCP_FLAG_SYN;
/* Set the value of usMSS for this socket. */
prvSocketSetMSS( pxSocket );
/* The initial sequence numbers at our side are known. Later
* vTCPWindowInit() will be called to fill in the peer's sequence numbers, but
* first wait for a SYN+ACK reply. */
if( prvTCPCreateWindow( pxSocket ) != pdTRUE )
{
xReturn = pdFALSE;
}
}
return xReturn;
}
/*-----------------------------------------------------------*/
/**
* @brief Common code for sending a TCP protocol control packet (i.e. no options, no
* payload, just flags).
*
* @param[in] pxNetworkBuffer The network buffer received from the peer.
* @param[in] ucTCPFlags The flags to determine what kind of packet this is.
*
* @return pdFAIL always indicating that the packet was not consumed.
*/
BaseType_t prvTCPSendSpecialPktHelper_IPV4( NetworkBufferDescriptor_t * pxNetworkBuffer,
uint8_t ucTCPFlags )
{
#if ( ipconfigIGNORE_UNKNOWN_PACKETS == 1 )
/* Configured to ignore unknown packets just suppress a compiler warning. */
( void ) pxNetworkBuffer;
( void ) ucTCPFlags;
#else
{
/* Map the ethernet buffer onto the TCPPacket_t struct for easy access to the fields. */
/* MISRA Ref 11.3.1 [Misaligned access] */
/* More details at: https://github.com/FreeRTOS/FreeRTOS-Plus-TCP/blob/main/MISRA.md#rule-113 */
/* coverity[misra_c_2012_rule_11_3_violation] */
TCPPacket_t * pxTCPPacket = ( ( TCPPacket_t * ) pxNetworkBuffer->pucEthernetBuffer );
const uint32_t ulSendLength =
ipSIZE_OF_IPv4_HEADER + ipSIZE_OF_TCP_HEADER; /* Plus 0 options. */
uint8_t ucFlagsReceived = pxTCPPacket->xTCPHeader.ucTCPFlags;
pxTCPPacket->xTCPHeader.ucTCPFlags = ucTCPFlags;
pxTCPPacket->xTCPHeader.ucTCPOffset = ( ipSIZE_OF_TCP_HEADER ) << 2;
if( ( ucFlagsReceived & tcpTCP_FLAG_SYN ) != 0U )
{
/* A synchronize packet is received. It counts as 1 pseudo byte of data,
* so increase the variable with 1. Before sending a reply, the values of
* 'ulSequenceNumber' and 'ulAckNr' will be swapped. */
uint32_t ulSequenceNumber = FreeRTOS_ntohl( pxTCPPacket->xTCPHeader.ulSequenceNumber );
ulSequenceNumber++;
pxTCPPacket->xTCPHeader.ulSequenceNumber = FreeRTOS_htonl( ulSequenceNumber );
}
prvTCPReturnPacket( NULL, pxNetworkBuffer, ulSendLength, pdFALSE );
}
#endif /* !ipconfigIGNORE_UNKNOWN_PACKETS */
/* The packet was not consumed. */
return pdFAIL;
}
/*-----------------------------------------------------------*/
/* *INDENT-OFF* */
#endif /* ( ipconfigUSE_IPv4 != 0 ) && ( ipconfigUSE_TCP == 1 ) */
/* *INDENT-ON* */
@@ -0,0 +1,539 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
/**
* @file FreeRTOS_TCP_Transmission_IPv6.c
* @brief Module which prepares the packet to be sent through
* a socket for FreeRTOS+TCP.
* It depends on FreeRTOS_TCP_WIN.c, which handles the TCP windowing
* schemes.
*
* Endianness: in this module all ports and IP addresses are stored in
* host byte-order, except fields in the IP-packets
*/
/* Standard includes. */
#include <stdint.h>
#include <stdio.h>
/* FreeRTOS includes. */
#include "FreeRTOS.h"
#include "task.h"
#include "queue.h"
#include "semphr.h"
/* FreeRTOS+TCP includes. */
#include "FreeRTOS_IP.h"
#include "FreeRTOS_Sockets.h"
#include "FreeRTOS_IP_Private.h"
#include "NetworkInterface.h"
#include "NetworkBufferManagement.h"
#include "FreeRTOSIPConfigDefaults.h"
#include "FreeRTOS_ND.h"
#include "FreeRTOS_TCP_IP.h"
#include "FreeRTOS_TCP_Reception.h"
#include "FreeRTOS_TCP_Transmission.h"
#include "FreeRTOS_TCP_State_Handling.h"
#include "FreeRTOS_TCP_Utils.h"
/* Just make sure the contents doesn't get compiled if TCP is not enabled. */
/* *INDENT-OFF* */
#if( ipconfigUSE_IPv6 != 0 ) && ( ipconfigUSE_TCP == 1 )
/* *INDENT-ON* */
/*------------------------------------------------------------------------*/
/**
* @brief Return (or send) a packet to the peer. The data is stored in pxBuffer,
* which may either point to a real network buffer or to a TCP socket field
* called 'xTCP.xPacket'. A temporary xNetworkBuffer will be used to pass
* the data to the NIC.
*
* @param[in] pxSocket The socket owning the connection.
* @param[in] pxDescriptor The network buffer descriptor carrying the packet.
* @param[in] ulLen Length of the packet being sent.
* @param[in] xReleaseAfterSend pdTRUE if the ownership of the descriptor is
* transferred to the network interface.
*/
void prvTCPReturnPacket_IPV6( FreeRTOS_Socket_t * pxSocket,
NetworkBufferDescriptor_t * pxDescriptor,
uint32_t ulLen,
BaseType_t xReleaseAfterSend )
{
TCPPacket_IPv6_t * pxTCPPacket = NULL;
ProtocolHeaders_t * pxProtocolHeaders = NULL;
IPHeader_IPv6_t * pxIPHeader = NULL;
BaseType_t xDoRelease = xReleaseAfterSend;
EthernetHeader_t * pxEthernetHeader = NULL;
NetworkBufferDescriptor_t * pxNetworkBuffer = pxDescriptor;
NetworkBufferDescriptor_t xTempBuffer;
/* memcpy() helper variables for MISRA Rule 21.15 compliance*/
MACAddress_t xMACAddress;
const void * pvCopySource = NULL;
void * pvCopyDest = NULL;
const size_t uxIPHeaderSize = ipSIZE_OF_IPv6_HEADER;
IPv6_Address_t xDestinationIPAddress;
do
{
/* Use do/while to be able to break out of the flow */
if( ( pxNetworkBuffer == NULL ) && ( pxSocket == NULL ) )
{
/* Either 'pxNetworkBuffer' or 'pxSocket' should be defined. */
break;
}
/* For sending, a pseudo network buffer will be used, as explained above. */
if( pxNetworkBuffer == NULL )
{
pxNetworkBuffer = &xTempBuffer;
( void ) memset( &xTempBuffer, 0, sizeof( xTempBuffer ) );
#if ( ipconfigUSE_LINKED_RX_MESSAGES != 0 )
{
pxNetworkBuffer->pxNextBuffer = NULL;
}
#endif
pxNetworkBuffer->pucEthernetBuffer = pxSocket->u.xTCP.xPacket.u.ucLastPacket;
pxNetworkBuffer->xDataLength = sizeof( pxSocket->u.xTCP.xPacket.u.ucLastPacket );
xDoRelease = pdFALSE;
}
#if ( ipconfigZERO_COPY_TX_DRIVER != 0 )
{
if( xDoRelease == pdFALSE )
{
/* A zero-copy network driver wants to pass the packet buffer
* to DMA, so a new buffer must be created. */
pxNetworkBuffer = pxDuplicateNetworkBufferWithDescriptor( pxNetworkBuffer, ( size_t ) pxNetworkBuffer->xDataLength );
if( pxNetworkBuffer != NULL )
{
xDoRelease = pdTRUE;
}
else
{
FreeRTOS_debug_printf( ( "prvTCPReturnPacket: duplicate failed\n" ) );
}
}
}
#endif /* ipconfigZERO_COPY_TX_DRIVER */
#ifndef __COVERITY__
if( pxNetworkBuffer != NULL ) /* LCOV_EXCL_BR_LINE the 2nd branch will never be reached */
#endif
{
eResolutionLookupResult_t eResult;
NetworkInterface_t * pxInterface;
configASSERT( pxNetworkBuffer->pucEthernetBuffer != NULL );
/* MISRA Ref 11.3.1 [Misaligned access] */
/* More details at: https://github.com/FreeRTOS/FreeRTOS-Plus-TCP/blob/main/MISRA.md#rule-113 */
/* coverity[misra_c_2012_rule_11_3_violation] */
pxIPHeader = ( ( IPHeader_IPv6_t * ) &( pxNetworkBuffer->pucEthernetBuffer[ ipSIZE_OF_ETH_HEADER ] ) );
/* Map the Ethernet buffer onto a TCPPacket_t struct for easy access to the fields. */
/* MISRA Ref 11.3.1 [Misaligned access] */
/* More details at: https://github.com/FreeRTOS/FreeRTOS-Plus-TCP/blob/main/MISRA.md#rule-113 */
/* coverity[misra_c_2012_rule_11_3_violation] */
pxTCPPacket = ( TCPPacket_IPv6_t * ) pxNetworkBuffer->pucEthernetBuffer;
pxEthernetHeader = ( EthernetHeader_t * ) &( pxTCPPacket->xEthernetHeader );
/* MISRA Ref 11.3.1 [Misaligned access] */
/* More details at: https://github.com/FreeRTOS/FreeRTOS-Plus-TCP/blob/main/MISRA.md#rule-113 */
/* coverity[misra_c_2012_rule_11_3_violation] */
pxProtocolHeaders = ( ProtocolHeaders_t * ) &( pxNetworkBuffer->pucEthernetBuffer[ ipSIZE_OF_ETH_HEADER + uxIPHeaderSize ] );
if( pxNetworkBuffer->pxEndPoint == NULL )
{
prvTCPReturn_SetEndPoint( pxSocket, pxNetworkBuffer, uxIPHeaderSize );
if( pxNetworkBuffer->pxEndPoint == NULL )
{
if( xDoRelease != pdFALSE )
{
vReleaseNetworkBufferAndDescriptor( pxNetworkBuffer );
}
pxNetworkBuffer = NULL;
break;
}
}
/* Fill the packet, swapping from- and to-addresses. */
if( pxSocket != NULL )
{
prvTCPReturn_CheckTCPWindow( pxSocket, pxNetworkBuffer, uxIPHeaderSize );
prvTCPReturn_SetSequenceNumber( pxSocket, pxNetworkBuffer, uxIPHeaderSize, ulLen );
( void ) memcpy( pxIPHeader->xDestinationAddress.ucBytes, pxSocket->u.xTCP.xRemoteIP.xIP_IPv6.ucBytes, ipSIZE_OF_IPv6_ADDRESS );
( void ) memcpy( pxIPHeader->xSourceAddress.ucBytes, pxNetworkBuffer->pxEndPoint->ipv6_settings.xIPAddress.ucBytes, ipSIZE_OF_IPv6_ADDRESS );
}
else
{
IPv6_Address_t xTempAddress;
/* Sending data without a socket, probably replying with a RST flag
* Just swap the two sequence numbers. */
vFlip_32( pxProtocolHeaders->xTCPHeader.ulSequenceNumber, pxProtocolHeaders->xTCPHeader.ulAckNr );
( void ) memcpy( xTempAddress.ucBytes, pxIPHeader->xDestinationAddress.ucBytes, ipSIZE_OF_IPv6_ADDRESS );
( void ) memcpy( pxIPHeader->xDestinationAddress.ucBytes, pxIPHeader->xSourceAddress.ucBytes, ipSIZE_OF_IPv6_ADDRESS );
( void ) memcpy( pxIPHeader->xSourceAddress.ucBytes, xTempAddress.ucBytes, ipSIZE_OF_IPv6_ADDRESS );
}
/* In IPv6, the "payload length" does not include the size of the IP-header */
pxIPHeader->usPayloadLength = FreeRTOS_htons( ulLen - sizeof( IPHeader_IPv6_t ) );
#if ( ipconfigDRIVER_INCLUDED_TX_IP_CHECKSUM == 0 )
{
/* calculate the TCP checksum for an outgoing packet. */
uint32_t ulTotalLength = ulLen + ipSIZE_OF_ETH_HEADER;
( void ) usGenerateProtocolChecksum( ( uint8_t * ) pxNetworkBuffer->pucEthernetBuffer, ulTotalLength, pdTRUE );
}
#endif /* ipconfigDRIVER_INCLUDED_TX_IP_CHECKSUM == 0 */
vFlip_16( pxProtocolHeaders->xTCPHeader.usSourcePort, pxProtocolHeaders->xTCPHeader.usDestinationPort );
/* Important: tell NIC driver how many bytes must be sent. */
pxNetworkBuffer->xDataLength = ( size_t ) ulLen;
pxNetworkBuffer->xDataLength += ipSIZE_OF_ETH_HEADER;
#if ( ipconfigUSE_LINKED_RX_MESSAGES != 0 )
{
pxNetworkBuffer->pxNextBuffer = NULL;
}
#endif
( void ) memcpy( xDestinationIPAddress.ucBytes, pxIPHeader->xDestinationAddress.ucBytes, ipSIZE_OF_IPv6_ADDRESS );
eResult = eNDGetCacheEntry( &xDestinationIPAddress, &xMACAddress, &( pxNetworkBuffer->pxEndPoint ) );
if( eResult == eResolutionCacheHit )
{
pvCopySource = &xMACAddress;
}
else
{
pvCopySource = &pxEthernetHeader->xSourceAddress;
}
/* Fill in the destination MAC addresses. */
pvCopyDest = &pxEthernetHeader->xDestinationAddress;
( void ) memcpy( pvCopyDest, pvCopySource, sizeof( pxEthernetHeader->xDestinationAddress ) );
/*
* Use helper variables for memcpy() to remain
* compliant with MISRA Rule 21.15. These should be
* optimized away.
*/
pvCopySource = pxNetworkBuffer->pxEndPoint->xMACAddress.ucBytes;
pvCopyDest = &pxEthernetHeader->xSourceAddress;
( void ) memcpy( pvCopyDest, pvCopySource, ( size_t ) ipMAC_ADDRESS_LENGTH_BYTES );
#if ( ipconfigETHERNET_MINIMUM_PACKET_BYTES > 0 )
{
if( pxNetworkBuffer->xDataLength < ( size_t ) ipconfigETHERNET_MINIMUM_PACKET_BYTES )
{
BaseType_t xIndex;
for( xIndex = ( BaseType_t ) pxNetworkBuffer->xDataLength; xIndex < ( BaseType_t ) ipconfigETHERNET_MINIMUM_PACKET_BYTES; xIndex++ )
{
pxNetworkBuffer->pucEthernetBuffer[ xIndex ] = 0U;
}
pxNetworkBuffer->xDataLength = ( size_t ) ipconfigETHERNET_MINIMUM_PACKET_BYTES;
}
}
#endif /* if( ipconfigETHERNET_MINIMUM_PACKET_BYTES > 0 ) */
/* Send! */
iptraceNETWORK_INTERFACE_OUTPUT( pxNetworkBuffer->xDataLength, pxNetworkBuffer->pucEthernetBuffer );
configASSERT( pxNetworkBuffer->pxEndPoint->pxNetworkInterface != NULL );
configASSERT( pxNetworkBuffer->pxEndPoint->pxNetworkInterface->pfOutput != NULL );
pxInterface = pxNetworkBuffer->pxEndPoint->pxNetworkInterface;
( void ) pxInterface->pfOutput( pxInterface, pxNetworkBuffer, xDoRelease );
if( xDoRelease == pdFALSE )
{
/* Swap-back some fields, as pxBuffer probably points to a socket field
* containing the packet header. */
vFlip_16( pxTCPPacket->xTCPHeader.usSourcePort, pxTCPPacket->xTCPHeader.usDestinationPort );
( void ) memcpy( pxIPHeader->xSourceAddress.ucBytes, pxIPHeader->xDestinationAddress.ucBytes, ipSIZE_OF_IPv6_ADDRESS );
}
else
{
/* Nothing to do: the buffer has been passed to DMA and will be released after use */
}
} /* if( pxNetworkBuffer != NULL ) */
} while( ipFALSE_BOOL );
}
/*-----------------------------------------------------------*/
/**
* @brief Let ND look-up the MAC-address of the peer and initialise the first SYN
* packet.
*
* @param[in] pxSocket The socket owning the TCP connection. The first packet shall
* be created in this socket.
*
* @return pdTRUE: if the packet was successfully created and the first SYN can be sent.
* Else pdFALSE.
*
* @note Connecting sockets have a special state: eCONNECT_SYN. In this phase,
* the Ethernet address of the target will be found using ND. In case the
* target IP address is not within the netmask, the hardware address of the
* gateway will be used.
*/
BaseType_t prvTCPPrepareConnect_IPV6( FreeRTOS_Socket_t * pxSocket )
{
TCPPacket_IPv6_t * pxTCPPacket = NULL;
IPHeader_IPv6_t * pxIPHeader = NULL;
eResolutionLookupResult_t eReturned;
IP_Address_t xRemoteIP;
MACAddress_t xEthAddress;
BaseType_t xReturn = pdTRUE;
uint32_t ulInitialSequenceNumber = 0;
ProtocolHeaders_t * pxProtocolHeaders = NULL;
NetworkEndPoint_t * pxEndPoint = NULL;
#if ( ipconfigHAS_PRINTF != 0 )
{
/* Only necessary for nicer logging. */
( void ) memset( xEthAddress.ucBytes, 0, sizeof( xEthAddress.ucBytes ) );
}
#endif /* ipconfigHAS_PRINTF != 0 */
( void ) memset( xRemoteIP.xIP_IPv6.ucBytes, 0, ipSIZE_OF_IPv6_ADDRESS );
( void ) memcpy( xRemoteIP.xIP_IPv6.ucBytes, pxSocket->u.xTCP.xRemoteIP.xIP_IPv6.ucBytes, ipSIZE_OF_IPv6_ADDRESS );
eReturned = eNDGetCacheEntry( &( xRemoteIP.xIP_IPv6 ), &( xEthAddress ), &( pxEndPoint ) );
FreeRTOS_printf( ( "eNDGetCacheEntry: %d with end-point %p\n", eReturned, ( void * ) pxEndPoint ) );
if( pxEndPoint != NULL )
{
pxSocket->pxEndPoint = pxEndPoint;
}
/* MISRA Ref 11.3.1 [Misaligned access] */
/* More details at: https://github.com/FreeRTOS/FreeRTOS-Plus-TCP/blob/main/MISRA.md#rule-113 */
/* coverity[misra_c_2012_rule_11_3_violation] */
pxProtocolHeaders = ( ( ProtocolHeaders_t * )
&( pxSocket->u.xTCP.xPacket.u.ucLastPacket[ ipSIZE_OF_ETH_HEADER + uxIPHeaderSizeSocket( pxSocket ) ] ) );
switch( eReturned )
{
case eResolutionCacheHit: /* An ND table lookup found a valid entry. */
break; /* We can now prepare the SYN packet. */
case eResolutionCacheMiss: /* An ND table lookup did not find a valid entry. */
case eResolutionFailed: /* There is no IP address, or an ND is still in progress. */
default:
/* Count the number of times it could not find the ND address. */
pxSocket->u.xTCP.ucRepCount++;
FreeRTOS_printf( ( "Looking up %pip with%s end-point\n", ( void * ) xRemoteIP.xIP_IPv6.ucBytes, ( pxEndPoint != NULL ) ? "" : "out" ) );
if( pxEndPoint != NULL )
{
size_t uxNeededSize;
NetworkBufferDescriptor_t * pxNetworkBuffer;
uxNeededSize = ipSIZE_OF_ETH_HEADER + ipSIZE_OF_IPv6_HEADER + sizeof( ICMPHeader_IPv6_t );
pxNetworkBuffer = pxGetNetworkBufferWithDescriptor( uxNeededSize, 0U );
if( pxNetworkBuffer != NULL )
{
pxNetworkBuffer->pxEndPoint = pxEndPoint;
vNDSendNeighbourSolicitation( pxNetworkBuffer, &( xRemoteIP.xIP_IPv6 ) );
}
}
xReturn = pdFALSE;
break;
}
if( xReturn != pdFALSE )
{
/* Get a difficult-to-predict initial sequence number for this 4-tuple. */
ulInitialSequenceNumber = ulApplicationGetNextSequenceNumber( pxSocket->xLocalAddress.ulIP_IPv4,
pxSocket->usLocalPort,
pxSocket->u.xTCP.xRemoteIP.ulIP_IPv4,
pxSocket->u.xTCP.usRemotePort );
/* Check for a random number generation error. */
if( ulInitialSequenceNumber == 0U )
{
xReturn = pdFALSE;
}
}
if( xReturn != pdFALSE )
{
/* The MAC-address of the peer (or gateway) has been found,
* now prepare the initial TCP packet and some fields in the socket. Map
* the buffer onto the TCPPacket_IPv6_t struct to easily access it's field. */
/* MISRA Ref 11.3.1 [Misaligned access] */
/* More details at: https://github.com/FreeRTOS/FreeRTOS-Plus-TCP/blob/main/MISRA.md#rule-113 */
/* coverity[misra_c_2012_rule_11_3_violation] */
pxTCPPacket = ( ( TCPPacket_IPv6_t * ) pxSocket->u.xTCP.xPacket.u.ucLastPacket );
pxIPHeader = &( pxTCPPacket->xIPHeader );
/* reset the retry counter to zero. */
pxSocket->u.xTCP.ucRepCount = 0U;
/* And remember that the connect/SYN data are prepared. */
pxSocket->u.xTCP.bits.bConnPrepared = ipTRUE_BOOL;
/* Now that the Ethernet address is known, the initial packet can be
* prepared. */
( void ) memset( pxSocket->u.xTCP.xPacket.u.ucLastPacket, 0, sizeof( pxSocket->u.xTCP.xPacket.u.ucLastPacket ) );
/* Write the Ethernet address in Source, because it will be swapped by
* prvTCPReturnPacket(). */
( void ) memcpy( ( void * ) ( &( pxTCPPacket->xEthernetHeader.xSourceAddress ) ), ( const void * ) ( &xEthAddress ), sizeof( xEthAddress ) );
if( pxSocket->bits.bIsIPv6 != pdFALSE_UNSIGNED )
{
/* 'ipIPv4_FRAME_TYPE' is already in network-byte-order. */
pxTCPPacket->xEthernetHeader.usFrameType = ipIPv6_FRAME_TYPE;
pxIPHeader->ucVersionTrafficClass = ( uint8_t ) 0x60U;
pxIPHeader->ucTrafficClassFlow = ( uint8_t ) 0x00;
pxIPHeader->usFlowLabel = ( uint16_t ) 0x0000U;
pxIPHeader->usPayloadLength = FreeRTOS_htons( sizeof( TCPHeader_t ) );
pxIPHeader->ucNextHeader = ( uint8_t ) ipPROTOCOL_TCP;
pxIPHeader->ucHopLimit = 128;
/* The Source and Destination addresses will be swapped later. */
( void ) memcpy( pxIPHeader->xSourceAddress.ucBytes, pxSocket->u.xTCP.xRemoteIP.xIP_IPv6.ucBytes, sizeof( pxIPHeader->xSourceAddress.ucBytes ) );
( void ) memcpy( pxIPHeader->xDestinationAddress.ucBytes, pxSocket->xLocalAddress.xIP_IPv6.ucBytes, sizeof( pxIPHeader->xDestinationAddress.ucBytes ) );
pxEndPoint = pxSocket->pxEndPoint;
}
}
if( pxEndPoint != NULL )
{
pxSocket->pxEndPoint = pxEndPoint;
pxProtocolHeaders->xTCPHeader.usSourcePort = FreeRTOS_htons( pxSocket->u.xTCP.usRemotePort );
pxProtocolHeaders->xTCPHeader.usDestinationPort = FreeRTOS_htons( pxSocket->usLocalPort );
/* We are actively connecting, so the peer's Initial Sequence Number (ISN)
* isn't known yet. */
pxSocket->u.xTCP.xTCPWindow.rx.ulCurrentSequenceNumber = 0U;
/* Start with ISN (Initial Sequence Number). */
pxSocket->u.xTCP.xTCPWindow.ulOurSequenceNumber = ulInitialSequenceNumber;
/* The TCP header size is 20 bytes, divided by 4 equals 5, which is put in
* the high nibble of the TCP offset field. */
pxProtocolHeaders->xTCPHeader.ucTCPOffset = 0x50U;
/* Only set the SYN flag. */
pxProtocolHeaders->xTCPHeader.ucTCPFlags = tcpTCP_FLAG_SYN;
/* Set the value of usMSS for this socket. */
prvSocketSetMSS( pxSocket );
/* The initial sequence numbers at our side are known. Later
* vTCPWindowInit() will be called to fill in the peer's sequence numbers, but
* first wait for a SYN+ACK reply. */
if( prvTCPCreateWindow( pxSocket ) != pdTRUE )
{
xReturn = pdFAIL;
}
}
else
{
FreeRTOS_printf( ( "prvTCPPrepareConnect: No pxEndPoint yet?\n" ) );
xReturn = pdFAIL;
}
return xReturn;
}
/*-----------------------------------------------------------*/
/**
* @brief Common code for sending a TCP protocol control packet (i.e. no options, no
* payload, just flags).
*
* @param[in] pxNetworkBuffer The network buffer received from the peer.
* @param[in] ucTCPFlags The flags to determine what kind of packet this is.
*
* @return pdFAIL always indicating that the packet was not consumed.
*/
BaseType_t prvTCPSendSpecialPktHelper_IPV6( NetworkBufferDescriptor_t * pxNetworkBuffer,
uint8_t ucTCPFlags )
{
#if ( ipconfigIGNORE_UNKNOWN_PACKETS == 1 )
/* Configured to ignore unknown packets just suppress a compiler warning. */
( void ) pxNetworkBuffer;
( void ) ucTCPFlags;
#else
{
/* Map the ethernet buffer onto the TCPPacket_t struct for easy access to the fields. */
/* MISRA Ref 11.3.1 [Misaligned access] */
/* More details at: https://github.com/FreeRTOS/FreeRTOS-Plus-TCP/blob/main/MISRA.md#rule-113 */
/* coverity[misra_c_2012_rule_11_3_violation] */
TCPPacket_IPv6_t * pxTCPPacket = ( ( TCPPacket_IPv6_t * ) pxNetworkBuffer->pucEthernetBuffer );
const uint32_t ulSendLength =
ipSIZE_OF_IPv6_HEADER + ipSIZE_OF_TCP_HEADER; /* Plus 0 options. */
uint8_t ucFlagsReceived = pxTCPPacket->xTCPHeader.ucTCPFlags;
pxTCPPacket->xTCPHeader.ucTCPFlags = ucTCPFlags;
pxTCPPacket->xTCPHeader.ucTCPOffset = ( ipSIZE_OF_TCP_HEADER ) << 2;
if( ( ucFlagsReceived & tcpTCP_FLAG_SYN ) != 0U )
{
/* A synchronize packet is received. It counts as 1 pseudo byte of data,
* so increase the variable with 1. Before sending a reply, the values of
* 'ulSequenceNumber' and 'ulAckNr' will be swapped. */
uint32_t ulSequenceNumber = FreeRTOS_ntohl( pxTCPPacket->xTCPHeader.ulSequenceNumber );
ulSequenceNumber++;
pxTCPPacket->xTCPHeader.ulSequenceNumber = FreeRTOS_htonl( ulSequenceNumber );
}
prvTCPReturnPacket( NULL, pxNetworkBuffer, ulSendLength, pdFALSE );
}
#endif /* !ipconfigIGNORE_UNKNOWN_PACKETS */
/* The packet was not consumed. */
return pdFAIL;
}
/*-----------------------------------------------------------*/
/* *INDENT-OFF* */
#endif /* ( ipconfigUSE_IPv6 != 0 ) && ( ipconfigUSE_TCP == 1 ) */
/* *INDENT-ON* */
@@ -0,0 +1,116 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
/**
* @file FreeRTOS_TCP_Utils.c
* @brief Module contains utility functions used by FreeRTOS+TCP module.
*
* Endianness: in this module all ports and IP addresses are stored in
* host byte-order, except fields in the IP-packets
*/
/* Standard includes. */
#include <stdint.h>
#include <stdio.h>
/* FreeRTOS includes. */
#include "FreeRTOS.h"
#include "task.h"
/* FreeRTOS+TCP includes. */
#include "FreeRTOS_IP.h"
#include "FreeRTOS_IP_Private.h"
#include "FreeRTOS_Routing.h"
#include "FreeRTOS_TCP_Utils.h"
/* Just make sure the contents doesn't get compiled if TCP is not enabled. */
#if ipconfigUSE_TCP == 1
/* For logging and debugging: make a string showing the TCP flags
*/
#if ( ipconfigHAS_DEBUG_PRINTF != 0 )
static char retString[ 10 ];
/**
* @brief Print out the value of flags in a human readable manner.
*
* @param[in] xFlags The TCP flags.
*
* @return The string containing the flags.
*/
const char * prvTCPFlagMeaning( UBaseType_t xFlags )
{
size_t uxFlags = ( size_t ) xFlags;
( void ) snprintf( retString,
sizeof( retString ), "%c%c%c%c%c%c%c%c",
( ( uxFlags & ( size_t ) tcpTCP_FLAG_FIN ) != 0 ) ? 'F' : '.', /* 0x0001: No more data from sender */
( ( uxFlags & ( size_t ) tcpTCP_FLAG_SYN ) != 0 ) ? 'S' : '.', /* 0x0002: Synchronize sequence numbers */
( ( uxFlags & ( size_t ) tcpTCP_FLAG_RST ) != 0 ) ? 'R' : '.', /* 0x0004: Reset the connection */
( ( uxFlags & ( size_t ) tcpTCP_FLAG_PSH ) != 0 ) ? 'P' : '.', /* 0x0008: Push function: please push buffered data to the recv application */
( ( uxFlags & ( size_t ) tcpTCP_FLAG_ACK ) != 0 ) ? 'A' : '.', /* 0x0010: Acknowledgment field is significant */
( ( uxFlags & ( size_t ) tcpTCP_FLAG_URG ) != 0 ) ? 'U' : '.', /* 0x0020: Urgent pointer field is significant */
( ( uxFlags & ( size_t ) tcpTCP_FLAG_ECN ) != 0 ) ? 'E' : '.', /* 0x0040: ECN-Echo */
( ( uxFlags & ( size_t ) tcpTCP_FLAG_CWR ) != 0 ) ? 'C' : '.' ); /* 0x0080: Congestion Window Reduced */
return retString;
}
#endif /* #if ( ipconfigHAS_DEBUG_PRINTF != 0 ) */
/*-----------------------------------------------------------*/
/**
* @brief Set the MSS (Maximum segment size) associated with the given socket.
*
* @param[in] pxSocket The socket whose MSS is to be set.
*/
void prvSocketSetMSS( FreeRTOS_Socket_t * pxSocket )
{
switch( pxSocket->bits.bIsIPv6 ) /* LCOV_EXCL_BR_LINE */
{
#if ( ipconfigUSE_IPv4 != 0 )
case ipFALSE_BOOL:
prvSocketSetMSS_IPV4( pxSocket );
break;
#endif /* ( ipconfigUSE_IPv4 != 0 ) */
#if ( ipconfigUSE_IPv6 != 0 )
case ipTRUE_BOOL:
prvSocketSetMSS_IPV6( pxSocket );
break;
#endif /* ( ipconfigUSE_IPv6 != 0 ) */
default: /* LCOV_EXCL_LINE */
/* Shouldn't reach here */
/* MISRA 16.4 Compliance */
break; /* LCOV_EXCL_LINE */
}
}
/*-----------------------------------------------------------*/
#endif /* ipconfigUSE_TCP == 1 */
@@ -0,0 +1,93 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
/**
* @file FreeRTOS_TCP_Utils_IPv4.c
* @brief Module contains utility functions used by FreeRTOS+TCP module.
*
* Endianness: in this module all ports and IP addresses are stored in
* host byte-order, except fields in the IP-packets
*/
/* Standard includes. */
#include <stdint.h>
#include <stdio.h>
/* FreeRTOS includes. */
#include "FreeRTOS.h"
/* FreeRTOS+TCP includes. */
#include "FreeRTOS_IP.h"
#include "FreeRTOS_IP_Private.h"
#include "FreeRTOS_TCP_Utils.h"
/* Just make sure the contents doesn't get compiled if TCP is not enabled. */
/* *INDENT-OFF* */
#if( ipconfigUSE_IPv4 != 0 ) && ( ipconfigUSE_TCP == 1 )
/* *INDENT-ON* */
/**
* @brief Set the MSS (Maximum segment size) associated with the given socket.
*
* @param[in] pxSocket The socket whose MSS is to be set.
*/
void prvSocketSetMSS_IPV4( FreeRTOS_Socket_t * pxSocket )
{
uint32_t ulMSS = ipconfigTCP_MSS;
const NetworkEndPoint_t * pxEndPoint = pxSocket->pxEndPoint;
if( pxEndPoint != NULL )
{
/* Do not allow MSS smaller than tcpMINIMUM_SEGMENT_LENGTH. */
#if ( ipconfigTCP_MSS >= tcpMINIMUM_SEGMENT_LENGTH )
{
ulMSS = ipconfigTCP_MSS;
}
#else
{
ulMSS = tcpMINIMUM_SEGMENT_LENGTH;
}
#endif
/* Check if the remote IP-address belongs to the same netmask. */
if( ( ( FreeRTOS_ntohl( pxSocket->u.xTCP.xRemoteIP.ulIP_IPv4 ) ^ pxEndPoint->ipv4_settings.ulIPAddress ) & pxEndPoint->ipv4_settings.ulNetMask ) != 0U )
{
/* Data for this peer will pass through a router, and maybe through
* the internet. Limit the MSS to 1400 bytes or less. */
ulMSS = FreeRTOS_min_uint32( ( uint32_t ) tcpREDUCED_MSS_THROUGH_INTERNET, ulMSS );
}
}
FreeRTOS_debug_printf( ( "prvSocketSetMSS: %u bytes for %xip port %u\n", ( unsigned ) ulMSS, ( unsigned ) pxSocket->u.xTCP.xRemoteIP.ulIP_IPv4, pxSocket->u.xTCP.usRemotePort ) );
pxSocket->u.xTCP.usMSS = ( uint16_t ) ulMSS;
}
/*-----------------------------------------------------------*/
/* *INDENT-OFF* */
#endif /* ( ipconfigUSE_IPv4 != 0 ) && ( ipconfigUSE_TCP == 1 ) */
/* *INDENT-ON* */
@@ -0,0 +1,115 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
/**
* @file FreeRTOS_TCP_Utils_IPv6.c
* @brief Module contains utility functions used by FreeRTOS+TCP module.
*
* Endianness: in this module all ports and IP addresses are stored in
* host byte-order, except fields in the IP-packets
*/
/* Standard includes. */
#include <stdint.h>
#include <stdio.h>
/* FreeRTOS includes. */
#include "FreeRTOS.h"
/* FreeRTOS+TCP includes. */
#include "FreeRTOS_IP.h"
#include "FreeRTOS_IP_Private.h"
#include "FreeRTOS_TCP_Utils.h"
/* Just make sure the contents doesn't get compiled if TCP is not enabled. */
/* *INDENT-OFF* */
#if( ipconfigUSE_IPv6 != 0 ) && ( ipconfigUSE_TCP == 1 )
/* *INDENT-ON* */
/**
* @brief Set the MSS (Maximum segment size) associated with the given socket.
*
* @param[in] pxSocket The socket whose MSS is to be set.
*/
void prvSocketSetMSS_IPV6( FreeRTOS_Socket_t * pxSocket )
{
uint32_t ulMSS = ipconfigTCP_MSS;
#if ( ipconfigHAS_DEBUG_PRINTF == 1 )
char cIPv6Address[ 40 ];
#endif
const NetworkEndPoint_t * pxEndPoint = NULL;
do
{
if( pxSocket == NULL )
{
/* If NULL socket handler, skip all following steps. */
FreeRTOS_debug_printf( ( "prvSocketSetMSS_IPV6: NULL socket handler\n" ) );
break;
}
pxEndPoint = pxSocket->pxEndPoint;
if( pxEndPoint != NULL )
{
IPv6_Type_t eType;
/* Compared to IPv4, an IPv6 header is 20 bytes longer.
* It must be subtracted from the MSS. */
size_t uxDifference = ipSIZE_OF_IPv6_HEADER - ipSIZE_OF_IPv4_HEADER;
/* Because ipconfigTCP_MSS is guaranteed not less than tcpMINIMUM_SEGMENT_LENGTH by FreeRTOSIPConfigDefaults.h,
* it's unnecessary to check if xSocket->u.xTCP.usMSS is greater than difference. */
ulMSS = ( uint32_t ) ( ipconfigTCP_MSS - uxDifference );
eType = xIPv6_GetIPType( &( pxSocket->u.xTCP.xRemoteIP.xIP_IPv6 ) );
if( eType == eIPv6_Global )
{
/* The packet will travel through Internet, make the MSS
* smaller. */
ulMSS = FreeRTOS_min_uint32( ( uint32_t ) tcpREDUCED_MSS_THROUGH_INTERNET, ulMSS );
}
}
#if ( ipconfigHAS_DEBUG_PRINTF == 1 )
{
( void ) FreeRTOS_inet_ntop( FREERTOS_AF_INET6, ( const void * ) pxSocket->u.xTCP.xRemoteIP.xIP_IPv6.ucBytes, cIPv6Address, sizeof( cIPv6Address ) );
FreeRTOS_debug_printf( ( "prvSocketSetMSS: %u bytes for %s ip port %u\n", ( unsigned ) ulMSS, cIPv6Address, pxSocket->u.xTCP.usRemotePort ) );
}
#endif
pxSocket->u.xTCP.usMSS = ( uint16_t ) ulMSS;
} while( ipFALSE_BOOL );
}
/*-----------------------------------------------------------*/
/* *INDENT-OFF* */
#endif /* ( ipconfigUSE_IPv6 != 0 ) && ( ipconfigUSE_TCP == 1 ) */
/* *INDENT-ON* */
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,501 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
/*=============================================================================
*
* ##### # ##### #### ######
* # # # # # # # # # # #
* # # # # # #
* # ### ##### # # # # # #
* # # # # # # # # #####
* # # # # # # #### # # #
* # # # # # # # # # #
* # # # # #### # # # #
* #### ##### # # # #### #### ####
* #
* ###
* Tiny-TCP: TCP without sliding windows.
*
*=============================================================================*/
/**
* @file FreeRTOS_TINY_TCP.c
* @brief Module which handles TCP when windowing is disabled
*
* In this module all ports and IP addresses and sequence numbers are
* being stored in host byte-order.
*/
/* Standard includes. */
#include <stdint.h>
/* FreeRTOS includes. */
#include "FreeRTOS.h"
#include "task.h"
/* FreeRTOS+TCP includes. */
#include "FreeRTOS_IP.h"
#include "FreeRTOS_UDP_IP.h"
#include "FreeRTOS_Sockets.h"
#include "FreeRTOS_IP_Private.h"
#if ( ipconfigUSE_TCP == 1 )
#if ( ipconfigUSE_TCP_WIN == 0 )
/** @brief Logging verbosity level. */
BaseType_t xTCPWindowLoggingLevel = 0;
static portINLINE BaseType_t xSequenceGreaterThanOrEqual( uint32_t a,
uint32_t b );
/**
* @brief Test if a>=b. This function is required since the sequence numbers can roll over.
*
* @param[in] a The first sequence number.
* @param[in] b The second sequence number.
*
* @return pdTRUE if a>=b, else pdFALSE.
*/
static portINLINE BaseType_t xSequenceGreaterThanOrEqual( uint32_t a,
uint32_t b )
{
BaseType_t xResult = pdFALSE;
/* Test if a >= b */
if( ( ( a - b ) & 0x80000000U ) == 0U )
{
xResult = pdTRUE;
}
return xResult;
}
static portINLINE void vTCPTimerSet( TCPTimer_t * pxTimer );
/**
* @brief Set the timer's "born" time.
*
* @param[in] pxTimer The TCP timer.
*/
static portINLINE void vTCPTimerSet( TCPTimer_t * pxTimer )
{
pxTimer->uxBorn = xTaskGetTickCount();
}
/*-----------------------------------------------------------*/
static portINLINE uint32_t ulTimerGetAge( const TCPTimer_t * pxTimer );
/**
* @brief Get the timer age in milliseconds.
*
* @param[in] pxTimer The timer whose age is to be fetched.
*
* @return The time in milliseconds since the timer was born.
*/
static portINLINE uint32_t ulTimerGetAge( const TCPTimer_t * pxTimer )
{
TickType_t uxNow = xTaskGetTickCount();
TickType_t uxDiff = uxNow - pxTimer->uxBorn;
return pdTICKS_TO_MS( uxDiff );
}
/*-----------------------------------------------------------*/
/**
* @brief Data was received at 'ulSequenceNumber'. See if it was expected
* and if there is enough space to store the new data.
*
* @param[in] pxWindow The window to be checked.
* @param[in] ulSequenceNumber Sequence number of the data received.
* @param[in] ulLength Length of the data received.
* @param[in] ulSpace Space in the buffer.
*
* @return A 0 is returned if there is enough space and the sequence number is correct,
* if not then a -1 is returned.
*
* @note if true may be passed directly to user (segment expected and window is empty).
* But pxWindow->ackno should always be used to set "BUF->ackno".
*/
int32_t lTCPWindowRxCheck( TCPWindow_t * pxWindow,
uint32_t ulSequenceNumber,
uint32_t ulLength,
uint32_t ulSpace,
uint32_t * pulSkipCount )
{
int32_t lReturn = -1;
*pulSkipCount = 0;
/* Data was received at 'ulSequenceNumber'. See if it was expected
* and if there is enough space to store the new data. */
if( ( pxWindow->rx.ulCurrentSequenceNumber != ulSequenceNumber ) || ( ulSpace < ulLength ) )
{
lReturn = -1;
}
else
{
pxWindow->rx.ulCurrentSequenceNumber += ( uint32_t ) ulLength;
lReturn = 0;
}
return lReturn;
}
#endif /* ipconfigUSE_TCP_WIN == 0 */
/*-----------------------------------------------------------*/
#if ( ipconfigUSE_TCP_WIN == 0 )
/**
* @brief Add data to the Tx Window.
*
* @param[in] pxWindow The window to which the data is to be added.
* @param[in] ulLength The length of the data to be added.
* @param[in] lPosition Position in the stream.
* @param[in] lMax Size of the Tx stream.
*
* @return The data actually added.
*/
int32_t lTCPWindowTxAdd( TCPWindow_t * pxWindow,
uint32_t ulLength,
int32_t lPosition,
int32_t lMax )
{
TCPSegment_t * pxSegment = &( pxWindow->xTxSegment );
int32_t lResult;
/* Data is being scheduled for transmission. */
/* lMax would indicate the size of the txStream. */
( void ) lMax;
/* This is tiny TCP: there is only 1 segment for outgoing data.
* As long as 'lDataLength' is unequal to zero, the segment is still occupied. */
if( pxSegment->lDataLength > 0 )
{
lResult = 0L;
}
else
{
if( ulLength > ( uint32_t ) pxSegment->lMaxLength )
{
if( ( xTCPWindowLoggingLevel != 0 ) && ( ipconfigTCP_MAY_LOG_PORT( pxWindow->usOurPortNumber ) != pdFALSE ) )
{
FreeRTOS_debug_printf( ( "lTCPWindowTxAdd: can only store %u / %d bytes\n", ( unsigned ) ulLength, ( int ) pxSegment->lMaxLength ) );
}
ulLength = ( uint32_t ) pxSegment->lMaxLength;
}
if( ( xTCPWindowLoggingLevel != 0 ) && ( ipconfigTCP_MAY_LOG_PORT( pxWindow->usOurPortNumber ) != pdFALSE ) )
{
FreeRTOS_debug_printf( ( "lTCPWindowTxAdd: SeqNr %u (%u) Len %u\n",
( unsigned ) ( pxWindow->ulNextTxSequenceNumber - pxWindow->tx.ulFirstSequenceNumber ),
( unsigned ) ( pxWindow->tx.ulCurrentSequenceNumber - pxWindow->tx.ulFirstSequenceNumber ),
( unsigned ) ulLength ) );
}
/* The sequence number of the first byte in this packet. */
pxSegment->ulSequenceNumber = pxWindow->ulNextTxSequenceNumber;
pxSegment->lDataLength = ( int32_t ) ulLength;
pxSegment->lStreamPos = lPosition;
pxSegment->u.ulFlags = 0U;
vTCPTimerSet( &( pxSegment->xTransmitTimer ) );
/* Increase the sequence number of the next data to be stored for
* transmission. */
pxWindow->ulNextTxSequenceNumber += ulLength;
lResult = ( int32_t ) ulLength;
}
return lResult;
}
#endif /* ipconfigUSE_TCP_WIN == 0 */
/*-----------------------------------------------------------*/
#if ( ipconfigUSE_TCP_WIN == 0 )
/**
* @brief Fetches data to be sent.
*
* @param[in] pxWindow The window for the connection.
* @param[in] ulWindowSize The size of the window.
* @param[out] plPosition plPosition will point to a location with the circular data buffer: txStream.
*
* @return return the amount of data which may be sent along with the position in the txStream.
*/
uint32_t ulTCPWindowTxGet( TCPWindow_t * pxWindow,
uint32_t ulWindowSize,
int32_t * plPosition )
{
TCPSegment_t * pxSegment = &( pxWindow->xTxSegment );
uint32_t ulLength = ( uint32_t ) pxSegment->lDataLength;
uint32_t ulMaxTime;
if( ulLength != 0U )
{
/* _HT_ Still under investigation */
( void ) ulWindowSize;
if( pxSegment->u.bits.bOutstanding != pdFALSE_UNSIGNED )
{
/* As 'ucTransmitCount' has a minimum of 1, take 2 * RTT */
ulMaxTime = ( ( uint32_t ) 1U ) << pxSegment->u.bits.ucTransmitCount;
ulMaxTime *= ( uint32_t ) pxWindow->lSRTT;
if( ulTimerGetAge( &( pxSegment->xTransmitTimer ) ) < ulMaxTime )
{
ulLength = 0U;
}
}
if( ulLength != 0U )
{
pxSegment->u.bits.bOutstanding = pdTRUE_UNSIGNED;
pxSegment->u.bits.ucTransmitCount++;
vTCPTimerSet( &pxSegment->xTransmitTimer );
pxWindow->ulOurSequenceNumber = pxSegment->ulSequenceNumber;
*plPosition = pxSegment->lStreamPos;
}
}
return ulLength;
}
#endif /* ipconfigUSE_TCP_WIN == 0 */
/*-----------------------------------------------------------*/
#if ( ipconfigUSE_TCP_WIN == 0 )
/**
* @brief Has the transmission completed.
*
* @param[in] pxWindow The window whose transmission window is to be checked.
*
* @return If there is no outstanding data then pdTRUE is returned,
* else pdFALSE.
*/
BaseType_t xTCPWindowTxDone( const TCPWindow_t * pxWindow )
{
BaseType_t xReturn;
/* Has the outstanding data been sent because user wants to shutdown? */
if( pxWindow->xTxSegment.lDataLength == 0 )
{
xReturn = pdTRUE;
}
else
{
xReturn = pdFALSE;
}
return xReturn;
}
#endif /* ipconfigUSE_TCP_WIN == 0 */
/*-----------------------------------------------------------*/
#if ( ipconfigUSE_TCP_WIN == 0 )
static BaseType_t prvTCPWindowTxHasSpace( TCPWindow_t const * pxWindow,
uint32_t ulWindowSize );
/**
* @brief Check if the window has space for one message.
*
* @param[in] pxWindow The window to be checked.
* @param[in] ulWindowSize Size of the window.
*
* @return pdTRUE if the window has space, pdFALSE otherwise.
*/
static BaseType_t prvTCPWindowTxHasSpace( TCPWindow_t const * pxWindow,
uint32_t ulWindowSize )
{
BaseType_t xReturn;
if( ulWindowSize >= pxWindow->usMSSInit )
{
xReturn = pdTRUE;
}
else
{
xReturn = pdFALSE;
}
return xReturn;
}
#endif /* ipconfigUSE_TCP_WIN == 0 */
/*-----------------------------------------------------------*/
#if ( ipconfigUSE_TCP_WIN == 0 )
/**
* @brief Check data to be sent and calculate the time period the process may sleep.
*
* @param[in] pxWindow The window to be checked.
* @param[in] ulWindowSize Size of the window.
* @param[out] pulDelay The time period (in ticks) that the process may sleep.
*
* @return pdTRUE if the process should sleep or pdFALSE.
*/
BaseType_t xTCPWindowTxHasData( TCPWindow_t const * pxWindow,
uint32_t ulWindowSize,
TickType_t * pulDelay )
{
TCPSegment_t const * pxSegment = &( pxWindow->xTxSegment );
BaseType_t xReturn;
TickType_t ulAge, ulMaxAge;
/* Check data to be sent. */
*pulDelay = ( TickType_t ) 0;
if( pxSegment->lDataLength == 0 )
{
/* Got nothing to send right now. */
xReturn = pdFALSE;
}
else
{
if( pxSegment->u.bits.bOutstanding != pdFALSE_UNSIGNED )
{
ulAge = ulTimerGetAge( &pxSegment->xTransmitTimer );
ulMaxAge = ( ( TickType_t ) 1U << pxSegment->u.bits.ucTransmitCount ) * ( ( uint32_t ) pxWindow->lSRTT );
if( ulMaxAge > ulAge )
{
*pulDelay = ulMaxAge - ulAge;
}
xReturn = pdTRUE;
}
else if( prvTCPWindowTxHasSpace( pxWindow, ulWindowSize ) == pdFALSE )
{
/* Too many outstanding messages. */
xReturn = pdFALSE;
}
else
{
xReturn = pdTRUE;
}
}
return xReturn;
}
#endif /* ipconfigUSE_TCP_WIN == 0 */
/*-----------------------------------------------------------*/
#if ( ipconfigUSE_TCP_WIN == 0 )
/**
* @brief Receive a normal ACK.
*
* @param[in] pxWindow The window for this particular connection.
* @param[in] ulSequenceNumber The sequence number of the packet.
*
* @return Number of bytes to send.
*/
uint32_t ulTCPWindowTxAck( TCPWindow_t * pxWindow,
uint32_t ulSequenceNumber )
{
TCPSegment_t * pxSegment = &( pxWindow->xTxSegment );
uint32_t ulDataLength = ( uint32_t ) pxSegment->lDataLength;
/* Receive a normal ACK */
if( ulDataLength != 0U )
{
if( ulSequenceNumber < ( pxWindow->tx.ulCurrentSequenceNumber + ulDataLength ) )
{
if( ipconfigTCP_MAY_LOG_PORT( pxWindow->usOurPortNumber ) != pdFALSE )
{
FreeRTOS_debug_printf( ( "win_tx_ack: acked %u expc %u len %u\n",
( unsigned ) ( ulSequenceNumber - pxWindow->tx.ulFirstSequenceNumber ),
( unsigned ) ( pxWindow->tx.ulCurrentSequenceNumber - pxWindow->tx.ulFirstSequenceNumber ),
( unsigned ) ulDataLength ) );
}
/* Nothing to send right now. */
ulDataLength = 0U;
}
else
{
pxWindow->tx.ulCurrentSequenceNumber += ulDataLength;
if( ( xTCPWindowLoggingLevel != 0 ) && ( ipconfigTCP_MAY_LOG_PORT( pxWindow->usOurPortNumber ) != pdFALSE ) )
{
FreeRTOS_debug_printf( ( "win_tx_ack: acked seqnr %u len %u\n",
( unsigned ) ( ulSequenceNumber - pxWindow->tx.ulFirstSequenceNumber ),
( unsigned ) ulDataLength ) );
}
pxSegment->lDataLength = 0;
}
}
return ulDataLength;
}
#endif /* ipconfigUSE_TCP_WIN == 0 */
/*-----------------------------------------------------------*/
#if ( ipconfigUSE_TCP_WIN == 0 )
/**
* @brief This function will be called as soon as a FIN is received to check
* whether all transmit queues are empty or not.
*
* @param[in] pxWindow The window to be checked.
*
* @return It will return true if there are no 'open' reception segments.
*/
BaseType_t xTCPWindowRxEmpty( const TCPWindow_t * pxWindow )
{
/* Return true if 'ulCurrentSequenceNumber >= ulHighestSequenceNumber'
* 'ulCurrentSequenceNumber' is the highest sequence number stored,
* 'ulHighestSequenceNumber' is the highest sequence number seen. */
return xSequenceGreaterThanOrEqual( pxWindow->rx.ulCurrentSequenceNumber, pxWindow->rx.ulHighestSequenceNumber );
}
#endif /* ipconfigUSE_TCP_WIN == 0 */
/*-----------------------------------------------------------*/
#if ( ipconfigUSE_TCP_WIN == 0 )
/**
* @brief Destroy a window.
*
* @param[in] pxWindow Pointer to the window to be destroyed.
*
* @return Always returns a NULL.
*/
void vTCPWindowDestroy( const TCPWindow_t * pxWindow )
{
/* As in tiny TCP there are no shared segments descriptors, there is
* nothing to release. */
( void ) pxWindow;
}
#endif /* ipconfigUSE_TCP_WIN == 0 */
/*-----------------------------------------------------------*/
#endif /* ipconfigUSE_TCP == 1 */
@@ -0,0 +1,149 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
/**
* @file FreeRTOS_UDP_IP.c
* @brief This file has the source code for the UDP-IP functionality of the FreeRTOS+TCP
* network stack.
*/
/* Standard includes. */
#include <stdint.h>
#include <stdio.h>
/* FreeRTOS includes. */
#include "FreeRTOS.h"
#include "task.h"
#include "queue.h"
#include "semphr.h"
#include "event_groups.h"
#include "list.h"
/* FreeRTOS+TCP includes. */
#include "FreeRTOS_IP.h"
#include "FreeRTOS_Sockets.h"
#include "FreeRTOS_IP_Private.h"
#include "FreeRTOS_UDP_IP.h"
#include "FreeRTOS_DNS.h"
#include "FreeRTOS_DHCP.h"
#include "FreeRTOS_IP_Utils.h"
#include "NetworkInterface.h"
#include "NetworkBufferManagement.h"
#if ( ipconfigUSE_DNS == 1 )
#include "FreeRTOS_DNS.h"
#endif
/**
* @brief Process the generated UDP packet and do other checks before sending the
* packet such as cache check and address resolution.
*
* @param[in] pxNetworkBuffer The network buffer carrying the packet.
*/
void vProcessGeneratedUDPPacket( NetworkBufferDescriptor_t * const pxNetworkBuffer )
{
const UDPPacket_t * pxUDPPacket;
if( pxNetworkBuffer != NULL )
{
/* Map the UDP packet onto the start of the frame. */
/* MISRA Ref 11.3.1 [Misaligned access] */
/* More details at: https://github.com/FreeRTOS/FreeRTOS-Plus-TCP/blob/main/MISRA.md#rule-113 */
/* coverity[misra_c_2012_rule_11_3_violation] */
pxUDPPacket = ( ( UDPPacket_t * ) pxNetworkBuffer->pucEthernetBuffer );
switch( pxUDPPacket->xEthernetHeader.usFrameType )
{
#if ( ipconfigUSE_IPv4 != 0 )
case ipIPv4_FRAME_TYPE:
vProcessGeneratedUDPPacket_IPv4( pxNetworkBuffer );
break;
#endif
#if ( ipconfigUSE_IPv6 != 0 )
case ipIPv6_FRAME_TYPE:
vProcessGeneratedUDPPacket_IPv6( pxNetworkBuffer );
break;
#endif
default:
/* do nothing, coverity happy */
break;
}
}
}
/*-----------------------------------------------------------*/
/**
* @brief Process the received UDP packet.
*
* @param[in] pxNetworkBuffer The network buffer carrying the UDP packet.
* @param[in] usPort The port number on which this packet was received.
* @param[out] pxIsWaitingForResolution If the packet is awaiting resolution,
* this pointer will be set to pdTRUE. pdFALSE otherwise.
*
* @return pdPASS in case the UDP packet could be processed. Else pdFAIL is returned.
*/
BaseType_t xProcessReceivedUDPPacket( NetworkBufferDescriptor_t * pxNetworkBuffer,
uint16_t usPort,
BaseType_t * pxIsWaitingForResolution )
{
/* Returning pdPASS means that the packet was consumed, released. */
BaseType_t xReturn = pdFAIL;
const UDPPacket_t * pxUDPPacket;
configASSERT( pxNetworkBuffer != NULL );
configASSERT( pxNetworkBuffer->pucEthernetBuffer != NULL );
/* Map the ethernet buffer to the UDPPacket_t struct for easy access to the fields. */
/* MISRA Ref 11.3.1 [Misaligned access] */
/* More details at: https://github.com/FreeRTOS/FreeRTOS-Plus-TCP/blob/main/MISRA.md#rule-113 */
/* coverity[misra_c_2012_rule_11_3_violation] */
pxUDPPacket = ( ( const UDPPacket_t * ) pxNetworkBuffer->pucEthernetBuffer );
switch( pxUDPPacket->xEthernetHeader.usFrameType )
{
#if ( ipconfigUSE_IPv4 != 0 )
case ipIPv4_FRAME_TYPE:
xReturn = xProcessReceivedUDPPacket_IPv4( pxNetworkBuffer,
usPort, pxIsWaitingForResolution );
break;
#endif
#if ( ipconfigUSE_IPv6 != 0 )
case ipIPv6_FRAME_TYPE:
xReturn = xProcessReceivedUDPPacket_IPv6( pxNetworkBuffer,
usPort, pxIsWaitingForResolution );
break;
#endif
default:
/* do nothing, coverity happy */
break;
}
return xReturn;
}
/*-----------------------------------------------------------*/
@@ -0,0 +1,579 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
/**
* @file FreeRTOS_UDP_IPv4.c
* @brief This file has the source code for the UDP-IP functionality of the FreeRTOS+TCP
* network stack.
*/
/* Standard includes. */
#include <stdint.h>
#include <stdio.h>
/* FreeRTOS includes. */
#include "FreeRTOS.h"
#include "task.h"
#include "queue.h"
#include "semphr.h"
#include "event_groups.h"
#include "list.h"
/* FreeRTOS+TCP includes. */
#include "FreeRTOS_IP.h"
#include "FreeRTOS_Sockets.h"
#include "FreeRTOS_IP_Private.h"
#include "FreeRTOS_UDP_IP.h"
#include "FreeRTOS_ARP.h"
#include "FreeRTOS_DNS.h"
#include "FreeRTOS_DHCP.h"
#include "FreeRTOS_IP_Utils.h"
#include "NetworkInterface.h"
#include "NetworkBufferManagement.h"
#if ( ipconfigUSE_DNS == 1 )
#include "FreeRTOS_DNS.h"
#endif
/* Just make sure the contents doesn't get compiled if IPv4 is not enabled. */
/* *INDENT-OFF* */
#if( ipconfigUSE_IPv4 != 0 )
/* *INDENT-ON* */
/*-----------------------------------------------------------*/
/**
* @brief Process the generated UDP packet and do other checks before sending the
* packet such as ARP cache check and address resolution.
*
* @param[in] pxNetworkBuffer The network buffer carrying the packet.
*/
void vProcessGeneratedUDPPacket_IPv4( NetworkBufferDescriptor_t * const pxNetworkBuffer )
{
UDPPacket_t * pxUDPPacket;
IPHeader_t * pxIPHeader;
eResolutionLookupResult_t eReturned;
uint32_t ulIPAddress = pxNetworkBuffer->xIPAddress.ulIP_IPv4;
NetworkEndPoint_t * pxEndPoint = pxNetworkBuffer->pxEndPoint;
size_t uxPayloadSize;
/* Map the UDP packet onto the start of the frame. */
/* MISRA Ref 11.3.1 [Misaligned access] */
/* More details at: https://github.com/FreeRTOS/FreeRTOS-Plus-TCP/blob/main/MISRA.md#rule-113 */
/* coverity[misra_c_2012_rule_11_3_violation] */
pxUDPPacket = ( ( UDPPacket_t * ) pxNetworkBuffer->pucEthernetBuffer );
#if ipconfigSUPPORT_OUTGOING_PINGS == 1
if( pxNetworkBuffer->usPort == ( uint16_t ) ipPACKET_CONTAINS_ICMP_DATA )
{
uxPayloadSize = pxNetworkBuffer->xDataLength - sizeof( ICMPPacket_t );
}
else
#endif
{
uxPayloadSize = pxNetworkBuffer->xDataLength - sizeof( UDPPacket_t );
}
/* Determine the ARP cache status for the requested IP address. */
eReturned = eARPGetCacheEntry( &( ulIPAddress ), &( pxUDPPacket->xEthernetHeader.xDestinationAddress ), &( pxEndPoint ) );
if( pxNetworkBuffer->pxEndPoint == NULL )
{
pxNetworkBuffer->pxEndPoint = pxEndPoint;
}
if( eReturned != eResolutionFailed )
{
if( eReturned == eResolutionCacheHit )
{
/* Part of the Ethernet and IP headers are always constant when sending an IPv4
* UDP packet. This array defines the constant parts, allowing this part of the
* packet to be filled in using a simple memcpy() instead of individual writes. */
static const uint8_t ucDefaultPartUDPPacketHeader[] =
{
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* Ethernet source MAC address. */
0x08, 0x00, /* Ethernet frame type. */
ipIPV4_VERSION_HEADER_LENGTH_MIN, /* ucVersionHeaderLength. */
0x00, /* ucDifferentiatedServicesCode. */
0x00, 0x00, /* usLength. */
0x00, 0x00, /* usIdentification. */
0x00, 0x00, /* usFragmentOffset. */
ipconfigUDP_TIME_TO_LIVE, /* ucTimeToLive */
ipPROTOCOL_UDP, /* ucProtocol. */
0x00, 0x00, /* usHeaderChecksum. */
0x00, 0x00, 0x00, 0x00 /* Source IP address. */
};
/* memcpy() helper variables for MISRA Rule 21.15 compliance*/
const void * pvCopySource;
void * pvCopyDest;
#if ( ipconfigDRIVER_INCLUDED_TX_IP_CHECKSUM == 0 )
uint8_t ucSocketOptions;
#endif
iptraceSENDING_UDP_PACKET( pxNetworkBuffer->xIPAddress.ulIP_IPv4 );
/* Create short cuts to the data within the packet. */
pxIPHeader = &( pxUDPPacket->xIPHeader );
#if ( ipconfigSUPPORT_OUTGOING_PINGS == 1 )
/* Is it possible that the packet is not actually a UDP packet
* after all, but an ICMP packet. */
if( pxNetworkBuffer->usPort != ( uint16_t ) ipPACKET_CONTAINS_ICMP_DATA )
#endif /* ipconfigSUPPORT_OUTGOING_PINGS */
{
UDPHeader_t * pxUDPHeader;
pxUDPHeader = &( pxUDPPacket->xUDPHeader );
pxUDPHeader->usDestinationPort = pxNetworkBuffer->usPort;
pxUDPHeader->usSourcePort = pxNetworkBuffer->usBoundPort;
pxUDPHeader->usLength = ( uint16_t ) ( uxPayloadSize + sizeof( UDPHeader_t ) );
pxUDPHeader->usLength = FreeRTOS_htons( pxUDPHeader->usLength );
pxUDPHeader->usChecksum = 0U;
}
/* memcpy() the constant parts of the header information into
* the correct location within the packet. This fills in:
* xEthernetHeader.xSourceAddress
* xEthernetHeader.usFrameType
* xIPHeader.ucVersionHeaderLength
* xIPHeader.ucDifferentiatedServicesCode
* xIPHeader.usLength
* xIPHeader.usIdentification
* xIPHeader.usFragmentOffset
* xIPHeader.ucTimeToLive
* xIPHeader.ucProtocol
* and
* xIPHeader.usHeaderChecksum
*/
/* Save options now, as they will be overwritten by memcpy */
#if ( ipconfigDRIVER_INCLUDED_TX_IP_CHECKSUM == 0 )
{
ucSocketOptions = pxNetworkBuffer->pucEthernetBuffer[ ipSOCKET_OPTIONS_OFFSET ];
}
#endif
/*
* Offset the memcpy by the size of a MAC address to start at the packet's
* Ethernet header 'source' MAC address; the preceding 'destination' should not be altered.
*/
/*
* Use helper variables for memcpy() to remain
* compliant with MISRA Rule 21.15. These should be
* optimized away.
*/
pvCopySource = ucDefaultPartUDPPacketHeader;
/* The Ethernet source address is at offset 6. */
pvCopyDest = &pxNetworkBuffer->pucEthernetBuffer[ sizeof( MACAddress_t ) ];
( void ) memcpy( pvCopyDest, pvCopySource, sizeof( ucDefaultPartUDPPacketHeader ) );
#if ipconfigSUPPORT_OUTGOING_PINGS == 1
if( pxNetworkBuffer->usPort == ( uint16_t ) ipPACKET_CONTAINS_ICMP_DATA )
{
pxIPHeader->ucProtocol = ipPROTOCOL_ICMP;
pxIPHeader->usLength = ( uint16_t ) ( uxPayloadSize + sizeof( IPHeader_t ) + sizeof( ICMPHeader_t ) );
}
else
#endif /* ipconfigSUPPORT_OUTGOING_PINGS */
{
pxIPHeader->usLength = ( uint16_t ) ( uxPayloadSize + sizeof( IPHeader_t ) + sizeof( UDPHeader_t ) );
}
pxIPHeader->usLength = FreeRTOS_htons( pxIPHeader->usLength );
pxIPHeader->ulDestinationIPAddress = pxNetworkBuffer->xIPAddress.ulIP_IPv4;
if( pxNetworkBuffer->pxEndPoint != NULL )
{
pxIPHeader->ulSourceIPAddress = pxNetworkBuffer->pxEndPoint->ipv4_settings.ulIPAddress;
}
/* The stack doesn't support fragments, so the fragment offset field must always be zero.
* The header was never memset to zero, so set both the fragment offset and fragmentation flags in one go.
*/
#if ( ipconfigFORCE_IP_DONT_FRAGMENT != 0 )
pxIPHeader->usFragmentOffset = ipFRAGMENT_FLAGS_DONT_FRAGMENT;
#else
pxIPHeader->usFragmentOffset = 0U;
#endif
#if ( ipconfigUSE_LLMNR == 1 )
{
/* LLMNR messages are typically used on a LAN and they're
* not supposed to cross routers */
if( pxNetworkBuffer->xIPAddress.ulIP_IPv4 == ipLLMNR_IP_ADDR )
{
pxIPHeader->ucTimeToLive = 0x01;
}
}
#endif
#if ( ipconfigUSE_MDNS == 1 )
{
/* mDNS messages have a hop-count of 255, see RFC 6762, section 11. */
if( pxNetworkBuffer->xIPAddress.ulIP_IPv4 == ipMDNS_IP_ADDRESS )
{
pxIPHeader->ucTimeToLive = 0xffU;
}
}
#endif
#if ( ipconfigDRIVER_INCLUDED_TX_IP_CHECKSUM == 0 )
{
pxIPHeader->usHeaderChecksum = 0U;
pxIPHeader->usHeaderChecksum = usGenerateChecksum( 0U, ( uint8_t * ) &( pxIPHeader->ucVersionHeaderLength ), uxIPHeaderSizePacket( pxNetworkBuffer ) );
pxIPHeader->usHeaderChecksum = ( uint16_t ) ~FreeRTOS_htons( pxIPHeader->usHeaderChecksum );
if( ( ucSocketOptions & ( uint8_t ) FREERTOS_SO_UDPCKSUM_OUT ) != 0U )
{
( void ) usGenerateProtocolChecksum( ( uint8_t * ) pxUDPPacket, pxNetworkBuffer->xDataLength, pdTRUE );
}
else
{
pxUDPPacket->xUDPHeader.usChecksum = 0U;
}
}
#endif /* if ( ipconfigDRIVER_INCLUDED_TX_IP_CHECKSUM == 0 ) */
}
else if( eReturned == eResolutionCacheMiss )
{
/* Add an entry to the ARP table with a null hardware address.
* This allows the ARP timer to know that an ARP reply is
* outstanding, and perform retransmissions if necessary. */
vARPRefreshCacheEntry( NULL, ulIPAddress, NULL );
/* Generate an ARP for the required IP address. */
iptracePACKET_DROPPED_TO_GENERATE_ARP( pxNetworkBuffer->xIPAddress.ulIP_IPv4 );
/* 'ulIPAddress' might have become the address of the Gateway.
* Find the route again. */
pxNetworkBuffer->pxEndPoint = FreeRTOS_FindEndPointOnNetMask( ulIPAddress );
if( pxNetworkBuffer->pxEndPoint == NULL )
{
eReturned = eResolutionFailed;
}
else
{
pxNetworkBuffer->xIPAddress.ulIP_IPv4 = ulIPAddress;
vARPGenerateRequestPacket( pxNetworkBuffer );
}
}
else
{
/* The lookup indicated that an ARP request has already been
* sent out for the queried IP address. */
eReturned = eResolutionFailed;
}
}
if( eReturned != eResolutionFailed )
{
/* The network driver is responsible for freeing the network buffer
* after the packet has been sent. */
if( pxNetworkBuffer->pxEndPoint != NULL )
{
NetworkInterface_t * pxInterface = pxNetworkBuffer->pxEndPoint->pxNetworkInterface;
/* MISRA Ref 11.3.1 [Misaligned access] */
/* More details at: https://github.com/FreeRTOS/FreeRTOS-Plus-TCP/blob/main/MISRA.md#rule-113 */
/* coverity[misra_c_2012_rule_11_3_violation] */
EthernetHeader_t * pxEthernetHeader = ( ( EthernetHeader_t * ) pxNetworkBuffer->pucEthernetBuffer );
( void ) memcpy( pxEthernetHeader->xSourceAddress.ucBytes, pxNetworkBuffer->pxEndPoint->xMACAddress.ucBytes, ( size_t ) ipMAC_ADDRESS_LENGTH_BYTES );
#if ( ipconfigETHERNET_MINIMUM_PACKET_BYTES > 0 )
{
if( pxNetworkBuffer->xDataLength < ( size_t ) ipconfigETHERNET_MINIMUM_PACKET_BYTES )
{
BaseType_t xIndex;
for( xIndex = ( BaseType_t ) pxNetworkBuffer->xDataLength; xIndex < ( BaseType_t ) ipconfigETHERNET_MINIMUM_PACKET_BYTES; xIndex++ )
{
pxNetworkBuffer->pucEthernetBuffer[ xIndex ] = 0U;
}
pxNetworkBuffer->xDataLength = ( size_t ) ipconfigETHERNET_MINIMUM_PACKET_BYTES;
}
}
#endif /* if( ipconfigETHERNET_MINIMUM_PACKET_BYTES > 0 ) */
iptraceNETWORK_INTERFACE_OUTPUT( pxNetworkBuffer->xDataLength, pxNetworkBuffer->pucEthernetBuffer );
if( ( pxInterface != NULL ) && ( pxInterface->pfOutput != NULL ) )
{
( void ) pxInterface->pfOutput( pxInterface, pxNetworkBuffer, pdTRUE );
}
}
else
{
/* The packet can't be sent (no route found). Drop the packet. */
vReleaseNetworkBufferAndDescriptor( pxNetworkBuffer );
}
}
else
{
/* The packet can't be sent (DHCP not completed?). Just drop the
* packet. */
vReleaseNetworkBufferAndDescriptor( pxNetworkBuffer );
}
}
/*-----------------------------------------------------------*/
/**
* @brief Process the received UDP packet.
*
* @param[in] pxNetworkBuffer The network buffer carrying the UDP packet.
* @param[in] usPort The port number on which this packet was received.
* @param[out] pxIsWaitingForARPResolution If the packet is awaiting ARP resolution,
* this pointer will be set to pdTRUE. pdFALSE otherwise.
*
* @return pdPASS in case the UDP packet could be processed. Else pdFAIL is returned.
*/
BaseType_t xProcessReceivedUDPPacket_IPv4( NetworkBufferDescriptor_t * pxNetworkBuffer,
uint16_t usPort,
BaseType_t * pxIsWaitingForARPResolution )
{
BaseType_t xReturn = pdPASS;
FreeRTOS_Socket_t * pxSocket;
const UDPPacket_t * pxUDPPacket;
const NetworkEndPoint_t * pxEndpoint;
configASSERT( pxNetworkBuffer != NULL );
configASSERT( pxNetworkBuffer->pucEthernetBuffer != NULL );
/* Map the ethernet buffer to the UDPPacket_t struct for easy access to the fields. */
/* MISRA Ref 11.3.1 [Misaligned access] */
/* More details at: https://github.com/FreeRTOS/FreeRTOS-Plus-TCP/blob/main/MISRA.md#rule-113 */
/* coverity[misra_c_2012_rule_11_3_violation] */
pxUDPPacket = ( ( UDPPacket_t * ) pxNetworkBuffer->pucEthernetBuffer );
pxEndpoint = pxNetworkBuffer->pxEndPoint;
/* Caller must check for minimum packet size. */
pxSocket = pxUDPSocketLookup( usPort );
*pxIsWaitingForARPResolution = pdFALSE;
do
{
if( pxSocket != NULL )
{
if( ( pxEndpoint != NULL ) && ( pxEndpoint->ipv4_settings.ulIPAddress != 0U ) )
{
if( xCheckRequiresARPResolution( pxNetworkBuffer ) == pdTRUE )
{
/* Mark this packet as waiting for ARP resolution. */
*pxIsWaitingForARPResolution = pdTRUE;
/* Return a fail to show that the frame will not be processed right now. */
xReturn = pdFAIL;
break;
}
else
{
/* Update the age of this cache entry since a packet was received. */
vARPRefreshCacheEntryAge( &( pxUDPPacket->xEthernetHeader.xSourceAddress ), pxUDPPacket->xIPHeader.ulSourceIPAddress );
}
}
else
{
/* During DHCP, IP address is not assigned and therefore ARP verification
* is not possible. */
}
#if ( ipconfigUSE_CALLBACKS == 1 )
{
/* Did the owner of this socket register a reception handler ? */
if( ipconfigIS_VALID_PROG_ADDRESS( pxSocket->u.xUDP.pxHandleReceive ) )
{
struct freertos_sockaddr xSourceAddress, destinationAddress;
void * pcData = &( pxNetworkBuffer->pucEthernetBuffer[ ipUDP_PAYLOAD_OFFSET_IPv4 ] );
FOnUDPReceive_t xHandler = ( FOnUDPReceive_t ) pxSocket->u.xUDP.pxHandleReceive;
xSourceAddress.sin_port = pxNetworkBuffer->usPort;
xSourceAddress.sin_address.ulIP_IPv4 = pxNetworkBuffer->xIPAddress.ulIP_IPv4;
xSourceAddress.sin_family = ( uint8_t ) FREERTOS_AF_INET4;
xSourceAddress.sin_len = ( uint8_t ) sizeof( xSourceAddress );
destinationAddress.sin_port = usPort;
destinationAddress.sin_address.ulIP_IPv4 = pxUDPPacket->xIPHeader.ulDestinationIPAddress;
destinationAddress.sin_family = ( uint8_t ) FREERTOS_AF_INET4;
destinationAddress.sin_len = ( uint8_t ) sizeof( destinationAddress );
/* The value of 'xDataLength' was proven to be at least the size of a UDP packet in prvProcessIPPacket(). */
if( xHandler( ( Socket_t ) pxSocket,
( void * ) pcData,
( size_t ) ( pxNetworkBuffer->xDataLength - ipUDP_PAYLOAD_OFFSET_IPv4 ),
&( xSourceAddress ),
&( destinationAddress ) ) != 0 )
{
xReturn = pdFAIL; /* xHandler has consumed the data, do not add it to .xWaitingPacketsList'. */
}
}
}
#endif /* ipconfigUSE_CALLBACKS */
#if ( ipconfigUDP_MAX_RX_PACKETS > 0U )
{
if( xReturn == pdPASS )
{
if( listCURRENT_LIST_LENGTH( &( pxSocket->u.xUDP.xWaitingPacketsList ) ) >= pxSocket->u.xUDP.uxMaxPackets )
{
FreeRTOS_debug_printf( ( "xProcessReceivedUDPPacket: buffer full %ld >= %ld port %u\n",
listCURRENT_LIST_LENGTH( &( pxSocket->u.xUDP.xWaitingPacketsList ) ),
pxSocket->u.xUDP.uxMaxPackets, pxSocket->usLocalPort ) );
xReturn = pdFAIL; /* we did not consume or release the buffer */
}
}
}
#endif /* if ( ipconfigUDP_MAX_RX_PACKETS > 0U ) */
#if ( ipconfigUSE_CALLBACKS == 1 ) || ( ipconfigUDP_MAX_RX_PACKETS > 0U )
if( xReturn == pdPASS ) /*lint !e774: Boolean within 'if' always evaluates to True, depending on configuration. [MISRA 2012 Rule 14.3, required. */
#else
/* xReturn is still pdPASS. */
#endif
{
vTaskSuspendAll();
{
/* Add the network packet to the list of packets to be
* processed by the socket. */
vListInsertEnd( &( pxSocket->u.xUDP.xWaitingPacketsList ), &( pxNetworkBuffer->xBufferListItem ) );
}
( void ) xTaskResumeAll();
/* Set the socket's receive event */
if( pxSocket->xEventGroup != NULL )
{
( void ) xEventGroupSetBits( pxSocket->xEventGroup, ( EventBits_t ) eSOCKET_RECEIVE );
}
#if ( ipconfigSUPPORT_SELECT_FUNCTION == 1 )
{
if( ( pxSocket->pxSocketSet != NULL ) && ( ( pxSocket->xSelectBits & ( ( EventBits_t ) eSELECT_READ ) ) != 0U ) )
{
( void ) xEventGroupSetBits( pxSocket->pxSocketSet->xSelectGroup, ( EventBits_t ) eSELECT_READ );
}
}
#endif
#if ( ipconfigSOCKET_HAS_USER_SEMAPHORE == 1 )
{
if( pxSocket->pxUserSemaphore != NULL )
{
( void ) xSemaphoreGive( pxSocket->pxUserSemaphore );
}
}
#endif
#if ( ipconfigUSE_DHCP == 1 )
{
if( xIsDHCPSocket( pxSocket ) != 0 )
{
( void ) xSendDHCPEvent( pxNetworkBuffer->pxEndPoint );
}
}
#endif
}
}
else
{
/* There is no socket listening to the target port, but still it might
* be for this node. */
#if ( ipconfigUSE_DNS == 1 ) && ( ipconfigDNS_USE_CALLBACKS == 1 )
/* A DNS reply, check for the source port. Although the DNS client
* does open a UDP socket to send a messages, this socket will be
* closed after a short timeout. Messages that come late (after the
* socket is closed) will be treated here. */
if( FreeRTOS_ntohs( pxUDPPacket->xUDPHeader.usSourcePort ) == ( uint16_t ) ipDNS_PORT )
{
vARPRefreshCacheEntry( &( pxUDPPacket->xEthernetHeader.xSourceAddress ), pxUDPPacket->xIPHeader.ulSourceIPAddress,
pxNetworkBuffer->pxEndPoint );
xReturn = xDNSHandlePacket( pxNetworkBuffer );
}
else
#endif
#if ( ipconfigUSE_DNS == 1 ) && ( ipconfigUSE_LLMNR == 1 )
/* A LLMNR request, check for the destination port. */
if( ( usPort == FreeRTOS_ntohs( ipLLMNR_PORT ) ) ||
( pxUDPPacket->xUDPHeader.usSourcePort == FreeRTOS_ntohs( ipLLMNR_PORT ) ) )
{
vARPRefreshCacheEntry( &( pxUDPPacket->xEthernetHeader.xSourceAddress ), pxUDPPacket->xIPHeader.ulSourceIPAddress,
pxNetworkBuffer->pxEndPoint );
xReturn = xDNSHandlePacket( pxNetworkBuffer );
}
else
#endif /* ipconfigUSE_LLMNR */
#if ( ipconfigUSE_DNS == 1 ) && ( ipconfigUSE_MDNS == 1 )
/* A MDNS request, check for the destination port. */
if( ( usPort == FreeRTOS_ntohs( ipMDNS_PORT ) ) ||
( pxUDPPacket->xUDPHeader.usSourcePort == FreeRTOS_ntohs( ipMDNS_PORT ) ) )
{
#if ( ipconfigUSE_IPv6 != 0 )
if( pxUDPPacket->xEthernetHeader.usFrameType == ipIPv6_FRAME_TYPE )
{
}
else
#endif
{
vARPRefreshCacheEntry( &( pxUDPPacket->xEthernetHeader.xSourceAddress ), pxUDPPacket->xIPHeader.ulSourceIPAddress,
pxNetworkBuffer->pxEndPoint );
}
xReturn = xDNSHandlePacket( pxNetworkBuffer );
}
else
#endif /* ipconfigUSE_MDNS */
#if ( ipconfigUSE_NBNS == 1 )
/* a NetBIOS request, check for the destination port */
if( ( usPort == FreeRTOS_ntohs( ipNBNS_PORT ) ) ||
( pxUDPPacket->xUDPHeader.usSourcePort == FreeRTOS_ntohs( ipNBNS_PORT ) ) )
{
vARPRefreshCacheEntry( &( pxUDPPacket->xEthernetHeader.xSourceAddress ), pxUDPPacket->xIPHeader.ulSourceIPAddress,
pxNetworkBuffer->pxEndPoint );
xReturn = ( BaseType_t ) ulNBNSHandlePacket( pxNetworkBuffer );
}
else
#endif /* ipconfigUSE_NBNS */
{
xReturn = pdFAIL;
}
}
} while( ipFALSE_BOOL );
return xReturn;
}
/*-----------------------------------------------------------*/
/* *INDENT-OFF* */
#endif /* ipconfigUSE_IPv4 != 0 ) */
/* *INDENT-ON* */
@@ -0,0 +1,593 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
/**
* @file FreeRTOS_UDP_IPv6.c
* @brief This file has the source code for the UDP-IP functionality of the FreeRTOS+TCP
* network stack.
*/
/* Standard includes. */
#include <stdint.h>
#include <stdio.h>
/* FreeRTOS includes. */
#include "FreeRTOS.h"
#include "task.h"
#include "queue.h"
#include "semphr.h"
#include "event_groups.h"
#include "list.h"
/* FreeRTOS+TCP includes. */
#include "FreeRTOS_IP.h"
#include "FreeRTOS_Sockets.h"
#include "FreeRTOS_IP_Private.h"
#include "FreeRTOS_UDP_IP.h"
#include "FreeRTOS_DNS.h"
#include "FreeRTOS_DHCP.h"
#include "FreeRTOS_ND.h"
#include "FreeRTOS_IP_Utils.h"
#include "NetworkInterface.h"
#include "NetworkBufferManagement.h"
#if ( ipconfigUSE_DNS == 1 )
#include "FreeRTOS_DNS.h"
#endif
/* Just make sure the contents doesn't get compiled if IPv6 is not enabled. */
/* *INDENT-OFF* */
#if( ipconfigUSE_IPv6 != 0 )
/* *INDENT-ON* */
/*-----------------------------------------------------------*/
/* _HT_ this is a temporary aid while testing. In case an end-0point is not found,
* this function will return the first end-point of the required type,
* either 'ipTYPE_IPv4' or 'ipTYPE_IPv6' */
static NetworkEndPoint_t * pxGetEndpoint( BaseType_t xIPType,
BaseType_t xIsGlobal );
/**
* @brief Get the first end point of the type (IPv4/IPv6) from the list
* the list of end points.
*
* @param[in] xIPType IP type (ipTYPE_IPv6/ipTYPE_IPv4)
* @param[in] xIsGlobal when pdTRUE, an endpoint with a global address must be
* returned. When pdFALSE, a local-link endpoint is returned.
* This only applies to IPv6 endpoints.
*
* @returns Pointer to the first end point of the given IP type from the
* list of end points.
*/
static NetworkEndPoint_t * pxGetEndpoint( BaseType_t xIPType,
BaseType_t xIsGlobal )
{
NetworkEndPoint_t * pxEndPoint;
for( pxEndPoint = FreeRTOS_FirstEndPoint( NULL );
pxEndPoint != NULL;
pxEndPoint = FreeRTOS_NextEndPoint( NULL, pxEndPoint ) )
{
if( xIPType == ( BaseType_t ) ipTYPE_IPv6 )
{
if( pxEndPoint->bits.bIPv6 != 0U )
{
IPv6_Type_t eEndpointType = xIPv6_GetIPType( &( pxEndPoint->ipv6_settings.xIPAddress ) );
BaseType_t xEndpointGlobal = ( eEndpointType == eIPv6_Global ) ? pdTRUE : pdFALSE;
if( xEndpointGlobal == xIsGlobal )
{
break;
}
}
}
}
return pxEndPoint;
}
/**
* @brief This function is called in case the IP-address was not found,
* i.e. in the cache 'eResolutionCacheMiss' was returned.
* A Neighbour solicitation will be emitted.
*
* @param[in] pxNetworkBuffer The network buffer carrying the UDP or ICMP packet.
*
* @param[out] pxLostBuffer The pointee will be set to true in case the network packet got released
* ( the ownership was taken ).
*/
static eResolutionLookupResult_t prvStartLookup( NetworkBufferDescriptor_t * const pxNetworkBuffer,
BaseType_t * pxLostBuffer )
{
eResolutionLookupResult_t eReturned = eResolutionCacheMiss;
FreeRTOS_printf( ( "Looking up %pip with%s end-point\n",
( void * ) pxNetworkBuffer->xIPAddress.xIP_IPv6.ucBytes,
( pxNetworkBuffer->pxEndPoint != NULL ) ? "" : "out" ) );
if( pxNetworkBuffer->pxEndPoint == NULL )
{
IPv6_Type_t eTargetType = xIPv6_GetIPType( &( pxNetworkBuffer->xIPAddress.xIP_IPv6 ) );
BaseType_t xIsGlobal = ( eTargetType == eIPv6_Global ) ? pdTRUE : pdFALSE;
pxNetworkBuffer->pxEndPoint = pxGetEndpoint( ( BaseType_t ) ipTYPE_IPv6, xIsGlobal );
FreeRTOS_printf( ( "prvStartLookup: Got an end-point: %s\n", pxNetworkBuffer->pxEndPoint ? "yes" : "no" ) );
}
if( pxNetworkBuffer->pxEndPoint != NULL )
{
vNDSendNeighbourSolicitation( pxNetworkBuffer, &( pxNetworkBuffer->xIPAddress.xIP_IPv6 ) );
/* pxNetworkBuffer has been sent and released.
* Make sure it won't be used again.. */
*pxLostBuffer = pdTRUE;
}
return eReturned;
}
/*-----------------------------------------------------------*/
/**
* @brief Process the generated UDP packet and do other checks before sending the
* packet such as ND cache check and address resolution.
*
* @param[in] pxNetworkBuffer The network buffer carrying the packet.
*/
void vProcessGeneratedUDPPacket_IPv6( NetworkBufferDescriptor_t * const pxNetworkBuffer )
{
UDPPacket_IPv6_t * pxUDPPacket_IPv6;
IPHeader_IPv6_t * pxIPHeader_IPv6;
eResolutionLookupResult_t eReturned;
size_t uxPayloadSize;
/* memcpy() helper variables for MISRA Rule 21.15 compliance*/
NetworkInterface_t * pxInterface = NULL;
EthernetHeader_t * pxEthernetHeader = NULL;
BaseType_t xLostBuffer = pdFALSE;
NetworkEndPoint_t * pxEndPoint = NULL;
IPv6_Address_t xIPv6Address;
/* Map the UDP packet onto the start of the frame. */
/* MISRA Ref 11.3.1 [Misaligned access] */
/* More details at: https://github.com/FreeRTOS/FreeRTOS-Plus-TCP/blob/main/MISRA.md#rule-113 */
/* coverity[misra_c_2012_rule_11_3_violation] */
pxUDPPacket_IPv6 = ( ( UDPPacket_IPv6_t * ) pxNetworkBuffer->pucEthernetBuffer );
pxIPHeader_IPv6 = &( pxUDPPacket_IPv6->xIPHeader );
/* Remember the original address. It might get replaced with
* the address of the gateway. */
( void ) memcpy( xIPv6Address.ucBytes, pxNetworkBuffer->xIPAddress.xIP_IPv6.ucBytes, sizeof( xIPv6Address.ucBytes ) );
#if ipconfigSUPPORT_OUTGOING_PINGS == 1
if( pxNetworkBuffer->usPort == ( uint16_t ) ipPACKET_CONTAINS_ICMP_DATA )
{
size_t uxHeadersSize = sizeof( EthernetHeader_t ) + sizeof( IPHeader_IPv6_t ) + sizeof( ICMPHeader_t );
uxPayloadSize = pxNetworkBuffer->xDataLength - uxHeadersSize;
}
else
#endif
{
uxPayloadSize = pxNetworkBuffer->xDataLength - sizeof( UDPPacket_IPv6_t );
}
/* Look in the IPv6 MAC-address cache for the target IP-address. */
eReturned = eNDGetCacheEntry( &( pxNetworkBuffer->xIPAddress.xIP_IPv6 ), &( pxUDPPacket_IPv6->xEthernetHeader.xDestinationAddress ),
&( pxEndPoint ) );
if( eReturned != eResolutionFailed )
{
if( eReturned == eResolutionCacheHit )
{
#if ( ipconfigDRIVER_INCLUDED_TX_IP_CHECKSUM == 0 )
uint8_t ucSocketOptions;
#endif
iptraceSENDING_UDP_PACKET( pxNetworkBuffer->xIPAddress.ulIP_IPv4 );
pxNetworkBuffer->pxEndPoint = pxEndPoint;
#if ( ipconfigSUPPORT_OUTGOING_PINGS == 1 )
/* Is it possible that the packet is not actually a UDP packet
* after all, but an ICMP packet. */
if( pxNetworkBuffer->usPort == ( uint16_t ) ipPACKET_CONTAINS_ICMP_DATA )
{
pxIPHeader_IPv6->ucVersionTrafficClass = 0x60;
pxIPHeader_IPv6->ucNextHeader = ipPROTOCOL_ICMP_IPv6;
pxIPHeader_IPv6->ucHopLimit = 128;
}
else
#endif /* ipconfigSUPPORT_OUTGOING_PINGS */
{
UDPHeader_t * pxUDPHeader = NULL;
pxUDPHeader = &( pxUDPPacket_IPv6->xUDPHeader );
pxIPHeader_IPv6->ucVersionTrafficClass = 0x60;
pxIPHeader_IPv6->ucTrafficClassFlow = 0;
pxIPHeader_IPv6->usFlowLabel = 0;
pxIPHeader_IPv6->ucHopLimit = 255;
pxUDPHeader->usLength = ( uint16_t ) ( pxNetworkBuffer->xDataLength - ( ipSIZE_OF_ETH_HEADER + ipSIZE_OF_IPv6_HEADER ) );
pxIPHeader_IPv6->ucNextHeader = ipPROTOCOL_UDP;
pxIPHeader_IPv6->usPayloadLength = ( uint16_t ) ( pxNetworkBuffer->xDataLength - sizeof( IPPacket_IPv6_t ) );
/* The total transmit size adds on the Ethernet header. */
pxIPHeader_IPv6->usPayloadLength = FreeRTOS_htons( pxIPHeader_IPv6->usPayloadLength );
pxUDPHeader->usDestinationPort = pxNetworkBuffer->usPort;
pxUDPHeader->usSourcePort = pxNetworkBuffer->usBoundPort;
pxUDPHeader->usLength = FreeRTOS_htons( pxUDPHeader->usLength );
pxUDPHeader->usChecksum = 0U;
if( pxNetworkBuffer->pxEndPoint != NULL )
{
( void ) memcpy( pxIPHeader_IPv6->xSourceAddress.ucBytes,
pxNetworkBuffer->pxEndPoint->ipv6_settings.xIPAddress.ucBytes,
ipSIZE_OF_IPv6_ADDRESS );
}
}
/* memcpy() the constant parts of the header information into
* the correct location within the packet. This fills in:
* xEthernetHeader.xSourceAddress
* xEthernetHeader.usFrameType
* xIPHeader.ucVersionHeaderLength
* xIPHeader.ucDifferentiatedServicesCode
* xIPHeader.usLength
* xIPHeader.usIdentification
* xIPHeader.usFragmentOffset
* xIPHeader.ucTimeToLive
* xIPHeader.ucProtocol
* and
* xIPHeader.usHeaderChecksum
*/
/* Save options now, as they will be overwritten by memcpy */
#if ( ipconfigDRIVER_INCLUDED_TX_IP_CHECKSUM == 0 )
{
ucSocketOptions = pxNetworkBuffer->pucEthernetBuffer[ ipSOCKET_OPTIONS_OFFSET ];
}
#endif
#if ipconfigSUPPORT_OUTGOING_PINGS == 1
if( pxNetworkBuffer->usPort == ( uint16_t ) ipPACKET_CONTAINS_ICMP_DATA )
{
pxIPHeader_IPv6->usPayloadLength = FreeRTOS_htons( sizeof( ICMPEcho_IPv6_t ) + uxPayloadSize );
}
else
#endif /* ipconfigSUPPORT_OUTGOING_PINGS */
{
pxIPHeader_IPv6->ucNextHeader = ipPROTOCOL_UDP;
pxIPHeader_IPv6->usPayloadLength = FreeRTOS_htons( sizeof( UDPHeader_t ) + uxPayloadSize );
}
#if ( ipconfigDRIVER_INCLUDED_TX_IP_CHECKSUM == 0 )
{
if( ( ucSocketOptions & ( uint8_t ) FREERTOS_SO_UDPCKSUM_OUT ) != 0U )
{
( void ) usGenerateProtocolChecksum( ( uint8_t * ) pxUDPPacket_IPv6, pxNetworkBuffer->xDataLength, pdTRUE );
}
else
{
pxUDPPacket_IPv6->xUDPHeader.usChecksum = 0U;
}
}
#endif /* if ( ipconfigDRIVER_INCLUDED_TX_IP_CHECKSUM == 0 ) */
}
else if( eReturned == eResolutionCacheMiss )
{
if( pxEndPoint != NULL )
{
pxNetworkBuffer->pxEndPoint = pxEndPoint;
}
eReturned = prvStartLookup( pxNetworkBuffer, &( xLostBuffer ) );
}
else
{
/* The lookup indicated that an ND Solicitation has already been
* sent out for the queried IP address. */
eReturned = eResolutionFailed;
}
}
if( xLostBuffer == pdTRUE )
{
/* An ND solicitation has been sent. */
}
else if( eReturned != eResolutionFailed )
{
/* The network driver is responsible for freeing the network buffer
* after the packet has been sent. */
if( pxNetworkBuffer->pxEndPoint != NULL )
{
pxInterface = pxNetworkBuffer->pxEndPoint->pxNetworkInterface;
/* MISRA Ref 11.3.1 [Misaligned access] */
/* More details at: https://github.com/FreeRTOS/FreeRTOS-Plus-TCP/blob/main/MISRA.md#rule-113 */
/* coverity[misra_c_2012_rule_11_3_violation] */
pxEthernetHeader = ( ( EthernetHeader_t * ) pxNetworkBuffer->pucEthernetBuffer );
( void ) memcpy( pxEthernetHeader->xSourceAddress.ucBytes,
pxNetworkBuffer->pxEndPoint->xMACAddress.ucBytes,
( size_t ) ipMAC_ADDRESS_LENGTH_BYTES );
#if ( ipconfigETHERNET_MINIMUM_PACKET_BYTES > 0 )
{
if( pxNetworkBuffer->xDataLength < ( size_t ) ipconfigETHERNET_MINIMUM_PACKET_BYTES )
{
BaseType_t xIndex;
for( xIndex = ( BaseType_t ) pxNetworkBuffer->xDataLength; xIndex < ( BaseType_t ) ipconfigETHERNET_MINIMUM_PACKET_BYTES; xIndex++ )
{
pxNetworkBuffer->pucEthernetBuffer[ xIndex ] = 0U;
}
pxNetworkBuffer->xDataLength = ( size_t ) ipconfigETHERNET_MINIMUM_PACKET_BYTES;
}
}
#endif /* if( ipconfigETHERNET_MINIMUM_PACKET_BYTES > 0 ) */
iptraceNETWORK_INTERFACE_OUTPUT( pxNetworkBuffer->xDataLength, pxNetworkBuffer->pucEthernetBuffer );
( void ) pxInterface->pfOutput( pxInterface, pxNetworkBuffer, pdTRUE );
}
else
{
/* The packet can't be sent (no route found). Drop the packet. */
vReleaseNetworkBufferAndDescriptor( pxNetworkBuffer );
}
}
else
{
/* The packet can't be sent (DHCP not completed?). Just drop the
* packet. */
vReleaseNetworkBufferAndDescriptor( pxNetworkBuffer );
}
}
/*-----------------------------------------------------------*/
/**
* @brief Process the received UDP packet.
*
* @param[in] pxNetworkBuffer The network buffer carrying the UDP packet.
* @param[in] usPort The port number on which this packet was received.
* @param[out] pxIsWaitingForNDResolution If the packet is awaiting ND resolution,
* this pointer will be set to pdTRUE. pdFALSE otherwise.
*
* @return pdPASS in case the UDP packet could be processed. Else pdFAIL is returned.
*/
BaseType_t xProcessReceivedUDPPacket_IPv6( NetworkBufferDescriptor_t * pxNetworkBuffer,
uint16_t usPort,
BaseType_t * pxIsWaitingForNDResolution )
{
/* Returning pdPASS means that the packet was consumed, released. */
BaseType_t xReturn = pdPASS;
FreeRTOS_Socket_t * pxSocket;
const UDPPacket_IPv6_t * pxUDPPacket_IPv6;
configASSERT( pxNetworkBuffer != NULL );
configASSERT( pxNetworkBuffer->pucEthernetBuffer != NULL );
/* When refreshing the ND cache with received UDP packets we must be
* careful; hundreds of broadcast messages may pass and if we're not
* handling them, no use to fill the cache with those IP addresses. */
/* MISRA Ref 11.3.1 [Misaligned access] */
/* More details at: https://github.com/FreeRTOS/FreeRTOS-Plus-TCP/blob/main/MISRA.md#rule-113 */
/* coverity[misra_c_2012_rule_11_3_violation] */
pxUDPPacket_IPv6 = ( ( UDPPacket_IPv6_t * ) pxNetworkBuffer->pucEthernetBuffer );
/* Caller must check for minimum packet size. */
pxSocket = pxUDPSocketLookup( usPort );
*pxIsWaitingForNDResolution = pdFALSE;
do
{
/* UDPv6 doesn't allow zero-checksum, refer to RFC2460 - section 8.1.
* Some platforms (such as Zynq) pass the packet to upper layer for flexibility to allow zero-checksum. */
if( pxUDPPacket_IPv6->xUDPHeader.usChecksum == 0U )
{
FreeRTOS_debug_printf( ( "xProcessReceivedUDPPacket_IPv6: Drop packets with checksum %d\n",
pxUDPPacket_IPv6->xUDPHeader.usChecksum ) );
xReturn = pdFAIL;
break;
}
if( pxSocket != NULL )
{
if( xCheckRequiresNDResolution( pxNetworkBuffer ) == pdTRUE )
{
/* Mark this packet as waiting for ND resolution. */
*pxIsWaitingForNDResolution = pdTRUE;
/* Return a fail to show that the frame will not be processed right now. */
xReturn = pdFAIL;
break;
}
vNDRefreshCacheEntry( &( pxUDPPacket_IPv6->xEthernetHeader.xSourceAddress ), &( pxUDPPacket_IPv6->xIPHeader.xSourceAddress ),
pxNetworkBuffer->pxEndPoint );
#if ( ipconfigUSE_CALLBACKS == 1 )
{
size_t uxIPLength = uxIPHeaderSizePacket( pxNetworkBuffer );
size_t uxPayloadSize;
/* Did the owner of this socket register a reception handler ? */
if( ipconfigIS_VALID_PROG_ADDRESS( pxSocket->u.xUDP.pxHandleReceive ) )
{
struct freertos_sockaddr xSourceAddress, destinationAddress;
/* The application hook needs to know the from- and to-addresses. */
void * pcData = &( pxNetworkBuffer->pucEthernetBuffer[ ipSIZE_OF_ETH_HEADER + uxIPLength + ipSIZE_OF_UDP_HEADER ] );
FOnUDPReceive_t xHandler = ( FOnUDPReceive_t ) pxSocket->u.xUDP.pxHandleReceive;
xSourceAddress.sin_port = pxNetworkBuffer->usPort;
destinationAddress.sin_port = usPort;
( void ) memcpy( xSourceAddress.sin_address.xIP_IPv6.ucBytes, pxUDPPacket_IPv6->xIPHeader.xSourceAddress.ucBytes, ipSIZE_OF_IPv6_ADDRESS );
( void ) memcpy( destinationAddress.sin_address.xIP_IPv6.ucBytes, pxUDPPacket_IPv6->xIPHeader.xDestinationAddress.ucBytes, ipSIZE_OF_IPv6_ADDRESS );
xSourceAddress.sin_family = ( uint8_t ) FREERTOS_AF_INET6;
destinationAddress.sin_family = ( uint8_t ) FREERTOS_AF_INET6;
xSourceAddress.sin_len = ( uint8_t ) sizeof( xSourceAddress );
destinationAddress.sin_len = ( uint8_t ) sizeof( destinationAddress );
uxPayloadSize = pxNetworkBuffer->xDataLength - ( ipSIZE_OF_ETH_HEADER + ipSIZE_OF_UDP_HEADER + ( size_t ) ipSIZE_OF_IPv6_HEADER );
/* The value of 'xDataLength' was proven to be at least the size of a UDP packet in prvProcessIPPacket(). */
if( xHandler( ( Socket_t ) pxSocket,
( void * ) pcData,
uxPayloadSize,
&( xSourceAddress ),
&( destinationAddress ) ) != 0 )
{
xReturn = pdFAIL; /* xHandler has consumed the data, do not add it to .xWaitingPacketsList'. */
}
}
}
#endif /* ipconfigUSE_CALLBACKS */
#if ( ipconfigUDP_MAX_RX_PACKETS > 0U )
{
if( xReturn == pdPASS )
{
if( listCURRENT_LIST_LENGTH( &( pxSocket->u.xUDP.xWaitingPacketsList ) ) >= pxSocket->u.xUDP.uxMaxPackets )
{
FreeRTOS_debug_printf( ( "xProcessReceivedUDPPacket: buffer full %ld >= %ld port %u\n",
listCURRENT_LIST_LENGTH( &( pxSocket->u.xUDP.xWaitingPacketsList ) ),
pxSocket->u.xUDP.uxMaxPackets, pxSocket->usLocalPort ) );
xReturn = pdFAIL; /* we did not consume or release the buffer */
}
}
}
#endif /* if ( ipconfigUDP_MAX_RX_PACKETS > 0U ) */
#if ( ipconfigUSE_CALLBACKS == 1 ) || ( ipconfigUDP_MAX_RX_PACKETS > 0U )
if( xReturn == pdPASS ) /*lint !e774: Boolean within 'if' always evaluates to True, depending on configuration. [MISRA 2012 Rule 14.3, required. */
#else
/* xReturn is still pdPASS. */
#endif
{
vTaskSuspendAll();
{
/* Add the network packet to the list of packets to be
* processed by the socket. */
vListInsertEnd( &( pxSocket->u.xUDP.xWaitingPacketsList ), &( pxNetworkBuffer->xBufferListItem ) );
}
( void ) xTaskResumeAll();
/* Set the socket's receive event */
if( pxSocket->xEventGroup != NULL )
{
( void ) xEventGroupSetBits( pxSocket->xEventGroup, ( EventBits_t ) eSOCKET_RECEIVE );
}
#if ( ipconfigSUPPORT_SELECT_FUNCTION == 1 )
{
if( ( pxSocket->pxSocketSet != NULL ) && ( ( pxSocket->xSelectBits & ( ( EventBits_t ) eSELECT_READ ) ) != 0U ) )
{
( void ) xEventGroupSetBits( pxSocket->pxSocketSet->xSelectGroup, ( EventBits_t ) eSELECT_READ );
}
}
#endif
#if ( ipconfigSOCKET_HAS_USER_SEMAPHORE == 1 )
{
if( pxSocket->pxUserSemaphore != NULL )
{
( void ) xSemaphoreGive( pxSocket->pxUserSemaphore );
}
}
#endif
#if ( ipconfigUSE_DHCP == 1 )
{
if( xIsDHCPSocket( pxSocket ) != 0 )
{
( void ) xSendDHCPEvent( pxNetworkBuffer->pxEndPoint );
}
}
#endif
}
}
else
{
/* There is no socket listening to the target port, but still it might
* be for this node. */
#if ( ipconfigUSE_DNS == 1 ) && ( ipconfigDNS_USE_CALLBACKS == 1 )
/* A DNS reply, check for the source port. Although the DNS client
* does open a UDP socket to send a messages, this socket will be
* closed after a short timeout. Messages that come late (after the
* socket is closed) will be treated here. */
if( FreeRTOS_ntohs( pxUDPPacket_IPv6->xUDPHeader.usSourcePort ) == ( uint16_t ) ipDNS_PORT )
{
xReturn = xDNSHandlePacket( pxNetworkBuffer );
}
else
#endif
#if ( ipconfigUSE_DNS == 1 ) && ( ipconfigUSE_LLMNR == 1 )
/* A LLMNR request, check for the destination port. */
if( ( usPort == FreeRTOS_htons( ipLLMNR_PORT ) ) ||
( pxUDPPacket_IPv6->xUDPHeader.usSourcePort == FreeRTOS_htons( ipLLMNR_PORT ) ) )
{
xReturn = xDNSHandlePacket( pxNetworkBuffer );
}
else
#endif /* ipconfigUSE_LLMNR */
#if ( ipconfigUSE_DNS == 1 ) && ( ipconfigUSE_MDNS == 1 )
/* A MDNS request, check for the destination port. */
if( ( usPort == FreeRTOS_ntohs( ipMDNS_PORT ) ) ||
( pxUDPPacket_IPv6->xUDPHeader.usSourcePort == FreeRTOS_ntohs( ipMDNS_PORT ) ) )
{
xReturn = xDNSHandlePacket( pxNetworkBuffer );
}
else
#endif /* ipconfigUSE_MDNS */
#if ( ipconfigUSE_NBNS == 1 )
/* a NetBIOS request, check for the destination port */
if( ( usPort == FreeRTOS_htons( ipNBNS_PORT ) ) ||
( pxUDPPacket_IPv6->xUDPHeader.usSourcePort == FreeRTOS_htons( ipNBNS_PORT ) ) )
{
xReturn = ( BaseType_t ) ulNBNSHandlePacket( pxNetworkBuffer );
}
else
#endif /* ipconfigUSE_NBNS */
{
xReturn = pdFAIL;
}
}
} while( ipFALSE_BOOL );
return xReturn;
}
/*-----------------------------------------------------------*/
/* *INDENT-OFF* */
#endif /* ipconfigUSE_IPv6 != 0 ) */
/* *INDENT-ON* */
@@ -0,0 +1,140 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
/**
* @file FreeRTOSIPDeprecatedDefinitions.h
* @brief File that ensures defined configuration constants are using the most up to date naming.
*/
#ifndef FREERTOS_IP_DEPRECATED_DEFINITIONS_H
#define FREERTOS_IP_DEPRECATED_DEFINITIONS_H
#ifndef FREERTOS_IP_CONFIG_DEFAULTS_H
#error FreeRTOSIPConfigDefaults.h has not been included yet
#endif
#ifdef dnsMAX_REQUEST_ATTEMPTS
#error dnsMAX_REQUEST_ATTEMPTS is now called ipconfigDNS_REQUEST_ATTEMPTS
#endif
#ifdef FreeRTOS_lprintf
#error FreeRTOS_lprintf is now called FreeRTOS_debug_printf/FreeRTOS_printf
#endif
#ifdef HAS_TX_CRC_OFFLOADING
#error HAS_TX_CRC_OFFLOADING is deprecated
#endif
#ifdef HAS_RX_CRC_OFFLOADING
#error HAS_RX_CRC_OFFLOADING is deprecated
#endif
#ifdef ipconfigBUFFER_ALLOC_FIXED_SIZE
#error ipconfigBUFFER_ALLOC_FIXED_SIZE is deprecated
#endif
#ifdef ipconfigDHCP_USES_USER_HOOK
#error ipconfigDHCP_USES_USER_HOOK has been replaced by ipconfigUSE_DHCP_HOOK
#endif
#ifdef ipconfigDRIVER_INCLUDED_RX_IP_FILTERING
#error ipconfigDRIVER_INCLUDED_RX_IP_FILTERING is now called ipconfigETHERNET_DRIVER_FILTERS_PACKETS
#endif
#ifdef ipconfigHAS_INLINE_FUNCTIONS
#error ipconfigHAS_INLINE_FUNCTIONS is deprecated
#endif
#ifdef ipconfigMAX_SEND_BLOCK_TIME_TICKS
#error ipconfigMAX_SEND_BLOCK_TIME_TICKS is now called ipconfigUDP_MAX_SEND_BLOCK_TIME_TICKS
#endif
#ifdef ipconfigNIC_SEND_PASSES_DMA
#error ipconfigNIC_SEND_PASSES_DMA is now called ipconfigZERO_COPY_TX_DRIVER
#endif
#ifdef ipconfigNUM_NETWORK_BUFFERS
#error ipconfigNUM_NETWORK_BUFFERS is now now called ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS
#endif
#ifdef ipconfigRAND32
#error ipconfigRAND32 has been replaced by xApplicationGetRandomNumber( uint32_t *pulValue )
#endif
#ifdef ipconfigTCP_HANG_PROT
#error ipconfigTCP_HANG_PROT is now called ipconfigTCP_HANG_PROTECTION
#endif
#ifdef ipconfigTCP_HANG_PROT_TIME
#error ipconfigTCP_HANG_PROT_TIME is now called ipconfigTCP_HANG_PROTECTION_TIME
#endif
#ifdef ipconfigTCP_RX_BUF_LEN
#error ipconfigTCP_RX_BUF_LEN is now called ipconfigTCP_RX_BUFFER_LENGTH
#endif
#ifdef ipconfigTCP_TX_BUF_LEN
#error ipconfigTCP_TX_BUF_LEN is now called ipconfigTCP_TX_BUFFER_LENGTH
#endif
#ifdef ipconfigUDP_TASK_PRIORITY
#error ipconfigUDP_TASK_PRIORITY is now called ipconfigIP_TASK_PRIORITY
#endif
#ifdef ipconfigUDP_TASK_STACK_SIZE_WORDS
#error ipconfigUDP_TASK_STACK_SIZE_WORDS is now called ipconfigIP_TASK_STACK_SIZE_WORDS
#endif
#ifdef ipconfigUSE_RECEIVE_CONNECT_CALLBACKS
#error ipconfigUSE_RECEIVE_CONNECT_CALLBACKS is now called ipconfigUSE_CALLBACKS
#endif
#ifdef ipconfigUSE_TCP_TIMESTAMPS
#error ipconfigUSE_TCP_TIMESTAMPS is deprecated
#endif
#ifdef ipFILLER_SIZE
#error ipFILLER_SIZE is now called ipconfigPACKET_FILLER_SIZE
#endif
#ifdef tcpconfigIP_TIME_TO_LIVE
#error tcpconfigIP_TIME_TO_LIVE is now called ipconfigTCP_TIME_TO_LIVE
#endif
#ifdef updconfigIP_TIME_TO_LIVE
#error updconfigIP_TIME_TO_LIVE is now called ipconfigUDP_TIME_TO_LIVE
#endif
#ifdef PHY_LS_HIGH_CHECK_TIME_MS
#error PHY_LS_HIGH_CHECK_TIME_MS is now called ipconfigPHY_LS_HIGH_CHECK_TIME_MS
#endif
#ifdef PHY_LS_LOW_CHECK_TIME_MS
#error PHY_LS_LOW_CHECK_TIME_MS is now called ipconfigPHY_LS_LOW_CHECK_TIME_MS
#endif
#endif /* FREERTOS_IP_DEPRECATED_DEFINITIONS_H */
@@ -0,0 +1,182 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
#ifndef FREERTOS_ARP_H
#define FREERTOS_ARP_H
/* Application level configuration options. */
#include "FreeRTOSIPConfig.h"
#include "FreeRTOSIPConfigDefaults.h"
#include "FreeRTOS_IP.h"
#include "FreeRTOS_Routing.h"
/* *INDENT-OFF* */
#ifdef __cplusplus
extern "C" {
#endif
/* *INDENT-ON* */
/*-----------------------------------------------------------*/
/* Miscellaneous structure and definitions. */
/*-----------------------------------------------------------*/
/* A forward declaration of 'xNetworkInterface' which is
* declared in FreeRTOS_Routing.h */
struct xNetworkInterface;
struct xNetworkEndPoint;
/**
* Structure for one row in the ARP cache table.
*/
typedef struct xARP_CACHE_TABLE_ROW
{
uint32_t ulIPAddress; /**< The IP address of an ARP cache entry. */
MACAddress_t xMACAddress; /**< The MAC address of an ARP cache entry. */
uint8_t ucAge; /**< A value that is periodically decremented but can also be refreshed by active communication. The ARP cache entry is removed if the value reaches zero. */
uint8_t ucValid; /**< pdTRUE: xMACAddress is valid, pdFALSE: waiting for ARP reply */
struct xNetworkEndPoint
* pxEndPoint; /**< The end-point on which the MAC address was last seen. */
} ARPCacheRow_t;
/** @brief A structure used internally in FreeRTOS_ARP.c.
* It is used as a parameter for the function prvFindCacheEntry().*/
typedef struct xCacheLocation
{
BaseType_t xIpEntry; /**< The index of the matching IP-address. */
BaseType_t xMacEntry; /**< The index of the matching MAC-address. */
BaseType_t xUseEntry; /**< The index of the first free location. */
} CacheLocation_t;
/**
* Look for an IP-MAC couple in ARP cache and reset the 'age' field. If no match
* is found then no action will be taken.
*/
void vARPRefreshCacheEntryAge( const MACAddress_t * pxMACAddress,
const uint32_t ulIPAddress );
/*
* If ulIPAddress is already in the ARP cache table then reset the age of the
* entry back to its maximum value. If ulIPAddress is not already in the ARP
* cache table then add it - replacing the oldest current entry if there is not
* a free space available.
*/
void vARPRefreshCacheEntry( const MACAddress_t * pxMACAddress,
const uint32_t ulIPAddress,
struct xNetworkEndPoint * pxEndPoint );
#if ( ipconfigARP_USE_CLASH_DETECTION != 0 )
/* Becomes non-zero if another device responded to a gratuitous ARP message. */
extern BaseType_t xARPHadIPClash;
/* MAC-address of the other device containing the same IP-address. */
extern MACAddress_t xARPClashMacAddress;
#endif /* ipconfigARP_USE_CLASH_DETECTION */
#if ( ipconfigUSE_ARP_REMOVE_ENTRY != 0 )
/*
* In some rare cases, it might be useful to remove a ARP cache entry of a
* known MAC address to make sure it gets refreshed.
*/
uint32_t ulARPRemoveCacheEntryByMac( const MACAddress_t * pxMACAddress );
#endif /* ipconfigUSE_ARP_REMOVE_ENTRY != 0 */
BaseType_t xIsIPInARPCache( uint32_t ulAddressToLookup );
BaseType_t xCheckRequiresARPResolution( const NetworkBufferDescriptor_t * pxNetworkBuffer );
/*
* Look for ulIPAddress in the ARP cache. If the IP address exists, copy the
* associated MAC address into pxMACAddress, refresh the ARP cache entry's
* age, and return eResolutionCacheHit. If the IP address does not exist in the ARP
* cache return eResolutionCacheMiss. If the packet cannot be sent for any reason
* (maybe DHCP is still in process, or the addressing needs a gateway but there
* isn't a gateway defined) then return eResolutionFailed.
*/
eResolutionLookupResult_t eARPGetCacheEntry( uint32_t * pulIPAddress,
MACAddress_t * const pxMACAddress,
struct xNetworkEndPoint ** ppxEndPoint );
#if ( ipconfigUSE_ARP_REVERSED_LOOKUP != 0 )
/* Lookup an IP-address if only the MAC-address is known */
eResolutionLookupResult_t eARPGetCacheEntryByMac( const MACAddress_t * const pxMACAddress,
uint32_t * pulIPAddress,
struct xNetworkInterface ** ppxInterface );
#endif
/*
* Reduce the age count in each entry within the ARP cache. An entry is no
* longer considered valid and is deleted if its age reaches zero.
*/
void vARPAgeCache( void );
/*
* After DHCP is ready and when changing IP address, force a quick send of our new IP
* address
*/
void vARPSendGratuitous( void );
/*
* Send out an ARP request for the IP address contained in pxNetworkBuffer, and
* add an entry into the ARP table that indicates that an ARP reply is
* outstanding so re-transmissions can be generated.
*/
void vARPGenerateRequestPacket( NetworkBufferDescriptor_t * const pxNetworkBuffer );
void FreeRTOS_OutputARPRequest( uint32_t ulIPAddress );
/*
* Create and send an ARP request packet to IPv4 endpoints of an interface.
*/
void FreeRTOS_OutputARPRequest_Multi( NetworkEndPoint_t * pxEndPoint,
uint32_t ulIPAddress );
/* xARPWaitResolution checks if an IPv4 address is already known. If not
* it may send an ARP request and wait for a reply. This function will
* only be called from an application. */
BaseType_t xARPWaitResolution( uint32_t ulIPAddress,
TickType_t uxTicksToWait );
/* Clear all entries in the ARp cache. */
void FreeRTOS_ClearARP( const struct xNetworkEndPoint * pxEndPoint );
/* Show all valid ARP entries */
#if ( ipconfigHAS_PRINTF != 0 ) || ( ipconfigHAS_DEBUG_PRINTF != 0 )
void FreeRTOS_PrintARPCache( void );
#endif
/* *INDENT-OFF* */
#ifdef __cplusplus
} /* extern "C" */
#endif
/* *INDENT-ON* */
#endif /* FREERTOS_ARP_H */
@@ -0,0 +1,82 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
/*
* FreeRTOS_Stream_Buffer.h
*
* A circular character buffer
* An implementation of a circular buffer without a length field
* If LENGTH defines the size of the buffer, a maximum of (LENGTH-1) bytes can be stored
* In order to add or read data from the buffer, memcpy() will be called at most 2 times
*/
#ifndef FREERTOS_BITCONFIG_H
#define FREERTOS_BITCONFIG_H
#ifdef __cplusplus
extern "C" {
#endif
/**< @brief The struct BitConfig_t holds a character array, its length and an index. */
typedef struct xBitConfig
{
uint8_t * ucContents; /**< An allocated buffer to hold the binary data stream. */
size_t uxIndex; /**< Points to the next character to analyse or write. */
size_t uxSize; /**< The size of the allocated buffer 'uxContents'. */
BaseType_t xHasError; /**< It will be set to pdTRUE in case an error occurred, usually because the buffer is too small. */
} BitConfig_t;
BaseType_t xBitConfig_init( BitConfig_t * pxConfig,
const uint8_t * pucData,
size_t uxSize );
uint8_t ucBitConfig_read_8( BitConfig_t * pxConfig );
uint16_t usBitConfig_read_16( BitConfig_t * pxConfig );
uint32_t ulBitConfig_read_32( BitConfig_t * pxConfig );
BaseType_t xBitConfig_read_uc( BitConfig_t * pxConfig,
uint8_t * pucData,
size_t uxSize );
BaseType_t pucBitConfig_peek_last_index_uc( BitConfig_t * pxConfig,
uint8_t * pucData,
size_t uxSize );
void vBitConfig_write_8( BitConfig_t * pxConfig,
uint8_t ucValue );
void vBitConfig_write_16( BitConfig_t * pxConfig,
uint16_t usValue );
void vBitConfig_write_32( BitConfig_t * pxConfig,
uint32_t ulValue );
void vBitConfig_write_uc( BitConfig_t * pxConfig,
const uint8_t * pucData,
size_t uxSize );
void vBitConfig_release( BitConfig_t * pxConfig );
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* FREERTOS_STREAM_BUFFER_H */
@@ -0,0 +1,282 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
#ifndef FREERTOS_DHCP_H
#define FREERTOS_DHCP_H
#include "FreeRTOS.h"
/* Application level configuration options. */
#include "FreeRTOSIPConfig.h"
#include "FreeRTOS_Sockets.h"
/* *INDENT-OFF* */
#ifdef __cplusplus
extern "C" {
#endif
#if ( ipconfigUSE_DHCP != 0 ) && ( ipconfigNETWORK_MTU < 586U )
/* DHCP must be able to receive an options field of 312 bytes, the fixed
* part of the DHCP packet is 240 bytes, and the IP/UDP headers take 28 bytes. */
#error ipconfigNETWORK_MTU needs to be at least 586 to use DHCP
#endif
/* Parameter widths in the DHCP packet. */
#define dhcpCLIENT_HARDWARE_ADDRESS_LENGTH 16 /**< Client hardware address length.*/
#define dhcpSERVER_HOST_NAME_LENGTH 64 /**< Server host name length. */
#define dhcpBOOT_FILE_NAME_LENGTH 128 /**< Boot file name length. */
/* Timer parameters */
#ifndef dhcpINITIAL_TIMER_PERIOD
/** @brief The interval at which the DHCP state handler is called. */
#define dhcpINITIAL_TIMER_PERIOD ( pdMS_TO_TICKS( 250U ) )
#endif
#ifndef dhcpINITIAL_DHCP_TX_PERIOD
/** @brief The initial amount of time to wait for a DHCP reply. When repeating an
* unanswered request, this time-out shall be multiplied by 2. */
#define dhcpINITIAL_DHCP_TX_PERIOD ( pdMS_TO_TICKS( 5000U ) )
#endif
#define dhcpIPv6_CLIENT_DUID_LENGTH ( 14U )
/* Codes of interest found in the DHCP options field. */
#define dhcpIPv4_ZERO_PAD_OPTION_CODE ( 0U ) /**< Used to pad other options to make them aligned. See RFC 2132. */
#define dhcpIPv4_SUBNET_MASK_OPTION_CODE ( 1U ) /**< Subnet mask. See RFC 2132. */
#define dhcpIPv4_GATEWAY_OPTION_CODE ( 3U ) /**< Available routers. See RFC 2132. */
#define dhcpIPv4_DNS_SERVER_OPTIONS_CODE ( 6U ) /**< Domain name server. See RFC 2132. */
#define dhcpIPv4_DNS_HOSTNAME_OPTIONS_CODE ( 12U ) /**< Host name. See RFC 2132. */
#define dhcpIPv4_REQUEST_IP_ADDRESS_OPTION_CODE ( 50U ) /**< Requested IP-address. See RFC 2132. */
#define dhcpIPv4_LEASE_TIME_OPTION_CODE ( 51U ) /**< IP-address lease time. See RFC 2132. */
#define dhcpIPv4_MESSAGE_TYPE_OPTION_CODE ( 53U ) /**< DHCP message type. See RFC 2132. */
#define dhcpIPv4_SERVER_IP_ADDRESS_OPTION_CODE ( 54U ) /**< Server Identifier. See RFC 2132. */
#define dhcpIPv4_PARAMETER_REQUEST_OPTION_CODE ( 55U ) /**< Parameter Request list. See RFC 2132. */
#define dhcpIPv4_CLIENT_IDENTIFIER_OPTION_CODE ( 61U ) /**< Client Identifier. See RFC 2132. */
/* The four DHCP message types of interest. */
#define dhcpMESSAGE_TYPE_DISCOVER ( 1 ) /**< DHCP discover message. */
#define dhcpMESSAGE_TYPE_OFFER ( 2 ) /**< DHCP offer message. */
#define dhcpMESSAGE_TYPE_REQUEST ( 3 ) /**< DHCP request message. */
#define dhcpMESSAGE_TYPE_ACK ( 5 ) /**< DHCP acknowledgement. */
#define dhcpMESSAGE_TYPE_NACK ( 6 ) /**< DHCP NACK. (Negative acknowledgement) */
/* Offsets into the transmitted DHCP options fields at which various parameters
* are located. */
#define dhcpCLIENT_IDENTIFIER_OFFSET ( 6U ) /**< Offset for the client ID option. */
#define dhcpREQUESTED_IP_ADDRESS_OFFSET ( 14U ) /**< Offset for the requested IP-address option. */
#define dhcpDHCP_SERVER_IP_ADDRESS_OFFSET ( 20U ) /**< Offset for the server IP-address option. */
#define dhcpOPTION_50_OFFSET ( 12U ) /**< Offset of option-50. */
#define dhcpOPTION_50_SIZE ( 6U ) /**< Number of bytes included in option-50. */
/* Values used in the DHCP packets. */
#define dhcpREQUEST_OPCODE ( 1U ) /**< DHCP request opcode. */
#define dhcpREPLY_OPCODE ( 2U ) /**< DHCP reply opcode. */
#define dhcpADDRESS_TYPE_ETHERNET ( 1U ) /**< Address type: ethernet opcode. */
#define dhcpETHERNET_ADDRESS_LENGTH ( 6U ) /**< Ethernet address length opcode. */
/** @brief If a lease time is not received, use the default of two days (48 hours in ticks).
* Can not use pdMS_TO_TICKS() as integer overflow can occur. */
#define dhcpDEFAULT_LEASE_TIME ( ( 48UL * 60UL * 60UL ) * configTICK_RATE_HZ )
/** @brief Don't allow the lease time to be too short. */
#define dhcpMINIMUM_LEASE_TIME ( pdMS_TO_TICKS( 60000UL ) ) /* 60 seconds in ticks. */
/** @brief Marks the end of the variable length options field in the DHCP packet. */
#define dhcpOPTION_END_BYTE 0xffu
/** @brief Offset into a DHCP message at which the first byte of the options is
* located. */
#define dhcpFIRST_OPTION_BYTE_OFFSET ( 0xf0U )
/* Standard DHCP port numbers and magic cookie value.
* DHCPv4 uses UDP port number 68 for clients and port number 67 for servers.
*/
#if ( ipconfigBYTE_ORDER == pdFREERTOS_LITTLE_ENDIAN )
#define dhcpCLIENT_PORT_IPv4 0x4400U /**< Little endian representation of port 68. */
#define dhcpSERVER_PORT_IPv4 0x4300U /**< Little endian representation of port 67. */
#define dhcpCOOKIE 0x63538263UL /**< Little endian representation of magic cookie. */
#define dhcpBROADCAST 0x0080U /**< Little endian representation of broadcast flag. */
#else
#define dhcpCLIENT_PORT_IPv4 0x0044U /**< Big endian representation of port 68. */
#define dhcpSERVER_PORT_IPv4 0x0043U /**< Big endian representation of port 67. */
#define dhcpCOOKIE 0x63825363UL /**< Big endian representation of magic cookie. */
#define dhcpBROADCAST 0x8000U /**< Big endian representation of broadcast flag. */
#endif /* ( ipconfigBYTE_ORDER == pdFREERTOS_LITTLE_ENDIAN ) */
#include "pack_struct_start.h"
struct xDHCPMessage_IPv4
{
uint8_t ucOpcode; /**< Operation Code: Specifies the general type of message. */
uint8_t ucAddressType; /**< Hardware type used on the local network. */
uint8_t ucAddressLength; /**< Hardware Address Length: Specifies how long hardware
* addresses are in this message. */
uint8_t ucHops; /**< Hops. */
uint32_t ulTransactionID; /**< A 32-bit identification field generated by the client,
* to allow it to match up the request with replies received
* from DHCP servers. */
uint16_t usElapsedTime; /**< Number of seconds elapsed since a client began an attempt to acquire or renew a lease. */
uint16_t usFlags; /**< Just one bit used to indicate broadcast. */
uint32_t ulClientIPAddress_ciaddr; /**< Client's IP address if it has one or 0 is put in this field. */
uint32_t ulYourIPAddress_yiaddr; /**< The IP address that the server is assigning to the client. */
uint32_t ulServerIPAddress_siaddr; /**< The DHCP server address that the client should use. */
uint32_t ulRelayAgentIPAddress_giaddr; /**< Gateway IP address in case the server client are on different subnets. */
uint8_t ucClientHardwareAddress[ dhcpCLIENT_HARDWARE_ADDRESS_LENGTH ]; /**< The client hardware address. */
uint8_t ucServerHostName[ dhcpSERVER_HOST_NAME_LENGTH ]; /**< Server's hostname. */
uint8_t ucBootFileName[ dhcpBOOT_FILE_NAME_LENGTH ]; /**< Boot file full directory path. */
uint32_t ulDHCPCookie; /**< Magic cookie option. */
/* Option bytes from here on. */
}
#include "pack_struct_end.h"
typedef struct xDHCPMessage_IPv4 DHCPMessage_IPv4_t;
#if ( ipconfigUSE_DHCP_HOOK != 0 )
/* Used in the DHCP callback if ipconfigUSE_DHCP_HOOK is set to 1. */
typedef enum eDHCP_PHASE
{
eDHCPPhasePreDiscover, /**< Driver is about to send a DHCP discovery. */
eDHCPPhasePreRequest /**< Driver is about to request DHCP an IP address. */
} eDHCPCallbackPhase_t;
/** @brief Used in the DHCP callback if ipconfigUSE_DHCP_HOOK is set to 1. */
typedef enum eDHCP_ANSWERS
{
eDHCPContinue, /**< Continue the DHCP process */
eDHCPUseDefaults, /**< Stop DHCP and use the static defaults. */
eDHCPStopNoChanges /**< Stop DHCP and continue with current settings. */
} eDHCPCallbackAnswer_t;
#endif /* #if( ipconfigUSE_DHCP_HOOK != 0 ) */
/** @brief DHCP state machine states. */
typedef enum
{
eInitialWait = 0, /**< Initial state: open a socket and wait a short time. */
eWaitingSendFirstDiscover, /**< Send a discover the first time it is called, and reset all timers. */
eWaitingOffer, /**< Either resend the discover, or, if the offer is forthcoming, send a request. */
eWaitingAcknowledge, /**< Either resend the request. */
eSendDHCPRequest, /**< Sendto failed earlier, resend the request to lease the IP-address offered. */
#if ( ipconfigDHCP_FALL_BACK_AUTO_IP != 0 )
eGetLinkLayerAddress, /**< When DHCP didn't respond, try to obtain a LinkLayer address 168.254.x.x. */
#endif
eLeasedAddress, /**< Resend the request at the appropriate time to renew the lease. */
eNotUsingLeasedAddress /**< DHCP failed, and a default IP address is being used. */
} eDHCPState_t;
/** @brief Hold information in between steps in the DHCP state machine. */
struct xDHCP_DATA
{
uint32_t ulTransactionId; /**< The ID used in all transactions. */
uint32_t ulOfferedIPAddress; /**< The IP-address offered by the DHCP server. */
uint32_t ulPreferredIPAddress; /**< A preferred IP address */
uint32_t ulDHCPServerAddress; /**< The IP-address of the DHCP server. */
uint32_t ulLeaseTime; /**< The maximum time that the IP-address can be leased. */
/* Hold information on the current timer state. */
TickType_t xDHCPTxTime; /**< The time at which a request was sent, initialised with xTaskGetTickCount(). */
TickType_t xDHCPTxPeriod; /**< The maximum time to wait for a response. */
/* Try both without and with the broadcast flag */
BaseType_t xUseBroadcast; /**< pdTRUE if the broadcast bit 'dhcpBROADCAST' must be set. */
/* Maintains the DHCP state machine state. */
eDHCPState_t eDHCPState; /**< The current state of the DHCP state machine. */
eDHCPState_t eExpectedState; /**< If the state is not equal the the expected state, no cycle needs to be done. */
Socket_t xDHCPSocket;
/**< Record latest client ID for DHCPv6. */
uint8_t ucClientDUID[ dhcpIPv6_CLIENT_DUID_LENGTH ];
};
typedef struct xDHCP_DATA DHCPData_t;
/** brief: a set of parameters that are passed to helper functions. */
typedef struct xProcessSet
{
uint8_t ucOptionCode; /**< The code currently being handled. */
size_t uxIndex; /**< The index within 'pucByte'. */
size_t uxPayloadDataLength; /**< The number of bytes in the UDP payload. */
size_t uxLength; /**< The size of the current option. */
uint32_t ulParameter; /**< The uint32 value of the answer, if available. */
uint32_t ulProcessed; /**< The number of essential options that were parsed. */
const uint8_t * pucByte; /**< A pointer to the data to be analysed. */
} ProcessSet_t;
/*
* NOT A PUBLIC API FUNCTION.
* It will be called when the DHCP timer expires, or when
* data has been received on the DHCP socket.
*/
void vDHCPProcess( BaseType_t xReset,
struct xNetworkEndPoint * pxEndPoint );
/*
* NOT A PUBLIC API FUNCTION.
* It will be called when the network interface, that the endpoint is associated with, goes down.
*/
void vDHCPStop( struct xNetworkEndPoint * pxEndPoint );
/* Internal call: returns true if socket is the current DHCP socket */
BaseType_t xIsDHCPSocket( const ConstSocket_t xSocket );
#if ( ipconfigUSE_DHCP_HOOK != 0 )
/* Prototype of the hook (or callback) function that must be provided by the
* application if ipconfigUSE_DHCP_HOOK is set to 1. See the following URL for
* usage information:
* http://www.FreeRTOS.org/FreeRTOS-Plus/FreeRTOS_Plus_TCP/TCP_IP_Configuration.html#ipconfigUSE_DHCP_HOOK
*/
#if ( ipconfigIPv4_BACKWARD_COMPATIBLE == 1 )
eDHCPCallbackAnswer_t xApplicationDHCPHook( eDHCPCallbackPhase_t eDHCPPhase,
uint32_t ulIPAddress );
#else /* ( ipconfigIPv4_BACKWARD_COMPATIBLE == 1 ) */
eDHCPCallbackAnswer_t xApplicationDHCPHook_Multi( eDHCPCallbackPhase_t eDHCPPhase,
struct xNetworkEndPoint * pxEndPoint,
IP_Address_t * pxIPAddress );
#endif /* ( ipconfigIPv4_BACKWARD_COMPATIBLE == 1 ) */
#endif /* ( ipconfigUSE_DHCP_HOOK != 0 ) */
#if ( ipconfigDHCP_FALL_BACK_AUTO_IP != 0 )
struct xNetworkEndPoint;
/**
* @brief When DHCP has failed, the code can assign a Link-Layer
* address, and check if another device already uses the IP-address.
*
* param[in] pxEndPoint: The end-point that wants to obtain a link-layer address.
*/
void prvPrepareLinkLayerIPLookUp( struct xNetworkEndPoint * pxEndPoint );
#endif
/* *INDENT-OFF* */
#ifdef __cplusplus
} /* extern "C" */
#endif
/* *INDENT-ON* */
#endif /* FREERTOS_DHCP_H */
@@ -0,0 +1,169 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
#ifndef FREERTOS_DHCPV6_H
#define FREERTOS_DHCPV6_H
/* Application level configuration options. */
#include "FreeRTOS_DHCP.h"
#include "FreeRTOSIPConfig.h"
#ifdef __cplusplus
extern "C" {
#endif
/* IPv6 option numbers. */
/** @brief IPv6 DHCP option number - Solicit */
#define DHCPv6_message_Type_Solicit 1U
/** @brief IPv6 DHCP option number - Advertise */
#define DHCPv6_message_Type_Advertise 2U
/** @brief IPv6 DHCP option number - Request */
#define DHCPv6_message_Type_Request 3U
/** @brief IPv6 DHCP option number - Confirm */
#define DHCPv6_message_Type_Confirm 4U
/** @brief IPv6 DHCP option number - Renew */
#define DHCPv6_message_Type_Renew 5U
/** @brief IPv6 DHCP option number - Reply */
#define DHCPv6_message_Type_Reply 7U
/** @brief IPv6 DHCP option number - Release */
#define DHCPv6_message_Type_Release 8U
/** @brief IPv6 DHCP option number - Decline */
#define DHCPv6_message_Type_Decline 9U
/* Note: IA stands for "Identity_Association". */
/** @brief IPv6 DHCP option - Client Identifier */
#define DHCPv6_Option_Client_Identifier 1U
/** @brief IPv6 DHCP option - Server Identifier */
#define DHCPv6_Option_Server_Identifier 2U
/** @brief IPv6 DHCP option - Non Temporary Address */
#define DHCPv6_Option_NonTemporaryAddress 3U
/** @brief IPv6 DHCP option - Temporary Address */
#define DHCPv6_Option_TemporaryAddress 4U
/** @brief IPv6 DHCP option - Identity_Association Address */
#define DHCPv6_Option_IA_Address 5U
/** @brief IPv6 DHCP option - Option */
#define DHCPv6_Option_Option_List 6U
/** @brief IPv6 DHCP option - Preference */
#define DHCPv6_Option_Preference 7U
/** @brief IPv6 DHCP option - Elapsed time */
#define DHCPv6_Option_Elapsed_Time 8U
/** @brief IPv6 DHCP option - Status code */
#define DHCPv6_Option_Status_Code 13U
/** @brief IPv6 DHCP option - Recursive name server */
#define DHCPv6_Option_DNS_recursive_name_server 23U
/** @brief IPv6 DHCP option - Search list */
#define DHCPv6_Option_Domain_Search_List 24U
/** @brief IPv6 DHCP option - IA for prefix delegation */
#define DHCPv6_Option_IA_for_Prefix_Delegation 25U
/** @brief IPv6 DHCP option - IA Prefix */
#define DHCPv6_Option_IA_Prefix 26U
/** @brief DHCPv6 option request, used in combination with 'DHCPv6_Option_Option_List' */
#define DHCP6_OPTION_REQUEST_DNS 0x0017
/** @brief DHCPv6 option request domain search list, used in combination with 'DHCPv6_Option_Option_List' */
#define DHCP6_OPTION_REQUEST_DOMAIN_SEARCH_LIST 0x0018
#define DHCPv6_MAX_CLIENT_SERVER_ID_LENGTH 128
/** @brief The function time() counts since 1-1-1970. The DHCPv6 time-stamp however
* uses a time stamp that had zero on 1-1-2000. */
#define SECS_FROM_1970_TILL_2000 946684800U
/** @brief If a lease time is not received, use the default of two days. 48 hours in ticks.
* Do not use the macro pdMS_TO_TICKS() here as integer overflow can occur. */
#define dhcpv6DEFAULT_LEASE_TIME ( ( 48U * 60U * 60U ) * configTICK_RATE_HZ )
/** @brief Don't allow the lease time to be too short. */
#define dhcpv6MINIMUM_LEASE_TIME ( pdMS_TO_TICKS( 60000U ) ) /* 60 seconds in ticks. */
/** @brief Default v6 DHCP client port. */
#define ipDHCPv6_CLIENT_PORT 546U
/** @brief Default v6 DHCP server port. */
#define ipDHCPv6_SERVER_PORT 547U
/** @brief The ID of a client or a server. */
typedef struct xClientServerID
{
uint16_t usDUIDType; /**< A DHCP Unique Identifier ( DUID ). */
uint16_t usHardwareType; /**< The hardware type: 1 = Ethernet. */
uint8_t pucID[ DHCPv6_MAX_CLIENT_SERVER_ID_LENGTH ]; /**< Universally Unique IDentifier (UUID) format. */
size_t uxLength; /**< The number of valid bytes within 'pucID'. */
} ClientServerID_t;
/** @brief DHCPMessage_IPv6_t holds all data of a DHCP client. */
typedef struct xDHCPMessage_IPv6
{
uint8_t uxMessageType; /**< The type of the last message received: Advertise / Confirm / Reply / Decline */
uint8_t ucTransactionID[ 3 ]; /**< ID of a transaction, shall be renewed when the transaction is ready ( and a reply has been received ). */
uint32_t ulTransactionID; /**< The same as above but now as a long integer. */
IP_Address_t xDNSServers[ ipconfigENDPOINT_DNS_ADDRESS_COUNT ]; /**< The IP-address of the DNS server. */
size_t uxDNSCount; /**< The number of the DNS server stored in xDNSServers. */
uint32_t ulPreferredLifeTime; /**< The preferred life time. */
uint32_t ulValidLifeTime; /**< The valid life time. */
uint32_t ulTimeStamp; /**< DUID Time: seconds since 1-1-2000. */
uint8_t ucprefixLength; /**< The length of the prefix offered. */
uint8_t ucHasUID; /**< When pdFALSE: a transaction ID must be created. */
IP_Address_t xPrefixAddress; /**< The prefix offered. */
IP_Address_t xIPAddress; /**< The IP-address offered. */
ClientServerID_t xClientID; /**< The UUID of the client. */
ClientServerID_t xServerID; /**< The UUID of the server. */
} DHCPMessage_IPv6_t;
/** @brief A struct describing an option. */
typedef struct xDHCPOptionSet
{
size_t uxOptionLength; /**< The length of the option being handled. */
size_t uxStart; /**< The position in xMessage where the option starts. */
} DHCPOptionSet_t;
struct xNetworkEndPoint;
/* Returns the current state of a DHCP process. */
eDHCPState_t eGetDHCPv6State( struct xNetworkEndPoint * pxEndPoint );
/*
* NOT A PUBLIC API FUNCTION.
* It will be called when the DHCP timer expires, or when
* data has been received on the DHCP socket.
*/
void vDHCPv6Process( BaseType_t xReset,
struct xNetworkEndPoint * pxEndPoint );
/*
* NOT A PUBLIC API FUNCTION.
* It will be called when the network interface, that the endpoint is associated with, goes down.
*/
void vDHCPv6Stop( struct xNetworkEndPoint * pxEndPoint );
#ifdef __cplusplus
} /* extern "C" */
#endif
/* The application should supply the following time-function.
* It must return the number of seconds that have passed since
* 1/1/1970. */
extern uint32_t ulApplicationTimeHook( void );
#endif /* FREERTOS_DHCPV6_H */
@@ -0,0 +1,175 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* https://github.com/FreeRTOS
* https://www.FreeRTOS.org
*/
#ifndef FREERTOS_DNS_H
#define FREERTOS_DNS_H
#include "FreeRTOS.h"
/* Application level configuration options. */
#include "FreeRTOS_DNS_Globals.h"
#include "FreeRTOS_DNS_Callback.h"
#include "FreeRTOS_DNS_Cache.h"
/* *INDENT-OFF* */
#ifdef __cplusplus
extern "C" {
#endif
/* *INDENT-ON* */
/* The LLMNR MAC address is 01:00:5e:00:00:fc */
extern const MACAddress_t xLLMNR_MacAddress;
/* The LLMNR IPv6 MAC address is 33:33:00:01:00:03 */
extern const MACAddress_t xLLMNR_MacAddressIPv6;
#if ( ( ipconfigUSE_LLMNR != 0 ) && ( ipconfigUSE_IPv6 != 0 ) )
/* The LLMNR IPv6 address is ff02::1:3 */
extern const IPv6_Address_t ipLLMNR_IP_ADDR_IPv6;
#endif /* ( ( ipconfigUSE_LLMNR != 0 ) && ( ipconfigUSE_IPv6 != 0 ) ) */
/* The MDNS MAC address is 01:00:5e:00:00:fc */
extern const MACAddress_t xMDNS_MacAddress;
/* The MDNS IPv6 MAC address is 33:33:00:01:00:03 */
/* This type-name was formally "misspelled" as
* xMDNS_MACAddressIPv6 with "MAC": */
extern const MACAddress_t xMDNS_MacAddressIPv6;
/* Guarantee backward compatibility. */
#define xMDNS_MACAddressIPv6 xMDNS_MacAddressIPv6
#if ( ( ipconfigUSE_MDNS != 0 ) && ( ipconfigUSE_IPv6 != 0 ) )
/* The MDNS IPv6 address is ff02::1:3 */
extern const IPv6_Address_t ipMDNS_IP_ADDR_IPv6;
#endif /* ( ( ipconfigUSE_MDNS != 0 ) && ( ipconfigUSE_IPv6 != 0 ) ) */
/** @brief While doing integration tests, it is necessary to influence the choice
* between DNS/IPv4 and DNS/IPv4. Depending on this, a DNS server will be
* addressed via IPv4 or IPv6 messages. */
typedef enum xIPPreference
{
xPreferenceNone,
xPreferenceIPv4
#if ( ipconfigUSE_IPv6 != 0 )
,
xPreferenceIPv6
#endif
} IPPreference_t;
/** @brief This variable determines he choice of DNS server, either IPv4 or IPv6. */
extern IPPreference_t xDNS_IP_Preference;
/*
* LLMNR is very similar to DNS, so is handled by the DNS routines.
*/
BaseType_t xDNSHandlePacket( const NetworkBufferDescriptor_t * pxNetworkBuffer );
#if ( ipconfigUSE_NBNS != 0 )
/*
* Inspect a NetBIOS Names-Service message. If the name matches with ours
* (xApplicationDNSQueryHook returns true) an answer will be sent back.
* Note that LLMNR is a better protocol for name services on a LAN as it is
* less polluted
*/
uint32_t ulNBNSHandlePacket( NetworkBufferDescriptor_t * pxNetworkBuffer );
#endif /* ipconfigUSE_NBNS */
#if ( ipconfigDNS_USE_CALLBACKS != 0 )
/*
* Asynchronous version of gethostbyname()
* xTimeout is in units of ms.
*/
uint32_t FreeRTOS_gethostbyname_a( const char * pcHostName,
FOnDNSEvent pCallback,
void * pvSearchID,
TickType_t uxTimeout );
void FreeRTOS_gethostbyname_cancel( void * pvSearchID );
/* The asynchronous versions of FreeRTOS_getaddrinfo(). */
BaseType_t FreeRTOS_getaddrinfo_a( const char * pcName, /* The name of the node or device */
const char * pcService, /* Ignored for now. */
const struct freertos_addrinfo * pxHints, /* If not NULL: preferences. */
struct freertos_addrinfo ** ppxResult, /* An allocated struct, containing the results. */
FOnDNSEvent pCallback,
void * pvSearchID,
TickType_t uxTimeout );
#endif /* if ( ipconfigDNS_USE_CALLBACKS != 0 ) */
/*
* Lookup a IPv4 node in a blocking-way.
* It returns a 32-bit IP-address, 0 when not found.
* gethostbyname() is already deprecated.
*/
uint32_t FreeRTOS_gethostbyname( const char * pcHostName );
/* _HT_ Although this function is private to the library, it needs a global declaration. */
struct freertos_addrinfo * pxNew_AddrInfo( const char * pcName,
BaseType_t xFamily,
const uint8_t * pucAddress );
/*
* FreeRTOS_getaddrinfo() replaces FreeRTOS_gethostbyname().
* When 'ipconfigUSE_IPv6' is defined, it can also retrieve IPv6 addresses,
* in case pxHints->ai_family equals FREERTOS_AF_INET6.
* Otherwise, or when pxHints is NULL, only IPv4 addresses will be returned.
*/
BaseType_t FreeRTOS_getaddrinfo( const char * pcName, /* The name of the node or device */
const char * pcService, /* Ignored for now. */
const struct freertos_addrinfo * pxHints, /* If not NULL: preferences. */
struct freertos_addrinfo ** ppxResult ); /* An allocated struct, containing the results. */
/* When FreeRTOS_getaddrinfo() is successful, ppxResult will point to an
* allocated structure. This pointer must be released by the user by calling
* FreeRTOS_freeaddrinfo().
*/
void FreeRTOS_freeaddrinfo( struct freertos_addrinfo * pxInfo );
/* Sets the DNS IP preference while doing DNS lookup to indicate the preference
* for a DNS server: either IPv4 or IPv6. Defaults to xPreferenceIPv4 */
BaseType_t FreeRTOS_SetDNSIPPreference( IPPreference_t eIPPreference );
#if ( ipconfigDNS_USE_CALLBACKS == 1 )
/*
* The function vDNSInitialise() initialises the DNS module.
* It will be called "internally", by the IP-task.
*/
void vDNSInitialise( void );
#endif /* ( ipconfigDNS_USE_CALLBACKS == 1 ) */
/* *INDENT-OFF* */
#ifdef __cplusplus
} /* extern "C" */
#endif
/* *INDENT-ON* */
#endif /* FREERTOS_DNS_H */
@@ -0,0 +1,84 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* https://github.com/FreeRTOS
* https://www.FreeRTOS.org
*/
#ifndef FREERTOS_DNS_CACHE_H
#define FREERTOS_DNS_CACHE_H
/* FreeRTOS includes. */
#include "FreeRTOS.h"
#include "FreeRTOS_DNS_Globals.h"
/* Standard includes. */
#include <stdint.h>
#if ( ( ipconfigUSE_DNS_CACHE == 1 ) && ( ipconfigUSE_DNS != 0 ) )
/**
* @brief cache entry format structure
*/
typedef struct xDNS_CACHE_TABLE_ROW
{
IPv46_Address_t xAddresses[ ipconfigDNS_CACHE_ADDRESSES_PER_ENTRY ]; /*!< The IP address(es) of a DNS cache entry. */
char pcName[ ipconfigDNS_CACHE_NAME_LENGTH ]; /*!< The name of the host */
uint32_t ulTTL; /*!< Time-to-Live (in seconds) from the DNS server. */
uint32_t ulTimeWhenAddedInSeconds; /*!< time at which the entry was added */
#if ( ipconfigDNS_CACHE_ADDRESSES_PER_ENTRY > 1 )
uint8_t ucNumIPAddresses; /*!< number of ip addresses for the same entry */
uint8_t ucCurrentIPAddress; /*!< current ip address index */
#endif
} DNSCacheRow_t;
/* Look for the indicated host name in the DNS cache. Returns the IPv4
* address if present, or 0x0 otherwise. */
uint32_t FreeRTOS_dnslookup( const char * pcHostName );
void FreeRTOS_dnsclear( void );
/**
* @brief For debugging only: prints the contents of the DNS cache table.
*/
void vShowDNSCacheTable( void );
BaseType_t FreeRTOS_dns_update( const char * pcName,
IPv46_Address_t * pxIP,
uint32_t ulTTL,
BaseType_t xLookUp,
struct freertos_addrinfo ** ppxAddressInfo );
BaseType_t FreeRTOS_ProcessDNSCache( const char * pcName,
IPv46_Address_t * pxIP,
uint32_t ulTTL,
BaseType_t xLookUp,
struct freertos_addrinfo ** ppxAddressInfo );
uint32_t Prepare_CacheLookup( const char * pcHostName,
BaseType_t xFamily,
struct freertos_addrinfo ** ppxAddressInfo );
#endif /* if ( ipconfigUSE_DNS_CACHE == 1 ) */
#endif /* FREERTOS_DNS_CACHE_H */
@@ -0,0 +1,75 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* https://github.com/FreeRTOS
* https://www.FreeRTOS.org
*/
#ifndef FREERTOS_DNS_CALLBACK_H
#define FREERTOS_DNS_CALLBACK_H
/* FreeRTOS includes. */
#include "FreeRTOS.h"
/* FreeRTOS+TCP includes. */
#include "FreeRTOS_IP.h"
#include "FreeRTOS_DNS_Globals.h"
/* Standard includes. */
#include <stdint.h>
/* *INDENT-OFF* */
#ifdef __cplusplus
extern "C" {
#endif
/* *INDENT-ON* */
/* Application level configuration options. */
#if ( ( ipconfigDNS_USE_CALLBACKS == 1 ) && ( ipconfigUSE_DNS != 0 ) )
BaseType_t xDNSDoCallback( ParseSet_t * pxSet,
struct freertos_addrinfo * pxAddress );
BaseType_t xDNSSetCallBack( const char * pcHostName,
void * pvSearchID,
FOnDNSEvent pCallbackFunction,
TickType_t uxTimeout,
TickType_t uxIdentifier,
BaseType_t xIsIPv6 );
void vDNSCheckCallBack( void * pvSearchID );
void vDNSCallbackInitialise( void );
#endif /* ipconfigDNS_USE_CALLBACKS && ipconfigUSE_DNS */
/* *INDENT-OFF* */
#ifdef __cplusplus
} /* extern "C" */
#endif
/* *INDENT-ON* */
#endif /* FREERTOS_DNS_CALLBACK_H */
@@ -0,0 +1,315 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
#ifndef FREERTOS_DNS_GLOBALS_H
#define FREERTOS_DNS_GLOBALS_H
#include "FreeRTOS.h"
#include "FreeRTOSIPConfig.h"
#include "FreeRTOSIPConfigDefaults.h"
#include "FreeRTOS_Sockets.h"
#define dnsPARSE_ERROR 0UL
#if ( ipconfigBYTE_ORDER == pdFREERTOS_LITTLE_ENDIAN )
#define dnsDNS_PORT 0x3500U /**< Little endian: Port used for DNS. */
#define dnsONE_QUESTION 0x0100U /**< Little endian representation of a DNS question.*/
#define dnsOUTGOING_FLAGS 0x0001U /**< Little endian representation of standard query. */
#define dnsRX_FLAGS_MASK 0x0f80U /**< Little endian: The bits of interest in the flags field of incoming DNS messages. */
#define dnsEXPECTED_RX_FLAGS 0x0080U /**< Little Endian: Should be a response, without any errors. */
#else
#define dnsDNS_PORT 0x0035U /**< Big endian: Port used for DNS. */
#define dnsONE_QUESTION 0x0001U /**< Big endian representation of a DNS question.*/
#define dnsOUTGOING_FLAGS 0x0100U /**< Big endian representation of standard query. */
#define dnsRX_FLAGS_MASK 0x800fU /**< Big endian: The bits of interest in the flags field of incoming DNS messages. */
#define dnsEXPECTED_RX_FLAGS 0x8000U /**< Big endian: Should be a response, without any errors. */
#endif /* ipconfigBYTE_ORDER */
#if ( ipconfigUSE_DNS != 0 )
/** @brief If the top two bits in the first character of a name field are set then the
* name field is an offset to the string, rather than the string itself. */
#define dnsNAME_IS_OFFSET ( ( uint8_t ) 0xc0 )
/* NBNS flags. */
#if ( ipconfigUSE_NBNS == 1 )
#define dnsNBNS_FLAGS_RESPONSE 0x8000U /**< NBNS response flag. */
#define dnsNBNS_FLAGS_OPCODE_MASK 0x7800U /**< NBNS opcode bitmask. */
#define dnsNBNS_FLAGS_OPCODE_QUERY 0x0000U /**< NBNS opcode query. */
#endif /* ( ipconfigUSE_NBNS == 1 ) */
/* Host types. */
#define dnsTYPE_A_HOST 0x01U /**< DNS type A host. */
#define dnsTYPE_AAAA_HOST 0x001CU
#define dnsTYPE_ANY_HOST 0x00FFU
#define dnsCLASS_IN 0x01U /**< DNS class IN (Internet). */
/* Maximum hostname length as defined in RFC 1035 section 3.1. */
#define dnsMAX_HOSTNAME_LENGTH 0xFFU
#ifndef _lint
/* LLMNR constants. */
#define dnsLLMNR_TTL_VALUE 300U /**< LLMNR time to live value of 5 minutes. */
#define dnsLLMNR_FLAGS_IS_RESPONSE 0x8000U /**< LLMNR flag value for response. */
#endif /* _lint */
/* NBNS constants. */
#if ( ipconfigUSE_NBNS != 0 )
#define dnsNBNS_TTL_VALUE 3600UL /**< NBNS TTL: 1 hour valid. */
#define dnsNBNS_TYPE_NET_BIOS 0x0020U /**< NBNS Type: NetBIOS. */
#define dnsNBNS_CLASS_IN 0x01U /**< NBNS Class: IN (Internet). */
#define dnsNBNS_NAME_FLAGS 0x6000U /**< NBNS name flags. */
#define dnsNBNS_ENCODED_NAME_LENGTH 32 /**< NBNS encoded name length. */
/** @brief If the queried NBNS name matches with the device's name,
* the query will be responded to with these flags: */
#define dnsNBNS_QUERY_RESPONSE_FLAGS ( 0x8500U )
#endif /* ( ipconfigUSE_NBNS != 0 ) */
/** @brief Define the ASCII value of '.' (Period/Full-stop). */
#define ASCII_BASELINE_DOT 46U
/* The Link-local Multicast Name Resolution (LLMNR)
* is included.
* Note that a special MAC address is required in addition to the NIC's actual
* MAC address: 01:00:5E:00:00:FC
*
* The target IP address will be 224.0.0.252
*/
#if ( ipconfigBYTE_ORDER == pdFREERTOS_BIG_ENDIAN )
#define ipLLMNR_IP_ADDR 0xE00000FCUL
#else
#define ipLLMNR_IP_ADDR 0xFC0000E0UL
#endif /* ipconfigBYTE_ORDER == pdFREERTOS_BIG_ENDIAN */
/* MDNS constants. */
#define ipMDNS_TIME_TO_LIVE 255U
#define dnsMDNS_FLAGS_IS_RESPONSE 0x8400U /**< MDNS flag value for response. */
#define ipLLMNR_PORT 5355U /* Standard LLMNR port. */
#define ipDNS_PORT 53U /* Standard DNS port. */
#define ipNBNS_PORT 137U /* NetBIOS Name Service. */
#define ipNBDGM_PORT 138U /* Datagram Service, not included. */
/** @brief freertos_addrinfo is the equivalent of 'struct addrinfo'. */
struct freertos_addrinfo
{
BaseType_t ai_flags; /**< The field is included for completeness, but it is not used. */
BaseType_t ai_family; /**< The type of IP-address, either FREERTOS_AF_INET4 or FREERTOS_AF_INET6. */
BaseType_t ai_socktype; /**< n.a. */
BaseType_t ai_protocol; /**< n.a. */
socklen_t ai_addrlen; /**< The length of the address, either ipSIZE_OF_IPv4_ADDRESS or ipSIZE_OF_IPv6_ADDRESS. */
struct freertos_sockaddr * ai_addr; /**< The socket address. */
char * ai_canonname; /**< The name of the host. */
struct freertos_addrinfo * ai_next; /**< A pointer to the next find result, or NULL. */
struct
{
/* In order to avoid allocations, reserve space here for *ai_addr and *ai_canonname. */
struct freertos_sockaddr sockaddr;
#if ( ipconfigUSE_DNS_CACHE != 0 )
char ucName[ ipconfigDNS_CACHE_NAME_LENGTH ];
#endif
}
xPrivateStorage; /**< In order to avoid extra calls to malloc, the necessary space is reserved 'statically'. */
};
/* DNS answer record header. */
#include "pack_struct_start.h"
struct xDNSAnswerRecord
{
uint16_t usType; /**< Type of DNS answer record. */
uint16_t usClass; /**< Class of DNS answer record. */
uint32_t ulTTL; /**< Number of seconds the result can be cached. */
uint16_t usDataLength; /**< Length of the data field. */
}
#include "pack_struct_end.h"
typedef struct xDNSAnswerRecord DNSAnswerRecord_t;
/* Below #include just tells the compiler to pack the structure.
* It is included in to make the code more readable */
#include "pack_struct_start.h"
struct xDNSMessage
{
uint16_t usIdentifier; /**< Query identifier. Used to match up replies to outstanding queries. */
uint16_t usFlags; /**< Flags. */
uint16_t usQuestions; /**< Number of questions asked in this query. */
uint16_t usAnswers; /**< Number of answers being provided in this query. */
uint16_t usAuthorityRRs; /**< Authoritative name server resource records. */
uint16_t usAdditionalRRs; /**< Additional resource records.*/
}
#include "pack_struct_end.h"
typedef struct xDNSMessage DNSMessage_t;
/** @brief A struct with a set of variables that are shared among the helper functions
* for the function 'DNS_ParseDNSReply()'. For internal use only.
*/
typedef struct xParseSet
{
DNSMessage_t * pxDNSMessageHeader; /**< A pointer to the UDP payload buffer where the DNS message is stored. */
uint16_t usQuestions; /**< The number of DNS questions that were asked. */
uint16_t usAnswers; /**< The number of DNS answers that were given. */
uint8_t * pucUDPPayloadBuffer; /**< A pointer to the original UDP load buffer. */
uint8_t * pucByte; /**< A pointer that is used while parsing. */
size_t uxSkipCount; /**< Points to the byte after the complete name (mDNS only) */
size_t uxBufferLength; /**< The total number of bytes received in the UDP payload. */
size_t uxSourceBytesRemaining; /**< As pucByte is incremented, 'uxSourceBytesRemaining' will be decremented. */
uint16_t usType; /**< The type of address, recognised are dnsTYPE_A_HOST ( Ipv4 ) and
* dnsTYPE_AAAA_HOST ( IPv6 ). */
uint32_t ulIPAddress; /**< The IPv4 address found. In an IPv6 look-up, store a non-zero value when
* an IPv6 address was found. */
size_t uxAddressLength; /**< The size of the address, either ipSIZE_OF_IPv4_ADDRESS or
* ipSIZE_OF_IPv6_ADDRESS */
uint16_t usNumARecordsStored; /**< The number of A-records stored during a look-up. */
uint16_t usPortNumber; /**< The port number that belong to the protocol ( DNS, MDNS etc ). */
#if ( ipconfigUSE_LLMNR == 1 ) || ( ipconfigUSE_MDNS == 1 )
uint16_t usClass; /**< Only the value 'dnsCLASS_IN' is recognised, which stands for "Internet". */
char * pcRequestedName; /**< A pointer to the full name of the host being looked up. */
#endif
#if ( ( ipconfigUSE_DNS_CACHE != 0 ) || ( ipconfigDNS_USE_CALLBACKS != 0 ) || ( ipconfigUSE_MDNS != 0 ) || ( ipconfigUSE_LLMNR != 0 ) )
BaseType_t xDoStore; /**< Becomes true when a DNS reply was requested by this device,
* i.e. it has a matching request ID. */
char pcName[ ipconfigDNS_CACHE_NAME_LENGTH ]; /**< A copy of the name that is mentioned in the questions. */
#endif
struct freertos_addrinfo * pxLastAddress; /**< This variable is used while creating a linked-list of IP-addresses. */
struct freertos_addrinfo ** ppxLastAddress; /**< This variable is also used while creating a linked-list of IP-addresses. */
} ParseSet_t;
#if ( ipconfigUSE_LLMNR == 1 ) || ( ipconfigUSE_MDNS == 1 )
#include "pack_struct_start.h"
struct xLLMNRAnswer
{
uint8_t ucNameCode; /**< Name type. */
uint8_t ucNameOffset; /**< The name is not repeated in the answer, only the offset is given with "0xc0 <offs>" */
uint16_t usType; /**< Type of the Resource record. */
uint16_t usClass; /**< Class of the Resource record. */
uint32_t ulTTL; /**< Seconds till this entry can be cached. */
uint16_t usDataLength; /**< Length of the address in this record. */
uint32_t ulIPAddress; /**< The IP-address. */
}
#include "pack_struct_end.h"
typedef struct xLLMNRAnswer LLMNRAnswer_t;
#endif /* if ( ipconfigUSE_LLMNR == 1 ) || ( ipconfigUSE_MDNS == 1 ) */
#if ( ipconfigUSE_NBNS == 1 )
#include "pack_struct_start.h"
struct xNBNSRequest
{
uint16_t usRequestId; /**< NBNS request ID. */
uint16_t usFlags; /**< Flags of the DNS message. */
uint16_t ulRequestCount; /**< The number of requests/questions in this query. */
uint16_t usAnswerRSS; /**< The number of answers in this query. */
uint16_t usAuthRSS; /**< Number of authoritative resource records. */
uint16_t usAdditionalRSS; /**< Number of additional resource records. */
uint8_t ucNameSpace; /**< Length of name. */
uint8_t ucName[ dnsNBNS_ENCODED_NAME_LENGTH ]; /**< The domain name. */
uint8_t ucNameZero; /**< Terminator of the name. */
uint16_t usType; /**< Type of NBNS record. */
uint16_t usClass; /**< Class of NBNS request. */
}
#include "pack_struct_end.h"
typedef struct xNBNSRequest NBNSRequest_t;
#include "pack_struct_start.h"
struct xNBNSAnswer
{
uint16_t usType; /**< Type of NBNS answer. */
uint16_t usClass; /**< Class of NBNS answer. */
uint32_t ulTTL; /**< Time in seconds for which the answer can be cached. */
uint16_t usDataLength; /**< Data length. */
uint16_t usNbFlags; /**< NetBIOS flags 0x6000 : IP-address, big-endian. */
uint32_t ulIPAddress; /**< The IPv4 address. */
}
#include "pack_struct_end.h"
typedef struct xNBNSAnswer NBNSAnswer_t;
#endif /* if ( ipconfigUSE_NBNS == 1 ) */
#if ( ipconfigDNS_USE_CALLBACKS != 0 )
/*
* Users may define this type of function as a callback.
* It will be called when a DNS reply is received or when a timeout has been reached.
*/
typedef void (* FOnDNSEvent ) ( const char * /* pcName */,
void * /* pvSearchID */,
struct freertos_addrinfo * /* pxAddressInfo */ );
/** @brief The structure to hold information for a DNS callback. */
typedef struct xDNS_Callback
{
TickType_t uxRemainingTime; /**< Timeout in ms */
FOnDNSEvent pCallbackFunction; /**< Function to be called when the address has been found or when a timeout has been reached */
TimeOut_t uxTimeoutState; /**< Timeout state. */
void * pvSearchID; /**< Search ID of the callback function. */
struct xLIST_ITEM xListItem; /**< List struct. */
BaseType_t xIsIPv6; /**< Remember whether this was a IPv6 lookup. */
char pcName[ 1 ]; /**< 1 character name. */
} DNSCallback_t;
#endif /* if ( ipconfigDNS_USE_CALLBACKS != 0 ) */
/**
* @brief structure to hold the buffer, its size and the data length
*/
typedef struct xDNSBuffer
{
uint8_t * pucPayloadBuffer; /**< Buffer pointer */
size_t uxPayloadLength; /**< Payload size */
} DNSBuffer_t;
#if ( ipconfigUSE_MDNS == 1 ) || ( ipconfigUSE_LLMNR == 1 ) || ( ipconfigUSE_NBNS == 1 )
/*
* The following function should be provided by the user and return true if it
* matches the domain name.
*/
#if ( ipconfigIPv4_BACKWARD_COMPATIBLE == 1 )
/* Even though the function is defined in main.c, the rule is violated. */
/* misra_c_2012_rule_8_6_violation */
extern BaseType_t xApplicationDNSQueryHook( const char * pcName );
#else
/* Even though the function is defined in main.c, the rule is violated. */
/* misra_c_2012_rule_8_6_violation */
extern BaseType_t xApplicationDNSQueryHook_Multi( struct xNetworkEndPoint * pxEndPoint,
const char * pcName );
#endif
#endif /* ( ipconfigUSE_LLMNR == 1 ) || ( ipconfigUSE_NBNS == 1 ) */
#endif /* ipconfigUSE_DNS */
/* Keeping this outside of ipconfigUSE_DNS flag as these are used inside IPv4 UDP code */
#define ipMDNS_PORT 5353U /* Standard mDNS port. */
#if ( ipconfigBYTE_ORDER == pdFREERTOS_BIG_ENDIAN )
#define ipMDNS_IP_ADDRESS 0xe00000fbU /* 224.0.0.251 */
#else
#define ipMDNS_IP_ADDRESS 0xfb0000e0U /* 224.0.0.251 */
#endif
#endif /* FREERTOS_DNS_GLOBALS_H */
@@ -0,0 +1,62 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* https://github.com/FreeRTOS
* https://www.FreeRTOS.org
*/
#ifndef FREERTOS_DNS_NETWORKING_H
#define FREERTOS_DNS_NETWORKING_H
#include "FreeRTOS_IP.h"
#include "FreeRTOS_Sockets.h"
#include "FreeRTOS_DNS_Globals.h"
#if ( ipconfigUSE_DNS != 0 )
/*
* Create a socket and bind it to the standard DNS port number. Return the
* the created socket - or NULL if the socket could not be created or bound.
*/
Socket_t DNS_CreateSocket( TickType_t uxReadTimeOut_ticks );
/**
* @brief Bind the socket to a port number.
* @param[in] xSocket: the socket that must be bound.
* @param[in] usPort: the port number to bind to.
* @return The created socket - or NULL if the socket could not be created or could not be bound.
*/
BaseType_t DNS_BindSocket( Socket_t xSocket,
uint16_t usPort );
BaseType_t DNS_SendRequest( Socket_t xDNSSocket,
const struct freertos_sockaddr * xAddress,
const struct xDNSBuffer * pxDNSBuf );
BaseType_t DNS_ReadReply( ConstSocket_t xDNSSocket,
struct freertos_sockaddr * xAddress,
struct xDNSBuffer * pxReceiveBuffer );
void DNS_CloseSocket( Socket_t xDNSSocket );
#endif /* if ( ipconfigUSE_DNS != 0 ) */
#endif /* FREERTOS_DNS_NETWORKING_H */
@@ -0,0 +1,104 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* https://github.com/FreeRTOS
* https://www.FreeRTOS.org
*/
#ifndef FREERTOS_DNS_PARSER_H
#define FREERTOS_DNS_PARSER_H
/* FreeRTOS includes. */
#include "FreeRTOS.h"
/* FreeRTOS+TCP includes. */
#include "FreeRTOS_IP.h"
#include "FreeRTOS_DNS_Globals.h"
/* Standard includes. */
#include <stdint.h>
/* *INDENT-OFF* */
#ifdef __cplusplus
extern "C" {
#endif
/* *INDENT-ON* */
#if ( ipconfigUSE_DNS != 0 )
/** @brief Flag DNS parsing errors in situations where an IPv4 address is the return
* type. */
#if ( ipconfigUSE_DNS_CACHE == 1 ) || ( ipconfigDNS_USE_CALLBACKS == 1 )
size_t DNS_ReadNameField( ParseSet_t * pxSet,
size_t uxDestLen );
#endif /* ipconfigUSE_DNS_CACHE || ipconfigDNS_USE_CALLBACKS */
/*
* Simple routine that jumps over the NAME field of a resource record.
* It returns the number of bytes read.
*/
size_t DNS_SkipNameField( const uint8_t * pucByte,
size_t uxLength );
/*
* Process a response packet from a DNS server.
* The parameter 'xExpected' indicates whether the identifier in the reply
* was expected, and thus if the DNS cache may be updated with the reply.
*/
uint32_t DNS_ParseDNSReply( uint8_t * pucUDPPayloadBuffer,
size_t uxBufferLength,
struct freertos_addrinfo ** ppxAddressInfo,
BaseType_t xExpected,
uint16_t usPort );
/*
* The NBNS and the LLMNR protocol share this reply function.
*/
#if ( ( ipconfigUSE_MDNS == 1 ) || ( ipconfigUSE_LLMNR == 1 ) || ( ipconfigUSE_NBNS == 1 ) )
void prepareReplyDNSMessage( NetworkBufferDescriptor_t * pxNetworkBuffer,
BaseType_t lNetLength );
#endif
#if ( ipconfigUSE_NBNS == 1 )
void DNS_TreatNBNS( uint8_t * pucPayload,
size_t uxBufferLength,
uint32_t ulIPAddress );
#endif
/**
* Parse the DNS answer/response.
*/
uint32_t parseDNSAnswer( ParseSet_t * pxSet,
struct freertos_addrinfo ** ppxAddressInfo,
size_t * uxBytesRead );
#endif /* if ( ipconfigUSE_DNS != 0 ) */
/* *INDENT-OFF* */
#ifdef __cplusplus
} /* extern "C" */
#endif
/* *INDENT-ON* */
#endif /* FREERTOS_DNS_PARSER_H */
@@ -0,0 +1,64 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
/**
* @file FreeRTOS_ICMP.h
* @brief Header file for Internet Control Message Protocol for the FreeRTOS+TCP network stack.
*/
#ifndef FREERTOS_ICMP_H
#define FREERTOS_ICMP_H
/* FreeRTOS+TCP includes. */
#include "FreeRTOS_IP.h"
#include "FreeRTOS_IP_Private.h"
/* *INDENT-OFF* */
#ifdef __cplusplus
extern "C" {
#endif
/* *INDENT-ON* */
/* ICMP protocol definitions. */
#define ipICMP_ECHO_REQUEST ( ( uint8_t ) 8 ) /**< ICMP echo request. */
#define ipICMP_ECHO_REPLY ( ( uint8_t ) 0 ) /**< ICMP echo reply. */
#if ( ipconfigREPLY_TO_INCOMING_PINGS == 1 ) || ( ipconfigSUPPORT_OUTGOING_PINGS == 1 )
/*
* Process incoming ICMP packets.
*/
eFrameProcessingResult_t ProcessICMPPacket( const NetworkBufferDescriptor_t * const pxNetworkBuffer );
#endif /* ( ipconfigREPLY_TO_INCOMING_PINGS == 1 ) || ( ipconfigSUPPORT_OUTGOING_PINGS == 1 ) */
/* *INDENT-OFF* */
#ifdef __cplusplus
} /* extern "C" */
#endif
/* *INDENT-ON* */
#endif /* FREERTOS_ICMP_H */
@@ -0,0 +1,501 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
#ifndef FREERTOS_IP_H
#define FREERTOS_IP_H
#include "FreeRTOS.h"
#include "task.h"
/* Application level configuration options. */
#include "FreeRTOSIPConfig.h"
#include "FreeRTOSIPConfigDefaults.h"
#include "FreeRTOS_IP_Common.h"
/* *INDENT-OFF* */
#ifdef __cplusplus
extern "C" {
#endif
/* *INDENT-ON* */
/* Constants defining the current version of the FreeRTOS+TCP
* network stack. */
#define ipFR_TCP_VERSION_NUMBER "V4.4.1"
#define ipFR_TCP_VERSION_MAJOR 4
#define ipFR_TCP_VERSION_MINOR 4
/* Development builds are always version 999. */
#define ipFR_TCP_VERSION_BUILD 1
/* Some constants defining the sizes of several parts of a packet.
* These defines come before including the configuration header files. */
/* The size of the Ethernet header is 14, meaning that 802.1Q VLAN tags
* are not ( yet ) supported. */
#define ipSIZE_OF_ETH_HEADER 14U
#define ipSIZE_OF_IGMP_HEADER 8U
#define ipSIZE_OF_UDP_HEADER 8U
#define ipSIZE_OF_TCP_HEADER 20U
/* The maximum of int32 value. */
#define ipINT32_MAX_VALUE ( ( int32_t ) 0x7FFFFFFFU )
/* The minimum of int32 value. */
#define ipINT32_MIN_VALUE ( ( int32_t ) 0x80000000U )
/*
* Generate a randomized TCP Initial Sequence Number per RFC.
* This function must be provided by the application builder.
*/
/* This function is defined generally by the application. */
extern uint32_t ulApplicationGetNextSequenceNumber( uint32_t ulSourceAddress,
uint16_t usSourcePort,
uint32_t ulDestinationAddress,
uint16_t usDestinationPort );
/* The number of octets in the MAC and IP addresses respectively. */
#define ipMAC_ADDRESS_LENGTH_BYTES ( 6U )
#define ipIP_ADDRESS_LENGTH_BYTES ( 4U )
/* IP protocol definitions. */
#define ipPROTOCOL_ICMP ( 1U )
#define ipPROTOCOL_IGMP ( 2U )
#define ipPROTOCOL_TCP ( 6U )
#define ipPROTOCOL_UDP ( 17U )
/* The character used to fill ICMP echo requests, and therefore also the
* character expected to fill ICMP echo replies. */
#define ipECHO_DATA_FILL_BYTE 'x'
/* Dimensions the buffers that are filled by received Ethernet frames. */
#define ipSIZE_OF_ETH_CRC_BYTES ( 4UL )
#define ipSIZE_OF_ETH_OPTIONAL_802_1Q_TAG_BYTES ( 4UL )
#define ipTOTAL_ETHERNET_FRAME_SIZE ( ( ( uint32_t ) ipconfigNETWORK_MTU ) + ( ( uint32_t ) ipSIZE_OF_ETH_HEADER ) + ipSIZE_OF_ETH_CRC_BYTES + ipSIZE_OF_ETH_OPTIONAL_802_1Q_TAG_BYTES )
/* Space left at the beginning of a network buffer storage area to store a
* pointer back to the network buffer. Should be a multiple of 8 to ensure 8 byte
* alignment is maintained on architectures that require it.
*
* In order to get a 32-bit or 64-bit alignment of network packets, an offset of 2 bytes
* is ideal as defined by ipconfigPACKET_FILLER_SIZE. So the malloc'd
* buffer will have the following contents:
*
* +---------+-----------+---------+
* | Offset | Alignment | Length |
* | 32 | 64 | 32 | 64 | 32 | 64 |
* |----|----|-----|-----|----|----|
* | 0 | 0 | 4 | 8 | 4 | 8 | uchar_8 * pointer; // Points to the 'NetworkBufferDescriptor_t'.
* | 4 | 8 | 4 | 8 | 6 | 6 | uchar_8 filler[6]; // To give the +2 byte offset.
* |-------------------------------|
* | 10 | 14 | 4+2 | 8+2 | 6 | 6 | uchar_8 dest_mac[6]; // Destination address.
* | 16 | 20 | 4 | 8 | 6 | 6 | uchar_8 src_mac[6]; // Source address.
* | 22 | 26 | 4+2 | 4+2 | 2 | 2 | uchar16_t ethertype;
* | 24 | 28 | 4 | 4 | ~ | ~ | << IP-header >> // word-aligned, either 4 or 8 bytes.
* uint8_t ucVersionHeaderLength;
* etc
*/
/* Use setting from FreeRTOS if defined and non-zero */
#if ( ipconfigBUFFER_PADDING != 0 )
#define ipBUFFER_PADDING ipconfigBUFFER_PADDING
#elif ( UINTPTR_MAX > 0xFFFFFFFFU )
#define ipBUFFER_PADDING ( 12U + ipconfigPACKET_FILLER_SIZE )
#else
#define ipBUFFER_PADDING ( 8U + ipconfigPACKET_FILLER_SIZE )
#endif
/* The offset of ucTCPFlags within the TCP header. */
#define ipTCP_FLAGS_OFFSET 13U
/** @brief Returned to indicate a valid checksum. */
#define ipCORRECT_CRC 0xffffU
/** @brief Returned to indicate incorrect checksum. */
#define ipWRONG_CRC 0x0000U
/** @brief Returned as the (invalid) checksum when the length of the data being checked
* had an invalid length. */
#define ipINVALID_LENGTH 0x1234U
/** @brief Returned as the (invalid) checksum when the protocol being checked is not
* handled. The value is chosen simply to be easy to spot when debugging. */
#define ipUNHANDLED_PROTOCOL 0x4321U
/* Trace macros to aid in debugging, disabled if ipconfigHAS_PRINTF != 1 */
#if ( ipconfigHAS_PRINTF == 1 )
#define DEBUG_DECLARE_TRACE_VARIABLE( type, var, init ) type var = ( init ) /**< Trace macro to set "type var = init". */
#define DEBUG_SET_TRACE_VARIABLE( var, value ) var = ( value ) /**< Trace macro to set var = value. */
#else
#define DEBUG_DECLARE_TRACE_VARIABLE( type, var, init ) /**< Empty definition since ipconfigHAS_PRINTF != 1. */
#define DEBUG_SET_TRACE_VARIABLE( var, value ) /**< Empty definition since ipconfigHAS_PRINTF != 1. */
#endif
/**
* The structure used to store buffers and pass them around the network stack.
* Buffers can be in use by the stack, in use by the network interface hardware
* driver, or free (not in use).
*/
typedef struct xNETWORK_BUFFER
{
ListItem_t xBufferListItem; /**< Used to reference the buffer form the free buffer list or a socket. */
IP_Address_t xIPAddress; /**< Source or destination IP address, depending on usage scenario. */
uint8_t * pucEthernetBuffer; /**< Pointer to the start of the Ethernet frame. */
size_t xDataLength; /**< Starts by holding the total Ethernet frame length, then the UDP/TCP payload length. */
struct xNetworkInterface * pxInterface; /**< The interface on which the packet was received. */
struct xNetworkEndPoint * pxEndPoint; /**< The end-point through which this packet shall be sent. */
uint16_t usPort; /**< Source or destination port, depending on usage scenario. */
uint16_t usBoundPort; /**< The port to which a transmitting socket is bound. */
#if ( ipconfigUSE_LINKED_RX_MESSAGES != 0 )
struct xNETWORK_BUFFER * pxNextBuffer; /**< Possible optimisation for expert users - requires network driver support. */
#endif
#define ul_IPAddress xIPAddress.xIP_IPv4
#define x_IPv6Address xIPAddress.xIP_IPv6
} NetworkBufferDescriptor_t;
#include "pack_struct_start.h"
/**
* MAC address structure.
*/
struct xMAC_ADDRESS
{
uint8_t ucBytes[ ipMAC_ADDRESS_LENGTH_BYTES ]; /**< Byte array of the MAC address */
}
#include "pack_struct_end.h"
typedef struct xMAC_ADDRESS MACAddress_t;
typedef enum eNETWORK_EVENTS
{
eNetworkUp, /* The network is configured. */
eNetworkDown /* The network connection has been lost. */
} eIPCallbackEvent_t;
/* MISRA check: some modules refer to this typedef even though
* ipconfigSUPPORT_OUTGOING_PINGS is not enabled. */
typedef enum ePING_REPLY_STATUS
{
eSuccess = 0, /**< A correct reply has been received for an outgoing ping. */
eInvalidChecksum, /**< A reply was received for an outgoing ping but the checksum of the reply was incorrect. */
eInvalidData /**< A reply was received to an outgoing ping but the payload of the reply was not correct. */
} ePingReplyStatus_t;
/**
* The software timer struct for various IP functions
*/
typedef struct xIP_TIMER
{
uint32_t
bActive : 1, /**< This timer is running and must be processed. */
bExpired : 1; /**< Timer has expired and a task must be processed. */
TimeOut_t xTimeOut; /**< The timeout value. */
TickType_t ulRemainingTime; /**< The amount of time remaining. */
TickType_t ulReloadTime; /**< The value of reload time. */
} IPTimer_t;
/* Endian related definitions. */
#if ( ipconfigBYTE_ORDER == pdFREERTOS_LITTLE_ENDIAN )
/* FreeRTOS_htons / FreeRTOS_htonl: some platforms might have built-in versions
* using a single instruction so allow these versions to be overridden. */
#ifndef FreeRTOS_htons
#define FreeRTOS_htons( usIn ) ( ( uint16_t ) ( ( ( usIn ) << 8U ) | ( ( usIn ) >> 8U ) ) )
#endif
#ifndef FreeRTOS_htonl
#define FreeRTOS_htonl( ulIn ) \
( \
( uint32_t ) \
( \
( ( ( ( uint32_t ) ( ulIn ) ) ) << 24 ) | \
( ( ( ( uint32_t ) ( ulIn ) ) & 0x0000ff00U ) << 8 ) | \
( ( ( ( uint32_t ) ( ulIn ) ) & 0x00ff0000U ) >> 8 ) | \
( ( ( ( uint32_t ) ( ulIn ) ) ) >> 24 ) \
) \
)
#endif /* ifndef FreeRTOS_htonl */
#else /* ipconfigBYTE_ORDER */
#define FreeRTOS_htons( x ) ( ( uint16_t ) ( x ) )
#define FreeRTOS_htonl( x ) ( ( uint32_t ) ( x ) )
#endif /* ipconfigBYTE_ORDER == pdFREERTOS_LITTLE_ENDIAN */
#define FreeRTOS_ntohs( x ) FreeRTOS_htons( x )
#define FreeRTOS_ntohl( x ) FreeRTOS_htonl( x )
/* Translate a pdFREERTOS_ERRNO code to a human readable string. */
const char * FreeRTOS_strerror_r( BaseType_t xErrnum,
char * pcBuffer,
size_t uxLength );
/* Some simple helper functions. */
int32_t FreeRTOS_max_int32( int32_t a,
int32_t b );
uint32_t FreeRTOS_max_uint32( uint32_t a,
uint32_t b );
size_t FreeRTOS_max_size_t( size_t a,
size_t b );
int32_t FreeRTOS_min_int32( int32_t a,
int32_t b );
uint32_t FreeRTOS_min_uint32( uint32_t a,
uint32_t b );
size_t FreeRTOS_min_size_t( size_t a,
size_t b );
int32_t FreeRTOS_add_int32( int32_t a,
int32_t b );
int32_t FreeRTOS_multiply_int32( int32_t a,
int32_t b );
uint32_t FreeRTOS_round_up( uint32_t a,
uint32_t d );
uint32_t FreeRTOS_round_down( uint32_t a,
uint32_t d );
#define ipMS_TO_MIN_TICKS( xTimeInMs ) ( ( pdMS_TO_TICKS( ( xTimeInMs ) ) < ( ( TickType_t ) 1U ) ) ? ( ( TickType_t ) 1U ) : pdMS_TO_TICKS( ( xTimeInMs ) ) )
/* For backward compatibility. */
#define pdMS_TO_MIN_TICKS( xTimeInMs ) ipMS_TO_MIN_TICKS( xTimeInMs )
#ifndef pdTRUE_SIGNED
#define pdTRUE_SIGNED pdTRUE
#endif /* pdTRUE_SIGNED */
#ifndef pdFALSE_SIGNED
#define pdFALSE_SIGNED pdFALSE
#endif /* pdFALSE_SIGNED */
#ifndef pdTRUE_UNSIGNED
#define pdTRUE_UNSIGNED ( 1U )
#endif /* pdTRUE_UNSIGNED */
#ifndef pdFALSE_UNSIGNED
#define pdFALSE_UNSIGNED ( 0U )
#endif /* pdFALSE_UNSIGNED */
#ifndef ipTRUE_BOOL
#define ipTRUE_BOOL ( pdPASS == pdPASS )
#endif /* ipTRUE_BOOL */
#ifndef ipFALSE_BOOL
#define ipFALSE_BOOL ( pdPASS == pdFAIL )
#endif /* ipFALSE_BOOL */
/*
* FULL, UP-TO-DATE AND MAINTAINED REFERENCE DOCUMENTATION FOR ALL THESE
* FUNCTIONS IS AVAILABLE ON THE FOLLOWING URL:
* https://freertos.org/Documentation/03-Libraries/02-FreeRTOS-plus/02-FreeRTOS-plus-TCP/09-API-reference/01-FreeRTOS-plus-TCP-APIs
*/
/* FreeRTOS_IPInit_Multi() replaces the earlier FreeRTOS_IPInit(). It assumes
* that network interfaces and IP-addresses have been added using the functions
* from FreeRTOS_Routing.h. */
BaseType_t FreeRTOS_IPInit_Multi( void );
struct xNetworkInterface;
#if ( ipconfigIPv4_BACKWARD_COMPATIBLE == 1 )
/* Do not call the following function directly. It is there for downward compatibility.
* The function FreeRTOS_IPInit() will call it to initialise the interface and end-point
* objects. See the description in FreeRTOS_Routing.h. */
struct xNetworkInterface * pxFillInterfaceDescriptor( BaseType_t xEMACIndex,
struct xNetworkInterface * pxInterface );
/* The following function is only provided to allow backward compatibility
* with the earlier version of FreeRTOS+TCP which had a single interface only. */
BaseType_t FreeRTOS_IPInit( const uint8_t ucIPAddress[ ipIP_ADDRESS_LENGTH_BYTES ],
const uint8_t ucNetMask[ ipIP_ADDRESS_LENGTH_BYTES ],
const uint8_t ucGatewayAddress[ ipIP_ADDRESS_LENGTH_BYTES ],
const uint8_t ucDNSServerAddress[ ipIP_ADDRESS_LENGTH_BYTES ],
const uint8_t ucMACAddress[ ipMAC_ADDRESS_LENGTH_BYTES ] );
/* The following 2 functions also assume that there is only 1 network endpoint/interface.
* The new function are called: FreeRTOS_GetEndPointConfiguration() and
* FreeRTOS_SetEndPointConfiguration() */
void FreeRTOS_GetAddressConfiguration( uint32_t * pulIPAddress,
uint32_t * pulNetMask,
uint32_t * pulGatewayAddress,
uint32_t * pulDNSServerAddress );
void FreeRTOS_SetAddressConfiguration( const uint32_t * pulIPAddress,
const uint32_t * pulNetMask,
const uint32_t * pulGatewayAddress,
const uint32_t * pulDNSServerAddress );
void * FreeRTOS_GetUDPPayloadBuffer( size_t uxRequestedSizeBytes,
TickType_t uxBlockTimeTicks );
#endif /* if ( ipconfigIPv4_BACKWARD_COMPATIBLE == 1 ) */
/*
* Returns the addresses stored in an end-point structure.
* This function already existed in the release with the single-interface.
* Only the first parameters is new: an end-point
*/
void FreeRTOS_GetEndPointConfiguration( uint32_t * pulIPAddress,
uint32_t * pulNetMask,
uint32_t * pulGatewayAddress,
uint32_t * pulDNSServerAddress,
const struct xNetworkEndPoint * pxEndPoint );
void FreeRTOS_SetEndPointConfiguration( const uint32_t * pulIPAddress,
const uint32_t * pulNetMask,
const uint32_t * pulGatewayAddress,
const uint32_t * pulDNSServerAddress,
struct xNetworkEndPoint * pxEndPoint );
TaskHandle_t FreeRTOS_GetIPTaskHandle( void );
void * FreeRTOS_GetUDPPayloadBuffer_Multi( size_t uxRequestedSizeBytes,
TickType_t uxBlockTimeTicks,
uint8_t ucIPType );
/* MISRA defining 'FreeRTOS_SendPingRequest' should be dependent on 'ipconfigSUPPORT_OUTGOING_PINGS'.
* In order not to break some existing project, define it unconditionally. */
BaseType_t FreeRTOS_SendPingRequest( uint32_t ulIPAddress,
size_t uxNumberOfBytesToSend,
TickType_t uxBlockTimeTicks );
void FreeRTOS_ReleaseUDPPayloadBuffer( void const * pvBuffer );
const uint8_t * FreeRTOS_GetMACAddress( void );
void FreeRTOS_UpdateMACAddress( const uint8_t ucMACAddress[ ipMAC_ADDRESS_LENGTH_BYTES ] );
#if ( ipconfigUSE_NETWORK_EVENT_HOOK == 1 )
/* This function shall be defined by the application. */
#if ( ipconfigIPv4_BACKWARD_COMPATIBLE == 1 )
void vApplicationIPNetworkEventHook( eIPCallbackEvent_t eNetworkEvent );
#else
void vApplicationIPNetworkEventHook_Multi( eIPCallbackEvent_t eNetworkEvent,
struct xNetworkEndPoint * pxEndPoint );
#endif
#endif
#if ( ipconfigSUPPORT_OUTGOING_PINGS == 1 )
void vApplicationPingReplyHook( ePingReplyStatus_t eStatus,
uint16_t usIdentifier );
#endif
BaseType_t FreeRTOS_IsNetworkUp( void );
#if ( ipconfigCHECK_IP_QUEUE_SPACE != 0 )
UBaseType_t uxGetMinimumIPQueueSpace( void );
#endif
BaseType_t xIsNetworkDownEventPending( void );
/*
* Defined in FreeRTOS_Sockets.c
* //_RB_ Don't think this comment is correct. If this is for internal use only it should appear after all the public API functions and not start with FreeRTOS_.
* Socket has had activity, reset the timer so it will not be closed
* because of inactivity
*/
#if ( ( ipconfigHAS_DEBUG_PRINTF != 0 ) || ( ipconfigHAS_PRINTF != 0 ) )
const char * FreeRTOS_GetTCPStateName( UBaseType_t ulState );
#endif
#if ( ipconfigDHCP_REGISTER_HOSTNAME == 1 )
/* DHCP has an option for clients to register their hostname. It doesn't
* have much use, except that a device can be found in a router along with its
* name. If this option is used the callback below must be provided by the
* application writer to return a const string, denoting the device's name. */
/* Typically this function is defined in a user module. */
const char * pcApplicationHostnameHook( void );
#endif /* ipconfigDHCP_REGISTER_HOSTNAME */
/* This xApplicationGetRandomNumber() will set *pulNumber to a random number,
* and return pdTRUE. When the random number generator is broken, it shall return
* pdFALSE.
* The function is defined in 'iot_secure_sockets.c'.
* If that module is not included in the project, the application must provide an
* implementation of it.
* The macro's ipconfigRAND32() and configRAND32() are not in use anymore. */
/* "xApplicationGetRandomNumber" is declared but never defined, because it may
* be defined in a user module. */
BaseType_t xApplicationGetRandomNumber( uint32_t * pulNumber );
/** @brief The pointers to buffers with packet waiting for resolution. These variables
* are defined in FreeRTOS_IP.c.
* These pointers are for internal use only. */
extern NetworkBufferDescriptor_t * pxARPWaitingNetworkBuffer;
extern NetworkBufferDescriptor_t * pxNDWaitingNetworkBuffer;
#if ( ipconfigENABLE_BACKWARD_COMPATIBILITY == 1 )
#define xIPStackEvent_t IPStackEvent_t
#define xNetworkBufferDescriptor_t NetworkBufferDescriptor_t
#define xMACAddress_t MACAddress_t
#define xWinProperties_t WinProperties_t
#define xSocket_t Socket_t
#define xSocketSet_t SocketSet_t
#define ipSIZE_OF_IP_HEADER ipSIZE_OF_IPv4_HEADER
/* Since August 2016, the public types and fields below have changed name:
* abbreviations TCP/UDP are now written in capitals, and type names now end with "_t". */
#define FOnConnected FOnConnected_t
#define FOnTcpReceive FOnTCPReceive_t
#define FOnTcpSent FOnTCPSent_t
#define FOnUdpReceive FOnUDPReceive_t
#define FOnUdpSent FOnUDPSent_t
#define pOnTcpConnected pxOnTCPConnected
#define pOnTcpReceive pxOnTCPReceive
#define pOnTcpSent pxOnTCPSent
#define pOnUdpReceive pxOnUDPReceive
#define pOnUdpSent pxOnUDPSent
#define FOnUdpSent FOnUDPSent_t
#define FOnTcpSent FOnTCPSent_t
#endif /* ipconfigENABLE_BACKWARD_COMPATIBILITY */
#if ( ipconfigHAS_PRINTF != 0 )
extern void vPrintResourceStats( void );
#else
#define vPrintResourceStats() do {} while( ipFALSE_BOOL ) /**< ipconfigHAS_PRINTF is not defined. Define vPrintResourceStats to a do-while( 0 ). */
#endif
#include "FreeRTOS_IP_Utils.h"
#include "FreeRTOS_IPv4.h"
#include "FreeRTOS_IPv6.h"
/* *INDENT-OFF* */
#ifdef __cplusplus
} /* extern "C" */
#endif
/* *INDENT-ON* */
#endif /* FREERTOS_IP_H */
@@ -0,0 +1,76 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
#ifndef FREERTOS_IP_COMMON_H
#define FREERTOS_IP_COMMON_H
/* *INDENT-OFF* */
#ifdef __cplusplus
extern "C" {
#endif
/* *INDENT-ON* */
struct xIPv6_Address
{
uint8_t ucBytes[ 16 ];
};
typedef struct xIPv6_Address IPv6_Address_t;
typedef union IP_Address
{
uint32_t ulIP_IPv4; /**< IPv4 address */
IPv6_Address_t xIP_IPv6; /**< IPv6 address */
} IP_Address_t;
/** @brief A struct that can hold either an IPv4 or an IPv6 address. */
typedef struct xxIPv46_Address
{
/* A struct that can hold either an IPv4 or an IPv6 address. */
IP_Address_t xIPAddress; /**< IP address contains either IPv4 or IPv6. */
BaseType_t xIs_IPv6; /**< pdTRUE if IPv6 address. */
} IPv46_Address_t;
struct xNetworkEndPoint;
struct xNetworkInterface;
/* Return true if a given end-point is up and running.
* When FreeRTOS_IsNetworkUp() is called with NULL as a parameter,
* it will return pdTRUE when all end-points are up. */
BaseType_t FreeRTOS_IsEndPointUp( const struct xNetworkEndPoint * pxEndPoint );
/* Return pdTRUE if all end-points are up.
* When pxInterface is null, all end-points will be checked. */
BaseType_t FreeRTOS_AllEndPointsUp( const struct xNetworkInterface * pxInterface );
/* *INDENT-OFF* */
#ifdef __cplusplus
} /* extern "C" */
#endif
/* *INDENT-ON* */
#endif /* FREERTOS_IP_COMMON_H */
@@ -0,0 +1,856 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* https://www.FreeRTOS.org
* https://github.com/FreeRTOS
*/
#ifndef FREERTOS_IP_PRIVATE_H
#define FREERTOS_IP_PRIVATE_H
/* Application level configuration options. */
#include "FreeRTOSIPConfig.h"
#include "FreeRTOSIPConfigDefaults.h"
#include "FreeRTOS_Sockets.h"
#include "FreeRTOS_Stream_Buffer.h"
#include "FreeRTOS_Routing.h"
#if ( ipconfigUSE_TCP == 1 )
#include "FreeRTOS_TCP_WIN.h"
#include "FreeRTOS_TCP_IP.h"
#endif
#include "semphr.h"
#include "event_groups.h"
/* *INDENT-OFF* */
#ifdef __cplusplus
extern "C" {
#endif
/* *INDENT-ON* */
#ifdef TEST
int ipFOREVER( void );
#else
#define ipFOREVER() 1
#endif
/* Forward declaration. */
struct xNetworkEndPoint;
typedef enum eFrameProcessingResult
{
eReleaseBuffer = 0, /* Processing the frame did not find anything to do - just release the buffer. */
eProcessBuffer, /* An Ethernet frame has a valid address - continue process its contents. */
eReturnEthernetFrame, /* The Ethernet frame contains an ARP or ICMP packet that can be returned to its source. */
eFrameConsumed, /* Processing the Ethernet packet contents resulted in the payload being sent to the stack. */
eWaitingResolution /* Frame is awaiting resolution. */
} eFrameProcessingResult_t;
typedef enum
{
eNoEvent = -1,
eNetworkDownEvent, /* 0: The network interface has been lost and/or needs [re]connecting. */
eNetworkRxEvent, /* 1: The network interface has queued a received Ethernet frame. */
eNetworkTxEvent, /* 2: Let the IP-task send a network packet. */
eARPTimerEvent, /* 3: The ARP timer expired. */
eNDTimerEvent, /* 4: The ND timer expired. */
eStackTxEvent, /* 5: The software stack has queued a packet to transmit. */
eDHCPEvent, /* 6: Process the DHCP state machine. */
eTCPTimerEvent, /* 7: See if any TCP socket needs attention. */
eTCPAcceptEvent, /* 8: Client API FreeRTOS_accept() waiting for client connections. */
eTCPNetStat, /* 9: IP-task is asked to produce a netstat listing. */
eSocketBindEvent, /*10: Send a message to the IP-task to bind a socket to a port. */
eSocketCloseEvent, /*11: Send a message to the IP-task to close a socket. */
eSocketSelectEvent, /*12: Send a message to the IP-task for select(). */
eSocketSignalEvent, /*13: A socket must be signalled. */
eSocketSetDeleteEvent /*14: A socket set must be deleted. */
} eIPEvent_t;
/**
* Structure to hold the information about the Network parameters.
*/
typedef struct xNetworkAddressingParameters
{
uint32_t ulDefaultIPAddress; /**< The default IP address */
uint32_t ulNetMask; /**< The netmask */
uint32_t ulGatewayAddress; /**< The gateway address */
uint32_t ulDNSServerAddress; /**< The DNS server address */
uint32_t ulBroadcastAddress; /**< The Broadcast address */
} NetworkAddressingParameters_t;
extern BaseType_t xTCPWindowLoggingLevel;
extern QueueHandle_t xNetworkEventQueue;
typedef struct xSOCKET FreeRTOS_Socket_t;
/*-----------------------------------------------------------*/
/* Protocol headers. */
/*-----------------------------------------------------------*/
#include "pack_struct_start.h"
struct xETH_HEADER
{
MACAddress_t xDestinationAddress; /**< Destination address 0 + 6 = 6 */
MACAddress_t xSourceAddress; /**< Source address 6 + 6 = 12 */
uint16_t usFrameType; /**< The EtherType field 12 + 2 = 14 */
}
#include "pack_struct_end.h"
typedef struct xETH_HEADER EthernetHeader_t;
#include "pack_struct_start.h"
struct xARP_HEADER
{
uint16_t usHardwareType; /**< Network Link Protocol type 0 + 2 = 2 */
uint16_t usProtocolType; /**< The internetwork protocol 2 + 2 = 4 */
uint8_t ucHardwareAddressLength; /**< Length in octets of a hardware address 4 + 1 = 5 */
uint8_t ucProtocolAddressLength; /**< Length in octets of the internetwork protocol 5 + 1 = 6 */
uint16_t usOperation; /**< Operation that the sender is performing 6 + 2 = 8 */
MACAddress_t xSenderHardwareAddress; /**< Media address of the sender 8 + 6 = 14 */
uint8_t ucSenderProtocolAddress[ 4 ]; /**< Internetwork address of sender 14 + 4 = 18 */
MACAddress_t xTargetHardwareAddress; /**< Media address of the intended receiver 18 + 6 = 24 */
uint32_t ulTargetProtocolAddress; /**< Internetwork address of the intended receiver 24 + 4 = 28 */
}
#include "pack_struct_end.h"
typedef struct xARP_HEADER ARPHeader_t;
#include "pack_struct_start.h"
struct xICMP_HEADER
{
uint8_t ucTypeOfMessage; /**< The ICMP type 0 + 1 = 1 */
uint8_t ucTypeOfService; /**< The ICMP subtype 1 + 1 = 2 */
uint16_t usChecksum; /**< The checksum of whole ICMP packet 2 + 2 = 4 */
uint16_t usIdentifier; /**< Used in some types of ICMP 4 + 2 = 6 */
uint16_t usSequenceNumber; /**< Used in some types of ICMP 6 + 2 = 8 */
}
#include "pack_struct_end.h"
typedef struct xICMP_HEADER ICMPHeader_t;
#include "pack_struct_start.h"
struct xICMPHeader_IPv6
{
uint8_t ucTypeOfMessage; /**< The message type. 0 + 1 = 1 */
uint8_t ucTypeOfService; /**< Type of service. 1 + 1 = 2 */
uint16_t usChecksum; /**< Checksum. 2 + 2 = 4 */
uint32_t ulReserved; /**< Reserved. 4 + 4 = 8 */
IPv6_Address_t xIPv6Address; /**< The IPv6 address. 8 + 16 = 24 */
uint8_t ucOptionType; /**< The option type. 24 + 1 = 25 */
uint8_t ucOptionLength; /**< The option length. 25 + 1 = 26 */
uint8_t ucOptionBytes[ 6 ]; /**< Option bytes. 26 + 6 = 32 */
}
#include "pack_struct_end.h"
typedef struct xICMPHeader_IPv6 ICMPHeader_IPv6_t;
#include "pack_struct_start.h"
struct xUDP_HEADER
{
uint16_t usSourcePort; /**< The source port 0 + 2 = 2 */
uint16_t usDestinationPort; /**< The destination port 2 + 2 = 4 */
uint16_t usLength; /**< The size of the whole UDP packet 4 + 2 = 6 */
uint16_t usChecksum; /**< The checksum of the whole UDP Packet 6 + 2 = 8 */
}
#include "pack_struct_end.h"
typedef struct xUDP_HEADER UDPHeader_t;
#include "pack_struct_start.h"
struct xTCP_HEADER
{
uint16_t usSourcePort; /**< The Source port + 2 = 2 */
uint16_t usDestinationPort; /**< The destination port + 2 = 4 */
uint32_t ulSequenceNumber; /**< The Sequence number + 4 = 8 */
uint32_t ulAckNr; /**< The acknowledgement number + 4 = 12 */
uint8_t ucTCPOffset; /**< The value of TCP offset + 1 = 13 */
uint8_t ucTCPFlags; /**< The TCP-flags field + 1 = 14 */
uint16_t usWindow; /**< The size of the receive window + 2 = 15 */
uint16_t usChecksum; /**< The checksum of the header + 2 = 18 */
uint16_t usUrgent; /**< Pointer to the last urgent data byte + 2 = 20 */
#if ipconfigUSE_TCP == 1
uint8_t ucOptdata[ ipSIZE_TCP_OPTIONS ]; /**< The options + 12 = 32 */
#endif
}
#include "pack_struct_end.h"
typedef struct xTCP_HEADER TCPHeader_t;
#include "pack_struct_start.h"
struct xARP_PACKET
{
EthernetHeader_t xEthernetHeader; /**< The ethernet header of an ARP Packet 0 + 14 = 14 */
ARPHeader_t xARPHeader; /**< The ARP header of an ARP Packet 14 + 28 = 42 */
}
#include "pack_struct_end.h"
typedef struct xARP_PACKET ARPPacket_t;
#include "FreeRTOS_IPv4_Private.h"
#include "FreeRTOS_IPv6_Private.h"
/**
* Union for the protocol packet to save space. Any packet cannot have more than one
* of the below protocol packets.
*/
typedef union XPROT_PACKET
{
ARPPacket_t xARPPacket; /**< Union member: ARP packet struct */
TCPPacket_t xTCPPacket; /**< Union member: TCP packet struct */
UDPPacket_t xUDPPacket; /**< Union member: UDP packet struct */
ICMPPacket_t xICMPPacket; /**< Union member: ICMP packet struct */
} ProtocolPacket_t;
/**
* Union for protocol headers to save space (RAM). Any packet cannot have more than one of
* the below protocols.
*/
typedef union xPROT_HEADERS
{
ICMPHeader_t xICMPHeader; /**< Union member: ICMP header */
UDPHeader_t xUDPHeader; /**< Union member: UDP header */
TCPHeader_t xTCPHeader; /**< Union member: TCP header */
ICMPHeader_IPv6_t xICMPHeaderIPv6; /**< Union member: ICMPv6 header */
} ProtocolHeaders_t;
/**
* Structure for the information of the commands issued to the IP task.
*/
typedef struct IP_TASK_COMMANDS
{
eIPEvent_t eEventType; /**< The event-type enum */
void * pvData; /**< The data in the event */
} IPStackEvent_t;
/** @brief This struct describes a packet, it is used by the function
* usGenerateProtocolChecksum(). */
struct xPacketSummary
{
BaseType_t xIsIPv6; /**< pdTRUE for IPv6 packets. */
#if ipconfigUSE_IPv6
const IPHeader_IPv6_t * pxIPPacket_IPv6; /**< A pointer to the IPv6 header. */
#endif
#if ( ipconfigHAS_DEBUG_PRINTF != 0 )
const char * pcType; /**< Just for logging purposes: the name of the protocol. */
#endif
size_t uxIPHeaderLength; /**< Either 40 or 20, depending on the IP-type */
size_t uxProtocolHeaderLength; /**< Either 8, 20, or more or 20, depending on the protocol-type */
uint16_t usChecksum; /**< Checksum accumulator. */
uint8_t ucProtocol; /**< ipPROTOCOL_TCP, ipPROTOCOL_UDP, ipPROTOCOL_ICMP */
const IPPacket_t * pxIPPacket; /**< A pointer to the IPv4 header. */
ProtocolHeaders_t * pxProtocolHeaders; /**< Points to first byte after IP-header */
uint16_t usPayloadLength; /**< Property of IP-header (for IPv4: length of IP-header included) */
uint16_t usProtocolBytes; /**< The total length of the protocol data. */
};
/* Offset into the Ethernet frame that is used to temporarily store information
* on the fragmentation status of the packet being sent. The value is important,
* as it is past the location into which the destination address will get placed. */
#define ipFRAGMENTATION_PARAMETERS_OFFSET ( 6 )
#define ipSOCKET_OPTIONS_OFFSET ( 6 )
#if ( ipconfigBYTE_ORDER == pdFREERTOS_LITTLE_ENDIAN )
/* Ethernet frame types. */
#define ipARP_FRAME_TYPE ( 0x0608U )
#define ipIPv4_FRAME_TYPE ( 0x0008U )
/* ARP related definitions. */
#define ipARP_PROTOCOL_TYPE ( 0x0008U )
#define ipARP_HARDWARE_TYPE_ETHERNET ( 0x0100U )
#define ipARP_REQUEST ( 0x0100U )
#define ipARP_REPLY ( 0x0200U )
/* The bits in the two byte IP header field that make up the fragment offset value. */
#define ipFRAGMENT_OFFSET_BIT_MASK ( ( uint16_t ) 0xff1fU )
/* The bits in the two byte IP header field that make up the flags value. */
#define ipFRAGMENT_FLAGS_BIT_MASK ( ( uint16_t ) 0x00e0U )
/* Don't Fragment Flag */
#define ipFRAGMENT_FLAGS_DONT_FRAGMENT ( ( uint16_t ) 0x0040U )
/* More Fragments Flag */
#define ipFRAGMENT_FLAGS_MORE_FRAGMENTS ( ( uint16_t ) 0x0020U )
#else /* if ( ipconfigBYTE_ORDER == pdFREERTOS_LITTLE_ENDIAN ) */
/* Ethernet frame types. */
#define ipARP_FRAME_TYPE ( 0x0806U )
#define ipIPv4_FRAME_TYPE ( 0x0800U )
/* ARP related definitions. */
#define ipARP_PROTOCOL_TYPE ( 0x0800U )
#define ipARP_HARDWARE_TYPE_ETHERNET ( 0x0001U )
#define ipARP_REQUEST ( 0x0001 )
#define ipARP_REPLY ( 0x0002 )
/* The bits in the two byte IP header field that make up the fragment offset value. */
#define ipFRAGMENT_OFFSET_BIT_MASK ( ( uint16_t ) 0x1fffU )
/* The bits in the two byte IP header field that make up the flags value. */
#define ipFRAGMENT_FLAGS_BIT_MASK ( ( uint16_t ) 0xe000U )
/* Don't Fragment Flag */
#define ipFRAGMENT_FLAGS_DONT_FRAGMENT ( ( uint16_t ) 0x4000U )
/* More Fragments Flag */
#define ipFRAGMENT_FLAGS_MORE_FRAGMENTS ( ( uint16_t ) 0x2000U )
#endif /* ipconfigBYTE_ORDER */
/* For convenience, a MAC address of all zeros and another of all 0xffs are
* defined const for quick reference. */
extern const MACAddress_t xBroadcastMACAddress; /* all 0xff's */
extern uint16_t usPacketIdentifier;
/** @brief The list that contains mappings between sockets and port numbers.
* Accesses to this list must be protected by critical sections of
* some kind.
*/
extern List_t xBoundUDPSocketsList;
/* True when BufferAllocation_1.c was included, false for BufferAllocation_2.c */
extern const BaseType_t xBufferAllocFixedSize;
/* As FreeRTOS_Routing is included later, use forward declarations
* of the two structs. */
struct xNetworkEndPoint;
struct xNetworkInterface;
/* A list of all network end-points: */
extern struct xNetworkEndPoint * pxNetworkEndPoints;
/* A list of all network interfaces: */
extern struct xNetworkInterface * pxNetworkInterfaces;
/* Defined in FreeRTOS_Sockets.c */
#if ( ipconfigUSE_TCP == 1 )
extern List_t xBoundTCPSocketsList;
#endif
/* ICMP packets are sent using the same function as UDP packets. The port
* number is used to distinguish between the two, as 0 is an invalid UDP port. */
#define ipPACKET_CONTAINS_ICMP_DATA ( 0 )
/* For now, the lower 8 bits in 'xEventBits' will be reserved for the above
* socket events. */
#define SOCKET_EVENT_BIT_COUNT 8
#define vSetField16( pxBase, xType, xField, usValue ) \
do { \
( ( uint8_t * ) ( pxBase ) )[ offsetof( xType, xField ) + 0 ] = ( uint8_t ) ( ( usValue ) >> 8 ); \
( ( uint8_t * ) ( pxBase ) )[ offsetof( xType, xField ) + 1 ] = ( uint8_t ) ( ( usValue ) & 0xffU ); \
} while( ipFALSE_BOOL )
#define vSetField32( pxBase, xType, xField, ulValue ) \
{ \
( ( uint8_t * ) ( pxBase ) )[ offsetof( xType, xField ) + 0 ] = ( uint8_t ) ( ( ulValue ) >> 24 ); \
( ( uint8_t * ) ( pxBase ) )[ offsetof( xType, xField ) + 1 ] = ( uint8_t ) ( ( ( ulValue ) >> 16 ) & 0xffU ); \
( ( uint8_t * ) ( pxBase ) )[ offsetof( xType, xField ) + 2 ] = ( uint8_t ) ( ( ( ulValue ) >> 8 ) & 0xffU ); \
( ( uint8_t * ) ( pxBase ) )[ offsetof( xType, xField ) + 3 ] = ( uint8_t ) ( ( ulValue ) & 0xffU ); \
}
#define vFlip_16( left, right ) \
do { \
uint16_t tmp = ( left ); \
( left ) = ( right ); \
( right ) = tmp; \
} while( ipFALSE_BOOL )
#define vFlip_32( left, right ) \
do { \
uint32_t tmp = ( left ); \
( left ) = ( right ); \
( right ) = tmp; \
} while( ipFALSE_BOOL )
/** @brief Macro calculates the number of elements in an array as a size_t. */
#ifndef ARRAY_SIZE_X
#ifndef _WINDOWS_
#define ARRAY_SIZE_X( x ) ( ( BaseType_t ) sizeof( x ) / ( BaseType_t ) sizeof( x[ 0 ] ) )
#else
#define ARRAY_SIZE_X( x ) ( sizeof( x ) / sizeof( x[ 0 ] ) )
#endif
#endif
/* WARNING: Do NOT use this macro when the array was received as a parameter. */
#ifndef ARRAY_SIZE
#define ARRAY_SIZE( x ) ( ( BaseType_t ) ( sizeof( x ) / sizeof( ( x )[ 0 ] ) ) )
#endif
#ifndef ARRAY_USIZE
#define ARRAY_USIZE( x ) ( ( UBaseType_t ) ( sizeof( x ) / sizeof( ( x )[ 0 ] ) ) )
#endif
/*
* Create a message that contains a command to initialise the network interface.
* This is used during initialisation, and at any time the network interface
* goes down thereafter. The network interface hardware driver is responsible
* for sending the message that contains the network interface down command/
* event.
*
* Only use the FreeRTOS_NetworkDownFromISR() version if the function is to be
* called from an interrupt service routine. If FreeRTOS_NetworkDownFromISR()
* returns a non-zero value then a context switch should be performed before
* the interrupt is exited.
*/
void FreeRTOS_NetworkDown( struct xNetworkInterface * pxNetworkInterface );
BaseType_t FreeRTOS_NetworkDownFromISR( struct xNetworkInterface * pxNetworkInterface );
/*
* Processes incoming ARP packets.
*/
eFrameProcessingResult_t eARPProcessPacket( const NetworkBufferDescriptor_t * pxNetworkBuffer );
/*
* Inspect an Ethernet frame to see if it contains data that the stack needs to
* process. eProcessBuffer is returned if the frame should be processed by the
* stack. eReleaseBuffer is returned if the frame should be discarded.
*/
eFrameProcessingResult_t eConsiderFrameForProcessing( const uint8_t * const pucEthernetBuffer );
/*
* Return the checksum generated over xDataLengthBytes from pucNextData.
*/
uint16_t usGenerateChecksum( uint16_t usSum,
const uint8_t * pucNextData,
size_t uxByteCount );
/* Socket related private functions. */
/*
* Initialize the socket list data structures for TCP and UDP.
*/
void vNetworkSocketsInit( void );
/*
* Returns pdTRUE if the IP task has been created and is initialised. Otherwise
* returns pdFALSE.
*/
BaseType_t xIPIsNetworkTaskReady( void );
#if ( ipconfigSOCKET_HAS_USER_WAKE_CALLBACK == 1 )
struct xSOCKET;
typedef void (* SocketWakeupCallback_t)( struct xSOCKET * pxSocket );
#endif
#if ( ipconfigUSE_TCP == 1 )
/*
* Actually a user thing, but because xBoundTCPSocketsList, let it do by the
* IP-task
*/
#if ( ipconfigHAS_PRINTF != 0 )
void vTCPNetStat( void );
#endif
/*
* At least one socket needs to check for timeouts
*/
TickType_t xTCPTimerCheck( BaseType_t xWillSleep );
/**
* About the TCP flags 'bPassQueued' and 'bPassAccept':
*
* When a new TCP connection request is received on a listening socket, the bPassQueued and
* bPassAccept members of the newly created socket are updated as follows:
*
* 1. bPassQueued is set to indicate that the 3-way TCP handshake is in progress.
* 2. When the 3-way TCP handshake is complete, bPassQueued is cleared. At the same time,
* bPassAccept is set to indicate that the socket is ready to be picked up by the task
* that called FreeRTOS_accept().
* 3. When the socket is picked up by the task that called FreeRTOS_accept, the bPassAccept
* is cleared.
*/
/**
* Every TCP socket has a buffer space just big enough to store
* the last TCP header received.
* As a reference of this field may be passed to DMA, force the
* alignment to 8 bytes.
*/
typedef union
{
struct
{
uint32_t ullAlignmentWord; /**< Increase the alignment of this union by adding a 32-bit variable. */
} a; /**< A struct to increase alignment. */
struct
{
/* The next field only serves to give 'ucLastPacket' a correct
* alignment of 4 + 2. See comments in FreeRTOS_IP.h */
uint8_t ucFillPacket[ ipconfigPACKET_FILLER_SIZE ];
uint8_t ucLastPacket[ TCP_PACKET_SIZE ];
} u; /**< The structure to give an alignment of 4 + 2 */
} LastTCPPacket_t;
/**
* Note that the values of all short and long integers in these structs
* are being stored in the native-endian way
* Translation should take place when accessing any structure which defines
* network packets, such as IPHeader_t and TCPHeader_t
*/
typedef struct TCPSOCKET
{
IP_Address_t xRemoteIP; /**< IP address of remote machine */
uint16_t usRemotePort; /**< Port on remote machine */
struct
{
/* Most compilers do like bit-flags */
uint32_t
bMssChange : 1, /**< This socket has seen a change in MSS */
bPassAccept : 1, /**< See comment here above. */
bPassQueued : 1, /**< See comment here above. */
bReuseSocket : 1, /**< When a listening socket gets a connection, do not create a new instance but keep on using it */
bCloseAfterSend : 1, /**< As soon as the last byte has been transmitted, finalise the connection
* Useful in e.g. FTP connections, where the last data bytes are sent along with the FIN flag */
bUserShutdown : 1, /**< User requesting a graceful shutdown */
bCloseRequested : 1, /**< Request to finalise the connection */
bLowWater : 1, /**< high-water level has been reached. Cleared as soon as 'rx-count < lo-water' */
bWinChange : 1, /**< The value of bLowWater has changed, must send a window update */
bSendKeepAlive : 1, /**< When this flag is true, a TCP keep-alive message must be send */
bWaitKeepAlive : 1, /**< When this flag is true, a TCP keep-alive reply is expected */
bConnPrepared : 1, /**< Connecting socket: Message has been prepared */
#if ( ipconfigSUPPORT_SELECT_FUNCTION == 1 )
bConnPassed : 1, /**< Connecting socket: Socket has been passed in a successful select() */
#endif /* ipconfigSUPPORT_SELECT_FUNCTION */
bFinAccepted : 1, /**< This socket has received (or sent) a FIN and accepted it */
bFinSent : 1, /**< We've sent out a FIN */
bFinRecv : 1, /**< We've received a FIN from our peer */
bFinAcked : 1, /**< Our FIN packet has been acked */
bFinLast : 1, /**< The last ACK (after FIN and FIN+ACK) has been sent or will be sent by the peer */
bRxStopped : 1, /**< Application asked to temporarily stop reception */
bMallocError : 1, /**< There was an error allocating a stream */
bWinScaling : 1; /**< A TCP-Window Scaling option was offered and accepted in the SYN phase. */
} bits; /**< The bits structure */
uint32_t ulHighestRxAllowed; /**< The highest sequence number that we can receive at any moment */
uint16_t usTimeout; /**< Time (in ticks) after which this socket needs attention */
uint16_t usMSS; /**< Current Maximum Segment Size */
uint16_t usChildCount; /**< In case of a listening socket: number of connections on this port number */
uint16_t usBacklog; /**< In case of a listening socket: maximum number of concurrent connections on this port number */
uint8_t ucRepCount; /**< Send repeat count, for retransmissions
* This counter is separate from the xmitCount in the
* TCP win segments */
eIPTCPState_t eTCPState; /**< TCP state: see eTCP_STATE */
struct xSOCKET * pxPeerSocket; /**< for server socket: child, for child socket: parent */
#if ( ipconfigTCP_KEEP_ALIVE == 1 )
uint8_t ucKeepRepCount;
TickType_t xLastAliveTime; /**< The last value of keepalive time.*/
#endif /* ipconfigTCP_KEEP_ALIVE */
#if ( ipconfigTCP_HANG_PROTECTION == 1 )
TickType_t xLastActTime; /**< The last time when hang-protection was done.*/
#endif /* ipconfigTCP_HANG_PROTECTION */
size_t uxLittleSpace; /**< The value deemed as low amount of space. */
size_t uxEnoughSpace; /**< The value deemed as enough space. */
size_t uxRxStreamSize; /**< The Receive stream size */
size_t uxTxStreamSize; /**< The transmit stream size */
StreamBuffer_t * rxStream; /**< The pointer to the receive stream buffer. */
StreamBuffer_t * txStream; /**< The pointer to the transmit stream buffer. */
#if ( ipconfigUSE_TCP_WIN == 1 )
NetworkBufferDescriptor_t * pxAckMessage; /**< The pointer to the ACK message */
#endif /* ipconfigUSE_TCP_WIN */
LastTCPPacket_t xPacket; /**< Buffer space to store the last TCP header received. */
uint8_t tcpflags; /**< TCP flags */
#if ( ipconfigUSE_TCP_WIN != 0 )
uint8_t ucMyWinScaleFactor; /**< Scaling factor of this device. */
uint8_t ucPeerWinScaleFactor; /**< Scaling factor of the peer. */
#endif
#if ( ipconfigUSE_CALLBACKS == 1 )
FOnTCPReceive_t pxHandleReceive; /**<
* In case of a TCP socket:
* typedef void (* FOnTCPReceive_t) (Socket_t xSocket, void *pData, size_t xLength );
*/
FOnTCPSent_t pxHandleSent; /**< Function pointer to handle a successful send event. */
FOnConnected_t pxHandleConnected; /**< Actually type: typedef void (* FOnConnected_t) (Socket_t xSocket, BaseType_t ulConnected ); */
#endif /* ipconfigUSE_CALLBACKS */
uint32_t ulWindowSize; /**< Current Window size advertised by peer */
size_t uxRxWinSize; /**< Fixed value: size of the TCP reception window */
size_t uxTxWinSize; /**< Fixed value: size of the TCP transmit window */
TCPWindow_t xTCPWindow; /**< The TCP window struct*/
} IPTCPSocket_t;
#endif /* ipconfigUSE_TCP */
/**
* Structure to hold the information about a UDP socket.
*/
typedef struct UDPSOCKET
{
List_t xWaitingPacketsList; /**< Incoming packets */
#if ( ipconfigUDP_MAX_RX_PACKETS > 0 )
UBaseType_t uxMaxPackets; /**< Protection: limits the number of packets buffered per socket */
#endif /* ipconfigUDP_MAX_RX_PACKETS */
#if ( ipconfigUSE_CALLBACKS == 1 )
FOnUDPReceive_t pxHandleReceive; /**<
* In case of a UDP socket:
* typedef void (* FOnUDPReceive_t) (Socket_t xSocket, void *pData, size_t xLength, struct freertos_sockaddr *pxAddr );
*/
FOnUDPSent_t pxHandleSent; /**< Function pointer to handle the events after a successful send. */
#endif /* ipconfigUSE_CALLBACKS */
} IPUDPSocket_t;
/* Formally typedef'd as eSocketEvent_t. */
enum eSOCKET_EVENT
{
eSOCKET_RECEIVE = 0x0001,
eSOCKET_SEND = 0x0002,
eSOCKET_ACCEPT = 0x0004,
eSOCKET_CONNECT = 0x0008,
eSOCKET_BOUND = 0x0010,
eSOCKET_CLOSED = 0x0020,
eSOCKET_INTR = 0x0040,
eSOCKET_ALL = 0x007F
};
/**
* Structure to hold information for a socket.
*/
struct xSOCKET
{
EventBits_t xEventBits; /**< The eventbits to keep track of events. */
EventGroupHandle_t xEventGroup; /**< The event group for this socket. */
/* Most compilers do like bit-flags */
struct
{
uint32_t bIsIPv6 : 1; /**< Non-zero in case the connection is using IPv6. */
uint32_t bSomeFlag : 1;
}
bits;
ListItem_t xBoundSocketListItem; /**< Used to reference the socket from a bound sockets list. */
TickType_t xReceiveBlockTime; /**< if recv[to] is called while no data is available, wait this amount of time. Unit in clock-ticks */
TickType_t xSendBlockTime; /**< if send[to] is called while there is not enough space to send, wait this amount of time. Unit in clock-ticks */
IP_Address_t xLocalAddress; /**< Local IP address */
uint16_t usLocalPort; /**< Local port on this machine */
uint8_t ucSocketOptions; /**< Socket options */
uint8_t ucProtocol; /**< choice of FREERTOS_IPPROTO_UDP/TCP */
#if ( ipconfigSOCKET_HAS_USER_SEMAPHORE == 1 )
SemaphoreHandle_t pxUserSemaphore; /**< The user semaphore */
#endif /* ipconfigSOCKET_HAS_USER_SEMAPHORE */
#if ( ipconfigSOCKET_HAS_USER_WAKE_CALLBACK == 1 )
SocketWakeupCallback_t pxUserWakeCallback; /**< Pointer to the callback function. */
#endif /* ipconfigSOCKET_HAS_USER_WAKE_CALLBACK */
#if ( ipconfigSUPPORT_SELECT_FUNCTION == 1 )
struct xSOCKET_SET * pxSocketSet; /**< Pointer to the socket set structure */
EventBits_t xSelectBits; /**< User may indicate which bits are interesting for this socket. */
EventBits_t xSocketBits; /**< These bits indicate the events which have actually occurred.
* They are maintained by the IP-task */
#endif /* ipconfigSUPPORT_SELECT_FUNCTION */
struct xNetworkEndPoint * pxEndPoint; /**< The end-point to which the socket is bound. */
/* This field is only only by the user, and can be accessed with
* vSocketSetSocketID() / vSocketGetSocketID().
* All fields of a socket will be cleared by memset() in FreeRTOS_socket().
*/
void * pvSocketID;
/* TCP/UDP specific fields: */
/* Before accessing any member of this structure, it should be confirmed */
/* that the protocol corresponds with the type of structure */
union
{
IPUDPSocket_t xUDP; /**< Union member: UDP socket*/
#if ( ipconfigUSE_TCP == 1 )
IPTCPSocket_t xTCP; /**< Union member: TCP socket */
#endif /* ipconfigUSE_TCP */
}
u; /**< Union of TCP/UDP socket */
};
#if ( ipconfigUSE_TCP == 1 )
/*
* Close the socket another time.
*/
void vSocketCloseNextTime( FreeRTOS_Socket_t * pxSocket );
/*
* Postpone a call to listen() by the IP-task.
*/
void vSocketListenNextTime( FreeRTOS_Socket_t * pxSocket );
/*
* Lookup a TCP socket, using a multiple matching: both port numbers and
* return IP address.
*/
FreeRTOS_Socket_t * pxTCPSocketLookup( uint32_t ulLocalIP,
UBaseType_t uxLocalPort,
IPv46_Address_t xRemoteIP,
UBaseType_t uxRemotePort );
#endif /* ipconfigUSE_TCP */
/*
* Look up a local socket by finding a match with the local port.
*/
FreeRTOS_Socket_t * pxUDPSocketLookup( UBaseType_t uxLocalPort );
/*
* Calculate the upper-layer checksum
* Works both for UDP, ICMP and TCP packages
* bOut = true: checksum will be set in outgoing packets
* bOut = false: checksum will be calculated for incoming packets
* returning 0xffff means: checksum was correct
*/
uint16_t usGenerateProtocolChecksum( uint8_t * pucEthernetBuffer,
size_t uxBufferLength,
BaseType_t xOutgoingPacket );
/*
* An Ethernet frame has been updated (maybe it was an ARP request or a PING
* request?) and is to be sent back to its source.
*/
void vReturnEthernetFrame( NetworkBufferDescriptor_t * pxNetworkBuffer,
BaseType_t xReleaseAfterSend );
/*
* The internal version of bind()
* If 'ulInternal' is true, it is called by the driver
* The TCP driver needs to bind a socket at the moment a listening socket
* creates a new connected socket
*/
BaseType_t vSocketBind( FreeRTOS_Socket_t * pxSocket,
struct freertos_sockaddr * pxBindAddress,
size_t uxAddressLength,
BaseType_t xInternal );
/*
* Internal function to add streaming data to a TCP socket. If ulIn == true,
* data will be added to the rxStream, otherwise to the tXStream. Normally data
* will be written with ulOffset == 0, meaning: at the end of the FIFO. When
* packet come in out-of-order, an offset will be used to put it in front and
* the head will not change yet.
*/
int32_t lTCPAddRxdata( FreeRTOS_Socket_t * pxSocket,
size_t uxOffset,
const uint8_t * pcData,
uint32_t ulByteCount );
/*
* Currently called for any important event.
*/
void vSocketWakeUpUser( FreeRTOS_Socket_t * pxSocket );
/*
* Some helping function, their meaning should be clear.
* Going by MISRA rules, these utility functions should not be defined
* if they are not being used anywhere. But their use depends on the
* application and hence these functions are defined unconditionally.
*/
extern uint32_t ulChar2u32( const uint8_t * pucPtr );
extern uint16_t usChar2u16( const uint8_t * pucPtr );
/* Check a single socket for retransmissions and timeouts */
BaseType_t xTCPSocketCheck( FreeRTOS_Socket_t * pxSocket );
BaseType_t xTCPCheckNewClient( FreeRTOS_Socket_t * pxSocket );
/* Defined in FreeRTOS_Sockets.c
* Close a socket
*/
void * vSocketClose( FreeRTOS_Socket_t * pxSocket );
/*
* Send the event eEvent to the IP task event queue, using a block time of
* zero. Return pdPASS if the message was sent successfully, otherwise return
* pdFALSE.
*/
BaseType_t xSendEventToIPTask( eIPEvent_t eEvent );
/*
* The same as above, but a struct as a parameter, containing:
* eIPEvent_t eEventType;
* void *pvData;
*/
BaseType_t xSendEventStructToIPTask( const IPStackEvent_t * pxEvent,
TickType_t uxTimeout );
/*
* Returns a pointer to the original NetworkBuffer from a pointer to a UDP
* payload buffer.
*/
NetworkBufferDescriptor_t * pxUDPPayloadBuffer_to_NetworkBuffer( const void * pvBuffer );
/* Get the size of the IP-header.
* 'usFrameType' must be filled in if IPv6is to be recognised. */
size_t uxIPHeaderSizePacket( const NetworkBufferDescriptor_t * pxNetworkBuffer );
/*-----------------------------------------------------------*/
/* Get the size of the IP-header.
* The socket is checked for its type: IPv4 or IPv6. */
size_t uxIPHeaderSizeSocket( const FreeRTOS_Socket_t * pxSocket );
/*-----------------------------------------------------------*/
/*
* Internal: Sets a new state for a TCP socket and performs the necessary
* actions like calling a OnConnected handler to notify the socket owner.
*/
#if ( ipconfigUSE_TCP == 1 )
void vTCPStateChange( FreeRTOS_Socket_t * pxSocket,
enum eTCP_STATE eTCPState );
#endif /* ipconfigUSE_TCP */
/* Returns pdTRUE is this function is called from the IP-task */
BaseType_t xIsCallingFromIPTask( void );
#if ( ipconfigSUPPORT_SELECT_FUNCTION == 1 )
/** @brief Structure for event groups of the Socket Select functions */
typedef struct xSOCKET_SET
{
/** @brief Event group for the socket select function.
*/
EventGroupHandle_t xSelectGroup;
} SocketSelect_t;
extern void vSocketSelect( const SocketSelect_t * pxSocketSet );
/** @brief Define the data that must be passed for a 'eSocketSelectEvent'. */
typedef struct xSocketSelectMessage
{
TaskHandle_t xTaskhandle; /**< Task handle for use in the socket select functionality. */
SocketSelect_t * pxSocketSet; /**< The event group for the socket select functionality. */
} SocketSelectMessage_t;
#endif /* ipconfigSUPPORT_SELECT_FUNCTION */
/* Send the network-up event and start the ARP/ND timers. */
void vIPNetworkUpCalls( struct xNetworkEndPoint * pxEndPoint );
/* Mark whether all interfaces are up or at least one interface is down. */
void vSetAllNetworksUp( BaseType_t xIsAllNetworksUp );
/* *INDENT-OFF* */
#ifdef __cplusplus
} /* extern "C" */
#endif
/* *INDENT-ON* */
#endif /* FREERTOS_IP_PRIVATE_H */
@@ -0,0 +1,175 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
/**
* @file FreeRTOS_IP_Timers.h
* @brief Header file for IP Timers on FreeRTOS+TCP network stack.
*/
#ifndef FREERTOS_IP_TIMERS_H
#define FREERTOS_IP_TIMERS_H
/* Standard includes. */
#include <stdint.h>
#include <stdio.h>
#include <string.h>
/* FreeRTOS includes. */
#include "FreeRTOS.h"
#include "task.h"
#include "queue.h"
#include "semphr.h"
/* FreeRTOS+TCP includes. */
#include "FreeRTOS_IP.h"
#include "FreeRTOS_Sockets.h"
#include "FreeRTOS_IP_Private.h"
#include "FreeRTOS_UDP_IP.h"
#include "FreeRTOS_DHCP.h"
#include "NetworkInterface.h"
#include "NetworkBufferManagement.h"
#include "FreeRTOS_DNS.h"
/* *INDENT-OFF* */
#ifdef __cplusplus
extern "C" {
#endif
/* *INDENT-ON* */
/*
* Checks the ARP, ND, DHCP and TCP timers to see if any periodic or timeout
* processing is required.
*/
void vCheckNetworkTimers( void );
/*
* Determine how long the IP task can sleep for, which depends on when the next
* periodic or timeout processing must be performed.
*/
TickType_t xCalculateSleepTime( void );
/*
* Enable/disable the TCP timer.
*/
void vIPSetTCPTimerExpiredState( BaseType_t xExpiredState );
#if ipconfigIS_ENABLED( ipconfigUSE_IPv4 )
/**
* Sets the reload time of an ARP timer and restarts it.
*/
void vARPTimerReload( TickType_t xTime );
/*
* Start an ARP Resolution timer.
*/
void vIPTimerStartARPResolution( TickType_t xTime );
/*
* Enable/disable the ARP timer.
*/
void vIPSetARPTimerEnableState( BaseType_t xEnableState );
/*
* Enable or disable the ARP resolution timer.
*/
void vIPSetARPResolutionTimerEnableState( BaseType_t xEnableState );
#endif /* if ipconfigIS_ENABLED( ipconfigUSE_IPv4 ) */
#if ipconfigIS_ENABLED( ipconfigUSE_IPv6 )
/**
* Sets the reload time of an ND timer and restarts it.
*/
void vNDTimerReload( TickType_t xTime );
/*
* Start an ND Resolution timer.
*/
void vIPTimerStartNDResolution( TickType_t xTime );
/*
* Enable/disable the ND timer.
*/
void vIPSetNDTimerEnableState( BaseType_t xEnableState );
/*
* Enable or disable the ARP resolution timer.
*/
void vIPSetNDResolutionTimerEnableState( BaseType_t xEnableState );
#endif /* if ipconfigIS_ENABLED( ipconfigUSE_IPv6 ) */
#if ( ipconfigUSE_DHCP == 1 ) || ( ipconfigUSE_RA == 1 )
/**
* @brief Enable/disable the DHCP/RA timer.
* @param[in] pxEndPoint: The end-point for which the timer will be called.
* @param[in] xEnableState: pdTRUE - enable timer; pdFALSE - disable timer.
*/
void vIPSetDHCP_RATimerEnableState( NetworkEndPoint_t * pxEndPoint,
BaseType_t xEnableState );
#endif /* ( ipconfigUSE_DHCP == 1 ) || ( ipconfigUSE_RA == 1 ) */
#if ( ipconfigDNS_USE_CALLBACKS != 0 )
/**
* @brief Enable/disable the DNS timer.
* @param[in] xEnableState: pdTRUE - enable timer; pdFALSE - disable timer.
*/
void vIPSetDNSTimerEnableState( BaseType_t xEnableState );
#endif /* ipconfigDNS_USE_CALLBACKS != 0 */
/**
* Sets the reload time of an TCP timer and restarts it.
*/
void vTCPTimerReload( TickType_t xTime );
#if ( ipconfigUSE_DHCP == 1 ) || ( ipconfigUSE_RA == 1 )
void vDHCP_RATimerReload( NetworkEndPoint_t * pxEndPoint,
TickType_t uxClockTicks );
#endif /* ( ipconfigUSE_DHCP == 1 ) || ( ipconfigUSE_RA == 1 ) */
#if ( ipconfigDNS_USE_CALLBACKS != 0 )
/**
* Reload the DNS timer.
*/
void vDNSTimerReload( uint32_t ulCheckTime );
#endif /* ipconfigDNS_USE_CALLBACKS != 0 */
/**
* Reload the Network timer.
*/
void vNetworkTimerReload( TickType_t xTime );
/* *INDENT-OFF* */
#ifdef __cplusplus
} /* extern "C" */
#endif
/* *INDENT-ON* */
#endif /* FREERTOS_IP_TIMERS_H */
@@ -0,0 +1,123 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
/**
* @file FreeRTOS_IP_Utils.h
* @brief Implements the utility functions for FreeRTOS_IP.c
*/
#ifndef FREERTOS_IP_UTILS_H
#define FREERTOS_IP_UTILS_H
/* Standard includes. */
#include <stdint.h>
#include <stdio.h>
#include <string.h>
/* FreeRTOS includes. */
#include "FreeRTOS.h"
#include "task.h"
#include "queue.h"
#include "semphr.h"
/* FreeRTOS+TCP includes. */
#include "FreeRTOS_IP.h"
#include "FreeRTOS_Sockets.h"
#include "FreeRTOS_IP_Private.h"
#include "FreeRTOS_UDP_IP.h"
#include "FreeRTOS_DHCP.h"
#include "NetworkInterface.h"
#include "NetworkBufferManagement.h"
#include "FreeRTOS_DNS.h"
#include "FreeRTOS_IPv4_Utils.h"
#include "FreeRTOS_IPv6_Utils.h"
/* *INDENT-OFF* */
#ifdef __cplusplus
extern "C" {
#endif
/* *INDENT-ON* */
/* Forward declaration. */
struct xNetworkInterface;
struct xNetworkEndPoint;
#if ( ( ipconfigUSE_DHCPv6 == 1 ) || ( ipconfigUSE_DHCP == 1 ) || ( ipconfigUSE_RA == 1 ) )
/**
* @brief Create a DHCP event.
*
* @return pdPASS or pdFAIL, depending on whether xSendEventStructToIPTask()
* succeeded.
*/
BaseType_t xSendDHCPEvent( struct xNetworkEndPoint * pxEndPoint );
#endif
#if ( ( ipconfigUSE_DHCPv6 == 1 ) || ( ipconfigUSE_DHCP == 1 ) )
/* Returns the current state of a DHCP process. */
eDHCPState_t eGetDHCPState( const struct xNetworkEndPoint * pxEndPoint );
#endif
#if ( ipconfigZERO_COPY_TX_DRIVER != 0 ) || ( ipconfigZERO_COPY_RX_DRIVER != 0 )
/**
* @brief Get the network buffer from the packet buffer.
*
* @param[in] pvBuffer: Pointer to the packet buffer.
*
* @return The network buffer if the alignment is correct. Else a NULL is returned.
*/
NetworkBufferDescriptor_t * pxPacketBuffer_to_NetworkBuffer( const void * pvBuffer );
#endif
/**
* @brief Check the values of configuration options and assert on it. Also verify that the IP-task
* has not already been initialized.
*/
void vPreCheckConfigs( void );
/**
* @brief Called to create a network connection when the stack is first
* started, or when the network connection is lost.
*/
void prvProcessNetworkDownEvent( struct xNetworkInterface * pxInterface );
/**
* @brief Release single UDP packet from a given socket
*/
void vReleaseSinglePacketFromUDPSocket( const ConstSocket_t xSocket );
/* *INDENT-OFF* */
#ifdef __cplusplus
} /* extern "C" */
#endif
/* *INDENT-ON* */
#endif /* FREERTOS_IP_UTILS_H */
@@ -0,0 +1,107 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
#ifndef FREERTOS_IPV4_H
#define FREERTOS_IPV4_H
#include "FreeRTOS.h"
#include "task.h"
/* Application level configuration options. */
#include "FreeRTOSIPConfig.h"
#include "FreeRTOSIPConfigDefaults.h"
/* *INDENT-OFF* */
#ifdef __cplusplus
extern "C" {
#endif
/* *INDENT-ON* */
/* Forward declarations. */
struct xNETWORK_BUFFER;
struct xIP_PACKET;
#define ipSIZE_OF_IPv4_HEADER 20U
#define ipSIZE_OF_IPv4_ADDRESS 4U
#define ipSIZE_OF_ICMPv4_HEADER 8U
#define ipTYPE_IPv4 ( 0x40U )
#define ipFIRST_LOOPBACK_IPv4 0x7F000000UL /**< Lowest IPv4 loopback address (including). */
#define ipLAST_LOOPBACK_IPv4 0x80000000UL /**< Highest IPv4 loopback address (excluding). */
/* The first byte in the IPv4 header combines the IP version (4) with
* with the length of the IP header. */
#define ipIPV4_VERSION_HEADER_LENGTH_MIN 0x45U /**< Minimum IPv4 header length. */
#define ipIPV4_VERSION_HEADER_LENGTH_MAX 0x4FU /**< Maximum IPv4 header length. */
/* IPv4 multicast MAC address starts with 01-00-5E. */
#define ipMULTICAST_MAC_ADDRESS_IPv4_0 0x01U
#define ipMULTICAST_MAC_ADDRESS_IPv4_1 0x00U
#define ipMULTICAST_MAC_ADDRESS_IPv4_2 0x5EU
/*
* These functions come from the IPv4-only library.
* void FreeRTOS_SetIPAddress( uint32_t ulIPAddress );
* void FreeRTOS_SetNetmask( uint32_t ulNetmask );
* void FreeRTOS_SetGatewayAddress( uint32_t ulGatewayAddress );
* uint32_t FreeRTOS_GetGatewayAddress( void );
* uint32_t FreeRTOS_GetDNSServerAddress( void );
* uint32_t FreeRTOS_GetNetmask( void );
*/
void FreeRTOS_SetIPAddress( uint32_t ulIPAddress );
void FreeRTOS_SetNetmask( uint32_t ulNetmask );
void FreeRTOS_SetGatewayAddress( uint32_t ulGatewayAddress );
uint32_t FreeRTOS_GetGatewayAddress( void );
uint32_t FreeRTOS_GetDNSServerAddress( void );
uint32_t FreeRTOS_GetNetmask( void );
uint32_t FreeRTOS_GetIPAddress( void );
/* Return pdTRUE if the IPv4 address is a multicast address. */
BaseType_t xIsIPv4Multicast( uint32_t ulIPAddress );
/* Return pdTRUE if the IPv4 address is a broadcast address. */
BaseType_t xIsIPv4Broadcast( uint32_t ulIPAddress,
struct xNetworkEndPoint ** ppxEndPoint );
/* Return pdTRUE if the IPv4 address is a loopback address. */
BaseType_t xIsIPv4Loopback( uint32_t ulAddress );
/*
* Return pdTRUE if either source or destination is a loopback address.
* A loopback IP-address may only communicate internally with another
* loopback IP-address.
*/
BaseType_t xBadIPv4Loopback( const IPHeader_t * const pxIPHeader );
/* *INDENT-OFF* */
#ifdef __cplusplus
} /* extern "C" */
#endif
/* *INDENT-ON* */
#endif /* FREERTOS_IPV4_H */
@@ -0,0 +1,143 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* https://www.FreeRTOS.org
* https://github.com/FreeRTOS
*/
#ifndef FREERTOS_IPV4_PRIVATE_H
#define FREERTOS_IPV4_PRIVATE_H
#include "FreeRTOS_IP_Private.h"
/* *INDENT-OFF* */
#ifdef __cplusplus
extern "C" {
#endif
/* *INDENT-ON* */
/* The maximum UDP payload length. */
#define ipMAX_UDP_PAYLOAD_LENGTH ( ( ipconfigNETWORK_MTU - ipSIZE_OF_IPv4_HEADER ) - ipSIZE_OF_UDP_HEADER )
#define TCP_PACKET_SIZE ( sizeof( TCPPacket_t ) )
/* The offset into an IP packet into which the IP data (payload) starts. */
#define ipIP_PAYLOAD_OFFSET ( sizeof( IPPacket_t ) )
/* The offset into a UDP packet at which the UDP data (payload) starts. */
#define ipUDP_PAYLOAD_OFFSET_IPv4 ( sizeof( UDPPacket_t ) )
/* The value of 'ipUDP_PAYLOAD_IP_TYPE_OFFSET' is 8 + 40 = 48 bytes. */
#define ipUDP_PAYLOAD_IP_TYPE_OFFSET ( sizeof( UDPHeader_t ) + sizeof( IPHeader_IPv6_t ) )
/* ipIP_TYPE_OFFSET is involved in some sorcery. pxUDPPayloadBuffer_to_NetworkBuffer() must be able to convert
* a payload pointer ( like for example a pointer to the DNS payload of a packet ) back to a NetworkBufferDescriptor_t.
* This must work for both IPv4 and IPv6 packets. The pointer conversion is done by subtracting a constant from the payload pointer.
* For IPv6, this magic number is ( sizeof( UDPHeader_t ) + sizeof( IPHeader_IPv6_t ) ) which equals 48 bytes.
* If however we use that same constant for an IPv4 packet, we end up somewhere in front of the Ethernet header.
* In order to accommodate that, the Ethernet frame buffer gets allocated a bit larger than needed.
* For IPv4 frames, prvProcessIPPacket() stores the version header field at a negative offset, a few bytes before the start
* of the Ethernet header. That IPv4 version field MUST be stored the same distance from the payload as in IPv6.
* ipIP_TYPE_OFFSET must be equal to: sizeof( UDPHeader_t ) + sizeof( IPHeader_IPv6_t ) - ( sizeof( UDPPacket_t )
* In most situations, ipIP_TYPE_OFFSET will end up being equal to 6. If the Ethernet header is enlarged to include VLAN
* tag support, ipIP_TYPE_OFFSET will shrink to 2. With the current design, the Ethernet header cannot be expanded to contain
* more than one VLAN tag or ipIP_TYPE_OFFSET will become less than zero. ipIP_TYPE_OFFSET should never be allowed to be <= 0
* or storing of the IPv4 version byte will overwrite the Ethernet header of the frame.
*/
#define ipIP_TYPE_OFFSET ( ( int32_t ) sizeof( UDPHeader_t ) + ( int32_t ) sizeof( IPHeader_IPv6_t ) - ( int32_t ) sizeof( UDPPacket_t ) )
#include "pack_struct_start.h"
struct xIP_HEADER
{
uint8_t ucVersionHeaderLength; /**< The version field + internet header length 0 + 1 = 1 */
uint8_t ucDifferentiatedServicesCode; /**< Differentiated services code point + ECN 1 + 1 = 2 */
uint16_t usLength; /**< Entire Packet size, ex. Ethernet header. 2 + 2 = 4 */
uint16_t usIdentification; /**< Identification field 4 + 2 = 6 */
uint16_t usFragmentOffset; /**< Fragment flags and fragment offset 6 + 2 = 8 */
uint8_t ucTimeToLive; /**< Time to live field 8 + 1 = 9 */
uint8_t ucProtocol; /**< Protocol used in the IP-datagram 9 + 1 = 10 */
uint16_t usHeaderChecksum; /**< Checksum of the IP-header 10 + 2 = 12 */
uint32_t ulSourceIPAddress; /**< IP address of the source 12 + 4 = 16 */
uint32_t ulDestinationIPAddress; /**< IP address of the destination 16 + 4 = 20 */
}
#include "pack_struct_end.h"
typedef struct xIP_HEADER IPHeader_t;
/*-----------------------------------------------------------*/
/* Nested protocol packets. */
/*-----------------------------------------------------------*/
#include "pack_struct_start.h"
struct xIP_PACKET
{
EthernetHeader_t xEthernetHeader;
IPHeader_t xIPHeader;
}
#include "pack_struct_end.h"
typedef struct xIP_PACKET IPPacket_t;
#include "pack_struct_start.h"
struct xICMP_PACKET
{
EthernetHeader_t xEthernetHeader; /**< The Ethernet header of an ICMP packet. */
IPHeader_t xIPHeader; /**< The IP header of an ICMP packet. */
ICMPHeader_t xICMPHeader; /**< The ICMP header of an ICMP packet. */
}
#include "pack_struct_end.h"
typedef struct xICMP_PACKET ICMPPacket_t;
#include "pack_struct_start.h"
struct xUDP_PACKET
{
EthernetHeader_t xEthernetHeader; /**< UDP-Packet ethernet header 0 + 14 = 14 */
IPHeader_t xIPHeader; /**< UDP-Packet IP header 14 + 20 = 34 */
UDPHeader_t xUDPHeader; /**< UDP-Packet UDP header 34 + 8 = 42 */
}
#include "pack_struct_end.h"
typedef struct xUDP_PACKET UDPPacket_t;
#include "pack_struct_start.h"
struct xTCP_PACKET
{
EthernetHeader_t xEthernetHeader; /**< The ethernet header 0 + 14 = 14 */
IPHeader_t xIPHeader; /**< The IP header 14 + 20 = 34 */
TCPHeader_t xTCPHeader; /**< The TCP header 34 + 32 = 66 */
}
#include "pack_struct_end.h"
typedef struct xTCP_PACKET TCPPacket_t;
/* The function 'prvAllowIPPacket()' checks if a packets should be processed. */
enum eFrameProcessingResult prvAllowIPPacketIPv4( const struct xIP_PACKET * const pxIPPacket,
const struct xNETWORK_BUFFER * const pxNetworkBuffer,
UBaseType_t uxHeaderLength );
/* Check if the IP-header is carrying options. */
enum eFrameProcessingResult prvCheckIP4HeaderOptions( struct xNETWORK_BUFFER * const pxNetworkBuffer );
/* *INDENT-OFF* */
#ifdef __cplusplus
} /* extern "C" */
#endif
/* *INDENT-ON* */
#endif /* FREERTOS_IPV4_PRIVATE_H */
@@ -0,0 +1,59 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
#ifndef FREERTOS_IPV4_SOCKETS_H
#define FREERTOS_IPV4_SOCKETS_H
/* Standard includes. */
#include <string.h>
/* FreeRTOS includes. */
#include "FreeRTOS.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Called by prvSendUDPPacket(), this function will UDP packet
* fields and IPv4 address for the packet to be send.
*/
void * xSend_UDP_Update_IPv4( NetworkBufferDescriptor_t * pxNetworkBuffer,
const struct freertos_sockaddr * pxDestinationAddress );
/**
* @brief Called by FreeRTOS_recvfrom(), this function will update socket
* address with IPv4 address from the packet received.
*/
size_t xRecv_Update_IPv4( const NetworkBufferDescriptor_t * pxNetworkBuffer,
struct freertos_sockaddr * pxSourceAddress );
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* FREERTOS_IPV4_SOCKETS_H */
@@ -0,0 +1,67 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
#ifndef FREERTOS_IPV4_UTILS_H
#define FREERTOS_IPV4_UTILS_H
/**
* @file FreeRTOS_IPv4_Utils.h
* @brief Implements the utility functions for FreeRTOS_IP.c
*/
/* Standard includes. */
#include <stdint.h>
#include <stdio.h>
/* FreeRTOS includes. */
#include "FreeRTOS.h"
/* FreeRTOS+TCP includes. */
#include "FreeRTOS_IP.h"
/* *INDENT-OFF* */
#ifdef __cplusplus
extern "C" {
#endif
/* *INDENT-ON* */
/* Set the MAC-address that belongs to a given IPv4 multi-cast address. */
void vSetMultiCastIPv4MacAddress( uint32_t ulIPAddress,
MACAddress_t * pxMACAddress );
/* The first IPv4 length checks at the IP-header level. */
BaseType_t prvChecksumIPv4Checks( uint8_t * pucEthernetBuffer,
size_t uxBufferLength,
struct xPacketSummary * pxSet );
/* *INDENT-OFF* */
#ifdef __cplusplus
} /* extern "C" */
#endif
/* *INDENT-ON* */
#endif /* FREERTOS_IPV4_UTILS_H */
@@ -0,0 +1,134 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
#ifndef FREERTOS_IPV6_H
#define FREERTOS_IPV6_H
#include "FreeRTOS.h"
#include "task.h"
#include "FreeRTOS_IP.h"
#include "FreeRTOS_IP_Common.h"
/* *INDENT-OFF* */
#ifdef __cplusplus
extern "C" {
#endif
/* *INDENT-ON* */
/* Some constants defining the sizes of several parts of a packet.
* These defines come before including the configuration header files. */
#define ipSIZE_OF_IPv6_HEADER 40U
#define ipSIZE_OF_ICMPv6_HEADER 24U
#define ipSIZE_OF_IPv6_ADDRESS 16U
#define ipPROTOCOL_ICMP_IPv6 ( 58U )
#define ipTYPE_IPv6 ( 0x60U )
/* Some IPv6 ICMP requests. */
#define ipICMP_DEST_UNREACHABLE_IPv6 ( ( uint8_t ) 1U )
#define ipICMP_PACKET_TOO_BIG_IPv6 ( ( uint8_t ) 2U )
#define ipICMP_TIME_EXCEEDED_IPv6 ( ( uint8_t ) 3U )
#define ipICMP_PARAMETER_PROBLEM_IPv6 ( ( uint8_t ) 4U )
#define ipICMP_PING_REQUEST_IPv6 ( ( uint8_t ) 128U )
#define ipICMP_PING_REPLY_IPv6 ( ( uint8_t ) 129U )
#define ipICMP_ROUTER_SOLICITATION_IPv6 ( ( uint8_t ) 133U )
#define ipICMP_ROUTER_ADVERTISEMENT_IPv6 ( ( uint8_t ) 134U )
#define ipICMP_NEIGHBOR_SOLICITATION_IPv6 ( ( uint8_t ) 135U )
#define ipICMP_NEIGHBOR_ADVERTISEMENT_IPv6 ( ( uint8_t ) 136U )
#define ipIPv6_EXT_HEADER_HOP_BY_HOP 0U
#define ipIPv6_EXT_HEADER_ROUTING_HEADER 43U
#define ipIPv6_EXT_HEADER_FRAGMENT_HEADER 44U
#define ipIPv6_EXT_HEADER_SECURE_PAYLOAD 50U
#define ipIPv6_EXT_HEADER_AUTHEN_HEADER 51U
#define ipIPv6_EXT_HEADER_DESTINATION_OPTIONS 60U
/* Destination options may follow here in case there are no routing options. */
#define ipIPv6_EXT_HEADER_MOBILITY_HEADER 135U
extern const struct xIPv6_Address FreeRTOS_in6addr_any;
extern const struct xIPv6_Address FreeRTOS_in6addr_loopback;
/* IPv6 multicast MAC address starts with 33-33-. */
#define ipMULTICAST_MAC_ADDRESS_IPv6_0 0x33U
#define ipMULTICAST_MAC_ADDRESS_IPv6_1 0x33U
/* A forward declaration of 'struct xNetworkEndPoint' and 'xNetworkInterface'.
* The actual declaration can be found in FreeRTOS_Routing.h which is included
* as the last +TCP header file. */
struct xNetworkEndPoint;
struct xNetworkInterface;
/* The function 'prvAllowIPPacket()' checks if a IPv6 packets should be processed. */
eFrameProcessingResult_t prvAllowIPPacketIPv6( const IPHeader_IPv6_t * const pxIPv6Header,
const NetworkBufferDescriptor_t * const pxNetworkBuffer,
UBaseType_t uxHeaderLength );
#if ( ipconfigETHERNET_DRIVER_FILTERS_PACKETS == 0 )
/*
* Return pdTRUE if either source or destination is a loopback address.
* A loopback IP-address may only communicate internally with another
* loopback IP-address.
*/
BaseType_t xBadIPv6Loopback( const IPHeader_IPv6_t * const pxIPv6Header );
#endif /* ipconfigETHERNET_DRIVER_FILTERS_PACKETS == 0 */
/*
* Check if the address is a loopback IP-address.
*/
BaseType_t xIsIPv6Loopback( const IPv6_Address_t * pxAddress );
/** @brief Handle the IPv6 extension headers. */
eFrameProcessingResult_t eHandleIPv6ExtensionHeaders( NetworkBufferDescriptor_t * const pxNetworkBuffer,
BaseType_t xDoRemove );
/* Check whether this IPv6 address is an allowed multicast address or not. */
BaseType_t xIsIPv6AllowedMulticast( const IPv6_Address_t * pxIPAddress );
/* Note that 'xCompareIPv6_Address' will also check if 'pxRight' is
* the special unicast address: ff02::1:ffnn:nnnn, where nn:nnnn are
* the last 3 bytes of the IPv6 address. */
BaseType_t xCompareIPv6_Address( const IPv6_Address_t * pxLeft,
const IPv6_Address_t * pxRight,
size_t uxPrefixLength );
/* FreeRTOS_dnslookup6() returns pdTRUE when a host has been found. */
uint32_t FreeRTOS_dnslookup6( const char * pcHostName,
IPv6_Address_t * pxAddress_IPv6 );
/* Return IPv6 header extension order number */
BaseType_t xGetExtensionOrder( uint8_t ucProtocol,
uint8_t ucNextHeader );
/* *INDENT-OFF* */
#ifdef __cplusplus
} /* extern "C" */
#endif
/* *INDENT-ON* */
#endif /* FREERTOS_IPV6_H */
@@ -0,0 +1,275 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* https://www.FreeRTOS.org
* https://github.com/FreeRTOS
*/
#ifndef FREERTOS_IPV6_PRIVATE_H
#define FREERTOS_IPV6_PRIVATE_H
/* Application level configuration options. */
#include "FreeRTOSIPConfig.h"
#include "FreeRTOSIPConfigDefaults.h"
#include "FreeRTOS_IP_Common.h"
#include "FreeRTOS_Sockets.h"
#include "FreeRTOS_Stream_Buffer.h"
#if ( ipconfigUSE_TCP == 1 )
#include "FreeRTOS_TCP_WIN.h"
#include "FreeRTOS_TCP_IP.h"
#endif
#include "semphr.h"
#include "event_groups.h"
/* *INDENT-OFF* */
#ifdef __cplusplus
extern "C" {
#endif
/* *INDENT-ON* */
/* MISRA Ref 20.5.1 [Use of undef] */
/* More details at: https://github.com/FreeRTOS/FreeRTOS-Plus-TCP/blob/main/MISRA.md#rule-2051 */
/* coverity[misra_c_2012_rule_20_5_violation] */
#undef TCP_PACKET_SIZE
#define TCP_PACKET_SIZE ( sizeof( TCPPacket_IPv6_t ) )
/* The offset into an IP packet into which the IP data (payload) starts. */
#define ipIPv6_PAYLOAD_OFFSET ( sizeof( IPPacket_IPv6_t ) )
/* The maximum UDP payload length. */
/* MISRA Ref 20.5.1 [Use of undef] */
/* More details at: https://github.com/FreeRTOS/FreeRTOS-Plus-TCP/blob/main/MISRA.md#rule-2051 */
/* coverity[misra_c_2012_rule_20_5_violation] */
#undef ipMAX_UDP_PAYLOAD_LENGTH
#define ipMAX_UDP_PAYLOAD_LENGTH ( ( ipconfigNETWORK_MTU - ipSIZE_OF_IPv6_HEADER ) - ipSIZE_OF_UDP_HEADER )
/* The offset into a UDP packet at which the UDP data (payload) starts. */
#define ipUDP_PAYLOAD_OFFSET_IPv6 ( sizeof( UDPPacket_IPv6_t ) )
#if ( ipconfigBYTE_ORDER == pdFREERTOS_LITTLE_ENDIAN )
#define ipIPv6_FRAME_TYPE ( 0xDD86U ) /* Ethernet frame types. */
#else /* if ( ipconfigBYTE_ORDER == pdFREERTOS_LITTLE_ENDIAN ) */
#define ipIPv6_FRAME_TYPE ( 0x86DDU ) /* Ethernet frame types. */
#endif /* ipconfigBYTE_ORDER */
/* In this library, there is often a cast from a character pointer
* to a pointer to a struct.
* In order to suppress MISRA warnings, do the cast within a macro,
* which can be exempt from warnings:
*
* 3 required by MISRA:
* -emacro(740,ipPOINTER_CAST) // 750: Unusual pointer cast (incompatible indirect types) [MISRA 2012 Rule 1.3, required])
* -emacro(9005,ipPOINTER_CAST) // 9005: attempt to cast away const/volatile from a pointer or reference [MISRA 2012 Rule 11.8, required]
* -emacro(9087,ipPOINTER_CAST) // 9087: cast performed between a pointer to object type and a pointer to a different object type [MISRA 2012 Rule 11.3, required]
*
* 2 advisory by MISRA:
* -emacro(9079,ipPOINTER_CAST) // 9079: conversion from pointer to void to pointer to other type [MISRA 2012 Rule 11.5, advisory])
* --emacro((826),ipPOINTER_CAST) // 826: Suspicious pointer-to-pointer conversion (area too small)
*
* The MISRA warnings can safely be suppressed because all casts are planned with care.
*/
#define ipPOINTER_CAST( TYPE, pointer ) ( ( TYPE ) ( pointer ) )
/* Sequence and ACK numbers are essentially unsigned (uint32_t). But when
* a distance is calculated, it is useful to use signed numbers:
* int32_t lDistance = ( int32_t ) ( ulSeq1 - ulSeq2 );
*
* 1 required by MISRA:
* -emacro(9033,ipNUMERIC_CAST) // 9033: Impermissible cast of composite expression (different essential type categories) [MISRA 2012 Rule 10.8, required])
*
* 1 advisory by MISRA:
* -emacro(9030,ipNUMERIC_CAST) // 9030: Impermissible cast; cannot cast from 'essentially Boolean' to 'essentially signed' [MISRA 2012 Rule 10.5, advisory])
*/
#define ipNUMERIC_CAST( TYPE, expression ) ( ( TYPE ) ( expression ) )
/** @brief The macros vSetField16() and vSetField32() will write either a short or a 32-bit
* value into an array of bytes. They will be stored big-endian.
* The helper functions do the actual work.
*/
/*extern void vSetField16helper( uint8_t * pucBase,
* size_t uxOffset,
* uint16_t usValue );
#define vSetField16( pucBase, xType, xField, usValue ) \
* vSetField16helper( pucBase, offsetof( xType, xField ), usValue )
*
* extern void vSetField32helper( uint8_t * pucBase,
* size_t uxOffset,
* uint32_t ulValue );
#define vSetField32( pucBase, xType, xField, ulValue ) \
* vSetField32helper( pucBase, offsetof( xType, xField ), ulValue )
*/
/* As FreeRTOS_Routing is included later, use forward declarations
* of the two structs. */
struct xNetworkEndPoint;
struct xNetworkInterface;
#define ipICMPv6_GENERAL_FIELD_SIZE ( 4U )
#include "pack_struct_start.h"
struct xIP_HEADER_IPv6
{
uint8_t ucVersionTrafficClass; /**< The version field. 0 + 1 = 1 */
uint8_t ucTrafficClassFlow; /**< Traffic class and flow. 1 + 1 = 2 */
uint16_t usFlowLabel; /**< Flow label. 2 + 2 = 4 */
uint16_t usPayloadLength; /**< Number of bytes after the IPv6 header. 4 + 2 = 6 */
uint8_t ucNextHeader; /**< Next header: TCP, UDP, or ICMP. 6 + 1 = 7 */
uint8_t ucHopLimit; /**< Replaces the time to live from IPv4. 7 + 1 = 8 */
IPv6_Address_t xSourceAddress; /**< The IPv6 address of the sender. 8 + 16 = 24 */
IPv6_Address_t xDestinationAddress; /**< The IPv6 address of the receiver. 24 + 16 = 40 */
}
#include "pack_struct_end.h"
typedef struct xIP_HEADER_IPv6 IPHeader_IPv6_t;
#include "pack_struct_start.h"
struct xIP_EXT_HEADER_IPv6
{
uint8_t ucNextHeader; /**< Next header: TCP, UDP, or ICMP. 0 + 1 = 1 */
uint8_t ucHeaderExtLength; /**< Length of this header in 8-octet units, not including the first 8 octets. 1 + 1 = 2 */
}
#include "pack_struct_end.h"
typedef struct xIP_EXT_HEADER_IPv6 IPExtHeader_IPv6_t;
#include "pack_struct_start.h"
struct xICMPEcho_IPv6
{
uint8_t ucTypeOfMessage; /**< The message type. 0 + 1 = 1 */
uint8_t ucTypeOfService; /**< Type of service. 1 + 1 = 2 */
uint16_t usChecksum; /**< Checksum. 2 + 2 = 4 */
uint16_t usIdentifier; /**< Identifier. 4 + 2 = 6 */
uint16_t usSequenceNumber; /**< Sequence number. 6 + 2 = 8 */
}
#include "pack_struct_end.h"
typedef struct xICMPEcho_IPv6 ICMPEcho_IPv6_t;
#include "pack_struct_start.h"
struct xICMPRouterSolicitation_IPv6
{
uint8_t ucTypeOfMessage; /**< 0 + 1 = 1 */
uint8_t ucTypeOfService; /**< 1 + 1 = 2 */
uint16_t usChecksum; /**< 2 + 2 = 4 */
uint32_t ulReserved; /**< 4 + 4 = 8 */
}
#include "pack_struct_end.h"
typedef struct xICMPRouterSolicitation_IPv6 ICMPRouterSolicitation_IPv6_t;
#include "pack_struct_start.h"
struct xICMPRouterAdvertisement_IPv6
{
uint8_t ucTypeOfMessage; /* 0 + 1 = 1 */
uint8_t ucTypeOfService; /* 1 + 1 = 2 */
uint16_t usChecksum; /* 2 + 2 = 4 */
uint8_t ucHopLimit; /* 4 + 1 = 5 */
uint8_t ucFlags; /* 5 + 1 = 6 */
uint16_t usLifetime; /* 6 + 2 = 8 */
uint16_t usReachableTime[ 2 ]; /* 8 + 4 = 12 */
uint16_t usRetransTime[ 2 ]; /* 12 + 4 = 16 */
}
#include "pack_struct_end.h"
typedef struct xICMPRouterAdvertisement_IPv6 ICMPRouterAdvertisement_IPv6_t;
#if ( ipconfigUSE_RA != 0 )
#include "pack_struct_start.h"
struct xICMPPrefixOption_IPv6
{
uint8_t ucType; /* 0 + 1 = 1 */
uint8_t ucLength; /* 1 + 1 = 2 */
uint8_t ucPrefixLength; /* 2 + 1 = 3 */
uint8_t ucFlags; /* 3 + 1 = 4 */
uint32_t ulValidLifeTime; /* 4 + 4 = 8 */
uint32_t ulPreferredLifeTime; /* 8 + 4 = 12 */
uint32_t ulReserved; /* 12 + 4 = 16 */
uint8_t ucPrefix[ 16 ]; /* 16 + 16 = 32 */
}
#include "pack_struct_end.h"
typedef struct xICMPPrefixOption_IPv6 ICMPPrefixOption_IPv6_t;
#endif /* ipconfigUSE_RA != 0 */
/*-----------------------------------------------------------*/
/* Nested protocol packets. */
/*-----------------------------------------------------------*/
#include "pack_struct_start.h"
struct xIP_PACKET_IPv6
{
EthernetHeader_t xEthernetHeader;
IPHeader_IPv6_t xIPHeader;
}
#include "pack_struct_end.h"
typedef struct xIP_PACKET_IPv6 IPPacket_IPv6_t;
#include "pack_struct_start.h"
struct xICMP_PACKET_IPv6
{
EthernetHeader_t xEthernetHeader; /* 0 + 14 = 14 */
IPHeader_IPv6_t xIPHeader; /* 14 + 40 = 54 */
ICMPHeader_IPv6_t xICMPHeaderIPv6; /* 54 + 8 = 62 */
}
#include "pack_struct_end.h"
typedef struct xICMP_PACKET_IPv6 ICMPPacket_IPv6_t;
#include "pack_struct_start.h"
struct xUDP_PACKET_IPv6
{
EthernetHeader_t xEthernetHeader; /* 0 + 14 = 14 */
IPHeader_IPv6_t xIPHeader; /* 14 + 40 = 54 */
UDPHeader_t xUDPHeader; /* 54 + 8 = 62 */
}
#include "pack_struct_end.h"
typedef struct xUDP_PACKET_IPv6 UDPPacket_IPv6_t;
#include "pack_struct_start.h"
struct xTCP_PACKET_IPv6
{
EthernetHeader_t xEthernetHeader; /* 0 + 14 = 14 */
IPHeader_IPv6_t xIPHeader; /* 14 + 40 = 54 */
TCPHeader_t xTCPHeader; /* 54 + 32 = 86 */
}
#include "pack_struct_end.h"
typedef struct xTCP_PACKET_IPv6 TCPPacket_IPv6_t;
/* prvProcessICMPMessage_IPv6() is declared in FreeRTOS_routing.c
* It handles all ICMP messages except the PING requests. */
eFrameProcessingResult_t prvProcessICMPMessage_IPv6( NetworkBufferDescriptor_t * const pxNetworkBuffer );
#if ( ( ipconfigHAS_DEBUG_PRINTF != 0 ) || ( ipconfigHAS_PRINTF != 0 ) )
/* prepare a string which describes a socket, just for logging. */
const char * prvSocketProps( FreeRTOS_Socket_t * pxSocket );
#endif /* ipconfigHAS_DEBUG_PRINTF || ipconfigHAS_PRINTF */
/* *INDENT-OFF* */
#ifdef __cplusplus
} /* extern "C" */
#endif
/* *INDENT-ON* */
#endif /* FREERTOS_IPV6_PRIVATE_H */
@@ -0,0 +1,118 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
#ifndef FREERTOS_IPV6_SOCKETS_H
#define FREERTOS_IPV6_SOCKETS_H
/* Standard includes. */
#include <string.h>
/* FreeRTOS includes. */
#include "FreeRTOS.h"
#include "FreeRTOS_IP_Common.h"
#ifdef __cplusplus
extern "C" {
#endif
/** @brief When ucASCIIToHex() can not convert a character,
* the value 255 will be returned.
*/
#define socketINVALID_HEX_CHAR ( 0xffU )
/** @brief The struct sNTOP6_Set is a set of parameters used by the function FreeRTOS_inet_ntop6().
* It passes this set to a few helper functions. */
struct sNTOP6_Set
{
const uint16_t * pusAddress; /**< The network address, 8 short values. */
BaseType_t xZeroStart; /**< The position of the first byte of the longest train of zero values. */
BaseType_t xZeroLength; /**< The number of short values in the longest train of zero values. */
BaseType_t xIndex; /**< The read index in the array of short values, the network address. */
socklen_t uxTargetIndex; /**< The write index in 'pcDestination'. */
};
/** @brief The struct sNTOP6_Set is a set of parameters used by the function FreeRTOS_inet_ntop6().
* It passes this set to a few helper functions.
*/
struct sPTON6_Set
{
uint32_t ulValue; /**< A 32-bit accumulator, only 16 bits are used. */
BaseType_t xHadDigit; /**< Becomes pdTRUE as soon as ulValue has valid data. */
BaseType_t xTargetIndex; /**< The index in the array pucTarget to write the next byte. */
BaseType_t xColon; /**< The position in the output where the train of zero's will start. */
BaseType_t xHighestIndex; /**< The highest allowed value of xTargetIndex. */
uint8_t * pucTarget; /**< The array of bytes in which the resulting IPv6 address is written. */
};
/**
* @brief Convert an ASCII character to its corresponding hexadecimal value.
* Accepted characters are 0-9, a-f, and A-F.
*/
uint8_t ucASCIIToHex( char cChar );
/* @brief Converts a hex value to a readable hex character, e.g. 14 becomes 'e'.
*/
char cHexToChar( uint16_t usValue );
/** @brief Converts a hex value to a readable hex character, *
* e.g. 14 becomes 'e'.static char cHexToChar( unsigned short usValue );
*/
socklen_t uxHexPrintShort( char * pcBuffer,
size_t uxBufferSize,
uint16_t usValue );
/** @brief Scan the binary IPv6 address and find the longest train of consecutive zero's.
* The result of this search will be stored in 'xZeroStart' and 'xZeroLength'.
*/
void prv_ntop6_search_zeros( struct sNTOP6_Set * pxSet );
/** @brief Called by pxTCPSocketLookup(), this function will check if a socket
* is connected to a remote IP-address. It will be called from a loop
* iterating through all sockets. */
FreeRTOS_Socket_t * pxTCPSocketLookup_IPv6( FreeRTOS_Socket_t * pxSocket,
const IPv46_Address_t * pxAddress );
/**
* @brief Called by prvSendUDPPacket(), this function will UDP packet
* fields and IPv6 address for the packet to be send.
*/
void * xSend_UDP_Update_IPv6( NetworkBufferDescriptor_t * pxNetworkBuffer,
const struct freertos_sockaddr * pxDestinationAddress );
/**
* @brief Called by FreeRTOS_recvfrom(), this function will update socket
* address with IPv6 address from the packet received.
*/
size_t xRecv_Update_IPv6( const NetworkBufferDescriptor_t * pxNetworkBuffer,
struct freertos_sockaddr * pxSourceAddress );
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* FREERTOS_IPV6_SOCKETS_H */
@@ -0,0 +1,78 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
#ifndef FREERTOS_IPV6_UTILS_H
#define FREERTOS_IPV6_UTILS_H
/**
* @file FreeRTOS_IPv6_Utils.h
* @brief Implements the utility functions for FreeRTOS_IP.c
*/
/* Standard includes. */
#include <stdint.h>
#include <stdio.h>
/* FreeRTOS includes. */
#include "FreeRTOS.h"
/* FreeRTOS+TCP includes. */
#include "FreeRTOS_IP.h"
/* *INDENT-OFF* */
#ifdef __cplusplus
extern "C" {
#endif
/* *INDENT-ON* */
/* Set the MAC-address that belongs to a given IPv6 multi-cast address. */
void vSetMultiCastIPv6MacAddress( const IPv6_Address_t * pxAddress,
MACAddress_t * pxMACAddress );
extern BaseType_t prvChecksumIPv6Checks( uint8_t * pucEthernetBuffer,
size_t uxBufferLength,
struct xPacketSummary * pxSet );
extern BaseType_t prvChecksumICMPv6Checks( size_t uxBufferLength,
struct xPacketSummary * pxSet );
/* Get total length of all extension headers in IPv6 packet. */
size_t usGetExtensionHeaderLength( const uint8_t * pucEthernetBuffer,
size_t uxBufferLength,
uint8_t * pucProtocol );
void vManageSolicitedNodeAddress( const struct xNetworkEndPoint * pxEndPoint,
BaseType_t xNetworkGoingUp );
/* *INDENT-OFF* */
#ifdef __cplusplus
} /* extern "C" */
#endif
/* *INDENT-ON* */
#endif /* FREERTOS_IPV6_UTILS_H */
@@ -0,0 +1,224 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
#ifndef FREERTOS_ND_H
#define FREERTOS_ND_H
#include "FreeRTOS.h"
/* Application level configuration options. */
#include "FreeRTOSIPConfig.h"
#include "FreeRTOSIPConfigDefaults.h"
#include "FreeRTOS_Routing.h"
/* *INDENT-OFF* */
#ifdef __cplusplus
extern "C" {
#endif
/* *INDENT-ON* */
#if ( ipconfigUSE_IPv6 != 0 )
/*-----------------------------------------------------------*/
/* Miscellaneous structure and definitions. */
/*-----------------------------------------------------------*/
/**
* @brief 'NDCacheRow_t' defines one row in the ND address cache.
* @note About A value that is periodically decremented but can
* also be refreshed by active communication. The ND cache entry
* is removed if the value reaches zero.
*/
typedef struct xND_CACHE_TABLE_ROW
{
IPv6_Address_t xIPAddress; /**< The IP address of an ND cache entry. */
MACAddress_t xMACAddress; /**< The MAC address of an ND cache entry. */
struct xNetworkEndPoint * pxEndPoint; /**< The end-point on which the
* remote device had responded. */
uint8_t ucAge; /**< See here above. */
uint8_t ucValid; /**< pdTRUE: xMACAddress is valid, pdFALSE: waiting for ND reply */
} NDCacheRow_t;
/*
* If ulIPAddress is already in the ND cache table then reset the age of the
* entry back to its maximum value. If ulIPAddress is not already in the ND
* cache table then add it - replacing the oldest current entry if there is not
* a free space available.
*/
void vNDRefreshCacheEntry( const MACAddress_t * pxMACAddress,
const IPv6_Address_t * pxIPAddress,
NetworkEndPoint_t * pxEndPoint );
/** @brief Options that can be sent in a ROuter Advertisement packet. */
#define ndICMP_SOURCE_LINK_LAYER_ADDRESS 1
#define ndICMP_TARGET_LINK_LAYER_ADDRESS 2
#define ndICMP_PREFIX_INFORMATION 3
#define ndICMP_REDIRECTED_HEADER 4
#define ndICMP_MTU_OPTION 5
/*
* @brief Send a neighbour solicitation.
* @param[in] pxIPAddress: A network buffer big enough to hold the ICMP packet.
* @param[in,out] pxMACAddress: When found, the array of 6 bytes will be filled
* with the MAC-address.
* @param[in,out] ppxEndPoint: The pointer to a pointer will point to an
* end-point to which the device has responded.
*
* @note Look for ulIPAddress in the ND cache. If the IP address exists, copy the
* associated MAC address into pxMACAddress, refresh the ND cache entry's
* age, and return eResolutionCacheHit. If the IP address does not exist in the ND
* cache return eResolutionCacheMiss. If the packet cannot be sent for any reason
* (maybe DHCP is still in process, or the addressing needs a gateway but there
* isn't a gateway defined) then return eResolutionFailed.
*/
eResolutionLookupResult_t eNDGetCacheEntry( IPv6_Address_t * pxIPAddress,
MACAddress_t * const pxMACAddress,
struct xNetworkEndPoint ** ppxEndPoint );
/**
* @brief Reduce the age counter in each entry within the ND cache. An entry is no
* longer considered valid and is deleted if its age reaches zero.
* Just before getting to zero, 3 times a neighbour solicitation will be sent.
*/
void vNDAgeCache( void );
/**
* @brief Send a neighbour solicitation.
* @param[in] pxNetworkBuffer: A network buffer big enough to hold the ICMP packet.
* @param[in] pxIPAddress: The IPv6 address of the target device.
*
* @note Send out an ND request for the IPv6 address contained in pxNetworkBuffer, and
* add an entry into the ND table that indicates that an ND reply is
* outstanding so re-transmissions can be generated.
*/
void vNDSendNeighbourSolicitation( NetworkBufferDescriptor_t * pxNetworkBuffer,
const IPv6_Address_t * pxIPAddress );
#if ( ipconfigUSE_RA != 0 )
/**
* @brief Send a router solicitation.
* @param[in] pxNetworkBuffer: A network buffer big enough to hold the ICMP packet.
* @param[in] pxIPAddress: The multi-cast address of the routers ( normally ff02::2 ).
*/
void vNDSendRouterSolicitation( NetworkBufferDescriptor_t * pxNetworkBuffer,
IPv6_Address_t * pxIPAddress );
#endif /* ( ipconfigUSE_RA != 0 ) */
#if ( ipconfigUSE_RA != 0 )
/**
* @brief Work on the RA/SLAAC processing.
* @param[in] xDoReset: WHen true, the state-machine will be reset and initialised.
* @param[in] pxEndPoint: The end-point for which the RA/SLAAC process should be done..
*/
void vRAProcess( BaseType_t xDoReset,
NetworkEndPoint_t * pxEndPoint );
#endif /* ( ipconfigUSE_RA != 0 ) */
/**
* @brief Send an ND advertisement.
* @param[in] pxEndPoint: The end-point for which an ND advertisement should be sent.
*/
void FreeRTOS_OutputAdvertiseIPv6( NetworkEndPoint_t * pxEndPoint );
#if ( ipconfigSUPPORT_OUTGOING_PINGS == 1 )
/**
* @brief Send an IPv6 ping message to a remote device.
* @param[in] pxIPAddress: The IPv6 address of the other device.
* @param[in] uxNumberOfBytesToSend: The number of bytes to be echoed.
* @param[in] uxBlockTimeTicks: The number of clock-tick to wait
* for space in the IP-task queue.
* @return pdTRUE when a packets was successfully created
* and passed to the IP-task.
*/
BaseType_t FreeRTOS_SendPingRequestIPv6( const IPv6_Address_t * pxIPAddress,
size_t uxNumberOfBytesToSend,
TickType_t uxBlockTimeTicks );
#endif
/**
* @brief Create an IPv16 address, based on a prefix.
*
* @param[out] pxIPAddress: The location where the new IPv6 address
* will be stored.
* @param[in] pxPrefix: The prefix to be used.
* @param[in] uxPrefixLength: The length of the prefix.
* @param[in] xDoRandom: A non-zero value if the bits after the
* prefix should have a random value.
*
* @return pdPASS if the operation was successful. Or pdFAIL in
* case xApplicationGetRandomNumber()
* returned an error.
*/
BaseType_t FreeRTOS_CreateIPv6Address( IPv6_Address_t * pxIPAddress,
const IPv6_Address_t * pxPrefix,
size_t uxPrefixLength,
BaseType_t xDoRandom );
/* Receive a Neighbour Advertisement. */
#if ( ipconfigUSE_RA != 0 )
/** @brief A neighbour advertisement has been received. Store its
* address in the ND address cache.
* @param[in] pxNetworkBuffer The buffer containing the packet.
*/
void vReceiveNA( const NetworkBufferDescriptor_t * pxNetworkBuffer );
#endif
/* Receive a Router Advertisement. */
#if ( ipconfigUSE_RA != 0 )
/** @brief A router advertisement has been received. See if it is
* applicable for this device.
* @param[in] pxNetworkBuffer The buffer containing the packet.
*/
void vReceiveRA( const NetworkBufferDescriptor_t * pxNetworkBuffer );
#endif
#if ( ( ipconfigHAS_PRINTF != 0 ) || ( ipconfigHAS_DEBUG_PRINTF != 0 ) )
/** @brief Print the contents of the ND cache, for debugging only. */
void FreeRTOS_PrintNDCache( void );
#endif
BaseType_t xCheckRequiresNDResolution( const NetworkBufferDescriptor_t * pxNetworkBuffer );
/* Clear all entries in the ND cache. */
void FreeRTOS_ClearND( const struct xNetworkEndPoint * pxEndPoint );
extern const uint8_t pcLOCAL_ALL_NODES_MULTICAST_IP[ ipSIZE_OF_IPv6_ADDRESS ];
extern const uint8_t pcLOCAL_ALL_NODES_MULTICAST_MAC[ ipMAC_ADDRESS_LENGTH_BYTES ];
#endif /* ipconfigUSE_IPv6 != 0 */
/* *INDENT-OFF* */
#ifdef __cplusplus
} /* extern "C" */
#endif
/* *INDENT-ON* */
#endif /* FREERTOS_ND_H */
@@ -0,0 +1,387 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
#ifndef FREERTOS_ROUTING_H
#define FREERTOS_ROUTING_H
#include "FreeRTOS.h"
#include "FreeRTOS_IP.h"
#include "FreeRTOS_Sockets.h"
#if ( ipconfigUSE_DHCP != 0 )
#include "FreeRTOS_DHCP.h"
#endif
#if ( ipconfigUSE_IPv6 != 0 )
#include "FreeRTOS_DHCPv6.h"
#endif
#ifdef __cplusplus
extern "C" {
#endif
/* Every NetworkInterface needs a set of access functions: */
/* Initialise the interface. */
typedef BaseType_t ( * NetworkInterfaceInitialiseFunction_t ) ( struct xNetworkInterface * pxDescriptor );
/* Send out an Ethernet packet. */
typedef BaseType_t ( * NetworkInterfaceOutputFunction_t ) ( struct xNetworkInterface * pxDescriptor,
NetworkBufferDescriptor_t * const pxNetworkBuffer,
BaseType_t xReleaseAfterSend );
/* Return true as long as the LinkStatus on the PHY is present. */
typedef BaseType_t ( * GetPhyLinkStatusFunction_t ) ( struct xNetworkInterface * pxDescriptor );
/* Functions that manipulate what MAC addresses are received by this interface */
typedef void ( * NetworkInterfaceMACFilterFunction_t ) ( struct xNetworkInterface * pxInterface,
const uint8_t * pucMacAddressBytes );
/** @brief These NetworkInterface access functions are collected in a struct: */
typedef struct xNetworkInterface
{
const char * pcName; /**< Just for logging, debugging. */
void * pvArgument; /**< Will be passed to the access functions. */
NetworkInterfaceInitialiseFunction_t pfInitialise; /**< This function will be called upon initialisation and repeated until it returns pdPASS. */
NetworkInterfaceOutputFunction_t pfOutput; /**< This function is supposed to send out a packet. */
GetPhyLinkStatusFunction_t pfGetPhyLinkStatus; /**< This function will return pdTRUE as long as the PHY Link Status is high. */
/*
* pfAddAllowedMAC and pfRemoveAllowedMAC form the network driver's address filtering API.
* The network stack uses these functions to alter which MAC addresses will be received.
* The MAC addresses passed to the functions can be unicast or multicast. It is important
* to note that the stack may call these functions multiple times for the the same MAC address.
* For example, if two sockets subscribe to the same multicast group, pfAddAllowedMAC()
* will be called twice with the same MAC address. The network driver is responsible for
* keeping track of these calls. The network driver should continue receiving that
* particular MAC address until pfRemoveAllowedMAC() is called the same number of times.
*
* Most EMAC hardware nowadays can filter frames based on both specific MAC address matching
* and hash matching. Specific address matching is ideal because as the name suggests,
* only frames with the exact MAC address are received. Usually however, the number of
* specific MAC addresses is limited ( to 4 in many cases ) and is sometimes not enough for
* all the MAC addresses that the network stack needs to receive.
* Hash matching is usually based around a 64-bit hash table. For every incoming frame,
* the EMAC calculates a hash value (mod 64) of the destination MAC address.
* The hash value is looked up in the 64-bit hash table and if that bit is set, the frame is
* received. If the bit is clear, the frame is dropped. With hash matching, multiple
* MAC addresses are represented by a single bit. It is the responsibility of the network
* driver to manage both the hash address matching and specific address matching capabilities
* of the EMAC hardware.
* A quick and dirty implementation option is to receive all MAC addresses and set both
* pfAddAllowedMAC and pfRemoveAllowedMAC to NULL. This results in an interface running
* in promiscuous mode and the entire burden of MAC filtering falls on the network stack.
* For a more realistic implementation, check out
* "portable/NetworkInterface/DriverSAM/NetworkInterface.c" It demonstrates the use of both
* specific and hash address matching as well as keeping count of how many time the
* individual registers/bits have been used. That implementation's init functions also
* demonstrates the use of prvAddAllowedMACAddress() function to register all end-point's
* MAC addresses whether the endpoints used the same or different MAC addresses.
*/
NetworkInterfaceMACFilterFunction_t pfAddAllowedMAC;
NetworkInterfaceMACFilterFunction_t pfRemoveAllowedMAC;
struct
{
uint32_t
bInterfaceUp : 1, /**< Non-zero as soon as the interface is up. */
bCallDownEvent : 1; /**< The down-event must be called. */
} bits; /**< A collection of boolean flags. */
struct xNetworkEndPoint * pxEndPoint; /**< A list of end-points bound to this interface. */
struct xNetworkInterface * pxNext; /**< The next interface in a linked list. */
} NetworkInterface_t;
/*
* // As an example:
* NetworkInterface_t xZynqDescriptor = {
* .pcName = "Zynq-GEM",
* .pvArgument = ( void * )1,
* .pfInitialise = xZynqGEMInitialise,
* .pfOutput = xZynqGEMOutput,
* .pfGetPhyLinkStatus = xZynqGEMGetPhyLinkStatus,
* };
*/
/** @brief The network settings for IPv4. */
typedef struct xIPV4Parameters
{
uint32_t ulIPAddress; /**< The actual IPv4 address. Will be 0 as long as end-point is still down. */
uint32_t ulNetMask; /**< The netmask. */
uint32_t ulGatewayAddress; /**< The IP-address of the gateway. */
uint32_t ulDNSServerAddresses[ ipconfigENDPOINT_DNS_ADDRESS_COUNT ]; /**< IP-addresses of DNS servers. */
uint32_t ulBroadcastAddress; /**< The local broadcast address, e.g. '192.168.1.255'. */
uint8_t ucDNSIndex; /**< The index of the next DNS address to be used. */
} IPV4Parameters_t;
#if ( ipconfigUSE_IPv6 != 0 )
typedef struct xIPV6Parameters
{
IPv6_Address_t xIPAddress; /* The actual IPv4 address. Will be 0 as long as end-point is still down. */
size_t uxPrefixLength; /* Number of valid bytes in the network prefix. */
IPv6_Address_t xPrefix; /* The network prefix, e.g. fe80::/10 */
IPv6_Address_t xGatewayAddress; /* Gateway to the web. */
IPv6_Address_t xDNSServerAddresses[ ipconfigENDPOINT_DNS_ADDRESS_COUNT ];
uint8_t ucDNSIndex; /**< The index of the next DNS address to be used. */
} IPV6Parameters_t;
#endif
#if ( ipconfigUSE_RA != 0 )
/* Router Advertisement (RA). End-points can obtain their IP-address by asking for a RA. */
typedef enum xRAState
{
eRAStateApply, /* Send a Router Solicitation. */
eRAStateWait, /* Wait for a Router Advertisement. */
eRAStateIPTest, /* Take a random IP address, test if another device is using it already. */
eRAStateIPWait, /* Wait for a reply, if any */
eRAStatePreLease, /* The device is ready to go to the 'eRAStateLease' state. */
eRAStateLease, /* The device is up, repeat the RA-process when timer expires. */
eRAStateFailed
} eRAState_t;
struct xRA_DATA
{
struct
{
uint32_t
bRouterReplied : 1,
bIPAddressInUse : 1;
}
bits;
TickType_t ulPreferredLifeTime;
UBaseType_t uxRetryCount;
/* Maintains the RA state machine state. */
eRAState_t eRAState;
};
typedef struct xRA_DATA RAData_t;
#endif /* ( ipconfigUSE_RA != 0 ) */
/** @brief The description of an end-point. */
typedef struct xNetworkEndPoint
{
#if ( ipconfigUSE_IPv4 != 0 )
IPV4Parameters_t ipv4_settings; /**< Actual IPv4 settings used by the end-point. */
IPV4Parameters_t ipv4_defaults; /**< Use values form "ipv4_defaults" in case DHCP has failed. */
#endif
#if ( ipconfigUSE_IPv6 != 0 )
IPV6Parameters_t ipv6_settings; /**< Actual IPv6 settings used by the end-point. */
IPV6Parameters_t ipv6_defaults; /**< Use values form "ipv6_defaults" in case DHCP has failed. */
#endif
MACAddress_t xMACAddress; /**< The MAC-address assigned to this end-point. */
struct
{
uint32_t
bIsDefault : 1, /**< This bit will be removed. */
#if ( ipconfigUSE_DHCP != 0 ) || ( ipconfigUSE_DHCPv6 != 0 )
bWantDHCP : 1, /**< This end-point wants to use DHCPv4 to obtain an IP-address. */
#endif /* ipconfigUSE_DHCP */
#if ( ipconfigUSE_RA != 0 )
bWantRA : 1, /**< This end-point wants to use RA/SLAAC to obtain an IP-address. */
#endif /* ipconfigUSE_RA */
bIPv6 : 1, /**< This end-point has an IP-address of type IPv6. */
#if ( ipconfigUSE_NETWORK_EVENT_HOOK != 0 )
bCallDownHook : 1, /**< The network down hook-must be called for this end-point. */
#endif /* ipconfigUSE_NETWORK_EVENT_HOOK */
bEndPointUp : 1; /**< The end-point is up. */
} bits; /**< A collection of boolean properties. */
uint8_t usDNSType; /**< A LLMNR/mDNS lookup is being done for an IPv6 address.
* This field is only valid while xApplicationDNSQueryHook() is called. */
#if ( ipconfigUSE_DHCP != 0 ) || ( ipconfigUSE_RA != 0 )
IPTimer_t xDHCP_RATimer; /**< The timer used to call the DHCP/DHCPv6/RA state machine. */
#endif /* ( ipconfigUSE_DHCP != 0 ) || ( ipconfigUSE_RA != 0 ) */
#if ( ipconfigUSE_DHCP != 0 ) || ( ipconfigUSE_DHCPv6 != 0 )
DHCPData_t xDHCPData; /**< A description of the DHCP client state machine. */
#endif /* ( ipconfigUSE_DHCP != 0 ) || ( ipconfigUSE_DHCPv6 != 0 ) */
#if ( ipconfigUSE_IPv6 != 0 )
DHCPMessage_IPv6_t * pxDHCPMessage; /**< A description of the DHCPv6 client state machine. */
#endif
#if ( ipconfigUSE_RA != 0 )
RAData_t xRAData; /**< A description of the Router Advertisement ( RA ) client state machine. */
#endif /* ( ipconfigUSE_RA != 0 ) */
NetworkInterface_t * pxNetworkInterface; /**< The network interface that owns this end-point. */
struct xNetworkEndPoint * pxNext; /**< The next end-point in the chain. */
} NetworkEndPoint_t;
#define END_POINT_USES_DHCP( pxEndPoint ) ( ( pxEndPoint )->bits.bWantDHCP != pdFALSE_UNSIGNED )
#define END_POINT_USES_RA( pxEndPoint ) ( ( ( pxEndPoint )->bits.bIPv6 != pdFALSE_UNSIGNED ) && ( ( pxEndPoint )->bits.bWantRA != pdFALSE_UNSIGNED ) )
#define ENDPOINT_IS_IPv4( pxEndPoint ) ( ( ( pxEndPoint ) != NULL ) && ( ( pxEndPoint )->bits.bIPv6 == 0U ) )
#define ENDPOINT_IS_IPv6( pxEndPoint ) ( ( ( pxEndPoint ) != NULL ) && ( ( pxEndPoint )->bits.bIPv6 != 0U ) )
/*
* Add a new physical Network Interface. The object pointed to by 'pxInterface'
* must continue to exist.
* Only the Network Interface function xx_FillInterfaceDescriptor() shall call this function.
*/
NetworkInterface_t * FreeRTOS_AddNetworkInterface( NetworkInterface_t * pxInterface );
/*
* Get the first Network Interface.
*/
NetworkInterface_t * FreeRTOS_FirstNetworkInterface( void );
/*
* Get the next Network Interface.
*/
NetworkInterface_t * FreeRTOS_NextNetworkInterface( const NetworkInterface_t * pxInterface );
/*
* Get the first end-point belonging to a given interface. When pxInterface is
* NULL, the very first end-point will be returned.
*/
NetworkEndPoint_t * FreeRTOS_FirstEndPoint( const NetworkInterface_t * pxInterface );
/*
* Get the next end-point. When pxInterface is null, all end-points can be
* iterated.
*/
NetworkEndPoint_t * FreeRTOS_NextEndPoint( const NetworkInterface_t * pxInterface,
NetworkEndPoint_t * pxEndPoint );
/*
* Find the end-point with given IP-address.
*/
NetworkEndPoint_t * FreeRTOS_FindEndPointOnIP_IPv4( uint32_t ulIPAddress );
#if ( ipconfigUSE_IPv6 != 0 )
/* Find the end-point with given IP-address. */
NetworkEndPoint_t * FreeRTOS_FindEndPointOnIP_IPv6( const IPv6_Address_t * pxIPAddress );
#endif /* ipconfigUSE_IPv6 */
/*
* Find the end-point with given MAC-address.
* The search can be limited by supplying a particular interface.
*/
NetworkEndPoint_t * FreeRTOS_FindEndPointOnMAC( const MACAddress_t * pxMACAddress,
const NetworkInterface_t * pxInterface );
/*
* Find the best fitting end-point to reach a given IP-address.
* Find an end-point whose IP-address is in the same network as the IP-address provided.
*/
NetworkEndPoint_t * FreeRTOS_FindEndPointOnNetMask( uint32_t ulIPAddress );
/*
* Find the best fitting IPv4 end-point to reach a given IP-address on a given interface
*/
NetworkEndPoint_t * FreeRTOS_InterfaceEndPointOnNetMask( const NetworkInterface_t * pxInterface,
uint32_t ulIPAddress );
/*
* Finds an endpoint on the given interface which is in the same subnet as the
* given IP address. If NULL is passed for pxInterface, it looks through all the
* interfaces to find an endpoint in the same subnet as the given IP address.
*/
NetworkEndPoint_t * FreeRTOS_InterfaceEPInSameSubnet_IPv6( const NetworkInterface_t * pxInterface,
const IPv6_Address_t * pxIPAddress );
#if ( ipconfigUSE_IPv6 != 0 )
NetworkEndPoint_t * FreeRTOS_FindEndPointOnNetMask_IPv6( const IPv6_Address_t * pxIPv6Address );
#endif /* ipconfigUSE_IPv6 */
#if ( ipconfigUSE_IPv6 != 0 )
/* Get the first end-point belonging to a given interface.
* When pxInterface is NULL, the very first end-point will be returned. */
NetworkEndPoint_t * FreeRTOS_FirstEndPoint_IPv6( const NetworkInterface_t * pxInterface );
#endif /* ipconfigUSE_IPv6 */
/* A ethernet packet has come in on a certain network interface.
* Find the best matching end-point. */
NetworkEndPoint_t * FreeRTOS_MatchingEndpoint( const NetworkInterface_t * pxNetworkInterface,
const uint8_t * pucEthernetBuffer );
/* Find an end-point that has a defined gateway.
* xIPType should equal ipTYPE_IPv4 or ipTYPE_IPv6. */
NetworkEndPoint_t * FreeRTOS_FindGateWay( BaseType_t xIPType );
/* Fill-in the end-point structure. */
void FreeRTOS_FillEndPoint( NetworkInterface_t * pxNetworkInterface,
NetworkEndPoint_t * pxEndPoint,
const uint8_t ucIPAddress[ ipIP_ADDRESS_LENGTH_BYTES ],
const uint8_t ucNetMask[ ipIP_ADDRESS_LENGTH_BYTES ],
const uint8_t ucGatewayAddress[ ipIP_ADDRESS_LENGTH_BYTES ],
const uint8_t ucDNSServerAddress[ ipIP_ADDRESS_LENGTH_BYTES ],
const uint8_t ucMACAddress[ ipMAC_ADDRESS_LENGTH_BYTES ] );
#if ( ipconfigUSE_IPv6 != 0 )
/* Fill-in the end-point structure. */
void FreeRTOS_FillEndPoint_IPv6( NetworkInterface_t * pxNetworkInterface,
NetworkEndPoint_t * pxEndPoint,
const IPv6_Address_t * pxIPAddress,
const IPv6_Address_t * pxNetPrefix,
size_t uxPrefixLength,
const IPv6_Address_t * pxGatewayAddress,
const IPv6_Address_t * pxDNSServerAddress, /* Not used yet. */
const uint8_t ucMACAddress[ ipMAC_ADDRESS_LENGTH_BYTES ] );
#endif
NetworkEndPoint_t * pxGetSocketEndpoint( ConstSocket_t xSocket );
void vSetSocketEndpoint( Socket_t xSocket,
NetworkEndPoint_t * pxEndPoint );
#if ( ( ipconfigHAS_PRINTF != 0 ) || ( ipconfigHAS_DEBUG_PRINTF != 0 ) )
const char * pcEndpointName( const NetworkEndPoint_t * pxEndPoint,
char * pcBuffer,
size_t uxSize );
#endif /* ( ( ipconfigHAS_PRINTF != 0 ) || ( ipconfigHAS_DEBUG_PRINTF != 0 ) ) */
typedef enum
{
eIPv6_Global, /* 001 */
eIPv6_LinkLocal, /* 1111 1110 10 */
eIPv6_SiteLocal, /* 1111 1110 11 */
eIPv6_Multicast, /* 1111 1111 */
eIPv6_Loopback, /* 1111 (::1) */
eIPv6_Unknown /* Not implemented. */
}
IPv6_Type_t;
#if ( ipconfigUSE_IPv6 != 0 )
/**
* @brief Check the type of an IPv16 address.
*
* @return A value from enum IPv6_Type_t.
*/
IPv6_Type_t xIPv6_GetIPType( const IPv6_Address_t * pxAddress );
#endif
BaseType_t xCheckRequiresResolution( const NetworkBufferDescriptor_t * pxNetworkBuffer );
typedef enum
{
eResolutionCacheMiss = 0, /* 0 A cache lookup did not find a valid entry. */
eResolutionCacheHit, /* 1 A cache lookup found a valid entry. */
eResolutionFailed /* 2 There is no IP address, or a resolution is still in progress, so the packet cannot be sent. */
} eResolutionLookupResult_t;
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* FREERTOS_ROUTING_H */
@@ -0,0 +1,597 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
#ifndef FREERTOS_SOCKETS_H
#define FREERTOS_SOCKETS_H
/* Standard includes. */
#include <string.h>
/* FreeRTOS includes. */
#include "FreeRTOS.h"
#include "task.h"
/* Application level configuration options. */
#include "FreeRTOSIPConfig.h"
#include "FreeRTOSIPConfigDefaults.h"
#ifndef FREERTOS_IP_CONFIG_H
#error FreeRTOSIPConfig.h has not been included yet
#endif
#include "FreeRTOS_IP_Common.h"
/* Event bit definitions are required by the select functions. */
#include "event_groups.h"
#ifdef __cplusplus
extern "C" {
#endif
#ifndef INC_FREERTOS_H
#error FreeRTOS.h must be included before FreeRTOS_Sockets.h.
#endif
#ifndef INC_TASK_H
#ifndef TASK_H /* For compatibility with older FreeRTOS versions. */
#error The FreeRTOS header file task.h must be included before FreeRTOS_Sockets.h.
#endif
#endif
/* Assigned to an Socket_t variable when the socket is not valid, probably
* because it could not be created. */
#define FREERTOS_INVALID_SOCKET ( ( Socket_t ) ~0U )
/* API function error values. As errno is supported, the FreeRTOS sockets
* functions return error codes rather than just a pass or fail indication.
*
* Like in errno.h, the error codes are defined as positive numbers.
* However, in case of an error, API 's will still negative values, e.g.
* return -pdFREERTOS_ERRNO_EWOULDBLOCK;
* in case an operation would block.
*
* The following defines are obsolete, please use -pdFREERTOS_ERRNO_Exxx. */
#define FREERTOS_SOCKET_ERROR ( -1 )
#define FREERTOS_EWOULDBLOCK ( -pdFREERTOS_ERRNO_EWOULDBLOCK )
#define FREERTOS_EINVAL ( -pdFREERTOS_ERRNO_EINVAL )
#define FREERTOS_EADDRNOTAVAIL ( -pdFREERTOS_ERRNO_EADDRNOTAVAIL )
#define FREERTOS_EADDRINUSE ( -pdFREERTOS_ERRNO_EADDRINUSE )
#define FREERTOS_ENOBUFS ( -pdFREERTOS_ERRNO_ENOBUFS )
#define FREERTOS_ENOPROTOOPT ( -pdFREERTOS_ERRNO_ENOPROTOOPT )
#define FREERTOS_ECLOSED ( -pdFREERTOS_ERRNO_ENOTCONN )
/* Values for the parameters to FreeRTOS_socket(), inline with the Berkeley
* standard. See the documentation of FreeRTOS_socket() for more information. */
#define FREERTOS_AF_INET ( 2 )
#define FREERTOS_AF_INET6 ( 10 )
#define FREERTOS_SOCK_DGRAM ( 2 )
#define FREERTOS_IPPROTO_UDP ( 17 )
#define FREERTOS_SOCK_STREAM ( 1 )
#define FREERTOS_IPPROTO_TCP ( 6 )
#define FREERTOS_SOCK_DEPENDENT_PROTO ( 0 )
#define FREERTOS_AF_INET4 FREERTOS_AF_INET
/* Values for xFlags parameter of Receive/Send functions. */
#define FREERTOS_ZERO_COPY ( 1 ) /* Can be used with recvfrom(), sendto() and recv(),
* Indicates that the zero copy interface is being used.
* See the documentation for FreeRTOS_sockets() for more information. */
#define FREERTOS_MSG_OOB ( 2 ) /* Not used. */
#define FREERTOS_MSG_PEEK ( 4 ) /* Can be used with recvfrom() and recv(). */
#define FREERTOS_MSG_DONTROUTE ( 8 ) /* Not used. */
#define FREERTOS_MSG_DONTWAIT ( 16 ) /* Can be used with recvfrom(), sendto(), recv() and send(). */
/* Values that can be passed in the option name parameter of calls to
* FreeRTOS_setsockopt(). */
#define FREERTOS_SO_RCVTIMEO ( 0 ) /* Used to set the receive time out. */
#define FREERTOS_SO_SNDTIMEO ( 1 ) /* Used to set the send time out. */
#define FREERTOS_SO_UDPCKSUM_OUT ( 2 ) /* Used to turn the use of the UDP checksum
* by a socket on or off. This also doubles
* as part of an 8-bit bitwise socket option. */
#if ( ipconfigSOCKET_HAS_USER_SEMAPHORE == 1 )
#define FREERTOS_SO_SET_SEMAPHORE ( 3 ) /* Used to set a user's semaphore. */
#endif
#if ( ipconfigUSE_TCP == 1 )
#define FREERTOS_SO_SNDBUF ( 4 ) /* Set the size of the send buffer (TCP only). */
#define FREERTOS_SO_RCVBUF ( 5 ) /* Set the size of the receive buffer (TCP only). */
#endif
#if ( ipconfigUSE_CALLBACKS == 1 )
/* Supply pointer to 'F_TCP_UDP_Handler_t' for pvOptionValue parameter in
* FreeRTOS_setsockopt() */
#define FREERTOS_SO_TCP_CONN_HANDLER ( 6 ) /* Install a callback for (dis) connection events. */
#define FREERTOS_SO_TCP_RECV_HANDLER ( 7 ) /* Install a callback for receiving TCP data. */
#define FREERTOS_SO_TCP_SENT_HANDLER ( 8 ) /* Install a callback for sending TCP data. */
#define FREERTOS_SO_UDP_RECV_HANDLER ( 9 ) /* Install a callback for receiving UDP data. */
#define FREERTOS_SO_UDP_SENT_HANDLER ( 10 ) /* Install a callback for sending UDP data. */
#endif
#if ( ipconfigUSE_TCP == 1 )
#define FREERTOS_SO_REUSE_LISTEN_SOCKET ( 11 ) /* When a listening socket gets connected, do not create a new one but re-use it. */
#define FREERTOS_SO_CLOSE_AFTER_SEND ( 12 ) /* As soon as the last byte has been transmitted, finalise the connection. */
#define FREERTOS_SO_WIN_PROPERTIES ( 13 ) /* Set all buffer and window properties in one call, parameter is pointer to WinProperties_t. */
#define FREERTOS_SO_SET_FULL_SIZE ( 14 ) /* Refuse to send packets smaller than MSS. */
#define FREERTOS_SO_STOP_RX ( 15 ) /* Temporarily hold up reception, used by streaming client. */
#endif
#if ( ipconfigUDP_MAX_RX_PACKETS > 0 )
#define FREERTOS_SO_UDP_MAX_RX_PACKETS ( 16 ) /* This option helps to limit the maximum number of packets a UDP socket will buffer. */
#endif
#if ( ipconfigSOCKET_HAS_USER_WAKE_CALLBACK == 1 )
#define FREERTOS_SO_WAKEUP_CALLBACK ( 17 )
#endif
#if ( ipconfigUSE_TCP == 1 )
#define FREERTOS_SO_SET_LOW_HIGH_WATER ( 18 )
#endif
#define FREERTOS_INADDR_ANY ( 0U ) /* The 0.0.0.0 IPv4 address. */
#define FREERTOS_INADDR_BROADCAST ( 0xffffffffUL ) /* 255.255.255.255 is a special broadcast address that represents all host attached to the physical network. */
#if ( 0 ) /* Not Used */
#define FREERTOS_NOT_LAST_IN_FRAGMENTED_PACKET ( 0x80 )
#define FREERTOS_FRAGMENTED_PACKET ( 0x40 )
#endif
#if ( ipconfigUSE_TCP == 1 )
/* Values for 'xHow' flag of FreeRTOS_shutdown(), currently ignored. */
#define FREERTOS_SHUT_RD ( 0 )
#define FREERTOS_SHUT_WR ( 1 )
#define FREERTOS_SHUT_RDWR ( 2 )
#endif
/* For compatibility with the expected Berkeley sockets naming. */
#define socklen_t uint32_t
/**
* For this limited implementation, only two members are required in the
* Berkeley style sockaddr structure.
*/
struct freertos_sockaddr
{
uint8_t sin_len; /**< length of this structure. */
uint8_t sin_family; /**< FREERTOS_AF_INET. */
uint16_t sin_port; /**< The port. */
uint32_t sin_flowinfo; /**< IPv6 flow information, not used in this library. */
IP_Address_t sin_address; /**< The IPv4/IPv6 address. */
};
#if ( ipconfigIPv4_BACKWARD_COMPATIBLE == 1 )
#define sin_addr sin_address.ulIP_IPv4
#endif
/** Introduce a short name to make casting easier. */
typedef struct freertos_sockaddr xFreertosSocAddr;
/* The socket type itself. */
struct xSOCKET;
typedef struct xSOCKET * Socket_t;
typedef struct xSOCKET const * ConstSocket_t;
extern BaseType_t xSocketValid( const ConstSocket_t xSocket );
/**
* FULL, UP-TO-DATE AND MAINTAINED REFERENCE DOCUMENTATION FOR ALL THESE
* FUNCTIONS IS AVAILABLE ON THE FOLLOWING URL:
* https://freertos.org/Documentation/03-Libraries/02-FreeRTOS-plus/02-FreeRTOS-plus-TCP/09-API-reference/01-FreeRTOS-plus-TCP-APIs
*/
/* Common Socket Attributes. */
/* Create a TCP or UDP socket. */
Socket_t FreeRTOS_socket( BaseType_t xDomain,
BaseType_t xType,
BaseType_t xProtocol );
/* Binds a socket to a local port number. */
BaseType_t FreeRTOS_bind( Socket_t xSocket,
struct freertos_sockaddr const * pxAddress,
socklen_t xAddressLength );
/* Sets a socket option. */
BaseType_t FreeRTOS_setsockopt( Socket_t xSocket,
int32_t lLevel,
int32_t lOptionName,
const void * pvOptionValue,
size_t uxOptionLength );
/* Close a socket. */
BaseType_t FreeRTOS_closesocket( Socket_t xSocket );
#if ( ipconfigSUPPORT_SIGNALS != 0 )
/* Send a signal to the task which is waiting for a given socket. */
BaseType_t FreeRTOS_SignalSocket( Socket_t xSocket );
/* Send a signal to the task which reads from this socket (FromISR version). */
BaseType_t FreeRTOS_SignalSocketFromISR( Socket_t xSocket,
BaseType_t * pxHigherPriorityTaskWoken );
#endif
/* This option adds the possibility to have a user-ID attached to a socket.
* The type of this ID is a void *. Both UDP and TCP sockets have
* this ID. It has a default value of NULL.
*/
BaseType_t xSocketSetSocketID( const Socket_t xSocket,
void * pvSocketID );
void * pvSocketGetSocketID( const ConstSocket_t xSocket );
/* Get the type of IP: either 'ipTYPE_IPv4' or 'ipTYPE_IPv6'. */
BaseType_t FreeRTOS_GetIPType( ConstSocket_t xSocket );
/* End Common Socket Attributes */
/* UDP Socket Attributes. */
/* Send data to a UDP socket. */
int32_t FreeRTOS_sendto( Socket_t xSocket,
const void * pvBuffer,
size_t uxTotalDataLength,
BaseType_t xFlags,
const struct freertos_sockaddr * pxDestinationAddress,
socklen_t xDestinationAddressLength );
/* Receive data from a UDP socket */
int32_t FreeRTOS_recvfrom( const ConstSocket_t xSocket,
void * pvBuffer,
size_t uxBufferLength,
BaseType_t xFlags,
struct freertos_sockaddr * pxSourceAddress,
socklen_t * pxSourceAddressLength );
/* Function to get the local address and IP port. */
size_t FreeRTOS_GetLocalAddress( ConstSocket_t xSocket,
struct freertos_sockaddr * pxAddress );
#if ( ipconfigETHERNET_DRIVER_FILTERS_PACKETS == 1 )
/* Returns true if an UDP socket exists bound to mentioned port number. */
BaseType_t xPortHasUDPSocket( uint16_t usPortNr );
#endif
/* End UDP Socket Attributes */
#if ( ipconfigUSE_TCP == 1 )
/* TCP Socket Attributes. */
/**
* Structure to hold the properties of Tx/Rx buffers and windows.
*/
typedef struct xWIN_PROPS
{
/* Properties of the Tx buffer and Tx window. */
int32_t lTxBufSize; /**< Unit: bytes. */
int32_t lTxWinSize; /**< Unit: MSS. */
/* Properties of the Rx buffer and Rx window. */
int32_t lRxBufSize; /**< Unit: bytes. */
int32_t lRxWinSize; /**< Unit: MSS. */
} WinProperties_t;
/**
* Structure to pass for the 'FREERTOS_SO_SET_LOW_HIGH_WATER' option.
*/
typedef struct xLOW_HIGH_WATER
{
size_t uxLittleSpace; /**< Send a STOP when buffer space drops below X bytes */
size_t uxEnoughSpace; /**< Send a GO when buffer space grows above X bytes */
} LowHighWater_t;
/* Connect a TCP socket to a remote socket. */
BaseType_t FreeRTOS_connect( Socket_t xClientSocket,
const struct freertos_sockaddr * pxAddress,
socklen_t xAddressLength );
/* Places a TCP socket into a state where it is listening for and can accept
* incoming connection requests from remote sockets. */
BaseType_t FreeRTOS_listen( Socket_t xSocket,
BaseType_t xBacklog );
/* Accept a connection on a TCP socket. */
Socket_t FreeRTOS_accept( Socket_t xServerSocket,
struct freertos_sockaddr * pxAddress,
socklen_t * pxAddressLength );
/* Send data to a TCP socket. */
BaseType_t FreeRTOS_send( Socket_t xSocket,
const void * pvBuffer,
size_t uxDataLength,
BaseType_t xFlags );
/* Receive data from a TCP socket */
BaseType_t FreeRTOS_recv( Socket_t xSocket,
void * pvBuffer,
size_t uxBufferLength,
BaseType_t xFlags );
/* Disable reads and writes on a connected TCP socket. */
BaseType_t FreeRTOS_shutdown( Socket_t xSocket,
BaseType_t xHow );
/* Release a TCP payload buffer that was obtained by
* calling FreeRTOS_recv() with the FREERTOS_ZERO_COPY flag,
* and a pointer to a void pointer. */
BaseType_t FreeRTOS_ReleaseTCPPayloadBuffer( Socket_t xSocket,
void const * pvBuffer,
BaseType_t xByteCount );
/* Returns the number of bytes available in the Rx buffer. */
BaseType_t FreeRTOS_rx_size( ConstSocket_t xSocket );
#define FreeRTOS_recvcount( xSocket ) FreeRTOS_rx_size( xSocket )
/* Returns the free space in the Tx buffer. */
BaseType_t FreeRTOS_tx_space( ConstSocket_t xSocket );
#define FreeRTOS_outstanding( xSocket ) FreeRTOS_tx_size( xSocket )
/* Returns the number of bytes stored in the Tx buffer. */
BaseType_t FreeRTOS_tx_size( ConstSocket_t xSocket );
/* Returns pdTRUE if TCP socket is connected. */
BaseType_t FreeRTOS_issocketconnected( ConstSocket_t xSocket );
/* Return the remote address and IP port of a connected TCP Socket. */
BaseType_t FreeRTOS_GetRemoteAddress( ConstSocket_t xSocket,
struct freertos_sockaddr * pxAddress );
/* Returns the number of bytes that may be added to txStream. */
BaseType_t FreeRTOS_maywrite( ConstSocket_t xSocket );
/* Returns the actual size of MSS being used. */
BaseType_t FreeRTOS_mss( ConstSocket_t xSocket );
/* For internal use only: return the connection status. */
BaseType_t FreeRTOS_connstatus( ConstSocket_t xSocket );
/* For advanced applications only:
* Get a direct pointer to the beginning of the circular transmit buffer.
* In case the buffer was not yet created, it will be created in
* this call.
*/
uint8_t * FreeRTOS_get_tx_base( Socket_t xSocket );
/* For advanced applications only:
* Get a direct pointer to the circular transmit buffer.
* '*pxLength' will contain the number of bytes that may be written. */
uint8_t * FreeRTOS_get_tx_head( Socket_t xSocket,
BaseType_t * pxLength );
/* For the web server: borrow the circular Rx buffer for inspection
* HTML driver wants to see if a sequence of 13/10/13/10 is available. */
const struct xSTREAM_BUFFER * FreeRTOS_get_rx_buf( ConstSocket_t xSocket );
void FreeRTOS_netstat( void );
/* End TCP Socket Attributes. */
#endif /* ( ipconfigUSE_TCP == 1 ) */
#if ( ipconfigUSE_CALLBACKS == 1 )
/*
* Callback handlers for a socket
* User-provided functions will be called for each sockopt callback defined
* For example:
* static void xOnTCPConnect( Socket_t xSocket, BaseType_t ulConnected ) {}
* static BaseType_t xOnTCPReceive( Socket_t xSocket, void * pData, size_t uxLength )
* {
* // handle the message
* return pdFALSE; // Not Used
* }
* static void xOnTCPSent( Socket_t xSocket, size_t xLength ) {}
* static BaseType_t xOnUDPReceive( Socket_t xSocket, void * pData, size_t xLength, const struct freertos_sockaddr * pxFrom, const struct freertos_sockaddr * pxDest )
* {
* // handle the message
* return pdTRUE; // message processing is finished, don't store
* }
* static void xOnUDPSent( Socket_t xSocket, size_t xLength ) {}
* F_TCP_UDP_Handler_t xHand = { xOnTCPConnect, xOnTCPReceive, xOnTCPSent, xOnUDPReceive, xOnUDPSent };
* FreeRTOS_setsockopt( sock, 0, FREERTOS_SO_TCP_CONN_HANDLER, ( void * ) &xHand, 0 );
*/
/* Connected callback handler for a TCP Socket. */
typedef void (* FOnConnected_t )( Socket_t xSocket,
BaseType_t ulConnected );
/* Received callback handler for a TCP Socket.
* Return value is not currently used. */
typedef BaseType_t (* FOnTCPReceive_t )( Socket_t xSocket,
void * pData,
size_t xLength );
/* Sent callback handler for a TCP Socket. */
typedef void (* FOnTCPSent_t )( Socket_t xSocket,
size_t xLength );
/* Received callback handler for a UDP Socket.
* If a positive number is returned, the messages will not be stored in
* xWaitingPacketsList for later processing by recvfrom(). */
typedef BaseType_t (* FOnUDPReceive_t ) ( Socket_t xSocket,
void * pData,
size_t xLength,
const struct freertos_sockaddr * pxFrom,
const struct freertos_sockaddr * pxDest );
/* Sent callback handler for a UDP Socket */
typedef void (* FOnUDPSent_t )( Socket_t xSocket,
size_t xLength );
/* The following values are used in the lOptionName parameter of setsockopt()
* to set the callback handlers options. */
typedef struct xTCP_UDP_HANDLER
{
FOnConnected_t pxOnTCPConnected; /* FREERTOS_SO_TCP_CONN_HANDLER */
FOnTCPReceive_t pxOnTCPReceive; /* FREERTOS_SO_TCP_RECV_HANDLER */
FOnTCPSent_t pxOnTCPSent; /* FREERTOS_SO_TCP_SENT_HANDLER */
FOnUDPReceive_t pxOnUDPReceive; /* FREERTOS_SO_UDP_RECV_HANDLER */
FOnUDPSent_t pxOnUDPSent; /* FREERTOS_SO_UDP_SENT_HANDLER */
} F_TCP_UDP_Handler_t;
#endif /* ( ipconfigUSE_CALLBACKS == 1 ) */
/* Conversion Functions */
/* Converts an IP address expressed as a 32-bit number in network byte order
* to a string in decimal dot notation. */
extern const char * FreeRTOS_inet_ntoa( uint32_t ulIPAddress,
char * pcBuffer );
#if ( ipconfigBYTE_ORDER == pdFREERTOS_LITTLE_ENDIAN )
/* Converts an IP address expressed as four separate numeric octets into an
* IP address expressed as a 32-bit number in network byte order */
#define FreeRTOS_inet_addr_quick( ucOctet0, ucOctet1, ucOctet2, ucOctet3 ) \
( ( ( ( uint32_t ) ( ucOctet3 ) ) << 24 ) | \
( ( ( uint32_t ) ( ucOctet2 ) ) << 16 ) | \
( ( ( uint32_t ) ( ucOctet1 ) ) << 8 ) | \
( ( uint32_t ) ( ucOctet0 ) ) )
#else /* ( ipconfigBYTE_ORDER == pdFREERTOS_BIG_ENDIAN ) */
#define FreeRTOS_inet_addr_quick( ucOctet0, ucOctet1, ucOctet2, ucOctet3 ) \
( ( ( ( uint32_t ) ( ucOctet0 ) ) << 24 ) | \
( ( ( uint32_t ) ( ucOctet1 ) ) << 16 ) | \
( ( ( uint32_t ) ( ucOctet2 ) ) << 8 ) | \
( ( uint32_t ) ( ucOctet3 ) ) )
#endif /* ( ipconfigBYTE_ORDER == pdFREERTOS_LITTLE_ENDIAN ) */
/* Convert a null-terminated string in dot-decimal-notation (d.d.d.d)
* to a 32-bit unsigned integer. */
uint32_t FreeRTOS_inet_addr( const char * pcIPAddress );
BaseType_t FreeRTOS_inet_pton( BaseType_t xAddressFamily,
const char * pcSource,
void * pvDestination );
const char * FreeRTOS_inet_ntop( BaseType_t xAddressFamily,
const void * pvSource,
char * pcDestination,
socklen_t uxSize );
/** @brief This function converts a human readable string, representing an 48-bit MAC address,
* into a 6-byte address. Valid inputs are e.g. "62:48:5:83:A0:b2" and "0-12-34-fe-dc-ba". */
BaseType_t FreeRTOS_EUI48_pton( const char * pcSource,
uint8_t * pucTarget );
/** @brief This function converts a 48-bit MAC address to a human readable string. */
void FreeRTOS_EUI48_ntop( const uint8_t * pucSource,
char * pcTarget,
char cTen,
char cSeparator );
/* End Conversion Functions */
#if ( ipconfigSUPPORT_SELECT_FUNCTION == 1 )
/* The SocketSet_t type is the equivalent to the fd_set type used by the
* Berkeley API. */
struct xSOCKET_SET;
typedef struct xSOCKET_SET * SocketSet_t;
typedef struct xSOCKET_SET const * ConstSocketSet_t;
/* Create a socket set for use with the FreeRTOS_select() function */
SocketSet_t FreeRTOS_CreateSocketSet( void );
void FreeRTOS_DeleteSocketSet( SocketSet_t xSocketSet );
/* Block on a "socket set" until an event of interest occurs on a
* socket within the set. */
BaseType_t FreeRTOS_select( SocketSet_t xSocketSet,
TickType_t xBlockTimeTicks );
/* For FD_SET and FD_CLR, a combination of the following bits can be used: */
typedef enum eSELECT_EVENT
{
eSELECT_READ = 0x0001,
eSELECT_WRITE = 0x0002,
eSELECT_EXCEPT = 0x0004,
eSELECT_INTR = 0x0008,
eSELECT_ALL = 0x000F,
/* Reserved for internal use: */
eSELECT_CALL_IP = 0x0010
/* end */
} eSelectEvent_t;
/* Add a socket to a socket set, and set the event bits of interest
* for the added socket. */
void FreeRTOS_FD_SET( Socket_t xSocket,
SocketSet_t xSocketSet,
EventBits_t xBitsToSet );
/* Clear a set event bit of interest for a socket of the socket set.
* If all the event bits are clear then the socket will be removed
* from the socket set. */
void FreeRTOS_FD_CLR( Socket_t xSocket,
SocketSet_t xSocketSet,
EventBits_t xBitsToClear );
/* Check if a socket in a socket set has an event bit set. */
EventBits_t FreeRTOS_FD_ISSET( const ConstSocket_t xSocket,
const ConstSocketSet_t xSocketSet );
#endif /* ( ipconfigSUPPORT_SELECT_FUNCTION == 1 ) */
#if ipconfigUSE_IPv4
/* Translate from dot-decimal notation (example 192.168.1.1) to a 32-bit number. */
BaseType_t FreeRTOS_inet_pton4( const char * pcSource,
void * pvDestination );
/* Translate 32-bit IPv4 address representation dot-decimal notation. */
const char * FreeRTOS_inet_ntop4( const void * pvSource,
char * pcDestination,
socklen_t uxSize );
#endif
#if ipconfigUSE_IPv6
/* Translate hexadecimal IPv6 address to 16 bytes binary format */
BaseType_t FreeRTOS_inet_pton6( const char * pcSource,
void * pvDestination );
/*
* Convert a string like 'fe80::8d11:cd9b:8b66:4a80'
* to a 16-byte IPv6 address
*/
const char * FreeRTOS_inet_ntop6( const void * pvSource,
char * pcDestination,
socklen_t uxSize );
#endif
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* FREERTOS_SOCKETS_H */
@@ -0,0 +1,101 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
/*
* FreeRTOS_Stream_Buffer.h
*
* An implementation of a circular character buffer without a length field
* If LENGTH defines the size of the buffer, a maximum of (LENGTH-1) bytes can be stored
* In order to add or read data from the buffer, memcpy() will be called at most 2 times
*/
#ifndef FREERTOS_STREAM_BUFFER_H
#define FREERTOS_STREAM_BUFFER_H
/* *INDENT-OFF* */
#ifdef __cplusplus
extern "C" {
#endif
/* *INDENT-ON* */
/* Struct to store all the details of a stream buffer. */
typedef struct xSTREAM_BUFFER
{
volatile size_t uxTail; /**< next item to read */
volatile size_t uxMid; /**< iterator within the valid items */
volatile size_t uxHead; /**< next position store a new item */
volatile size_t uxFront; /**< iterator within the free space */
size_t LENGTH; /**< const value: number of reserved elements */
uint8_t ucArray[ sizeof( size_t ) ]; /**< array big enough to store any pointer address */
} StreamBuffer_t;
size_t uxStreamBufferSpace( const StreamBuffer_t * const pxBuffer,
size_t uxLower,
size_t uxUpper );
size_t uxStreamBufferDistance( const StreamBuffer_t * const pxBuffer,
size_t uxLower,
size_t uxUpper );
size_t uxStreamBufferGetSpace( const StreamBuffer_t * const pxBuffer );
size_t uxStreamBufferFrontSpace( const StreamBuffer_t * const pxBuffer );
size_t uxStreamBufferGetSize( const StreamBuffer_t * const pxBuffer );
size_t uxStreamBufferMidSpace( const StreamBuffer_t * const pxBuffer );
void vStreamBufferClear( StreamBuffer_t * const pxBuffer );
void vStreamBufferMoveMid( StreamBuffer_t * const pxBuffer,
const size_t uxCount );
BaseType_t xStreamBufferLessThenEqual( const StreamBuffer_t * const pxBuffer,
size_t uxLeft,
size_t uxRight );
size_t uxStreamBufferGetPtr( StreamBuffer_t * const pxBuffer,
uint8_t ** const ppucData );
size_t uxStreamBufferAdd( StreamBuffer_t * const pxBuffer,
size_t uxOffset,
const uint8_t * const pucData,
size_t uxByteCount );
size_t uxStreamBufferGet( StreamBuffer_t * const pxBuffer,
size_t uxOffset,
uint8_t * const pucData,
size_t uxMaxCount,
BaseType_t xPeek );
/* *INDENT-OFF* */
#ifdef __cplusplus
} /* extern "C" */
#endif
/* *INDENT-ON* */
#endif /* FREERTOS_STREAM_BUFFER_H */
@@ -0,0 +1,200 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
#ifndef FREERTOS_TCP_IP_H
#define FREERTOS_TCP_IP_H
/* *INDENT-OFF* */
#ifdef __cplusplus
extern "C" {
#endif
/* *INDENT-ON* */
/**
* @brief Process the received TCP packet.
*
*/
BaseType_t xProcessReceivedTCPPacket( NetworkBufferDescriptor_t * pxDescriptor );
/**
* @brief Process the received TCP packet.
*/
BaseType_t xProcessReceivedTCPPacket_IPV4( NetworkBufferDescriptor_t * pxDescriptor );
/**
* @brief Process the received TCP packet.
*/
BaseType_t xProcessReceivedTCPPacket_IPV6( NetworkBufferDescriptor_t * pxDescriptor );
typedef enum eTCP_STATE
{
/* Comments about the TCP states are borrowed from the very useful
* Wiki page:
* http://en.wikipedia.org/wiki/Transmission_Control_Protocol */
eCLOSED = 0U, /* 0 (server + client) no connection state at all. */
eTCP_LISTEN, /* 1 (server) waiting for a connection request
* from any remote TCP and port. */
eCONNECT_SYN, /* 2 (client) internal state: socket wants to send
* a connect */
eSYN_FIRST, /* 3 (server) Just created, must ACK the SYN request. */
eSYN_RECEIVED, /* 4 (server) waiting for a confirming connection request
* acknowledgement after having both received and sent a connection request. */
eESTABLISHED, /* 5 (server + client) an open connection, data received can be
* delivered to the user. The normal state for the data transfer phase of the connection. */
eFIN_WAIT_1, /* 6 (server + client) waiting for a connection termination request from the remote TCP,
* or an acknowledgement of the connection termination request previously sent. */
eFIN_WAIT_2, /* 7 (server + client) waiting for a connection termination request from the remote TCP. */
eCLOSE_WAIT, /* 8 (server + client) waiting for a connection termination request from the local user. */
eCLOSING, /* 9 (server + client) waiting for a connection termination request acknowledgement from the remote TCP. */
eLAST_ACK, /*10 (server + client) waiting for an acknowledgement of the connection termination request
* previously sent to the remote TCP
* (which includes an acknowledgement of its connection termination request). */
eTIME_WAIT /*11 (either server or client) waiting for enough time to pass to be sure the remote TCP received the
* acknowledgement of its connection termination request. [According to RFC 793 a connection can
* stay in TIME-WAIT for a maximum of four minutes known as a MSL (maximum segment lifetime).] */
} eIPTCPState_t;
/*
* The meaning of the TCP flags:
*/
#define tcpTCP_FLAG_FIN ( ( uint8_t ) 0x01U ) /**< No more data from sender. */
#define tcpTCP_FLAG_SYN ( ( uint8_t ) 0x02U ) /**< Synchronize sequence numbers. */
#define tcpTCP_FLAG_RST ( ( uint8_t ) 0x04U ) /**< Reset the connection. */
#define tcpTCP_FLAG_PSH ( ( uint8_t ) 0x08U ) /**< Push function: please push buffered data to the recv application. */
#define tcpTCP_FLAG_ACK ( ( uint8_t ) 0x10U ) /**< Acknowledgment field is significant. */
#define tcpTCP_FLAG_URG ( ( uint8_t ) 0x20U ) /**< Urgent pointer field is significant. */
#define tcpTCP_FLAG_ECN ( ( uint8_t ) 0x40U ) /**< ECN-Echo. */
#define tcpTCP_FLAG_CWR ( ( uint8_t ) 0x80U ) /**< Congestion Window Reduced. */
#define tcpTCP_FLAG_CTRL ( ( uint8_t ) 0x1FU ) /**< A mask to filter all protocol flags. */
/*
* A few values of the TCP options:
*/
#define tcpTCP_OPT_END 0U /**< End of TCP options list. */
#define tcpTCP_OPT_NOOP 1U /**< "No-operation" TCP option. */
#define tcpTCP_OPT_MSS 2U /**< Maximum segment size TCP option. */
#define tcpTCP_OPT_WSOPT 3U /**< TCP Window Scale Option (3-byte long). */
#define tcpTCP_OPT_SACK_P 4U /**< Advertise that SACK is permitted. */
#define tcpTCP_OPT_SACK_A 5U /**< SACK option with first/last. */
#define tcpTCP_OPT_TIMESTAMP 8U /**< Time-stamp option. */
#define tcpTCP_OPT_MSS_LEN 4U /**< Length of TCP MSS option. */
#define tcpTCP_OPT_WSOPT_LEN 3U /**< Length of TCP WSOPT option. */
#define tcpTCP_OPT_WSOPT_MAXIMUM_VALUE ( 14U ) /**< Maximum value of TCP WSOPT option. */
#define tcpTCP_OPT_TIMESTAMP_LEN 10 /**< fixed length of the time-stamp option. */
/** @brief
* Minimum segment length as outlined by RFC 791 section 3.1.
* Minimum segment length ( 536 ) = Minimum MTU ( 576 ) - IP Header ( 20 ) - TCP Header ( 20 ).
*/
#define tcpMINIMUM_SEGMENT_LENGTH 536U
/** @brief
* The macro tcpNOW_CONNECTED() is use to determine if the connection makes a
* transition from connected to non-connected and vice versa.
* tcpNOW_CONNECTED() returns true when the status has one of these values:
* eESTABLISHED, eFIN_WAIT_1, eFIN_WAIT_2, eCLOSING, eLAST_ACK, eTIME_WAIT
* Technically the connection status is closed earlier, but the library wants
* to prevent that the socket will be deleted before the last ACK has been
* and thus causing a 'RST' packet on either side.
*/
#define tcpNOW_CONNECTED( status ) \
( ( ( ( status ) >= ( BaseType_t ) eESTABLISHED ) && ( ( status ) != ( BaseType_t ) eCLOSE_WAIT ) ) ? 1 : 0 )
/** @brief
* The highest 4 bits in the TCP offset byte indicate the total length of the
* TCP header, divided by 4.
*/
#define tcpVALID_BITS_IN_TCP_OFFSET_BYTE ( 0xF0U )
/*
* Acknowledgements to TCP data packets may be delayed as long as more is being expected.
* A normal delay would be 200ms. Here a much shorter delay of 20 ms is being used to
* gain performance.
*/
#define tcpDELAYED_ACK_SHORT_DELAY_MS ( 2 ) /**< Should not become smaller than 1. */
#define tcpDELAYED_ACK_LONGER_DELAY_MS ( 20 ) /**< Longer delay for ACK. */
/** @brief
* The MSS (Maximum Segment Size) will be taken as large as possible. However, packets with
* an MSS of 1460 bytes won't be transported through the internet. The MSS will be reduced
* to 1400 bytes.
*/
#define tcpREDUCED_MSS_THROUGH_INTERNET ( 1400 )
/** @brief
* When there are no TCP options, the TCP offset equals 20 bytes, which is stored as
* the number 5 (words) in the higher nibble of the TCP-offset byte.
*/
#define tcpTCP_OFFSET_LENGTH_BITS ( 0xf0U )
#define tcpTCP_OFFSET_STANDARD_LENGTH ( 0x50U ) /**< Standard TCP packet offset. */
/** @brief
* Each TCP socket is checked regularly to see if it can send data packets.
* By default, the maximum number of packets sent during one check is limited to 8.
* This amount may be further limited by setting the socket's TX window size.
*/
#if ( !defined( SEND_REPEATED_COUNT ) )
#define SEND_REPEATED_COUNT ( 8 )
#endif /* !defined( SEND_REPEATED_COUNT ) */
/** @brief
* Define a maximum period of time (ms) to leave a TCP-socket unattended.
* When a TCP timer expires, retries and keep-alive messages will be checked.
*/
#ifndef tcpMAXIMUM_TCP_WAKEUP_TIME_MS
#define tcpMAXIMUM_TCP_WAKEUP_TIME_MS 20000U
#endif
struct xSOCKET;
/*
* For anti-hang protection and TCP keep-alive messages. Called in two places:
* after receiving a packet and after a state change. The socket's alive timer
* may be reset.
*/
void prvTCPTouchSocket( struct xSOCKET * pxSocket );
/*
* Calculate when this socket needs to be checked to do (re-)transmissions.
*/
TickType_t prvTCPNextTimeout( struct xSOCKET * pxSocket );
/* *INDENT-OFF* */
#ifdef __cplusplus
} /* extern "C" */
#endif
/* *INDENT-ON* */
#endif /* FREERTOS_TCP_IP_H */
@@ -0,0 +1,66 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
#ifndef FREERTOS_TCP_RECEPTION_H
#define FREERTOS_TCP_RECEPTION_H
/* *INDENT-OFF* */
#ifdef __cplusplus
extern "C" {
#endif
/* *INDENT-ON* */
/*
* Called from xProcessReceivedTCPPacket. Parse the TCP option(s) received,
* if present. This function returns pdFALSE if the options are not well formed.
*/
BaseType_t prvCheckOptions( FreeRTOS_Socket_t * pxSocket,
const NetworkBufferDescriptor_t * pxNetworkBuffer );
/*
* Called from prvTCPHandleState(). Find the TCP payload data and check and
* return its length.
*/
BaseType_t prvCheckRxData( const NetworkBufferDescriptor_t * pxNetworkBuffer,
uint8_t ** ppucRecvData );
/*
* Called from prvTCPHandleState(). Check if the payload data may be accepted.
* If so, it will be added to the socket's reception queue.
*/
BaseType_t prvStoreRxData( FreeRTOS_Socket_t * pxSocket,
const uint8_t * pucRecvData,
NetworkBufferDescriptor_t * pxNetworkBuffer,
uint32_t ulReceiveLength );
/* *INDENT-OFF* */
#ifdef __cplusplus
} /* extern "C" */
#endif
/* *INDENT-ON* */
#endif /* FREERTOS_TCP_RECEPTION_H */
@@ -0,0 +1,117 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
#ifndef FREERTOS_TCP_STATE_HANDLING_H
#define FREERTOS_TCP_STATE_HANDLING_H
#include "FreeRTOS_TCP_IP.h"
/* *INDENT-OFF* */
#ifdef __cplusplus
extern "C" {
#endif
/* *INDENT-ON* */
/*
* Returns true if the socket must be checked. Non-active sockets are waiting
* for user action, either connect() or close().
*/
BaseType_t prvTCPSocketIsActive( eIPTCPState_t eStatus );
/*
* prvTCPStatusAgeCheck() will see if the socket has been in a non-connected
* state for too long. If so, the socket will be closed, and -1 will be
* returned.
*/
#if ( ipconfigTCP_HANG_PROTECTION == 1 )
BaseType_t prvTCPStatusAgeCheck( FreeRTOS_Socket_t * pxSocket );
#endif
/*
* The heart of all: check incoming packet for valid data and acks and do what
* is necessary in each state.
*/
BaseType_t prvTCPHandleState( FreeRTOS_Socket_t * pxSocket,
NetworkBufferDescriptor_t ** ppxNetworkBuffer );
/*
* Return either a newly created socket, or the current socket in a connected
* state (depends on the 'bReuseSocket' flag).
*/
FreeRTOS_Socket_t * prvHandleListen( FreeRTOS_Socket_t * pxSocket,
NetworkBufferDescriptor_t * pxNetworkBuffer );
/*
* Return either a newly created socket, or the current socket in a connected
* state (depends on the 'bReuseSocket' flag).
*/
FreeRTOS_Socket_t * prvHandleListen_IPV4( FreeRTOS_Socket_t * pxSocket,
NetworkBufferDescriptor_t * pxNetworkBuffer );
/*
* Return either a newly created socket, or the current socket in a connected
* state (depends on the 'bReuseSocket' flag).
*/
FreeRTOS_Socket_t * prvHandleListen_IPV6( FreeRTOS_Socket_t * pxSocket,
NetworkBufferDescriptor_t * pxNetworkBuffer );
/*
* Common code for sending a TCP protocol control packet (i.e. no options, no
* payload, just flags).
*/
BaseType_t prvTCPSendSpecialPacketHelper( NetworkBufferDescriptor_t * pxNetworkBuffer,
uint8_t ucTCPFlags );
/*
* Common code for sending a TCP protocol control packet (i.e. no options, no
* payload, just flags).
*/
BaseType_t prvTCPSendSpecialPktHelper_IPV4( NetworkBufferDescriptor_t * pxNetworkBuffer,
uint8_t ucTCPFlags );
/*
* Common code for sending a TCP protocol control packet (i.e. no options, no
* payload, just flags).
*/
BaseType_t prvTCPSendSpecialPktHelper_IPV6( NetworkBufferDescriptor_t * pxNetworkBuffer,
uint8_t ucTCPFlags );
/*
* After a listening socket receives a new connection, it may duplicate itself.
* The copying takes place in prvTCPSocketCopy.
*/
BaseType_t prvTCPSocketCopy( FreeRTOS_Socket_t * pxNewSocket,
FreeRTOS_Socket_t * pxSocket );
/* *INDENT-OFF* */
#ifdef __cplusplus
} /* extern "C" */
#endif
/* *INDENT-ON* */
#endif /* FREERTOS_TCP_STATE_HANDLING_H */
@@ -0,0 +1,175 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
#ifndef FREERTOS_TCP_TRANSMISSION_H
#define FREERTOS_TCP_TRANSMISSION_H
/* *INDENT-OFF* */
#ifdef __cplusplus
extern "C" {
#endif
/* *INDENT-ON* */
/*
* Either sends a SYN or calls prvTCPSendRepeated (for regular messages).
*/
int32_t prvTCPSendPacket( FreeRTOS_Socket_t * pxSocket );
/*
* Try to send a series of messages.
*/
int32_t prvTCPSendRepeated( FreeRTOS_Socket_t * pxSocket,
NetworkBufferDescriptor_t ** ppxNetworkBuffer );
/*
* Return or send a packet to the other party.
*/
void prvTCPReturnPacket( FreeRTOS_Socket_t * pxSocket,
NetworkBufferDescriptor_t * pxDescriptor,
uint32_t ulLen,
BaseType_t xReleaseAfterSend );
/**
* Called by prvTCPReturnPacket(), this function will set the the window
* size on this side: 'xTCPHeader.usWindow'.
*/
void prvTCPReturn_CheckTCPWindow( FreeRTOS_Socket_t * pxSocket,
const NetworkBufferDescriptor_t * pxNetworkBuffer,
size_t uxIPHeaderSize );
/*
* Called by prvTCPReturnPacket(), this function sets the sequence and ack numbers
* in the TCP-header.
*/
void prvTCPReturn_SetSequenceNumber( FreeRTOS_Socket_t * pxSocket,
const NetworkBufferDescriptor_t * pxNetworkBuffer,
size_t uxIPHeaderSize,
uint32_t ulLen );
/*
* Return or send a packet to the other party.
*/
void prvTCPReturnPacket_IPV4( FreeRTOS_Socket_t * pxSocket,
NetworkBufferDescriptor_t * pxDescriptor,
uint32_t ulLen,
BaseType_t xReleaseAfterSend );
/*
* Return or send a packet to the other party.
*/
void prvTCPReturnPacket_IPV6( FreeRTOS_Socket_t * pxSocket,
NetworkBufferDescriptor_t * pxDescriptor,
uint32_t ulLen,
BaseType_t xReleaseAfterSend );
void prvTCPReturn_SetEndPoint( const FreeRTOS_Socket_t * pxSocket,
NetworkBufferDescriptor_t * pxNetworkBuffer,
size_t uxIPHeaderSize );
/*
* Let ARP look-up the MAC-address of the peer and initialise the first SYN
* packet.
*/
BaseType_t prvTCPPrepareConnect_IPV4( FreeRTOS_Socket_t * pxSocket );
/*
* Let ND look-up the MAC-address of the peer and initialise the first SYN
* packet.
*/
BaseType_t prvTCPPrepareConnect_IPV6( FreeRTOS_Socket_t * pxSocket );
/*
* Initialise the data structures which keep track of the TCP windowing system.
*/
BaseType_t prvTCPCreateWindow( FreeRTOS_Socket_t * pxSocket );
/*
* Set the initial properties in the options fields, like the preferred
* value of MSS and whether SACK allowed. Will be transmitted in the state
* 'eCONNECT_SYN'.
*/
UBaseType_t prvSetSynAckOptions( FreeRTOS_Socket_t * pxSocket,
TCPHeader_t * pxTCPHeader );
/*
* Prepare an outgoing message, if anything has to be sent.
*/
int32_t prvTCPPrepareSend( FreeRTOS_Socket_t * pxSocket,
NetworkBufferDescriptor_t ** ppxNetworkBuffer,
UBaseType_t uxOptionsLength );
/*
* The API FreeRTOS_send() adds data to the TX stream. Add
* this data to the windowing system to it can be transmitted.
*/
void prvTCPAddTxData( FreeRTOS_Socket_t * pxSocket );
/*
* Set the TCP options (if any) for the outgoing packet.
*/
UBaseType_t prvSetOptions( FreeRTOS_Socket_t * pxSocket,
const NetworkBufferDescriptor_t * pxNetworkBuffer );
/*
* Called from prvTCPHandleState(). There is data to be sent.
* If ipconfigUSE_TCP_WIN is defined, and if only an ACK must be sent, it will
* be checked if it would better be postponed for efficiency.
*/
BaseType_t prvSendData( FreeRTOS_Socket_t * pxSocket,
NetworkBufferDescriptor_t ** ppxNetworkBuffer,
uint32_t ulReceiveLength,
BaseType_t xByteCount );
/*
* A "challenge ACK" is as per https://tools.ietf.org/html/rfc5961#section-3.2,
* case #3. In summary, an RST was received with a sequence number that is
* unexpected but still within the window.
*/
BaseType_t prvTCPSendChallengeAck( NetworkBufferDescriptor_t * pxNetworkBuffer,
uint32_t ulCurrentSequenceNumber,
uint32_t ulOurSequenceNumber );
/*
* Reply to a peer with the RST flag on, in case a packet can not be handled.
*/
BaseType_t prvTCPSendReset( NetworkBufferDescriptor_t * pxNetworkBuffer );
/*
* Check if the size of a network buffer is big enough to hold the outgoing message.
* Allocate a new bigger network buffer when necessary.
*/
NetworkBufferDescriptor_t * prvTCPBufferResize( const FreeRTOS_Socket_t * pxSocket,
NetworkBufferDescriptor_t * pxNetworkBuffer,
int32_t lDataLen,
UBaseType_t uxOptionsLength );
/* *INDENT-OFF* */
#ifdef __cplusplus
} /* extern "C" */
#endif
/* *INDENT-ON* */
#endif /* FREERTOS_TCP_TRANSMISSION_H */
@@ -0,0 +1,66 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
#ifndef FREERTOS_TCP_UTILS_H
#define FREERTOS_TCP_UTILS_H
/* *INDENT-OFF* */
#ifdef __cplusplus
extern "C" {
#endif
/* *INDENT-ON* */
/*
* For logging and debugging: make a string showing the TCP flags.
*/
#if ( ipconfigHAS_DEBUG_PRINTF != 0 )
const char * prvTCPFlagMeaning( UBaseType_t xFlags );
#endif /* ipconfigHAS_DEBUG_PRINTF != 0 */
/*
* Set the initial value for MSS (Maximum Segment Size) to be used.
*/
void prvSocketSetMSS( FreeRTOS_Socket_t * pxSocket );
/*
* Set the initial value for MSS (Maximum Segment Size) to be used.
*/
void prvSocketSetMSS_IPV4( FreeRTOS_Socket_t * pxSocket );
/*
* Set the initial value for MSS (Maximum Segment Size) to be used.
*/
void prvSocketSetMSS_IPV6( FreeRTOS_Socket_t * pxSocket );
/* *INDENT-OFF* */
#ifdef __cplusplus
} /* extern "C" */
#endif
/* *INDENT-ON* */
#endif /* FREERTOS_TCP_UTILS_H */
@@ -0,0 +1,258 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
/*
* FreeRTOS_TCP_WIN.c
* Module which handles the TCP windowing schemes for FreeRTOS-PLUS-TCP
*/
#ifndef FREERTOS_TCP_WIN_H
#define FREERTOS_TCP_WIN_H
/* *INDENT-OFF* */
#ifdef __cplusplus
extern "C" {
#endif
/* *INDENT-ON* */
/** @brief A very simple timer that registers the time that a packet was sent. It is used to trigger re-sending. */
typedef struct xTCPTimerStruct
{
TickType_t uxBorn; /**< The time at which a packet was sent ( using xTaskGetTickCount() ). */
} TCPTimer_t;
/** @brief This struct collects the properties of a TCP segment. A segment is a chunk of data which
* is sent in a single TCP packet, at most 1460 bytes. */
typedef struct xTCP_SEGMENT
{
uint32_t ulSequenceNumber; /**< The sequence number of the first byte in this packet */
int32_t lMaxLength; /**< Maximum space, number of bytes which can be stored in this segment */
int32_t lDataLength; /**< Actual number of bytes */
int32_t lStreamPos; /**< reference to the [t|r]xStream of the socket */
TCPTimer_t xTransmitTimer; /**< saves a timestamp at the moment this segment gets transmitted (TX only) */
union
{
struct
{
uint32_t
ucTransmitCount : 8, /**< Number of times the segment has been transmitted, used to calculate the RTT */
ucDupAckCount : 8, /**< Counts the number of times that a higher segment was ACK'd. After 3 times a Fast Retransmission takes place */
bOutstanding : 1, /**< It the peer's turn, we're just waiting for an ACK */
bAcked : 1, /**< This segment has been acknowledged */
bIsForRx : 1; /**< pdTRUE if segment is used for reception */
} bits;
uint32_t ulFlags;
} u; /**< A collection of boolean flags. */
#if ( ipconfigUSE_TCP_WIN != 0 )
struct xLIST_ITEM xQueueItem; /**< TX only: segments can be linked in one of three queues: xPriorityQueue, xTxQueue, and xWaitQueue */
struct xLIST_ITEM xSegmentItem; /**< With this item the segment can be connected to a list, depending on who is owning it */
#endif
} TCPSegment_t;
/** @brief This struct describes the windows sizes, both for incoming and outgoing. */
typedef struct xTCP_WINSIZE
{
uint32_t ulRxWindowLength; /**< The TCP window size of the incoming stream. */
uint32_t ulTxWindowLength; /**< The TCP window size of the outgoing stream. */
} TCPWinSize_t;
/** @brief If TCP time-stamps are being used, they will occupy 12 bytes in
* each packet, and thus the message space will become smaller.
* Keep this as a multiple of 4 */
#if ( ipconfigUSE_TCP_WIN == 1 )
#define ipSIZE_TCP_OPTIONS 16U
#else
#define ipSIZE_TCP_OPTIONS 12U
#endif
/** @brief Every TCP connection owns a TCP window for the administration of all packets
* It owns two sets of segment descriptors, incoming and outgoing
*/
typedef struct xTCP_WINDOW
{
union
{
struct
{
uint32_t
bHasInit : 1, /**< The window structure has been initialised */
bSendFullSize : 1, /**< May only send packets with a size equal to MSS (for optimisation) */
bTimeStamps : 1; /**< Socket is supposed to use TCP time-stamps. This depends on the */
} bits; /**< party which opens the connection */
uint32_t ulFlags;
} u; /**< A collection of boolean flags. */
TCPWinSize_t xSize; /**< The TCP window sizes of the incoming and outgoing streams. */
struct
{
uint32_t ulFirstSequenceNumber; /**< Logging & debug: the first segment received/sent in this connection
* for Tx: initial send sequence number (ISS)
* for Rx: initial receive sequence number (IRS) */
uint32_t ulCurrentSequenceNumber; /**< Tx/Rx: the oldest sequence number not yet confirmed, also SND.UNA / RCV.NXT
* In other words: the sequence number of the left side of the sliding window */
uint32_t ulFINSequenceNumber; /**< The sequence number which carried the FIN flag */
uint32_t ulHighestSequenceNumber; /**< Sequence number of the right-most byte + 1 */
} rx, /**< Sequence number of the incoming data stream. */
tx; /**< Sequence number of the outgoing data stream. */
uint32_t ulOurSequenceNumber; /**< The SEQ number we're sending out */
uint32_t ulUserDataLength; /**< Number of bytes in Rx buffer which may be passed to the user, after having received a 'missing packet' */
uint32_t ulNextTxSequenceNumber; /**< The sequence number given to the next byte to be added for transmission */
int32_t lSRTT; /**< Smoothed Round Trip Time, it may increment quickly and it decrements slower */
uint8_t ucOptionLength; /**< Number of valid bytes in ulOptionsData[] */
#if ( ipconfigUSE_TCP_WIN == 1 )
List_t xPriorityQueue; /**< Priority queue: segments which must be sent immediately */
List_t xTxQueue; /**< Transmit queue: segments queued for transmission */
List_t xWaitQueue; /**< Waiting queue: outstanding segments */
TCPSegment_t * pxHeadSegment; /**< points to a segment which has not been transmitted and it's size is still growing (user data being added) */
uint32_t ulOptionsData[ ipSIZE_TCP_OPTIONS / sizeof( uint32_t ) ]; /**< Contains the options we send out */
List_t xTxSegments; /**< A linked list of all transmission segments, sorted on sequence number */
List_t xRxSegments; /**< A linked list of reception segments, order depends on sequence of arrival */
#else
/* For tiny TCP, there is only 1 outstanding TX segment */
TCPSegment_t xTxSegment; /**< Priority queue */
#endif
uint16_t usOurPortNumber; /**< Mostly for debugging/logging: our TCP port number */
uint16_t usPeerPortNumber; /**< debugging/logging: the peer's TCP port number */
uint16_t usMSS; /**< Current accepted MSS */
uint16_t usMSSInit; /**< MSS as configured by the socket owner */
} TCPWindow_t;
/*=============================================================================
*
* Creation and destruction
*
*=============================================================================*/
/* Create and initialize a window */
BaseType_t xTCPWindowCreate( TCPWindow_t * pxWindow,
uint32_t ulRxWindowLength,
uint32_t ulTxWindowLength,
uint32_t ulAckNumber,
uint32_t ulSequenceNumber,
uint32_t ulMSS );
/* Destroy a window (always returns NULL)
* It will free some resources: a collection of segments */
void vTCPWindowDestroy( TCPWindow_t const * pxWindow );
/* Initialize a window */
void vTCPWindowInit( TCPWindow_t * pxWindow,
uint32_t ulAckNumber,
uint32_t ulSequenceNumber,
uint32_t ulMSS );
/* Clean up allocated segments. Should only be called when FreeRTOS+TCP will no longer be used. */
void vTCPSegmentCleanup( void );
/*=============================================================================
*
* Rx functions
*
*=============================================================================*/
/* if true may be passed directly to user (segment expected and window is empty)
* But pxWindow->ackno should always be used to set "BUF->ackno" */
int32_t lTCPWindowRxCheck( TCPWindow_t * pxWindow,
uint32_t ulSequenceNumber,
uint32_t ulLength,
uint32_t ulSpace,
uint32_t * pulSkipCount );
/* This function will be called as soon as a FIN is received. It will return true
* if there are no 'open' reception segments */
BaseType_t xTCPWindowRxEmpty( const TCPWindow_t * pxWindow );
/*=============================================================================
*
* Tx functions
*
*=============================================================================*/
/* Adds data to the Tx-window */
int32_t lTCPWindowTxAdd( TCPWindow_t * pxWindow,
uint32_t ulLength,
int32_t lPosition,
int32_t lMax );
/* Check data to be sent and calculate the time period we may sleep */
BaseType_t xTCPWindowTxHasData( TCPWindow_t const * pxWindow,
uint32_t ulWindowSize,
TickType_t * pulDelay );
/* See if anything is left to be sent
* Function will be called when a FIN has been received. Only when the TX window is clean,
* it will return pdTRUE */
BaseType_t xTCPWindowTxDone( const TCPWindow_t * pxWindow );
/* Fetches data to be sent.
* 'plPosition' will point to a location with the circular data buffer: txStream */
uint32_t ulTCPWindowTxGet( TCPWindow_t * pxWindow,
uint32_t ulWindowSize,
int32_t * plPosition );
/* Receive a normal ACK */
uint32_t ulTCPWindowTxAck( TCPWindow_t * pxWindow,
uint32_t ulSequenceNumber );
/* Receive a SACK option */
uint32_t ulTCPWindowTxSack( TCPWindow_t * pxWindow,
uint32_t ulFirst,
uint32_t ulLast );
/**
* @brief Check if a > b, where a and b are rolling counters.
*
* @param[in] a: The value on the left-hand side.
* @param[in] b: The value on the right-hand side.
*
* @return pdTRUE if a > b, otherwise pdFALSE.
*
* @note GreaterThan is calculated as "( a - ( b + 1U ) ) < 0x80000000".
*/
BaseType_t xSequenceGreaterThan( uint32_t a,
uint32_t b );
/**
* @brief Check if a < b, where a and b are rolling counters.
*
* @param[in] a: The value on the left-hand side.
* @param[in] b: The value on the right-hand side.
*
* @return pdTRUE if a < b, otherwise pdFALSE.
*
* @note LessThan is implemented as "( b - ( a + 1 ) ) < 0x80000000".
*/
BaseType_t xSequenceLessThan( uint32_t a,
uint32_t b );
/* *INDENT-OFF* */
#ifdef __cplusplus
} /* extern "C" */
#endif
/* *INDENT-ON* */
#endif /* FREERTOS_TCP_WIN_H */
@@ -0,0 +1,73 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
#ifndef FREERTOS_UDP_IP_H
#define FREERTOS_UDP_IP_H
/* Application level configuration options. */
#include "FreeRTOSIPConfig.h"
#include "FreeRTOSIPConfigDefaults.h"
#include "FreeRTOS_IP.h"
/* *INDENT-OFF* */
#ifdef __cplusplus
extern "C" {
#endif
/* *INDENT-ON* */
/*
* Called when the application has generated a UDP packet to send.
*/
void vProcessGeneratedUDPPacket( NetworkBufferDescriptor_t * const pxNetworkBuffer );
void vProcessGeneratedUDPPacket_IPv4( NetworkBufferDescriptor_t * const pxNetworkBuffer );
void vProcessGeneratedUDPPacket_IPv6( NetworkBufferDescriptor_t * const pxNetworkBuffer );
/*
* The caller must ensure that pxNetworkBuffer->xDataLength is the UDP packet
* payload size (excluding packet headers) and that the packet in pucEthernetBuffer
* is at least the size of UDPPacket_t.
*/
BaseType_t xProcessReceivedUDPPacket( NetworkBufferDescriptor_t * pxNetworkBuffer,
uint16_t usPort,
BaseType_t * pxIsWaitingForResolution );
BaseType_t xProcessReceivedUDPPacket_IPv4( NetworkBufferDescriptor_t * pxNetworkBuffer,
uint16_t usPort,
BaseType_t * pxIsWaitingForARPResolution );
BaseType_t xProcessReceivedUDPPacket_IPv6( NetworkBufferDescriptor_t * pxNetworkBuffer,
uint16_t usPort,
BaseType_t * pxIsWaitingForNDResolution );
/* *INDENT-OFF* */
#ifdef __cplusplus
} /* extern "C" */
#endif
/* *INDENT-ON* */
#endif /* FREERTOS_UDP_IP_H */
@@ -0,0 +1,900 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
/**
* @file IPTraceMacroDefaults.h
* @brief This file provides default (empty) implementations for any IP trace
* macros that are not defined by the user. See
* https://freertos.org/Documentation/03-Libraries/02-FreeRTOS-plus/02-FreeRTOS-plus-TCP/08-Trace-macros
*/
#ifndef IP_TRACE_MACRO_DEFAULTS_H
#define IP_TRACE_MACRO_DEFAULTS_H
#ifndef FREERTOS_IP_CONFIG_DEFAULTS_H
#error FreeRTOSIPConfigDefaults.h has not been included yet
#endif
/*===========================================================================*/
/*---------------------------------------------------------------------------*/
/*===========================================================================*/
/* NETWORK TRACE MACROS */
/*===========================================================================*/
/*---------------------------------------------------------------------------*/
/*
* iptraceFAILED_TO_OBTAIN_NETWORK_BUFFER
*
* Called when a task attempts to obtain a network buffer, but a buffer was
* not available even after any defined block period.
*/
#ifndef iptraceFAILED_TO_OBTAIN_NETWORK_BUFFER
#define iptraceFAILED_TO_OBTAIN_NETWORK_BUFFER()
#endif
/*---------------------------------------------------------------------------*/
/*
* iptraceFAILED_TO_OBTAIN_NETWORK_BUFFER_FROM_ISR
*
* Called when an interrupt service routine attempts to obtain a network
* buffer, but a buffer was not available.
*/
#ifndef iptraceFAILED_TO_OBTAIN_NETWORK_BUFFER_FROM_ISR
#define iptraceFAILED_TO_OBTAIN_NETWORK_BUFFER_FROM_ISR()
#endif
/*---------------------------------------------------------------------------*/
/*
* iptraceNETWORK_BUFFER_OBTAINED
*
* Called when the network buffer at address pxBufferAddress is obtained from
* the TCP/IP stack by an RTOS task.
*/
#ifndef iptraceNETWORK_BUFFER_OBTAINED
#define iptraceNETWORK_BUFFER_OBTAINED( pxBufferAddress )
#endif
/*---------------------------------------------------------------------------*/
/*
* iptraceNETWORK_BUFFER_OBTAINED_FROM_ISR
*
* Called when the network buffer at address pxBufferAddress is obtained from
* the TCP/IP stack by an interrupt service routine.
*/
#ifndef iptraceNETWORK_BUFFER_OBTAINED_FROM_ISR
#define iptraceNETWORK_BUFFER_OBTAINED_FROM_ISR( pxBufferAddress )
#endif
/*---------------------------------------------------------------------------*/
/*
* iptraceNETWORK_BUFFER_RELEASED
*
* Called when the network buffer at address pxBufferAddress is released back
* to the TCP/IP stack.
*/
#ifndef iptraceNETWORK_BUFFER_RELEASED
#define iptraceNETWORK_BUFFER_RELEASED( pxBufferAddress )
#endif
/*---------------------------------------------------------------------------*/
/*
* iptraceNETWORK_DOWN
*
* Called when the network driver indicates that the network connection has
* been lost (not implemented by all network drivers).
*/
#ifndef iptraceNETWORK_DOWN
#define iptraceNETWORK_DOWN()
#endif
/*---------------------------------------------------------------------------*/
/*
* iptraceNETWORK_EVENT_RECEIVED
*
* Called when the TCP/IP stack processes an event previously posted to the
* network event queue. eEvent will be one of the following values:
*
* eNetworkDownEvent - The network interface has been lost and/or needs
* [re]connecting.
* eNetworkRxEvent - The network interface has queued a received Ethernet
* frame.
* eARPTimerEvent - The Resolution timer expired.
* eStackTxEvent - The software stack has queued a packet to transmit.
* eDHCPEvent - Process the DHCP state machine.
*
* Note the events are defined by the private eIPEvent_t type which is not
* generally accessible.
*/
#ifndef iptraceNETWORK_EVENT_RECEIVED
#define iptraceNETWORK_EVENT_RECEIVED( eEvent )
#endif
/*---------------------------------------------------------------------------*/
/*
* iptraceNETWORK_INTERFACE_INPUT
*
* Called when a packet of length uxDataLength and with the contents at
* address pucEthernetBuffer has been received.
*/
#ifndef iptraceNETWORK_INTERFACE_INPUT
#define iptraceNETWORK_INTERFACE_INPUT( uxDataLength, pucEthernetBuffer )
#endif
/*---------------------------------------------------------------------------*/
/*
* iptraceNETWORK_INTERFACE_OUTPUT
*
* Called when a packet of length uxDataLength and with the contents at
* address pucEthernetBuffer has been sent.
*/
#ifndef iptraceNETWORK_INTERFACE_OUTPUT
#define iptraceNETWORK_INTERFACE_OUTPUT( uxDataLength, pucEthernetBuffer )
#endif
/*---------------------------------------------------------------------------*/
/*
* iptraceNETWORK_INTERFACE_RECEIVE
*
* Called when a packet is received from the network by the network driver.
* Note this macro is called by the network driver rather than the TCP/IP stack
* and may not be called at all by drivers provided by third parties.
*/
#ifndef iptraceNETWORK_INTERFACE_RECEIVE
#define iptraceNETWORK_INTERFACE_RECEIVE()
#endif
/*---------------------------------------------------------------------------*/
/*
* iptraceNETWORK_INTERFACE_TRANSMIT
*
* Called when a packet is sent to the network by the network driver. Note this
* macro is called by the network driver rather than the TCP/IP stack and may
* not be called at all by drivers provided by third parties.
*/
#ifndef iptraceNETWORK_INTERFACE_TRANSMIT
#define iptraceNETWORK_INTERFACE_TRANSMIT()
#endif
/*---------------------------------------------------------------------------*/
/*
* iptraceSTACK_TX_EVENT_LOST
*
* Called when a packet generated by the TCP/IP stack is dropped because there
* is insufficient space in the network event queue (see the
* ipconfigEVENT_QUEUE_LENGTH setting in FreeRTOSIPConfig.h).
*/
#ifndef iptraceSTACK_TX_EVENT_LOST
#define iptraceSTACK_TX_EVENT_LOST( xEvent )
#endif
/*---------------------------------------------------------------------------*/
/*===========================================================================*/
/* NETWORK TRACE MACROS */
/*===========================================================================*/
/*---------------------------------------------------------------------------*/
/*===========================================================================*/
/*---------------------------------------------------------------------------*/
/*===========================================================================*/
/* DRIVER TRACE MACROS */
/*===========================================================================*/
/*---------------------------------------------------------------------------*/
/*
* iptraceETHERNET_RX_EVENT_LOST
*
* Called when a packet received by the network driver is dropped for one of
* the following reasons: There is insufficient space in the network event
* queue (see the ipconfigEVENT_QUEUE_LENGTH setting in FreeRTOSIPConfig.h),
* the received packet has an invalid data length, or there are no network
* buffers available (see the ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS setting
* in FreeRTOSIPConfig.h). Note this macro is called by the network driver
* rather than the TCP/IP stack and may not be called at all by drivers
* provided by third parties.
*/
#ifndef iptraceETHERNET_RX_EVENT_LOST
#define iptraceETHERNET_RX_EVENT_LOST()
#endif
/*---------------------------------------------------------------------------*/
/*
* iptraceWAITING_FOR_TX_DMA_DESCRIPTOR
*
* Called when a transmission at the network driver level cannot complete
* immediately because the driver is having to wait for a DMA descriptor to
* become free. Try increasing the configNUM_TX_ETHERNET_DMA_DESCRIPTORS
* setting in FreeRTOSConfig.h (if it exists for the network driver being
* used).
*/
#ifndef iptraceWAITING_FOR_TX_DMA_DESCRIPTOR
#define iptraceWAITING_FOR_TX_DMA_DESCRIPTOR()
#endif
/*---------------------------------------------------------------------------*/
/*===========================================================================*/
/* DRIVER TRACE MACROS */
/*===========================================================================*/
/*---------------------------------------------------------------------------*/
/*===========================================================================*/
/*---------------------------------------------------------------------------*/
/*===========================================================================*/
/* UDP TRACE MACROS */
/*===========================================================================*/
/*---------------------------------------------------------------------------*/
/*
* iptraceSENDING_UDP_PACKET
*
* Called when a UDP packet is sent to the IP address ulIPAddress. ulIPAddress
* is expressed as a 32-bit number in network byte order.
*/
#ifndef iptraceSENDING_UDP_PACKET
#define iptraceSENDING_UDP_PACKET( ulIPAddress )
#endif
/*---------------------------------------------------------------------------*/
/*===========================================================================*/
/* UDP TRACE MACROS */
/*===========================================================================*/
/*---------------------------------------------------------------------------*/
/*===========================================================================*/
/*---------------------------------------------------------------------------*/
/*===========================================================================*/
/* SOCKET TRACE MACROS */
/*===========================================================================*/
/*---------------------------------------------------------------------------*/
/*
* iptraceBIND_FAILED
*
* A call to FreeRTOS_bind() failed. usPort is the port number the socket
* xSocket was to be bound to.
*/
#ifndef iptraceBIND_FAILED
#define iptraceBIND_FAILED( xSocket, usPort )
#endif
/*---------------------------------------------------------------------------*/
/*
* iptraceFAILED_TO_CREATE_EVENT_GROUP
*
* Called when an event group could not be created, possibly due to
* insufficient heap space, during new socket creation.
*/
#ifndef iptraceFAILED_TO_CREATE_EVENT_GROUP
#define iptraceFAILED_TO_CREATE_EVENT_GROUP()
#endif
/*---------------------------------------------------------------------------*/
/*
* iptraceFAILED_TO_CREATE_SOCKET
*
* A call to FreeRTOS_socket() failed because there was insufficient FreeRTOS
* heap memory available for the socket structure to be created.
*/
#ifndef iptraceFAILED_TO_CREATE_SOCKET
#define iptraceFAILED_TO_CREATE_SOCKET()
#endif
/*---------------------------------------------------------------------------*/
/*
* iptraceFAILED_TO_NOTIFY_SELECT_GROUP
*/
#ifndef iptraceFAILED_TO_NOTIFY_SELECT_GROUP
#define iptraceFAILED_TO_NOTIFY_SELECT_GROUP( xSocket )
#endif
/*-----------------------------------------------------------------------*/
/*
* iptraceNO_BUFFER_FOR_SENDTO
*
* Called when a call to FreeRTOS_sendto() tries to allocate a buffer, but a
* buffer was not available even after any defined block period.
*/
#ifndef iptraceNO_BUFFER_FOR_SENDTO
#define iptraceNO_BUFFER_FOR_SENDTO()
#endif
/*---------------------------------------------------------------------------*/
/*
* iptraceRECVFROM_DISCARDING_BYTES
*
* FreeRTOS_recvfrom() is discarding xNumberOfBytesDiscarded bytes because the
* number of bytes received is greater than the number of bytes that will fit
* in the user supplied buffer (the buffer passed in as a FreeRTOS_recvfrom()
* function parameter).
*/
#ifndef iptraceRECVFROM_DISCARDING_BYTES
#define iptraceRECVFROM_DISCARDING_BYTES( xNumberOfBytesDiscarded )
#endif
/*---------------------------------------------------------------------------*/
/*
* iptraceRECVFROM_INTERRUPTED
*
* Called when a blocking call to FreeRTOS_recvfrom() is interrupted through a
* call to FreeRTOS_SignalSocket().
*/
#ifndef iptraceRECVFROM_INTERRUPTED
#define iptraceRECVFROM_INTERRUPTED()
#endif
/*---------------------------------------------------------------------------*/
/*
* iptraceRECVFROM_TIMEOUT
*
* Called when FreeRTOS_recvfrom() gets no data on the given socket even after
* any defined block period.
*/
#ifndef iptraceRECVFROM_TIMEOUT
#define iptraceRECVFROM_TIMEOUT()
#endif
/*---------------------------------------------------------------------------*/
/*
* iptraceSENDTO_DATA_TOO_LONG
*
* Called when the data requested to be sent using a call to FreeRTOS_sendto()
* is too long and could not be sent.
*/
#ifndef iptraceSENDTO_DATA_TOO_LONG
#define iptraceSENDTO_DATA_TOO_LONG()
#endif
/*---------------------------------------------------------------------------*/
/*
* iptraceSENDTO_SOCKET_NOT_BOUND
*
* Called when the socket used in the call to FreeRTOS_sendto() is not already
* bound to a port.
*/
#ifndef iptraceSENDTO_SOCKET_NOT_BOUND
#define iptraceSENDTO_SOCKET_NOT_BOUND()
#endif
/*---------------------------------------------------------------------------*/
/*===========================================================================*/
/* SOCKET TRACE MACROS */
/*===========================================================================*/
/*---------------------------------------------------------------------------*/
/*===========================================================================*/
/*---------------------------------------------------------------------------*/
/*===========================================================================*/
/* ARP TRACE MACROS */
/*===========================================================================*/
/*---------------------------------------------------------------------------*/
/*
* iptraceARP_PACKET_RECEIVED
*
* Called when an ARP packet is received, even if the local network node is not
* involved in the ARP transaction.
*/
#ifndef iptraceARP_PACKET_RECEIVED
#define iptraceARP_PACKET_RECEIVED()
#endif
/*---------------------------------------------------------------------------*/
/*
* iptraceARP_TABLE_ENTRY_CREATED
*
* Called when a new entry in the ARP table is created to map the IP address
* ulIPAddress to the MAC address ucMACAddress. ulIPAddress is expressed as a
* 32-bit number in network byte order. ucMACAddress is a pointer to an
* MACAddress_t structure.
*/
#ifndef iptraceARP_TABLE_ENTRY_CREATED
#define iptraceARP_TABLE_ENTRY_CREATED( ulIPAddress, ucMACAddress )
#endif
/*---------------------------------------------------------------------------*/
/*
* iptraceARP_TABLE_ENTRY_EXPIRED
*
* Called when the entry for the IP address ulIPAddress in the ARP cache is
* removed. ulIPAddress is expressed as a 32-bit number in network byte order.
*/
#ifndef iptraceARP_TABLE_ENTRY_EXPIRED
#define iptraceARP_TABLE_ENTRY_EXPIRED( ulIPAddress )
#endif
/*---------------------------------------------------------------------------*/
/*
* iptraceARP_TABLE_ENTRY_WILL_EXPIRE
*
* Called when an ARP request is about to be sent because the entry for the IP
* address ulIPAddress in the ARP cache has become stale. ulIPAddress is
* expressed as a 32-bit number in network byte order.
*/
#ifndef iptraceARP_TABLE_ENTRY_WILL_EXPIRE
#define iptraceARP_TABLE_ENTRY_WILL_EXPIRE( ulIPAddress )
#endif
/*---------------------------------------------------------------------------*/
/*
* iptraceCREATING_ARP_REQUEST
*
* Called when the IP generates an ARP request packet.
*/
#ifndef iptraceCREATING_ARP_REQUEST
#define iptraceCREATING_ARP_REQUEST( ulIPAddress )
#endif
/*---------------------------------------------------------------------------*/
/*
* iptraceDELAYED_ARP_BUFFER_FULL
*
* A packet has come in from an unknown IPv4 address. An ARP request has been
* sent, but the queue is still filled with a different packet.
*/
#ifndef iptraceDELAYED_ARP_BUFFER_FULL
#define iptraceDELAYED_ARP_BUFFER_FULL()
#endif
/*---------------------------------------------------------------------------*/
/*
* iptrace_DELAYED_ARP_REQUEST_REPLIED
*
* An ARP request has been sent, and a matching reply is received. Now the
* original packet will be processed by the IP-task.
*/
#ifndef iptrace_DELAYED_ARP_REQUEST_REPLIED
#define iptrace_DELAYED_ARP_REQUEST_REPLIED()
#endif
/*---------------------------------------------------------------------------*/
/*
* iptraceDELAYED_ARP_REQUEST_STARTED
*
* A packet came in from an unknown IPv4 address. An ARP request has been sent
* and the network buffer is stored for processing later.
*/
#ifndef iptraceDELAYED_ARP_REQUEST_STARTED
#define iptraceDELAYED_ARP_REQUEST_STARTED()
#endif
/*---------------------------------------------------------------------------*/
/*
* iptraceDELAYED_ARP_TIMER_EXPIRED
*
* A packet was stored for delayed processing, but there is no ARP reply. The
* network buffer will be released without being processed.
*/
#ifndef iptraceDELAYED_ARP_TIMER_EXPIRED
#define iptraceDELAYED_ARP_TIMER_EXPIRED()
#endif
/*---------------------------------------------------------------------------*/
/*
* iptraceDROPPED_INVALID_ARP_PACKET
*
* Called when an ARP packet is dropped due to invalid protocol and hardware
* fields in the header at address pxARPHeader.
*/
#ifndef iptraceDROPPED_INVALID_ARP_PACKET
#define iptraceDROPPED_INVALID_ARP_PACKET( pxARPHeader )
#endif
/*---------------------------------------------------------------------------*/
/*
* iptracePACKET_DROPPED_TO_GENERATE_ARP
*
* Called when a packet destined for the IP address ulIPAddress is dropped
* because the ARP cache does not contain an entry for the IP address. The
* packet is automatically replaced by an ARP packet. ulIPAddress is expressed
* as a 32-bit number in network byte order.
*/
#ifndef iptracePACKET_DROPPED_TO_GENERATE_ARP
#define iptracePACKET_DROPPED_TO_GENERATE_ARP( ulIPAddress )
#endif
/*---------------------------------------------------------------------------*/
/*
* iptracePROCESSING_RECEIVED_ARP_REPLY
*
* Called when the ARP cache is about to be updated in response to the
* reception of an ARP reply. ulIPAddress holds the ARP message's target IP
* address (as a 32-bit number in network byte order), which may not be the
* local network node (depending on the FreeRTOSIPConfig.h settings).
*/
#ifndef iptracePROCESSING_RECEIVED_ARP_REPLY
#define iptracePROCESSING_RECEIVED_ARP_REPLY( ulIPAddress )
#endif
/*---------------------------------------------------------------------------*/
/*
* iptraceSENDING_ARP_REPLY
*
* An ARP reply is being sent in response to an ARP request from the IP address
* ulIPAddress. ulIPAddress is expressed as a 32-bit number in network byte
* order.
*/
#ifndef iptraceSENDING_ARP_REPLY
#define iptraceSENDING_ARP_REPLY( ulIPAddress )
#endif
/*---------------------------------------------------------------------------*/
/*===========================================================================*/
/* ARP TRACE MACROS */
/*===========================================================================*/
/*---------------------------------------------------------------------------*/
/*===========================================================================*/
/*---------------------------------------------------------------------------*/
/*===========================================================================*/
/* ND TRACE MACROS */
/*===========================================================================*/
/*---------------------------------------------------------------------------*/
/*
* iptraceND_TABLE_ENTRY_EXPIRED
*/
#ifndef iptraceND_TABLE_ENTRY_EXPIRED
#define iptraceND_TABLE_ENTRY_EXPIRED( pxIPAddress )
#endif
/*---------------------------------------------------------------------------*/
/*
* iptraceND_TABLE_ENTRY_WILL_EXPIRE
*/
#ifndef iptraceND_TABLE_ENTRY_WILL_EXPIRE
#define iptraceND_TABLE_ENTRY_WILL_EXPIRE( pxIPAddress )
#endif
/*---------------------------------------------------------------------------*/
/*
* iptraceDELAYED_ND_BUFFER_FULL
*
* A packet has come in from an unknown IPv6 address. An ND request has been
* sent, but the queue is still filled with a different packet.
*/
#ifndef iptraceDELAYED_ND_BUFFER_FULL
#define iptraceDELAYED_ND_BUFFER_FULL()
#endif
/*---------------------------------------------------------------------------*/
/*
* iptrace_DELAYED_ND_REQUEST_REPLIED
*/
#ifndef iptrace_DELAYED_ND_REQUEST_REPLIED
#define iptrace_DELAYED_ND_REQUEST_REPLIED()
#endif
/*---------------------------------------------------------------------------*/
/*
* iptraceDELAYED_ND_REQUEST_STARTED
*
* A packet came in from an unknown IPv6 address. An ND request has been sent
* and the network buffer is stored for processing later.
*/
#ifndef iptraceDELAYED_ND_REQUEST_STARTED
#define iptraceDELAYED_ND_REQUEST_STARTED()
#endif
/*---------------------------------------------------------------------------*/
/*
* iptraceDELAYED_ND_TIMER_EXPIRED
*
* A packet was stored for delayed processing, but there is no ND reply. The
* network buffer will be released without being processed.
*/
#ifndef iptraceDELAYED_ND_TIMER_EXPIRED
#define iptraceDELAYED_ND_TIMER_EXPIRED()
#endif
/*---------------------------------------------------------------------------*/
/*===========================================================================*/
/* ND TRACE MACROS */
/*===========================================================================*/
/*---------------------------------------------------------------------------*/
/*===========================================================================*/
/*---------------------------------------------------------------------------*/
/*===========================================================================*/
/* DHCP TRACE MACROS */
/*===========================================================================*/
/*---------------------------------------------------------------------------*/
/*
* iptraceDHCP_REQUESTS_FAILED_USING_DEFAULT_IP_ADDRESS
*
* Called when the default IP address is used because an IP address could not
* be obtained from a DHCP. ulIPAddress is expressed as a 32-bit number in
* network byte order.
*/
#ifndef iptraceDHCP_REQUESTS_FAILED_USING_DEFAULT_IP_ADDRESS
#define iptraceDHCP_REQUESTS_FAILED_USING_DEFAULT_IP_ADDRESS( ulIPAddress )
#endif
/*-----------------------------------------------------------------------*/
/*
* iptraceDHCP_REQUESTS_FAILED_USING_DEFAULT_IPv6_ADDRESS
*/
#ifndef iptraceDHCP_REQUESTS_FAILED_USING_DEFAULT_IPv6_ADDRESS
#define iptraceDHCP_REQUESTS_FAILED_USING_DEFAULT_IPv6_ADDRESS( xIPAddress )
#endif
/*-----------------------------------------------------------------------*/
/*
* iptraceDHCP_SUCCEEDED
*
* Called when DHCP negotiation is complete and the IP address in
* ulOfferedIPAddress is offered to the device.
*/
#ifndef iptraceDHCP_SUCCEEDED
#define iptraceDHCP_SUCCEEDED( ulOfferedIPAddress )
#endif
/*-----------------------------------------------------------------------*/
/*
* iptraceSENDING_DHCP_DISCOVER
*
* Called when a DHCP discover packet is sent.
*/
#ifndef iptraceSENDING_DHCP_DISCOVER
#define iptraceSENDING_DHCP_DISCOVER()
#endif
/*-----------------------------------------------------------------------*/
/*
* iptraceSENDING_DHCP_REQUEST
*
* Called when a DHCP request packet is sent.
*/
#ifndef iptraceSENDING_DHCP_REQUEST
#define iptraceSENDING_DHCP_REQUEST()
#endif
/*-----------------------------------------------------------------------*/
/*===========================================================================*/
/* DHCP TRACE MACROS */
/*===========================================================================*/
/*---------------------------------------------------------------------------*/
/*===========================================================================*/
/*---------------------------------------------------------------------------*/
/*===========================================================================*/
/* DNS TRACE MACROS */
/*===========================================================================*/
/*---------------------------------------------------------------------------*/
/*
* iptraceSENDING_DNS_REQUEST
*
* Called when a DNS request is sent.
*/
#ifndef iptraceSENDING_DNS_REQUEST
#define iptraceSENDING_DNS_REQUEST()
#endif
/*---------------------------------------------------------------------------*/
/*===========================================================================*/
/* DNS TRACE MACROS */
/*===========================================================================*/
/*---------------------------------------------------------------------------*/
/*===========================================================================*/
/*---------------------------------------------------------------------------*/
/*===========================================================================*/
/* ICMP TRACE MACROS */
/*===========================================================================*/
/*---------------------------------------------------------------------------*/
/*
* iptraceICMP_PACKET_RECEIVED
*
* Called when an ICMP packet is received.
*/
#ifndef iptraceICMP_PACKET_RECEIVED
#define iptraceICMP_PACKET_RECEIVED()
#endif
/*-----------------------------------------------------------------------*/
/*
* iptraceSENDING_PING_REPLY
*
* Called when an ICMP echo reply (ping reply) is sent to the IP address
* ulIPAddress in response to an ICMP echo request (ping request) originating
* from the same address. ulIPAddress is expressed as a 32-bit number in
* network byte order.
*/
#ifndef iptraceSENDING_PING_REPLY
#define iptraceSENDING_PING_REPLY( ulIPAddress )
#endif
/*-----------------------------------------------------------------------*/
/*===========================================================================*/
/* ICMP TRACE MACROS */
/*===========================================================================*/
/*---------------------------------------------------------------------------*/
/*===========================================================================*/
/*---------------------------------------------------------------------------*/
/*===========================================================================*/
/* ROUTER ADVERTISEMENT TRACE MACROS */
/*===========================================================================*/
/*---------------------------------------------------------------------------*/
/*
* iptraceRA_REQUESTS_FAILED_USING_DEFAULT_IP_ADDRESS
*/
#ifndef iptraceRA_REQUESTS_FAILED_USING_DEFAULT_IP_ADDRESS
#define iptraceRA_REQUESTS_FAILED_USING_DEFAULT_IP_ADDRESS( ipv6_address )
#endif
/*---------------------------------------------------------------------------*/
/*
* iptraceRA_SUCCEEDED
*/
#ifndef iptraceRA_SUCCEEDED
#define iptraceRA_SUCCEEDED( ipv6_address )
#endif
/*---------------------------------------------------------------------------*/
/*===========================================================================*/
/* ROUTER ADVERTISEMENT TRACE MACROS */
/*===========================================================================*/
/*---------------------------------------------------------------------------*/
/*===========================================================================*/
/*---------------------------------------------------------------------------*/
/*===========================================================================*/
/* MEM STATS MACROS */
/*===========================================================================*/
/*-----------------------------------------------------------------------*/
/*
* iptraceMEM_STATS_CLOSE
*
* Should be called by the application when the collection of memory
* statistics should be stopped.
*/
#ifndef iptraceMEM_STATS_CLOSE
#define iptraceMEM_STATS_CLOSE()
#endif
/*-----------------------------------------------------------------------*/
/*
* iptraceMEM_STATS_CREATE
*
* Called when an object at address pxObject of type xMemType and size
* uxSize has been allocated from the heap.
*/
#ifndef iptraceMEM_STATS_CREATE
#define iptraceMEM_STATS_CREATE( xMemType, pxObject, uxSize )
#endif
/*-----------------------------------------------------------------------*/
/*
* iptraceMEM_STATS_DELETE
*
* Called when an object at address pxObject has been deallocated and the
* memory has been returned to the heap.
*/
#ifndef iptraceMEM_STATS_DELETE
#define iptraceMEM_STATS_DELETE( pxObject )
#endif
/*-----------------------------------------------------------------------*/
/*===========================================================================*/
/* MEM STATS MACROS */
/*===========================================================================*/
/*---------------------------------------------------------------------------*/
/*===========================================================================*/
/*---------------------------------------------------------------------------*/
/*===========================================================================*/
/* TCP DUMP TRACE MACROS */
/*===========================================================================*/
/*-----------------------------------------------------------------------*/
/*
* iptraceDUMP_INIT
*/
#ifndef iptraceDUMP_INIT
#define iptraceDUMP_INIT( pcFileName, pxEntries )
#endif
/*-----------------------------------------------------------------------*/
/*
* iptraceDUMP_PACKET
*/
#ifndef iptraceDUMP_PACKET
#define iptraceDUMP_PACKET( pucBuffer, uxLength, xIncoming )
#endif
/*-----------------------------------------------------------------------*/
/*===========================================================================*/
/* TCP DUMP TRACE MACROS */
/*===========================================================================*/
/*---------------------------------------------------------------------------*/
/*===========================================================================*/
#endif /* IP_TRACE_MACRO_DEFAULTS_H */
@@ -0,0 +1,90 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
#ifndef NETWORK_BUFFER_MANAGEMENT_H
#define NETWORK_BUFFER_MANAGEMENT_H
/* *INDENT-OFF* */
#ifdef __cplusplus
extern "C" {
#endif
/* *INDENT-ON* */
#include "FreeRTOS_IP.h"
/* _HT_ Two macro's needed while debugging/testing, please ignore. */
#define BUFFER_FROM_WHERE_DECL
#define BUFFER_FROM_WHERE_CALL( aWhere )
/* NOTE PUBLIC API FUNCTIONS. */
BaseType_t xNetworkBuffersInitialise( void );
NetworkBufferDescriptor_t * pxGetNetworkBufferWithDescriptor( size_t xRequestedSizeBytes,
TickType_t xBlockTimeTicks );
/* The definition of the below function is only available if BufferAllocation_2.c has been linked into the source. */
NetworkBufferDescriptor_t * pxNetworkBufferGetFromISR( size_t xRequestedSizeBytes );
void vReleaseNetworkBufferAndDescriptor( NetworkBufferDescriptor_t * const pxNetworkBuffer );
/* The definition of the below function is only available if BufferAllocation_2.c has been linked into the source. */
BaseType_t vNetworkBufferReleaseFromISR( NetworkBufferDescriptor_t * const pxNetworkBuffer );
uint8_t * pucGetNetworkBuffer( size_t * pxRequestedSizeBytes );
void vReleaseNetworkBuffer( uint8_t * pucEthernetBuffer );
/* Get the current number of free network buffers. */
UBaseType_t uxGetNumberOfFreeNetworkBuffers( void );
/* Get the lowest number of free network buffers. */
UBaseType_t uxGetMinimumFreeNetworkBuffers( void );
/* Copy a network buffer into a bigger buffer. */
NetworkBufferDescriptor_t * pxDuplicateNetworkBufferWithDescriptor( const NetworkBufferDescriptor_t * const pxNetworkBuffer,
size_t uxNewLength );
/* Increase the size of a Network Buffer.
* In case BufferAllocation_2.c is used, the new space must be allocated. */
NetworkBufferDescriptor_t * pxResizeNetworkBufferWithDescriptor( NetworkBufferDescriptor_t * pxNetworkBuffer,
size_t xNewSizeBytes );
#if ipconfigTCP_IP_SANITY
/*
* Check if an address is a valid pointer to a network descriptor
* by looking it up in the array of network descriptors
*/
UBaseType_t bIsValidNetworkDescriptor( const NetworkBufferDescriptor_t * pxDesc );
BaseType_t prvIsFreeBuffer( const NetworkBufferDescriptor_t * pxDescr );
#endif
/* *INDENT-OFF* */
#ifdef __cplusplus
} /* extern "C" */
#endif
/* *INDENT-ON* */
#endif /* NETWORK_BUFFER_MANAGEMENT_H */
@@ -0,0 +1,64 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
#ifndef NETWORK_INTERFACE_H
#define NETWORK_INTERFACE_H
/* *INDENT-OFF* */
#ifdef __cplusplus
extern "C" {
#endif
/* *INDENT-ON* */
#include "FreeRTOS_IP.h"
/* INTERNAL API FUNCTIONS. */
/* Since there are multiple interfaces, there are multiple versions
* of the following functions.
* These are now declared static in NetworkInterface.c and their addresses
* are stored in a struct NetworkInterfaceDescriptor_t.
*
* BaseType_t xNetworkInterfaceInitialise( struct xNetworkInterface *pxInterface );
* BaseType_t xGetPhyLinkStatus( struct xNetworkInterface *pxInterface );
*/
/* The following function is defined only when BufferAllocation_1.c is linked in the project. */
size_t uxNetworkInterfaceAllocateRAMToBuffers( NetworkBufferDescriptor_t pxNetworkBuffers[ ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS ] );
BaseType_t xGetPhyLinkStatus( struct xNetworkInterface * pxInterface );
#define MAC_IS_MULTICAST( pucMACAddressBytes ) ( ( pucMACAddressBytes[ 0 ] & 1U ) != 0U )
#define MAC_IS_UNICAST( pucMACAddressBytes ) ( ( pucMACAddressBytes[ 0 ] & 1U ) == 0U )
/* *INDENT-OFF* */
#ifdef __cplusplus
} /* extern "C" */
#endif
/* *INDENT-ON* */
#endif /* NETWORK_INTERFACE_H */
@@ -0,0 +1,453 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
/******************************************************************************
*
* See the following web page for essential buffer allocation scheme usage and
* configuration details:
* https://freertos.org/Documentation/03-Libraries/02-FreeRTOS-plus/02-FreeRTOS-plus-TCP/05-Buffer-management
*
******************************************************************************/
/* Standard includes. */
#include <stdint.h>
/* FreeRTOS includes. */
#include "FreeRTOS.h"
#include "task.h"
#include "queue.h"
#include "semphr.h"
/* FreeRTOS+TCP includes. */
#include "FreeRTOS_IP.h"
#include "FreeRTOS_IP_Private.h"
#include "NetworkInterface.h"
#include "NetworkBufferManagement.h"
/* For an Ethernet interrupt to be able to obtain a network buffer there must
* be at least this number of buffers available. */
#define baINTERRUPT_BUFFER_GET_THRESHOLD ( 3 )
/* A list of free (available) NetworkBufferDescriptor_t structures. */
static List_t xFreeBuffersList;
/* Some statistics about the use of buffers. */
static UBaseType_t uxMinimumFreeNetworkBuffers = 0U;
/* Declares the pool of NetworkBufferDescriptor_t structures that are available
* to the system. All the network buffers referenced from xFreeBuffersList exist
* in this array. The array is not accessed directly except during initialisation,
* when the xFreeBuffersList is filled (as all the buffers are free when the system
* is booted). */
static NetworkBufferDescriptor_t xNetworkBuffers[ ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS ];
/* This constant is defined as true to let FreeRTOS_TCP_IP.c know that the
* network buffers have constant size, large enough to hold the biggest Ethernet
* packet. No resizing will be done. */
const BaseType_t xBufferAllocFixedSize = pdTRUE;
static size_t uxMaxNetworkInterfaceAllocatedSizeBytes;
/* The semaphore used to obtain network buffers. */
static SemaphoreHandle_t xNetworkBufferSemaphore = NULL;
#if ( ipconfigTCP_IP_SANITY != 0 )
static char cIsLow = pdFALSE;
UBaseType_t bIsValidNetworkDescriptor( const NetworkBufferDescriptor_t * pxDesc );
#else
static UBaseType_t bIsValidNetworkDescriptor( const NetworkBufferDescriptor_t * pxDesc );
#endif /* ipconfigTCP_IP_SANITY */
static void prvShowWarnings( void );
/* The user can define their own ipconfigBUFFER_ALLOC_LOCK() and
* ipconfigBUFFER_ALLOC_UNLOCK() macros, especially for use form an ISR. If these
* are not defined then default them to call the normal enter/exit critical
* section macros. */
#if !defined( ipconfigBUFFER_ALLOC_LOCK )
#define ipconfigBUFFER_ALLOC_INIT() do {} while( ipFALSE_BOOL )
#define ipconfigBUFFER_ALLOC_LOCK_FROM_ISR() \
UBaseType_t uxSavedInterruptStatus = ( UBaseType_t ) portSET_INTERRUPT_MASK_FROM_ISR(); \
{
#define ipconfigBUFFER_ALLOC_UNLOCK_FROM_ISR() \
portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); \
}
#define ipconfigBUFFER_ALLOC_LOCK() taskENTER_CRITICAL()
#define ipconfigBUFFER_ALLOC_UNLOCK() taskEXIT_CRITICAL()
#endif /* ipconfigBUFFER_ALLOC_LOCK */
/*-----------------------------------------------------------*/
#if ( ipconfigTCP_IP_SANITY != 0 )
/* HT: SANITY code will be removed as soon as the library is stable
* and and ready to become public
* Function below gives information about the use of buffers */
#define WARN_LOW ( 2 )
#define WARN_HIGH ( ( 5 * ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS ) / 10 )
#endif /* ipconfigTCP_IP_SANITY */
/*-----------------------------------------------------------*/
#if ( ipconfigTCP_IP_SANITY != 0 )
BaseType_t prvIsFreeBuffer( const NetworkBufferDescriptor_t * pxDescr )
{
return ( bIsValidNetworkDescriptor( pxDescr ) != 0 ) &&
( listIS_CONTAINED_WITHIN( &xFreeBuffersList, &( pxDescr->xBufferListItem ) ) != 0 );
}
/*-----------------------------------------------------------*/
static void prvShowWarnings( void )
{
UBaseType_t uxCount = uxGetNumberOfFreeNetworkBuffers();
if( ( ( cIsLow == 0 ) && ( uxCount <= WARN_LOW ) ) || ( ( cIsLow != 0 ) && ( uxCount >= WARN_HIGH ) ) )
{
cIsLow = !cIsLow;
FreeRTOS_debug_printf( ( "*** Warning *** %s %lu buffers left\n", cIsLow ? "only" : "now", uxCount ) );
}
}
/*-----------------------------------------------------------*/
UBaseType_t bIsValidNetworkDescriptor( const NetworkBufferDescriptor_t * pxDesc )
{
uint32_t offset = ( uint32_t ) ( ( ( const char * ) pxDesc ) - ( ( const char * ) xNetworkBuffers ) );
if( ( offset >= sizeof( xNetworkBuffers ) ) ||
( ( offset % sizeof( xNetworkBuffers[ 0 ] ) ) != 0 ) )
{
return pdFALSE;
}
return ( UBaseType_t ) ( pxDesc - xNetworkBuffers ) + 1;
}
/*-----------------------------------------------------------*/
#else /* if ( ipconfigTCP_IP_SANITY != 0 ) */
static UBaseType_t bIsValidNetworkDescriptor( const NetworkBufferDescriptor_t * pxDesc )
{
( void ) pxDesc;
return ( UBaseType_t ) pdTRUE;
}
/*-----------------------------------------------------------*/
static void prvShowWarnings( void )
{
}
/*-----------------------------------------------------------*/
#endif /* ipconfigTCP_IP_SANITY */
BaseType_t xNetworkBuffersInitialise( void )
{
BaseType_t xReturn;
uint32_t x;
/* Only initialise the buffers and their associated kernel objects if they
* have not been initialised before. */
if( xNetworkBufferSemaphore == NULL )
{
/* In case alternative locking is used, the mutexes can be initialised
* here */
ipconfigBUFFER_ALLOC_INIT();
#if ( configSUPPORT_STATIC_ALLOCATION == 1 )
{
static StaticSemaphore_t xNetworkBufferSemaphoreBuffer;
xNetworkBufferSemaphore = xSemaphoreCreateCountingStatic(
( UBaseType_t ) ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS,
( UBaseType_t ) ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS,
&xNetworkBufferSemaphoreBuffer );
}
#else
{
xNetworkBufferSemaphore = xSemaphoreCreateCounting( ( UBaseType_t ) ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS, ( UBaseType_t ) ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS );
}
#endif /* configSUPPORT_STATIC_ALLOCATION */
configASSERT( xNetworkBufferSemaphore != NULL );
if( xNetworkBufferSemaphore != NULL )
{
vListInitialise( &xFreeBuffersList );
/* Initialise all the network buffers. The buffer storage comes
* from the network interface, and different hardware has different
* requirements. */
uxMaxNetworkInterfaceAllocatedSizeBytes = uxNetworkInterfaceAllocateRAMToBuffers( xNetworkBuffers );
/* The allocated buffer should hold atleast ipconfigNETWORK_MTU + ipSIZE_OF_ETH_HEADER bytes */
configASSERT( ( uxMaxNetworkInterfaceAllocatedSizeBytes >= ( ipconfigNETWORK_MTU + ipSIZE_OF_ETH_HEADER ) ) );
for( x = 0U; x < ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS; x++ )
{
/* Initialise and set the owner of the buffer list items. */
vListInitialiseItem( &( xNetworkBuffers[ x ].xBufferListItem ) );
listSET_LIST_ITEM_OWNER( &( xNetworkBuffers[ x ].xBufferListItem ), &xNetworkBuffers[ x ] );
/* Currently, all buffers are available for use. */
vListInsert( &xFreeBuffersList, &( xNetworkBuffers[ x ].xBufferListItem ) );
}
uxMinimumFreeNetworkBuffers = ( UBaseType_t ) ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS;
}
}
if( xNetworkBufferSemaphore == NULL )
{
xReturn = pdFAIL;
}
else
{
xReturn = pdPASS;
}
return xReturn;
}
/*-----------------------------------------------------------*/
NetworkBufferDescriptor_t * pxGetNetworkBufferWithDescriptor( size_t xRequestedSizeBytes,
TickType_t xBlockTimeTicks )
{
NetworkBufferDescriptor_t * pxReturn = NULL;
BaseType_t xInvalid = pdFALSE;
UBaseType_t uxCount;
if( ( xNetworkBufferSemaphore != NULL ) &&
( xRequestedSizeBytes <= uxMaxNetworkInterfaceAllocatedSizeBytes ) )
{
/* If there is a semaphore available, there is a network buffer
* available. */
if( xSemaphoreTake( xNetworkBufferSemaphore, xBlockTimeTicks ) == pdPASS )
{
/* Protect the structure as it is accessed from tasks and
* interrupts. */
ipconfigBUFFER_ALLOC_LOCK();
{
pxReturn = ( NetworkBufferDescriptor_t * ) listGET_OWNER_OF_HEAD_ENTRY( &xFreeBuffersList );
if( ( bIsValidNetworkDescriptor( pxReturn ) != pdFALSE_UNSIGNED ) &&
listIS_CONTAINED_WITHIN( &xFreeBuffersList, &( pxReturn->xBufferListItem ) ) )
{
( void ) uxListRemove( &( pxReturn->xBufferListItem ) );
}
else
{
xInvalid = pdTRUE;
}
}
ipconfigBUFFER_ALLOC_UNLOCK();
if( xInvalid == pdTRUE )
{
/* _RB_ Can printf() be called from an interrupt? (comment
* above says this can be called from an interrupt too) */
/* _HT_ The function shall not be called from an ISR. Comment
* was indeed misleading. Hopefully clear now?
* So the printf()is OK here. */
FreeRTOS_debug_printf( ( "pxGetNetworkBufferWithDescriptor: INVALID BUFFER: %p (valid %lu)\n",
pxReturn, bIsValidNetworkDescriptor( pxReturn ) ) );
pxReturn = NULL;
}
else
{
/* Reading UBaseType_t, no critical section needed. */
uxCount = listCURRENT_LIST_LENGTH( &xFreeBuffersList );
/* For stats, latch the lowest number of network buffers since
* booting. */
if( uxMinimumFreeNetworkBuffers > uxCount )
{
uxMinimumFreeNetworkBuffers = uxCount;
}
pxReturn->xDataLength = xRequestedSizeBytes;
pxReturn->pxInterface = NULL;
pxReturn->pxEndPoint = NULL;
#if ( ipconfigTCP_IP_SANITY != 0 )
{
prvShowWarnings();
}
#endif /* ipconfigTCP_IP_SANITY */
#if ( ipconfigUSE_LINKED_RX_MESSAGES != 0 )
{
/* make sure the buffer is not linked */
pxReturn->pxNextBuffer = NULL;
}
#endif /* ipconfigUSE_LINKED_RX_MESSAGES */
}
iptraceNETWORK_BUFFER_OBTAINED( pxReturn );
}
else
{
FreeRTOS_printf( ( "pxGetNetworkBufferWithDescriptor: module not initialised or `xRequestedSizeBytes` too small" ) );
/* lint wants to see at least a comment. */
iptraceFAILED_TO_OBTAIN_NETWORK_BUFFER();
}
}
return pxReturn;
}
/*-----------------------------------------------------------*/
NetworkBufferDescriptor_t * pxNetworkBufferGetFromISR( size_t xRequestedSizeBytes )
{
NetworkBufferDescriptor_t * pxReturn = NULL;
/* The current implementation only has a single size memory block, so
* the requested size parameter is not used (yet). */
( void ) xRequestedSizeBytes;
/* If there is a semaphore available then there is a buffer available, but,
* as this is called from an interrupt, only take a buffer if there are at
* least baINTERRUPT_BUFFER_GET_THRESHOLD buffers remaining. This prevents,
* to a certain degree at least, a rapidly executing interrupt exhausting
* buffer and in so doing preventing tasks from continuing. */
if( uxQueueMessagesWaitingFromISR( ( QueueHandle_t ) xNetworkBufferSemaphore ) > ( UBaseType_t ) baINTERRUPT_BUFFER_GET_THRESHOLD )
{
if( xSemaphoreTakeFromISR( xNetworkBufferSemaphore, NULL ) == pdPASS )
{
/* Protect the structure as it is accessed from tasks and interrupts. */
ipconfigBUFFER_ALLOC_LOCK_FROM_ISR();
{
pxReturn = ( NetworkBufferDescriptor_t * ) listGET_OWNER_OF_HEAD_ENTRY( &xFreeBuffersList );
uxListRemove( &( pxReturn->xBufferListItem ) );
}
ipconfigBUFFER_ALLOC_UNLOCK_FROM_ISR();
iptraceNETWORK_BUFFER_OBTAINED_FROM_ISR( pxReturn );
}
}
if( pxReturn == NULL )
{
iptraceFAILED_TO_OBTAIN_NETWORK_BUFFER_FROM_ISR();
}
return pxReturn;
}
/*-----------------------------------------------------------*/
BaseType_t vNetworkBufferReleaseFromISR( NetworkBufferDescriptor_t * const pxNetworkBuffer )
{
BaseType_t xHigherPriorityTaskWoken = pdFALSE;
/* Ensure the buffer is returned to the list of free buffers before the
* counting semaphore is 'given' to say a buffer is available. */
ipconfigBUFFER_ALLOC_LOCK_FROM_ISR();
{
vListInsertEnd( &xFreeBuffersList, &( pxNetworkBuffer->xBufferListItem ) );
}
ipconfigBUFFER_ALLOC_UNLOCK_FROM_ISR();
( void ) xSemaphoreGiveFromISR( xNetworkBufferSemaphore, &xHigherPriorityTaskWoken );
iptraceNETWORK_BUFFER_RELEASED( pxNetworkBuffer );
return xHigherPriorityTaskWoken;
}
/*-----------------------------------------------------------*/
void vReleaseNetworkBufferAndDescriptor( NetworkBufferDescriptor_t * const pxNetworkBuffer )
{
BaseType_t xListItemAlreadyInFreeList;
if( bIsValidNetworkDescriptor( pxNetworkBuffer ) == pdFALSE_UNSIGNED )
{
FreeRTOS_debug_printf( ( "vReleaseNetworkBufferAndDescriptor: Invalid buffer %p\n", pxNetworkBuffer ) );
}
else
{
/* Ensure the buffer is returned to the list of free buffers before the
* counting semaphore is 'given' to say a buffer is available. */
ipconfigBUFFER_ALLOC_LOCK();
{
{
xListItemAlreadyInFreeList = listIS_CONTAINED_WITHIN( &xFreeBuffersList, &( pxNetworkBuffer->xBufferListItem ) );
if( xListItemAlreadyInFreeList == pdFALSE )
{
vListInsertEnd( &xFreeBuffersList, &( pxNetworkBuffer->xBufferListItem ) );
}
}
}
ipconfigBUFFER_ALLOC_UNLOCK();
if( xListItemAlreadyInFreeList )
{
FreeRTOS_debug_printf( ( "vReleaseNetworkBufferAndDescriptor: %p ALREADY RELEASED (now %lu)\n",
pxNetworkBuffer, uxGetNumberOfFreeNetworkBuffers() ) );
}
else
{
( void ) xSemaphoreGive( xNetworkBufferSemaphore );
prvShowWarnings();
}
iptraceNETWORK_BUFFER_RELEASED( pxNetworkBuffer );
}
}
/*-----------------------------------------------------------*/
UBaseType_t uxGetMinimumFreeNetworkBuffers( void )
{
return uxMinimumFreeNetworkBuffers;
}
/*-----------------------------------------------------------*/
UBaseType_t uxGetNumberOfFreeNetworkBuffers( void )
{
return listCURRENT_LIST_LENGTH( &xFreeBuffersList );
}
NetworkBufferDescriptor_t * pxResizeNetworkBufferWithDescriptor( NetworkBufferDescriptor_t * pxNetworkBuffer,
size_t xNewSizeBytes )
{
if( xNewSizeBytes <= uxMaxNetworkInterfaceAllocatedSizeBytes )
{
/* In BufferAllocation_1.c all network buffer are allocated with a
* maximum size of 'ipTOTAL_ETHERNET_FRAME_SIZE'.No need to resize the
* network buffer. */
pxNetworkBuffer->xDataLength = xNewSizeBytes;
}
else
{
pxNetworkBuffer = NULL;
}
return pxNetworkBuffer;
}
/*#endif */ /* ipconfigINCLUDE_TEST_CODE */
@@ -0,0 +1,501 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://www.FreeRTOS.org
* http://aws.amazon.com/freertos
*
* 1 tab == 4 spaces!
*/
/******************************************************************************
*
* See the following web page for essential buffer allocation scheme usage and
* configuration details:
* https://freertos.org/Documentation/03-Libraries/02-FreeRTOS-plus/02-FreeRTOS-plus-TCP/05-Buffer-management
*
******************************************************************************/
/* THIS FILE SHOULD NOT BE USED IF THE PROJECT INCLUDES A MEMORY ALLOCATOR
* THAT WILL FRAGMENT THE HEAP MEMORY. For example, heap_2 must not be used,
* heap_4 can be used. */
/* Standard includes. */
#include <stdint.h>
/* FreeRTOS includes. */
#include "FreeRTOS.h"
#include "task.h"
#include "semphr.h"
/* FreeRTOS+TCP includes. */
#include "FreeRTOS_IP.h"
#include "FreeRTOS_UDP_IP.h"
#include "FreeRTOS_IP_Private.h"
#include "NetworkInterface.h"
#include "NetworkBufferManagement.h"
/* The obtained network buffer must be large enough to hold a packet that might
* replace the packet that was requested to be sent. */
#if ipconfigUSE_TCP == 1
#define baMINIMAL_BUFFER_SIZE sizeof( TCPPacket_t )
#else
#define baMINIMAL_BUFFER_SIZE sizeof( ARPPacket_t )
#endif /* ipconfigUSE_TCP == 1 */
#define baALIGNMENT_BYTES ( sizeof( size_t ) )
#define baALIGNMENT_MASK ( baALIGNMENT_BYTES - 1U )
#define baADD_WILL_OVERFLOW( a, b ) ( ( a ) > ( SIZE_MAX - ( b ) ) )
STATIC_ASSERT( ipconfigETHERNET_MINIMUM_PACKET_BYTES <= baMINIMAL_BUFFER_SIZE );
/* A list of free (available) NetworkBufferDescriptor_t structures. */
static List_t xFreeBuffersList;
/* Some statistics about the use of buffers. */
static size_t uxMinimumFreeNetworkBuffers;
/* This constant is defined as false to let FreeRTOS_TCP_IP.c know that the
* network buffers have a variable size: resizing may be necessary */
const BaseType_t xBufferAllocFixedSize = pdFALSE;
/* The semaphore used to obtain network buffers. */
static SemaphoreHandle_t xNetworkBufferSemaphore = NULL;
/*-----------------------------------------------------------*/
BaseType_t xNetworkBuffersInitialise( void )
{
/* Declares the pool of NetworkBufferDescriptor_t structures that are available
* to the system. All the network buffers referenced from xFreeBuffersList exist
* in this array. The array is not accessed directly except during initialisation,
* when the xFreeBuffersList is filled (as all the buffers are free when the system
* is booted). */
static NetworkBufferDescriptor_t xNetworkBufferDescriptors[ ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS ];
BaseType_t xReturn;
uint32_t x;
/* Only initialise the buffers and their associated kernel objects if they
* have not been initialised before. */
if( xNetworkBufferSemaphore == NULL )
{
#if ( configSUPPORT_STATIC_ALLOCATION == 1 )
{
static StaticSemaphore_t xNetworkBufferSemaphoreBuffer;
xNetworkBufferSemaphore = xSemaphoreCreateCountingStatic(
ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS,
ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS,
&xNetworkBufferSemaphoreBuffer );
}
#else
{
xNetworkBufferSemaphore = xSemaphoreCreateCounting( ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS, ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS );
}
#endif /* configSUPPORT_STATIC_ALLOCATION */
configASSERT( xNetworkBufferSemaphore != NULL );
if( xNetworkBufferSemaphore != NULL )
{
#if ( configQUEUE_REGISTRY_SIZE > 0 )
{
vQueueAddToRegistry( xNetworkBufferSemaphore, "NetBufSem" );
}
#endif /* configQUEUE_REGISTRY_SIZE */
/* If the trace recorder code is included name the semaphore for viewing
* in FreeRTOS+Trace. */
#if ( ipconfigINCLUDE_EXAMPLE_FREERTOS_PLUS_TRACE_CALLS == 1 )
{
extern QueueHandle_t xNetworkEventQueue;
vTraceSetQueueName( xNetworkEventQueue, "IPStackEvent" );
vTraceSetQueueName( xNetworkBufferSemaphore, "NetworkBufferCount" );
}
#endif /* ipconfigINCLUDE_EXAMPLE_FREERTOS_PLUS_TRACE_CALLS == 1 */
vListInitialise( &xFreeBuffersList );
/* Initialise all the network buffers. No storage is allocated to
* the buffers yet. */
for( x = 0U; x < ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS; x++ )
{
/* Initialise and set the owner of the buffer list items. */
xNetworkBufferDescriptors[ x ].pucEthernetBuffer = NULL;
vListInitialiseItem( &( xNetworkBufferDescriptors[ x ].xBufferListItem ) );
listSET_LIST_ITEM_OWNER( &( xNetworkBufferDescriptors[ x ].xBufferListItem ), &xNetworkBufferDescriptors[ x ] );
/* Currently, all buffers are available for use. */
vListInsert( &xFreeBuffersList, &( xNetworkBufferDescriptors[ x ].xBufferListItem ) );
}
uxMinimumFreeNetworkBuffers = ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS;
}
}
if( xNetworkBufferSemaphore == NULL )
{
xReturn = pdFAIL;
}
else
{
xReturn = pdPASS;
}
return xReturn;
}
/*-----------------------------------------------------------*/
uint8_t * pucGetNetworkBuffer( size_t * pxRequestedSizeBytes )
{
uint8_t * pucEthernetBuffer = NULL;
size_t uxMaxAllowedBytes = ( SIZE_MAX >> 1 );
size_t xSize = *pxRequestedSizeBytes;
size_t xBytesRequiredForAlignment, xAllocatedBytes;
BaseType_t xIntegerOverflowed = pdFALSE;
if( xSize < baMINIMAL_BUFFER_SIZE )
{
/* Buffers must be at least large enough to hold a TCP-packet with
* headers, or an ARP packet, in case TCP is not included. */
xSize = baMINIMAL_BUFFER_SIZE;
}
/* Round up xSize to the nearest multiple of N bytes,
* where N equals 'sizeof( size_t )'. */
if( ( xSize & baALIGNMENT_MASK ) != 0U )
{
xBytesRequiredForAlignment = baALIGNMENT_BYTES - ( xSize & baALIGNMENT_MASK );
if( baADD_WILL_OVERFLOW( xSize, xBytesRequiredForAlignment ) == ipFALSE_BOOL )
{
xSize += xBytesRequiredForAlignment;
}
else
{
xIntegerOverflowed = pdTRUE;
}
}
if( baADD_WILL_OVERFLOW( xSize, ipBUFFER_PADDING ) == ipFALSE_BOOL )
{
xAllocatedBytes = xSize + ipBUFFER_PADDING;
}
else
{
xIntegerOverflowed = pdTRUE;
}
if( ( xIntegerOverflowed == pdFALSE ) && ( xAllocatedBytes <= uxMaxAllowedBytes ) )
{
*pxRequestedSizeBytes = xSize;
/* Allocate a buffer large enough to store the requested Ethernet frame size
* and a pointer to a network buffer structure (hence the addition of
* ipBUFFER_PADDING bytes). */
pucEthernetBuffer = ( uint8_t * ) pvPortMalloc( xAllocatedBytes );
configASSERT( pucEthernetBuffer != NULL );
if( pucEthernetBuffer != NULL )
{
/* Enough space is left at the start of the buffer to place a pointer to
* the network buffer structure that references this Ethernet buffer.
* Return a pointer to the start of the Ethernet buffer itself. */
/* MISRA Ref 18.4.1 [Usage of +, -, += and -= operators on expression of pointer type]. */
/* More details at: https://github.com/FreeRTOS/FreeRTOS-Plus-TCP/blob/main/MISRA.md#rule-184. */
/* coverity[misra_c_2012_rule_18_4_violation] */
pucEthernetBuffer += ipBUFFER_PADDING;
}
}
return pucEthernetBuffer;
}
/*-----------------------------------------------------------*/
void vReleaseNetworkBuffer( uint8_t * pucEthernetBuffer )
{
uint8_t * pucEthernetBufferCopy = pucEthernetBuffer;
/* There is space before the Ethernet buffer in which a pointer to the
* network buffer that references this Ethernet buffer is stored. Remove the
* space before freeing the buffer. */
if( pucEthernetBufferCopy != NULL )
{
/* MISRA Ref 18.4.1 [Usage of +, -, += and -= operators on expression of pointer type]. */
/* More details at: https://github.com/FreeRTOS/FreeRTOS-Plus-TCP/blob/main/MISRA.md#rule-184. */
/* coverity[misra_c_2012_rule_18_4_violation] */
pucEthernetBufferCopy -= ipBUFFER_PADDING;
vPortFree( ( void * ) pucEthernetBufferCopy );
}
}
/*-----------------------------------------------------------*/
NetworkBufferDescriptor_t * pxGetNetworkBufferWithDescriptor( size_t xRequestedSizeBytes,
TickType_t xBlockTimeTicks )
{
NetworkBufferDescriptor_t * pxReturn = NULL;
size_t uxCount;
size_t uxMaxAllowedBytes = ( SIZE_MAX >> 1 );
size_t xRequestedSizeBytesCopy = xRequestedSizeBytes;
size_t xBytesRequiredForAlignment, xAllocatedBytes;
BaseType_t xIntegerOverflowed = pdFALSE;
if( ( xRequestedSizeBytesCopy < ( size_t ) baMINIMAL_BUFFER_SIZE ) )
{
/* ARP packets can replace application packets, so the storage must be
* at least large enough to hold an ARP. */
xRequestedSizeBytesCopy = baMINIMAL_BUFFER_SIZE;
}
/* Add 2 bytes to xRequestedSizeBytesCopy and round up xRequestedSizeBytesCopy
* to the nearest multiple of N bytes, where N equals 'sizeof( size_t )'. */
if( baADD_WILL_OVERFLOW( xRequestedSizeBytesCopy, 2U ) == ipFALSE_BOOL )
{
xRequestedSizeBytesCopy += 2U;
}
else
{
xIntegerOverflowed = pdTRUE;
}
if( ( xRequestedSizeBytesCopy & baALIGNMENT_MASK ) != 0U )
{
xBytesRequiredForAlignment = baALIGNMENT_BYTES - ( xRequestedSizeBytesCopy & baALIGNMENT_MASK );
if( baADD_WILL_OVERFLOW( xRequestedSizeBytesCopy, xBytesRequiredForAlignment ) == ipFALSE_BOOL )
{
xRequestedSizeBytesCopy += xBytesRequiredForAlignment;
}
else
{
xIntegerOverflowed = pdTRUE;
}
}
if( baADD_WILL_OVERFLOW( xRequestedSizeBytesCopy, ipBUFFER_PADDING ) == ipFALSE_BOOL )
{
xAllocatedBytes = xRequestedSizeBytesCopy + ipBUFFER_PADDING;
}
else
{
xIntegerOverflowed = pdTRUE;
}
if( ( xIntegerOverflowed == pdFALSE ) && ( xAllocatedBytes <= uxMaxAllowedBytes ) && ( xNetworkBufferSemaphore != NULL ) )
{
/* If there is a semaphore available, there is a network buffer available. */
if( xSemaphoreTake( xNetworkBufferSemaphore, xBlockTimeTicks ) == pdPASS )
{
/* Protect the structure as it is accessed from tasks and interrupts. */
taskENTER_CRITICAL();
{
pxReturn = ( NetworkBufferDescriptor_t * ) listGET_OWNER_OF_HEAD_ENTRY( &xFreeBuffersList );
( void ) uxListRemove( &( pxReturn->xBufferListItem ) );
}
taskEXIT_CRITICAL();
/* Reading UBaseType_t, no critical section needed. */
uxCount = listCURRENT_LIST_LENGTH( &xFreeBuffersList );
if( uxMinimumFreeNetworkBuffers > uxCount )
{
uxMinimumFreeNetworkBuffers = uxCount;
}
/* Allocate storage of exactly the requested size to the buffer. */
configASSERT( pxReturn->pucEthernetBuffer == NULL );
if( xRequestedSizeBytesCopy > 0U )
{
/* Extra space is obtained so a pointer to the network buffer can
* be stored at the beginning of the buffer. */
pxReturn->pucEthernetBuffer = ( uint8_t * ) pvPortMalloc( xAllocatedBytes );
if( pxReturn->pucEthernetBuffer == NULL )
{
/* The attempt to allocate storage for the buffer payload failed,
* so the network buffer structure cannot be used and must be
* released. */
vReleaseNetworkBufferAndDescriptor( pxReturn );
pxReturn = NULL;
}
else
{
/* Store a pointer to the network buffer structure in the
* buffer storage area, then move the buffer pointer on past the
* stored pointer so the pointer value is not overwritten by the
* application when the buffer is used. */
/* MISRA Ref 11.3.1 [Misaligned access] */
/* More details at: https://github.com/FreeRTOS/FreeRTOS-Plus-TCP/blob/main/MISRA.md#rule-113 */
/* coverity[misra_c_2012_rule_11_3_violation] */
*( ( NetworkBufferDescriptor_t ** ) ( pxReturn->pucEthernetBuffer ) ) = pxReturn;
/* MISRA Ref 18.4.1 [Usage of +, -, += and -= operators on expression of pointer type]. */
/* More details at: https://github.com/FreeRTOS/FreeRTOS-Plus-TCP/blob/main/MISRA.md#rule-184. */
/* coverity[misra_c_2012_rule_18_4_violation] */
pxReturn->pucEthernetBuffer += ipBUFFER_PADDING;
/* Store the actual size of the allocated buffer, which may be
* greater than the original requested size. */
pxReturn->xDataLength = xRequestedSizeBytesCopy;
pxReturn->pxInterface = NULL;
pxReturn->pxEndPoint = NULL;
#if ( ipconfigUSE_LINKED_RX_MESSAGES != 0 )
{
/* make sure the buffer is not linked */
pxReturn->pxNextBuffer = NULL;
}
#endif /* ipconfigUSE_LINKED_RX_MESSAGES */
}
}
else
{
/* A descriptor is being returned without an associated buffer being
* allocated. */
}
}
}
if( pxReturn == NULL )
{
iptraceFAILED_TO_OBTAIN_NETWORK_BUFFER();
}
else
{
/* No action. */
iptraceNETWORK_BUFFER_OBTAINED( pxReturn );
}
return pxReturn;
}
/*-----------------------------------------------------------*/
void vReleaseNetworkBufferAndDescriptor( NetworkBufferDescriptor_t * const pxNetworkBuffer )
{
BaseType_t xListItemAlreadyInFreeList;
/* Ensure the buffer is returned to the list of free buffers before the
* counting semaphore is 'given' to say a buffer is available. Release the
* storage allocated to the buffer payload. THIS FILE SHOULD NOT BE USED
* IF THE PROJECT INCLUDES A MEMORY ALLOCATOR THAT WILL FRAGMENT THE HEAP
* MEMORY. For example, heap_2 must not be used, heap_4 can be used. */
vReleaseNetworkBuffer( pxNetworkBuffer->pucEthernetBuffer );
pxNetworkBuffer->pucEthernetBuffer = NULL;
pxNetworkBuffer->xDataLength = 0U;
taskENTER_CRITICAL();
{
xListItemAlreadyInFreeList = listIS_CONTAINED_WITHIN( &xFreeBuffersList, &( pxNetworkBuffer->xBufferListItem ) );
if( xListItemAlreadyInFreeList == pdFALSE )
{
vListInsertEnd( &xFreeBuffersList, &( pxNetworkBuffer->xBufferListItem ) );
}
}
taskEXIT_CRITICAL();
/*
* Update the network state machine, unless the program fails to release its 'xNetworkBufferSemaphore'.
* The program should only try to release its semaphore if 'xListItemAlreadyInFreeList' is false.
*/
if( xListItemAlreadyInFreeList == pdFALSE )
{
if( xSemaphoreGive( xNetworkBufferSemaphore ) == pdTRUE )
{
iptraceNETWORK_BUFFER_RELEASED( pxNetworkBuffer );
}
}
else
{
/* No action. */
iptraceNETWORK_BUFFER_RELEASED( pxNetworkBuffer );
}
}
/*-----------------------------------------------------------*/
/*
* Returns the number of free network buffers
*/
UBaseType_t uxGetNumberOfFreeNetworkBuffers( void )
{
return listCURRENT_LIST_LENGTH( &xFreeBuffersList );
}
/*-----------------------------------------------------------*/
UBaseType_t uxGetMinimumFreeNetworkBuffers( void )
{
return uxMinimumFreeNetworkBuffers;
}
/*-----------------------------------------------------------*/
NetworkBufferDescriptor_t * pxResizeNetworkBufferWithDescriptor( NetworkBufferDescriptor_t * pxNetworkBuffer,
size_t xNewSizeBytes )
{
size_t xOriginalLength;
uint8_t * pucBuffer;
size_t uxSizeBytes = xNewSizeBytes;
NetworkBufferDescriptor_t * pxNetworkBufferCopy = pxNetworkBuffer;
xOriginalLength = pxNetworkBufferCopy->xDataLength + ipBUFFER_PADDING;
if( baADD_WILL_OVERFLOW( uxSizeBytes, ipBUFFER_PADDING ) == ipFALSE_BOOL )
{
uxSizeBytes = uxSizeBytes + ipBUFFER_PADDING;
pucBuffer = pucGetNetworkBuffer( &( uxSizeBytes ) );
if( pucBuffer == NULL )
{
/* In case the allocation fails, return NULL. */
pxNetworkBufferCopy = NULL;
}
else
{
pxNetworkBufferCopy->xDataLength = uxSizeBytes;
if( uxSizeBytes > xOriginalLength )
{
uxSizeBytes = xOriginalLength;
}
/* MISRA Ref 18.4.1 [Usage of +, -, += and -= operators on expression of pointer type]. */
/* More details at: https://github.com/FreeRTOS/FreeRTOS-Plus-TCP/blob/main/MISRA.md#rule-184. */
/* coverity[misra_c_2012_rule_18_4_violation] */
( void ) memcpy( pucBuffer - ipBUFFER_PADDING,
/* MISRA Ref 18.4.1 [Usage of +, -, += and -= operators on expression of pointer type]. */
/* More details at: https://github.com/FreeRTOS/FreeRTOS-Plus-TCP/blob/main/MISRA.md#rule-184. */
/* coverity[misra_c_2012_rule_18_4_violation] */
pxNetworkBufferCopy->pucEthernetBuffer - ipBUFFER_PADDING,
uxSizeBytes );
vReleaseNetworkBuffer( pxNetworkBufferCopy->pucEthernetBuffer );
pxNetworkBufferCopy->pucEthernetBuffer = pucBuffer;
}
}
else
{
pxNetworkBufferCopy = NULL;
}
return pxNetworkBufferCopy;
}
@@ -0,0 +1,37 @@
add_library( freertos_plus_tcp_port STATIC )
target_sources( freertos_plus_tcp_port
PRIVATE
BufferManagement/BufferAllocation_${FREERTOS_PLUS_TCP_BUFFER_ALLOCATION}.c
# Note: There's NetworkInterface/pic32mzef that has it's own BufferAllocation_2.c
)
target_include_directories( freertos_plus_tcp_port
PUBLIC
# Using Cmake to detect except for unknown compilers.
$<$<STREQUAL:${FREERTOS_PLUS_TCP_COMPILER},CCS>:${CMAKE_CURRENT_SOURCE_DIR}/Compiler/CCS>
$<$<C_COMPILER_ID:CCS>:${CMAKE_CURRENT_SOURCE_DIR}/Compiler/CCS>
$<$<C_COMPILER_ID:GNU,Clang,ARMClang>:${CMAKE_CURRENT_SOURCE_DIR}/Compiler/GCC>
$<$<C_COMPILER_ID:Tasking>:${CMAKE_CURRENT_SOURCE_DIR}/Compiler/Tasking>
$<$<C_COMPILER_ID:IAR>:${CMAKE_CURRENT_SOURCE_DIR}/Compiler/IAR>
$<$<C_COMPILER_ID:ARMCC>:${CMAKE_CURRENT_SOURCE_DIR}/Compiler/Keil>
$<$<C_COMPILER_ID:MSVC>:${CMAKE_CURRENT_SOURCE_DIR}/Compiler/MSVC>
$<$<STREQUAL:${FREERTOS_PLUS_TCP_COMPILER},Renesas>:${CMAKE_CURRENT_SOURCE_DIR}/Compiler/Renesas>
)
target_compile_options( freertos_plus_tcp_port
PRIVATE
$<$<COMPILE_LANG_AND_ID:C,Clang>:-Wno-cast-align>
$<$<COMPILE_LANG_AND_ID:C,Clang>:-Wno-extra-semi-stmt>
$<$<COMPILE_LANG_AND_ID:C,GNU>:-Wno-pedantic> # Strange definition for STATIC_ASSERT
)
target_link_libraries( freertos_plus_tcp_port
PRIVATE
freertos_kernel
freertos_plus_tcp
freertos_plus_tcp_network_if
)
#------------------------------------------------------------------------------
add_subdirectory(NetworkInterface)
@@ -0,0 +1,34 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
/*****************************************************************************
*
* See the following URL for an explanation of this file:
* https://freertos.org/Documentation/03-Libraries/02-FreeRTOS-plus/02-FreeRTOS-plus-TCP/10-Porting/02-Embedded_Compiler_Porting
*
*****************************************************************************/
__attribute__( ( packed ) );
@@ -0,0 +1,35 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
/*****************************************************************************
*
* See the following URL for an explanation of this file:
* https://freertos.org/Documentation/03-Libraries/02-FreeRTOS-plus/02-FreeRTOS-plus-TCP/10-Porting/02-Embedded_Compiler_Porting
*
*****************************************************************************/
/* Nothing to do here. */
@@ -0,0 +1,36 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
/*****************************************************************************
*
* See the following URL for an explanation of this file:
* https://freertos.org/Documentation/03-Libraries/02-FreeRTOS-plus/02-FreeRTOS-plus-TCP/10-Porting/02-Embedded_Compiler_Porting
*
*****************************************************************************/
;
#pragma pack( pop )
@@ -0,0 +1,35 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
/*****************************************************************************
*
* See the following URL for an explanation of this file:
* https://freertos.org/Documentation/03-Libraries/02-FreeRTOS-plus/02-FreeRTOS-plus-TCP/10-Porting/02-Embedded_Compiler_Porting
*
*****************************************************************************/
#pragma pack( push, 1 )
@@ -0,0 +1,57 @@
add_library( freertos_plus_tcp_network_if_common STATIC )
target_sources( freertos_plus_tcp_network_if_common
PRIVATE
Common/phyHandling.c
include/phyHandling.h
)
target_include_directories( freertos_plus_tcp_network_if_common
PUBLIC
include
)
target_compile_options( freertos_plus_tcp_network_if_common
PRIVATE
$<$<COMPILE_LANG_AND_ID:C,Clang>:-Wno-conditional-uninitialized>
$<$<COMPILE_LANG_AND_ID:C,Clang>:-Wno-implicit-int-conversion>
$<$<COMPILE_LANG_AND_ID:C,Clang>:-Wno-padded>
$<$<COMPILE_LANG_AND_ID:C,Clang>:-Wno-uninitialized>
$<$<COMPILE_LANG_AND_ID:C,Clang>:-Wno-unused-but-set-variable>
$<$<COMPILE_LANG_AND_ID:C,Clang>:-Wno-unused-macros>
)
target_link_libraries( freertos_plus_tcp_network_if_common
PRIVATE
freertos_kernel
freertos_plus_tcp
)
#------------------------------------------------------------------------------
add_subdirectory(ATSAM4E)
add_subdirectory(ATSAME5x)
#add_subdirectory(board_family) - This is only an example.
add_subdirectory(DriverSAM)
add_subdirectory(esp32)
add_subdirectory(ksz8851snl)
add_subdirectory(libslirp)
add_subdirectory(linux)
add_subdirectory(loopback)
add_subdirectory(LPC17xx)
add_subdirectory(LPC18xx)
add_subdirectory(LPC54018)
add_subdirectory(M487)
add_subdirectory(MPS2_AN385)
add_subdirectory(MPS3_AN552)
add_subdirectory(MPS4_CS315)
add_subdirectory(NXP1060)
add_subdirectory(mw300_rd)
add_subdirectory(pic32mzef)
add_subdirectory(RX)
add_subdirectory(SH2A)
add_subdirectory(STM32)
add_subdirectory(ThirdParty/MSP432)
add_subdirectory(TM4C)
add_subdirectory(WinPCap)
add_subdirectory(xilinx_ultrascale)
add_subdirectory(Zynq)
@@ -0,0 +1,831 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
/**
* @brief
* Handling of Ethernet PHY's
* PHY's communicate with an EMAC either through
* a Media-Independent Interface (MII), or a Reduced Media-Independent Interface (RMII).
* The EMAC can poll for PHY ports on 32 different addresses. Each of the PHY ports
* shall be treated independently.
*
*/
/* Standard includes. */
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
/* FreeRTOS includes. */
#include "FreeRTOS.h"
#include "task.h"
#include "queue.h"
#include "semphr.h"
/* FreeRTOS+TCP includes. */
#include "FreeRTOS_IP.h"
#include "FreeRTOS_Sockets.h"
#include "phyHandling.h"
#define phyMIN_PHY_ADDRESS 0
#define phyMAX_PHY_ADDRESS 31
/* As the following 3 macro's are OK in most situations, and so they're not
* included in 'FreeRTOSIPConfigDefaults.h'.
* Users can change their values in the project's 'FreeRTOSIPConfig.h'. */
#ifndef phyPHY_MAX_RESET_TIME_MS
#define phyPHY_MAX_RESET_TIME_MS 1000U
#endif
#ifndef phyPHY_MAX_NEGOTIATE_TIME_MS
#define phyPHY_MAX_NEGOTIATE_TIME_MS 3000U
#endif
#ifndef phySHORT_DELAY_MS
#define phySHORT_DELAY_MS 50U
#endif
/* Naming and numbering of basic PHY registers. */
#define phyREG_00_BMCR 0x00U /* Basic Mode Control Register. */
#define phyREG_01_BMSR 0x01U /* Basic Mode Status Register. */
#define phyREG_02_PHYSID1 0x02U /* PHYS ID 1 */
#define phyREG_03_PHYSID2 0x03U /* PHYS ID 2 */
#define phyREG_04_ADVERTISE 0x04U /* Advertisement control reg */
/* Naming and numbering of extended PHY registers. */
#define PHYREG_10_PHYSTS 0x10U /* 16 PHY status register Offset */
#define phyREG_19_PHYCR 0x19U /* 25 RW PHY Control Register */
#define phyREG_1F_PHYSPCS 0x1FU /* 31 RW PHY Special Control Status */
/* Bit fields for 'phyREG_00_BMCR', the 'Basic Mode Control Register'. */
#define phyBMCR_FULL_DUPLEX 0x0100U /* Full duplex. */
#define phyBMCR_AN_RESTART 0x0200U /* Auto negotiation restart. */
#define phyBMCR_ISOLATE 0x0400U /* 1 = Isolates 0 = Normal operation. */
#define phyBMCR_AN_ENABLE 0x1000U /* Enable auto negotiation. */
#define phyBMCR_SPEED_100 0x2000U /* Select 100Mbps. */
#define phyBMCR_RESET 0x8000U /* Reset the PHY. */
/* Bit fields for 'phyREG_19_PHYCR', the 'PHY Control Register'. */
#define PHYCR_MDIX_EN 0x8000U /* Enable Auto MDIX. */
#define PHYCR_MDIX_FORCE 0x4000U /* Force MDIX crossed. */
#define phyBMSR_AN_COMPLETE 0x0020U /* Auto-Negotiation process completed */
#define phyBMSR_LINK_STATUS 0x0004U
#define phyPHYSTS_LINK_STATUS 0x0001U /* PHY Link mask */
#define phyPHYSTS_SPEED_STATUS 0x0002U /* PHY Speed mask */
#define phyPHYSTS_DUPLEX_STATUS 0x0004U /* PHY Duplex mask */
/* Bit fields for 'phyREG_1F_PHYSPCS
* 001 = 10BASE-T half-duplex
* 101 = 10BASE-T full-duplex
* 010 = 100BASE-TX half-duplex
* 110 = 100BASE-TX full-duplex
*/
#define phyPHYSPCS_SPEED_MASK 0x000CU
#define phyPHYSPCS_SPEED_10 0x0004U
#define phyPHYSPCS_FULL_DUPLEX 0x0010U
/*
* Description of all capabilities that can be advertised to
* the peer (usually a switch or router).
*/
#define phyADVERTISE_CSMA 0x0001U /* Supports IEEE 802.3u: Fast Ethernet at 100 Mbit/s */
#define phyADVERTISE_10HALF 0x0020U /* Try for 10mbps half-duplex. */
#define phyADVERTISE_10FULL 0x0040U /* Try for 10mbps full-duplex. */
#define phyADVERTISE_100HALF 0x0080U /* Try for 100mbps half-duplex. */
#define phyADVERTISE_100FULL 0x0100U /* Try for 100mbps full-duplex. */
#define phyADVERTISE_ALL \
( phyADVERTISE_10HALF | phyADVERTISE_10FULL | \
phyADVERTISE_100HALF | phyADVERTISE_100FULL | \
phyADVERTISE_CSMA )
/* Send a reset command to a set of PHY-ports. */
static uint32_t xPhyReset( EthernetPhy_t * pxPhyObject,
uint32_t ulPhyMask );
static BaseType_t xHas_1F_PHYSPCS( uint32_t ulPhyID )
{
BaseType_t xResult = pdFALSE;
switch( ulPhyID )
{
case PHY_ID_LAN8720:
case PHY_ID_LAN8742A:
case PHY_ID_KSZ8041:
/*
* case PHY_ID_KSZ8051: // same ID as 8041
* case PHY_ID_KSZ8081: // same ID as 8041
*/
case PHY_ID_KSZ8081MNXIA:
case PHY_ID_KSZ8863:
default:
/* Most PHY's have a 1F_PHYSPCS */
xResult = pdTRUE;
break;
case PHY_ID_DP83848I:
case PHY_ID_DP83TC811S:
case PHY_ID_TM4C129X:
case PHY_ID_MV88E6071:
/* Has no 0x1F register "PHY Special Control Status". */
break;
}
return xResult;
}
/*-----------------------------------------------------------*/
static BaseType_t xHas_19_PHYCR( uint32_t ulPhyID )
{
BaseType_t xResult = pdFALSE;
switch( ulPhyID )
{
case PHY_ID_LAN8742A:
case PHY_ID_DP83848I:
case PHY_ID_TM4C129X:
xResult = pdTRUE;
break;
case PHY_ID_MV88E6071: /* Marvell 88E6071 */
default:
/* Most PHY's do not have a 19_PHYCR */
break;
}
return xResult;
}
/*-----------------------------------------------------------*/
/* Initialise the struct and assign a PHY-read and -write function. */
void vPhyInitialise( EthernetPhy_t * pxPhyObject,
xApplicationPhyReadHook_t fnPhyRead,
xApplicationPhyWriteHook_t fnPhyWrite )
{
memset( ( void * ) pxPhyObject, 0, sizeof( *pxPhyObject ) );
pxPhyObject->fnPhyRead = fnPhyRead;
pxPhyObject->fnPhyWrite = fnPhyWrite;
}
/*-----------------------------------------------------------*/
/* Discover all PHY's connected by polling 32 indexes ( zero-based ) */
BaseType_t xPhyDiscover( EthernetPhy_t * pxPhyObject )
{
BaseType_t xPhyAddress;
pxPhyObject->xPortCount = 0;
for( xPhyAddress = phyMIN_PHY_ADDRESS; xPhyAddress <= phyMAX_PHY_ADDRESS; xPhyAddress++ )
{
uint32_t ulLowerID = 0U;
pxPhyObject->fnPhyRead( xPhyAddress, phyREG_03_PHYSID2, &ulLowerID );
/* A valid PHY id can not be all zeros or all ones. */
if( ( ulLowerID != ( uint16_t ) ~0U ) && ( ulLowerID != ( uint16_t ) 0U ) )
{
uint32_t ulUpperID;
uint32_t ulPhyID;
pxPhyObject->fnPhyRead( xPhyAddress, phyREG_02_PHYSID1, &ulUpperID );
ulPhyID = ( ( ( uint32_t ) ulUpperID ) << 16 ) | ( ulLowerID & 0xFFF0U );
pxPhyObject->ucPhyIndexes[ pxPhyObject->xPortCount ] = ( uint8_t ) xPhyAddress;
pxPhyObject->ulPhyIDs[ pxPhyObject->xPortCount ] = ulPhyID;
pxPhyObject->xPortCount++;
/* See if there is more storage space. */
if( pxPhyObject->xPortCount == ipconfigPHY_MAX_PORTS )
{
break;
}
}
}
if( pxPhyObject->xPortCount > 0 )
{
FreeRTOS_printf( ( "PHY ID %X\n", ( unsigned int ) pxPhyObject->ulPhyIDs[ 0 ] ) );
}
return pxPhyObject->xPortCount;
}
/*-----------------------------------------------------------*/
/* Send a reset command to a set of PHY-ports. */
static uint32_t xPhyReset( EthernetPhy_t * pxPhyObject,
uint32_t ulPhyMask )
{
uint32_t ulDoneMask, ulConfig;
TickType_t xRemainingTime;
TimeOut_t xTimer;
BaseType_t xPhyIndex;
/* A bit-mask of PHY ports that are ready. */
ulDoneMask = 0U;
/* Set the RESET bits high. */
for( xPhyIndex = 0; xPhyIndex < pxPhyObject->xPortCount; xPhyIndex++ )
{
BaseType_t xPhyAddress = pxPhyObject->ucPhyIndexes[ xPhyIndex ];
/* Read Control register. */
pxPhyObject->fnPhyRead( xPhyAddress, phyREG_00_BMCR, &ulConfig );
pxPhyObject->fnPhyWrite( xPhyAddress, phyREG_00_BMCR, ulConfig | phyBMCR_RESET );
}
xRemainingTime = ( TickType_t ) pdMS_TO_TICKS( phyPHY_MAX_RESET_TIME_MS );
vTaskSetTimeOutState( &xTimer );
/* The reset should last less than a second. */
for( ; ; )
{
for( xPhyIndex = 0; xPhyIndex < pxPhyObject->xPortCount; xPhyIndex++ )
{
BaseType_t xPhyAddress = pxPhyObject->ucPhyIndexes[ xPhyIndex ];
pxPhyObject->fnPhyRead( xPhyAddress, phyREG_00_BMCR, &ulConfig );
if( ( ulConfig & phyBMCR_RESET ) == 0 )
{
FreeRTOS_printf( ( "xPhyReset: phyBMCR_RESET %d ready\n", ( int ) xPhyIndex ) );
ulDoneMask |= ( 1U << xPhyIndex );
}
}
if( ulDoneMask == ulPhyMask )
{
break;
}
if( xTaskCheckForTimeOut( &xTimer, &xRemainingTime ) != pdFALSE )
{
FreeRTOS_printf( ( "xPhyReset: phyBMCR_RESET timed out ( done 0x%02X )\n", ( unsigned int ) ulDoneMask ) );
break;
}
/* Block for a while */
vTaskDelay( pdMS_TO_TICKS( phySHORT_DELAY_MS ) );
}
/* Clear the reset bits. */
for( xPhyIndex = 0; xPhyIndex < pxPhyObject->xPortCount; xPhyIndex++ )
{
if( ( ulDoneMask & ( 1U << xPhyIndex ) ) == 0U )
{
BaseType_t xPhyAddress = pxPhyObject->ucPhyIndexes[ xPhyIndex ];
/* The reset operation timed out, clear the bit manually. */
pxPhyObject->fnPhyRead( xPhyAddress, phyREG_00_BMCR, &ulConfig );
pxPhyObject->fnPhyWrite( xPhyAddress, phyREG_00_BMCR, ulConfig & ~phyBMCR_RESET );
}
}
vTaskDelay( pdMS_TO_TICKS( phySHORT_DELAY_MS ) );
return ulDoneMask;
}
/*-----------------------------------------------------------*/
BaseType_t xPhyConfigure( EthernetPhy_t * pxPhyObject,
const PhyProperties_t * pxPhyProperties )
{
uint32_t ulConfig, ulAdvertise;
BaseType_t xPhyIndex;
if( pxPhyObject->xPortCount < 1 )
{
FreeRTOS_printf( ( "xPhyConfigure: No PHY's detected.\n" ) );
return -1;
}
/* The expected ID for the 'LAN8742A' is 0x0007c130. */
/* The expected ID for the 'LAN8720' is 0x0007c0f0. */
/* The expected ID for the 'DP83848I' is 0x20005C90. */
/* Set advertise register. */
if( ( pxPhyProperties->ucSpeed == ( uint8_t ) PHY_SPEED_AUTO ) && ( pxPhyProperties->ucDuplex == ( uint8_t ) PHY_DUPLEX_AUTO ) )
{
ulAdvertise = phyADVERTISE_ALL;
/* Reset auto-negotiation capability. */
}
else
{
/* Always select protocol 802.3u. */
ulAdvertise = phyADVERTISE_CSMA;
if( pxPhyProperties->ucSpeed == ( uint8_t ) PHY_SPEED_AUTO )
{
if( pxPhyProperties->ucDuplex == ( uint8_t ) PHY_DUPLEX_FULL )
{
ulAdvertise |= phyADVERTISE_10FULL | phyADVERTISE_100FULL;
}
else
{
ulAdvertise |= phyADVERTISE_10HALF | phyADVERTISE_100HALF;
}
}
else if( pxPhyProperties->ucDuplex == ( uint8_t ) PHY_DUPLEX_AUTO )
{
if( pxPhyProperties->ucSpeed == ( uint8_t ) PHY_SPEED_10 )
{
ulAdvertise |= phyADVERTISE_10FULL | phyADVERTISE_10HALF;
}
else
{
ulAdvertise |= phyADVERTISE_100FULL | phyADVERTISE_100HALF;
}
}
else if( pxPhyProperties->ucSpeed == ( uint8_t ) PHY_SPEED_100 )
{
if( pxPhyProperties->ucDuplex == ( uint8_t ) PHY_DUPLEX_FULL )
{
ulAdvertise |= phyADVERTISE_100FULL;
}
else
{
ulAdvertise |= phyADVERTISE_100HALF;
}
}
else
{
if( pxPhyProperties->ucDuplex == ( uint8_t ) PHY_DUPLEX_FULL )
{
ulAdvertise |= phyADVERTISE_10FULL;
}
else
{
ulAdvertise |= phyADVERTISE_10HALF;
}
}
}
/* Send a reset command to a set of PHY-ports. */
xPhyReset( pxPhyObject, xPhyGetMask( pxPhyObject ) );
for( xPhyIndex = 0; xPhyIndex < pxPhyObject->xPortCount; xPhyIndex++ )
{
BaseType_t xPhyAddress = pxPhyObject->ucPhyIndexes[ xPhyIndex ];
uint32_t ulPhyID = pxPhyObject->ulPhyIDs[ xPhyIndex ];
/* Write advertise register. */
pxPhyObject->fnPhyWrite( xPhyAddress, phyREG_04_ADVERTISE, ulAdvertise );
/*
* AN_EN AN1 AN0 Forced Mode
* 0 0 0 10BASE-T, Half-Duplex
* 0 0 1 10BASE-T, Full-Duplex
* 0 1 0 100BASE-TX, Half-Duplex
* 0 1 1 100BASE-TX, Full-Duplex
* AN_EN AN1 AN0 Advertised Mode
* 1 0 0 10BASE-T, Half/Full-Duplex
* 1 0 1 100BASE-TX, Half/Full-Duplex
* 1 1 0 10BASE-T Half-Duplex
* 100BASE-TX, Half-Duplex
* 1 1 1 10BASE-T, Half/Full-Duplex
* 100BASE-TX, Half/Full-Duplex
*/
/* Read Control register. */
pxPhyObject->fnPhyRead( xPhyAddress, phyREG_00_BMCR, &ulConfig );
ulConfig &= ~( phyBMCR_SPEED_100 | phyBMCR_FULL_DUPLEX );
ulConfig |= phyBMCR_AN_ENABLE;
if( ( pxPhyProperties->ucSpeed == ( uint8_t ) PHY_SPEED_100 ) || ( pxPhyProperties->ucSpeed == ( uint8_t ) PHY_SPEED_AUTO ) )
{
ulConfig |= phyBMCR_SPEED_100;
}
else if( pxPhyProperties->ucSpeed == ( uint8_t ) PHY_SPEED_10 )
{
ulConfig &= ~phyBMCR_SPEED_100;
}
if( ( pxPhyProperties->ucDuplex == ( uint8_t ) PHY_DUPLEX_FULL ) || ( pxPhyProperties->ucDuplex == ( uint8_t ) PHY_DUPLEX_AUTO ) )
{
ulConfig |= phyBMCR_FULL_DUPLEX;
}
else if( pxPhyProperties->ucDuplex == ( uint8_t ) PHY_DUPLEX_HALF )
{
ulConfig &= ~phyBMCR_FULL_DUPLEX;
}
if( xHas_19_PHYCR( ulPhyID ) )
{
uint32_t ulPhyControl;
/* Read PHY Control register. */
pxPhyObject->fnPhyRead( xPhyAddress, phyREG_19_PHYCR, &ulPhyControl );
/* Clear bits which might get set: */
ulPhyControl &= ~( PHYCR_MDIX_EN | PHYCR_MDIX_FORCE );
if( pxPhyProperties->ucMDI_X == PHY_MDIX_AUTO )
{
ulPhyControl |= PHYCR_MDIX_EN;
}
else if( pxPhyProperties->ucMDI_X == PHY_MDIX_CROSSED )
{
/* Force direct link = Use crossed RJ45 cable. */
ulPhyControl &= ~PHYCR_MDIX_FORCE;
}
else
{
/* Force crossed link = Use direct RJ45 cable. */
ulPhyControl |= PHYCR_MDIX_FORCE;
}
/* update PHY Control Register. */
pxPhyObject->fnPhyWrite( xPhyAddress, phyREG_19_PHYCR, ulPhyControl );
}
FreeRTOS_printf( ( "+TCP: advertise: %04X config %04X\n", ( unsigned int ) ulAdvertise, ( unsigned int ) ulConfig ) );
}
/* Keep these values for later use. */
pxPhyObject->ulBCRValue = ulConfig & ~phyBMCR_ISOLATE;
pxPhyObject->ulACRValue = ulAdvertise;
return 0;
}
/*-----------------------------------------------------------*/
/* xPhyFixedValue(): this function is called in case auto-negotiation is disabled.
* The caller has set the values in 'xPhyPreferences' (ucDuplex and ucSpeed).
* The PHY register phyREG_00_BMCR will be set for every connected PHY that matches
* with ulPhyMask. */
BaseType_t xPhyFixedValue( EthernetPhy_t * pxPhyObject,
uint32_t ulPhyMask )
{
BaseType_t xPhyIndex;
uint32_t ulValue, ulBitMask = ( uint32_t ) 1U;
ulValue = ( uint32_t ) 0U;
if( pxPhyObject->xPhyPreferences.ucDuplex == PHY_DUPLEX_FULL )
{
ulValue |= phyBMCR_FULL_DUPLEX;
}
if( pxPhyObject->xPhyPreferences.ucSpeed == PHY_SPEED_100 )
{
ulValue |= phyBMCR_SPEED_100;
}
for( xPhyIndex = 0; xPhyIndex < pxPhyObject->xPortCount; xPhyIndex++, ulBitMask <<= 1 )
{
if( ( ulPhyMask & ulBitMask ) != 0lu )
{
BaseType_t xPhyAddress = pxPhyObject->ucPhyIndexes[ xPhyIndex ];
/* Enable Auto-Negotiation. */
pxPhyObject->fnPhyWrite( xPhyAddress, phyREG_00_BMCR, ulValue );
}
}
return 0;
}
/*-----------------------------------------------------------*/
/* xPhyStartAutoNegotiation() is the alternative xPhyFixedValue():
* It sets the BMCR_AN_RESTART bit and waits for the auto-negotiation completion
* ( phyBMSR_AN_COMPLETE ). */
BaseType_t xPhyStartAutoNegotiation( EthernetPhy_t * pxPhyObject,
uint32_t ulPhyMask )
{
uint32_t xPhyIndex, ulDoneMask, ulBitMask;
uint32_t ulRegValue;
TickType_t xRemainingTime;
TimeOut_t xTimer;
if( ulPhyMask == ( uint32_t ) 0U )
{
return 0;
}
for( xPhyIndex = 0; xPhyIndex < ( uint32_t ) pxPhyObject->xPortCount; xPhyIndex++ )
{
if( ( ulPhyMask & ( 1lu << xPhyIndex ) ) != 0lu )
{
BaseType_t xPhyAddress = pxPhyObject->ucPhyIndexes[ xPhyIndex ];
/* Enable Auto-Negotiation. */
pxPhyObject->fnPhyWrite( xPhyAddress, phyREG_04_ADVERTISE, pxPhyObject->ulACRValue );
pxPhyObject->fnPhyWrite( xPhyAddress, phyREG_00_BMCR, pxPhyObject->ulBCRValue | phyBMCR_AN_RESTART );
}
}
xRemainingTime = ( TickType_t ) pdMS_TO_TICKS( phyPHY_MAX_NEGOTIATE_TIME_MS );
vTaskSetTimeOutState( &xTimer );
ulDoneMask = 0;
/* Wait until the auto-negotiation will be completed */
for( ; ; )
{
ulBitMask = ( uint32_t ) 1U;
for( xPhyIndex = 0; xPhyIndex < ( uint32_t ) pxPhyObject->xPortCount; xPhyIndex++, ulBitMask <<= 1 )
{
if( ( ulPhyMask & ulBitMask ) != 0lu )
{
if( ( ulDoneMask & ulBitMask ) == 0lu )
{
BaseType_t xPhyAddress = pxPhyObject->ucPhyIndexes[ xPhyIndex ];
pxPhyObject->fnPhyRead( xPhyAddress, phyREG_01_BMSR, &ulRegValue );
if( ( ulRegValue & phyBMSR_AN_COMPLETE ) != 0 )
{
ulDoneMask |= ulBitMask;
}
}
}
}
if( ulPhyMask == ulDoneMask )
{
break;
}
if( xTaskCheckForTimeOut( &xTimer, &xRemainingTime ) != pdFALSE )
{
FreeRTOS_printf( ( "xPhyStartAutoNegotiation: phyBMSR_AN_COMPLETE timed out ( done 0x%02X )\n", ( unsigned int ) ulDoneMask ) );
break;
}
vTaskDelay( pdMS_TO_TICKS( phySHORT_DELAY_MS ) );
}
if( ulDoneMask != ( uint32_t ) 0U )
{
ulBitMask = ( uint32_t ) 1U;
pxPhyObject->ulLinkStatusMask &= ~( ulDoneMask );
for( xPhyIndex = 0; xPhyIndex < ( uint32_t ) pxPhyObject->xPortCount; xPhyIndex++, ulBitMask <<= 1 )
{
BaseType_t xPhyAddress = pxPhyObject->ucPhyIndexes[ xPhyIndex ];
uint32_t ulPhyID = pxPhyObject->ulPhyIDs[ xPhyIndex ];
if( ( ulDoneMask & ulBitMask ) == ( uint32_t ) 0U )
{
continue;
}
/* Clear the 'phyBMCR_AN_RESTART' bit. */
pxPhyObject->fnPhyWrite( xPhyAddress, phyREG_00_BMCR, pxPhyObject->ulBCRValue );
pxPhyObject->fnPhyRead( xPhyAddress, phyREG_01_BMSR, &ulRegValue );
if( ( ulRegValue & phyBMSR_LINK_STATUS ) != 0U )
{
pxPhyObject->ulLinkStatusMask |= ulBitMask;
}
if( ulPhyID == PHY_ID_KSZ8081MNXIA )
{
uint32_t ulControlStatus;
pxPhyObject->fnPhyRead( xPhyAddress, 0x1E, &ulControlStatus );
switch( ulControlStatus & 0x07 )
{
case 0x01:
case 0x05:
/* [001] = 10BASE-T half-duplex */
/* [101] = 10BASE-T full-duplex */
/* 10 Mbps. */
ulRegValue |= phyPHYSTS_SPEED_STATUS;
break;
case 0x02:
case 0x06:
/* [010] = 100BASE-TX half-duplex */
/* [110] = 100BASE-TX full-duplex */
break;
}
switch( ulControlStatus & 0x07 )
{
case 0x05:
case 0x06:
/* [101] = 10BASE-T full-duplex */
/* [110] = 100BASE-TX full-duplex */
/* Full duplex. */
ulRegValue |= phyPHYSTS_DUPLEX_STATUS;
break;
case 0x01:
case 0x02:
/* [001] = 10BASE-T half-duplex */
/* [010] = 100BASE-TX half-duplex */
break;
}
}
else if( ulPhyID == PHY_ID_KSZ8795 )
{
/* KSZ8795 has a different mapping for the Port Operation Mode Indication field
* in the phyREG_1F_PHYSPCS than other similar PHYs:
* 010 = 10BASE-T half-duplex
* 101 = 10BASE-T full-duplex
* 011 = 100BASE-TX half-duplex
* 110 = 100BASE-TX full-duplex
*/
uint32_t ulControlStatus = 0u;
uint32_t ulPortOperationMode = 0u;
pxPhyObject->fnPhyRead( xPhyAddress, phyREG_1F_PHYSPCS, &ulControlStatus );
ulPortOperationMode = ( ulControlStatus >> 8u ) & 0x07u;
ulRegValue = 0;
/* Detect 10baseT operation */
if( ( 0x02u == ulPortOperationMode ) || ( 0x05u == ulPortOperationMode ) )
{
ulRegValue |= phyPHYSTS_SPEED_STATUS;
}
/* Detect full duplex operation */
if( ( 0x05u == ulPortOperationMode ) || ( 0x06u == ulPortOperationMode ) )
{
ulRegValue |= phyPHYSTS_DUPLEX_STATUS;
}
}
else if( ulPhyID == PHY_ID_ADIN1200 )
{
/* ADIN1200 get the resolved speed information from register 0x1A (PHY_STATUS_1)
*/
uint32_t ulControlStatus = 0u;
uint32_t ulPortOperationMode = 0u;
pxPhyObject->fnPhyRead( xPhyAddress, 0x1A, &ulControlStatus );
/* Bits 7-9 indicate the speed and duplex. */
ulPortOperationMode = ( ulControlStatus >> 7u ) & 0x07u;
ulRegValue = 0;
/* Detect 10Mb operation */
if( ( ulPortOperationMode & 0x2 ) == 0 )
{
/* phyPHYSTS_SPEED_STATUS: 1=10Mb, 0=100Mb */
ulRegValue |= phyPHYSTS_SPEED_STATUS;
}
/* Detect full duplex operation */
if( ulPortOperationMode & 0x1 )
{
ulRegValue |= phyPHYSTS_DUPLEX_STATUS;
}
}
else if( xHas_1F_PHYSPCS( ulPhyID ) )
{
/* 31 RW PHY Special Control Status */
uint32_t ulControlStatus;
pxPhyObject->fnPhyRead( xPhyAddress, phyREG_1F_PHYSPCS, &ulControlStatus );
ulRegValue = 0;
if( ( ulControlStatus & phyPHYSPCS_FULL_DUPLEX ) != 0 )
{
ulRegValue |= phyPHYSTS_DUPLEX_STATUS;
}
if( ( ulControlStatus & phyPHYSPCS_SPEED_MASK ) == phyPHYSPCS_SPEED_10 )
{
ulRegValue |= phyPHYSTS_SPEED_STATUS;
}
}
else
{
/* Read the result of the auto-negotiation. */
pxPhyObject->fnPhyRead( xPhyAddress, PHYREG_10_PHYSTS, &ulRegValue );
}
FreeRTOS_printf( ( "Autonego ready: %08x: %s duplex %u mbit %s status\n",
( unsigned int ) ulRegValue,
( ulRegValue & phyPHYSTS_DUPLEX_STATUS ) ? "full" : "half",
( ulRegValue & phyPHYSTS_SPEED_STATUS ) ? 10 : 100,
( ( pxPhyObject->ulLinkStatusMask & ulBitMask ) != 0U ) ? "high" : "low" ) );
if( ( ulRegValue & phyPHYSTS_DUPLEX_STATUS ) != ( uint32_t ) 0U )
{
pxPhyObject->xPhyProperties.ucDuplex = PHY_DUPLEX_FULL;
}
else
{
pxPhyObject->xPhyProperties.ucDuplex = PHY_DUPLEX_HALF;
}
if( ( ulRegValue & phyPHYSTS_SPEED_STATUS ) != 0 )
{
pxPhyObject->xPhyProperties.ucSpeed = PHY_SPEED_10;
}
else
{
pxPhyObject->xPhyProperties.ucSpeed = PHY_SPEED_100;
}
}
} /* if( ulDoneMask != ( uint32_t) 0U ) */
return 0;
}
/*-----------------------------------------------------------*/
BaseType_t xPhyCheckLinkStatus( EthernetPhy_t * pxPhyObject,
BaseType_t xHadReception )
{
uint32_t ulStatus, ulBitMask = 1U;
BaseType_t xPhyIndex;
BaseType_t xNeedCheck = pdFALSE;
if( xHadReception > 0 )
{
/* A packet was received. No need to check for the PHY status now,
* but set a timer to check it later on. */
vTaskSetTimeOutState( &( pxPhyObject->xLinkStatusTimer ) );
pxPhyObject->xLinkStatusRemaining = pdMS_TO_TICKS( ipconfigPHY_LS_HIGH_CHECK_TIME_MS );
for( xPhyIndex = 0; xPhyIndex < pxPhyObject->xPortCount; xPhyIndex++, ulBitMask <<= 1 )
{
if( ( pxPhyObject->ulLinkStatusMask & ulBitMask ) == 0UL )
{
pxPhyObject->ulLinkStatusMask |= ulBitMask;
FreeRTOS_printf( ( "xPhyCheckLinkStatus: PHY LS now %02X\n", ( unsigned int ) pxPhyObject->ulLinkStatusMask ) );
xNeedCheck = pdTRUE;
}
}
}
else if( xTaskCheckForTimeOut( &( pxPhyObject->xLinkStatusTimer ), &( pxPhyObject->xLinkStatusRemaining ) ) != pdFALSE )
{
/* Frequent checking the PHY Link Status can affect for the performance of Ethernet controller.
* As long as packets are received, no polling is needed.
* Otherwise, polling will be done when the 'xLinkStatusTimer' expires. */
for( xPhyIndex = 0; xPhyIndex < pxPhyObject->xPortCount; xPhyIndex++, ulBitMask <<= 1 )
{
BaseType_t xPhyAddress = pxPhyObject->ucPhyIndexes[ xPhyIndex ];
if( pxPhyObject->fnPhyRead( xPhyAddress, phyREG_01_BMSR, &ulStatus ) == 0 )
{
if( !!( pxPhyObject->ulLinkStatusMask & ulBitMask ) != !!( ulStatus & phyBMSR_LINK_STATUS ) )
{
if( ( ulStatus & phyBMSR_LINK_STATUS ) != 0 )
{
pxPhyObject->ulLinkStatusMask |= ulBitMask;
}
else
{
pxPhyObject->ulLinkStatusMask &= ~( ulBitMask );
}
FreeRTOS_printf( ( "xPhyCheckLinkStatus: PHY LS now %02X\n", ( unsigned int ) pxPhyObject->ulLinkStatusMask ) );
xNeedCheck = pdTRUE;
}
}
}
vTaskSetTimeOutState( &( pxPhyObject->xLinkStatusTimer ) );
if( ( pxPhyObject->ulLinkStatusMask & ( ulBitMask >> 1 ) ) != 0 )
{
/* The link status is high, so don't poll the PHY too often. */
pxPhyObject->xLinkStatusRemaining = pdMS_TO_TICKS( ipconfigPHY_LS_HIGH_CHECK_TIME_MS );
}
else
{
/* The link status is low, polling may be done more frequently. */
pxPhyObject->xLinkStatusRemaining = pdMS_TO_TICKS( ipconfigPHY_LS_LOW_CHECK_TIME_MS );
}
}
return xNeedCheck;
}
/*-----------------------------------------------------------*/
@@ -0,0 +1,10 @@
Network drivers are provided as examples only, and do not form part of the
FreeRTOS+TCP stack itself. They:
+ May be based on driver code provided by the chip vendors,
+ May not have been tested in all possible configurations,
+ Will not necessarily be optimised.
+ May have a dependency on a particular PHY part number.
+ May not necessarily comply with any particular coding standard.
+ May have dependencies on chip company libraries.
+ May include other hardware board dependencies.
@@ -0,0 +1,46 @@
if (NOT ( (FREERTOS_PLUS_TCP_NETWORK_IF STREQUAL "STM32") ) )
return()
endif()
#------------------------------------------------------------------------------
add_library( freertos_plus_tcp_network_if STATIC )
set( FREERTOS_PLUS_TCP_STM32_IF_DRIVER "None" CACHE STRING "The driver sources to use with STM32 Network interface" )
target_sources( freertos_plus_tcp_network_if
PRIVATE
NetworkInterface.c
$<$<STREQUAL:${FREERTOS_PLUS_TCP_STM32_IF_DRIVER},F4>:
Drivers/F4/stm32f4xx_hal_eth.c>
$<$<STREQUAL:${FREERTOS_PLUS_TCP_STM32_IF_DRIVER},F7>:
Drivers/F7/stm32f7xx_hal_eth.c>
$<$<STREQUAL:${FREERTOS_PLUS_TCP_STM32_IF_DRIVER},H5>:
Drivers/H5/stm32h5xx_hal_eth_ex.c>
$<$<STREQUAL:${FREERTOS_PLUS_TCP_STM32_IF_DRIVER},H5>:
Drivers/H5/stm32h5xx_hal_eth.c>
$<$<STREQUAL:${FREERTOS_PLUS_TCP_STM32_IF_DRIVER},H7>:
Drivers/H7/stm32h7xx_hal_eth_ex.c>
$<$<STREQUAL:${FREERTOS_PLUS_TCP_STM32_IF_DRIVER},H7>:
Drivers/H7/stm32h7xx_hal_eth.c>
)
target_include_directories( freertos_plus_tcp_network_if
PUBLIC
$<$<STREQUAL:${FREERTOS_PLUS_TCP_STM32_IF_DRIVER},F4>:
Drivers/F4>
$<$<STREQUAL:${FREERTOS_PLUS_TCP_STM32_IF_DRIVER},F7>:
Drivers/F7>
$<$<STREQUAL:${FREERTOS_PLUS_TCP_STM32_IF_DRIVER},H5>:
Drivers/H5>
$<$<STREQUAL:${FREERTOS_PLUS_TCP_STM32_IF_DRIVER},H7>:
Drivers/H7>
)
target_link_libraries( freertos_plus_tcp_network_if
PUBLIC
freertos_plus_tcp_port
freertos_plus_tcp_network_if_common
PRIVATE
freertos_kernel
freertos_plus_tcp
)
Loaded 100 of 1955 files, more files were not shown because too many files have changed in this diff. Show more