Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found
Select Git revision
  • add_menu_vibration
  • blinkisync-as-preload
  • ch3/api-speed-eval2
  • ch3/dual-core
  • ch3/genapi-refactor
  • ch3/leds-api
  • ch3/splashscreen
  • dualcore
  • dx/flatten-config-module
  • dx/meh-bdf-to-stm
  • freertos-btle
  • genofire/ble-follow-py
  • koalo/bhi160-works-but-dirty
  • koalo/factory-reset
  • koalo/wip/i2c-for-python
  • master
  • msgctl/faultscreen
  • msgctl/textbuffer_api
  • plaetzchen/ios-workaround
  • rahix/bhi
  • rahix/bluetooth-app-favorite
  • rahix/bma
  • rahix/user-space-ctx
  • renze/hatchery_apps
  • renze/safe_mode
  • schleicher-test
  • schneider/212-reset-hardware-when-entering-repl
  • schneider/ancs
  • schneider/ble-buffers
  • schneider/ble-central
  • schneider/ble-ecg-stream-visu
  • schneider/ble-fixes-2020-3
  • schneider/ble-mini-demo
  • schneider/ble-stability
  • schneider/ble-stability-new-phy
  • schneider/bonding
  • schneider/bonding-fail-if-full
  • schneider/bootloader-update-9a0d158
  • schneider/deepsleep
  • schneider/deepsleep2
  • schneider/deepsleep4
  • schneider/default-main
  • schneider/freertos-list-debug
  • schneider/fundamental-test
  • schneider/iaq-python
  • schneider/ir
  • schneider/max30001
  • schneider/max30001-epicaridum
  • schneider/max30001-pycardium
  • schneider/maxim-sdk-update
  • schneider/mp-exception-print
  • schneider/mp-for-old-bl
  • schneider/png
  • schneider/schleicher-test
  • schneider/sdk-0.2.1-11
  • schneider/sdk-0.2.1-7
  • schneider/sleep-display
  • schneider/spo2-playground
  • schneider/stream-locks
  • schneider/v1.17-changelog
  • bootloader-v1
  • release-1
  • v0.0
  • v1.0
  • v1.1
  • v1.10
  • v1.11
  • v1.12
  • v1.13
  • v1.14
  • v1.15
  • v1.16
  • v1.17
  • v1.18
  • v1.2
  • v1.3
  • v1.4
  • v1.5
  • v1.6
  • v1.7
  • v1.8
  • v1.9
82 results

Target

Select target project
  • card10/firmware
  • annejan/firmware
  • astro/firmware
  • fpletz/firmware
  • gerd/firmware
  • fleur/firmware
  • swym/firmware
  • l/firmware
  • uberardy/firmware
  • wink/firmware
  • madonius/firmware
  • mot/firmware
  • filid/firmware
  • q3k/firmware
  • hauke/firmware
  • Woazboat/firmware
  • pink/firmware
  • mossmann/firmware
  • omniskop/firmware
  • zenox/firmware
  • trilader/firmware
  • Danukeru/firmware
  • shoragan/firmware
  • zlatko/firmware
  • sistason/firmware
  • datenwolf/firmware
  • bene/firmware
  • amedee/firmware
  • martinling/firmware
  • griffon/firmware
  • chris007/firmware
  • adisbladis/firmware
  • dbrgn/firmware
  • jelly/firmware
  • rnestler/firmware
  • mh/firmware
  • ln/firmware
  • penguineer/firmware
  • monkeydom/firmware
  • jens/firmware
  • jnaulty/firmware
  • jeffmakes/firmware
  • marekventur/firmware
  • pete/firmware
  • h2obrain/firmware
  • DooMMasteR/firmware
  • jackie/firmware
  • prof_r/firmware
  • Draradech/firmware
  • Kartoffel/firmware
  • hinerk/firmware
  • abbradar/firmware
  • JustTB/firmware
  • LuKaRo/firmware
  • iggy/firmware
  • ente/firmware
  • flgr/firmware
  • Lorphos/firmware
  • matejo/firmware
  • ceddral7/firmware
  • danb/firmware
  • joshi/firmware
  • melle/firmware
  • fitch/firmware
  • deurknop/firmware
  • sargon/firmware
  • markus/firmware
  • kloenk/firmware
  • lucaswerkmeister/firmware
  • derf/firmware
  • meh/firmware
  • dx/card10-firmware
  • torben/firmware
  • yuvadm/firmware
  • AndyBS/firmware
  • klausdieter1/firmware
  • katzenparadoxon/firmware
  • xiretza/firmware
  • ole/firmware
  • techy/firmware
  • thor77/firmware
  • TilCreator/firmware
  • fuchsi/firmware
  • dos/firmware
  • yrlf/firmware
  • PetePriority/firmware
  • SuperVirus/firmware
  • sur5r/firmware
  • tazz/firmware
  • Alienmaster/firmware
  • flo_h/firmware
  • baldo/firmware
  • mmu_man/firmware
  • Foaly/firmware
  • sodoku/firmware
  • Guinness/firmware
  • ssp/firmware
  • led02/firmware
  • Stormwind/firmware
  • arist/firmware
  • coon/firmware
  • mdik/firmware
  • pippin/firmware
  • royrobotiks/firmware
  • zigot83/firmware
  • mo_k/firmware
106 results
Select Git revision
  • aj-01
  • master
  • micropython
3 results
Show changes
Contains source and header files that implement FreeRTOS+CLI. See
http://www.FreeRTOS.org/cli for documentation and license information.
\ No newline at end of file
It is not possible to create an example FreeRTOS+IO project for the Windows
simulator. FreeRTOS+IO information can be found on http://www.FreeRTOS.org/IO.
A featured demo that includes telnet like functionality, a web server,
a command line interface (using FreeRTOS+CLI) and a FAT file system is
described on
http://www.freertos.org/FreeRTOS-Plus/FreeRTOS_Plus_IO/Demo_Applications/LPCXpresso_LPC1769/NXP_LPC1769_Demo_Description.shtml
\ No newline at end of file
/*
* FreeRTOS+TCP V2.0.11
* Copyright (C) 2017 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
*/
/* 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_ARP.h"
#include "FreeRTOS_UDP_IP.h"
#include "FreeRTOS_DHCP.h"
#if( ipconfigUSE_LLMNR == 1 )
#include "FreeRTOS_DNS.h"
#endif /* ipconfigUSE_LLMNR */
#include "NetworkInterface.h"
#include "NetworkBufferManagement.h"
/* When the age of an entry in the ARP table reaches this value (it counts down
to zero, so this is an old entry) an ARP request will be sent to see if the
entry is still valid and can therefore be refreshed. */
#define arpMAX_ARP_AGE_BEFORE_NEW_ARP_REQUEST ( 3 )
/* The time between gratuitous ARPs. */
#ifndef arpGRATUITOUS_ARP_PERIOD
#define arpGRATUITOUS_ARP_PERIOD ( pdMS_TO_TICKS( 20000 ) )
#endif
/*-----------------------------------------------------------*/
/*
* Lookup an MAC address in the ARP cache from the IP address.
*/
static eARPLookupResult_t prvCacheLookup( uint32_t ulAddressToLookup, MACAddress_t * const pxMACAddress );
/*-----------------------------------------------------------*/
/* The ARP cache. */
static ARPCacheRow_t xARPCache[ ipconfigARP_CACHE_ENTRIES ];
/* The time at which the last gratuitous ARP was sent. Gratuitous ARPs are used
to ensure ARP tables are up to date and to detect IP address conflicts. */
static TickType_t xLastGratuitousARPTime = ( TickType_t ) 0;
/*
* IP-clash detection is currently only used internally. When DHCP doesn't respond, the
* driver can try out a random LinkLayer IP address (169.254.x.x). It will send out a
* gratuitos ARP message and, after a period of time, check the variables here below:
*/
#if( ipconfigARP_USE_CLASH_DETECTION != 0 )
/* Becomes non-zero if another device responded to a gratuitos ARP message. */
BaseType_t xARPHadIPClash;
/* MAC-address of the other device containing the same IP-address. */
MACAddress_t xARPClashMacAddress;
#endif /* ipconfigARP_USE_CLASH_DETECTION */
/* Part of the Ethernet and ARP headers are always constant when sending an IPv4
ARP 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 xDefaultPartARPPacketHeader[] =
{
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* Ethernet destination address. */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* Ethernet source address. */
0x08, 0x06, /* Ethernet frame type (ipARP_FRAME_TYPE). */
0x00, 0x01, /* usHardwareType (ipARP_HARDWARE_TYPE_ETHERNET). */
0x08, 0x00, /* usProtocolType. */
ipMAC_ADDRESS_LENGTH_BYTES, /* ucHardwareAddressLength. */
ipIP_ADDRESS_LENGTH_BYTES, /* ucProtocolAddressLength. */
0x00, 0x01, /* usOperation (ipARP_REQUEST). */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* xSenderHardwareAddress. */
0x00, 0x00, 0x00, 0x00, /* ulSenderProtocolAddress. */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00 /* xTargetHardwareAddress. */
};
/*-----------------------------------------------------------*/
eFrameProcessingResult_t eARPProcessPacket( ARPPacket_t * const pxARPFrame )
{
eFrameProcessingResult_t eReturn = eReleaseBuffer;
ARPHeader_t *pxARPHeader;
uint32_t ulTargetProtocolAddress, ulSenderProtocolAddress;
pxARPHeader = &( pxARPFrame->xARPHeader );
/* The field ulSenderProtocolAddress is badly aligned, copy byte-by-byte. */
memcpy( ( void *)&( ulSenderProtocolAddress ), ( void * )pxARPHeader->ucSenderProtocolAddress, sizeof( ulSenderProtocolAddress ) );
/* The field ulTargetProtocolAddress is well-aligned, a 32-bits copy. */
ulTargetProtocolAddress = pxARPHeader->ulTargetProtocolAddress;
traceARP_PACKET_RECEIVED();
/* Don't do anything if the local IP address is zero because
that means a DHCP request has not completed. */
if( *ipLOCAL_IP_ADDRESS_POINTER != 0UL )
{
switch( pxARPHeader->usOperation )
{
case ipARP_REQUEST :
/* The packet contained an ARP request. Was it for the IP
address of the node running this code? */
if( ulTargetProtocolAddress == *ipLOCAL_IP_ADDRESS_POINTER )
{
iptraceSENDING_ARP_REPLY( ulSenderProtocolAddress );
/* The request is for the address of this node. Add the
entry into the ARP cache, or refresh the entry if it
already exists. */
vARPRefreshCacheEntry( &( pxARPHeader->xSenderHardwareAddress ), ulSenderProtocolAddress );
/* Generate a reply payload in the same buffer. */
pxARPHeader->usOperation = ( uint16_t ) ipARP_REPLY;
if( ulTargetProtocolAddress == ulSenderProtocolAddress )
{
/* A double IP address is detected! */
/* Give the sources MAC address the value of the broadcast address, will be swapped later */
memcpy( pxARPFrame->xEthernetHeader.xSourceAddress.ucBytes, xBroadcastMACAddress.ucBytes, sizeof( xBroadcastMACAddress ) );
memset( pxARPHeader->xTargetHardwareAddress.ucBytes, '\0', sizeof( MACAddress_t ) );
pxARPHeader->ulTargetProtocolAddress = 0UL;
}
else
{
memcpy( pxARPHeader->xTargetHardwareAddress.ucBytes, pxARPHeader->xSenderHardwareAddress.ucBytes, sizeof( MACAddress_t ) );
pxARPHeader->ulTargetProtocolAddress = ulSenderProtocolAddress;
}
memcpy( pxARPHeader->xSenderHardwareAddress.ucBytes, ( void * ) ipLOCAL_MAC_ADDRESS, sizeof( MACAddress_t ) );
memcpy( ( void* )pxARPHeader->ucSenderProtocolAddress, ( void* )ipLOCAL_IP_ADDRESS_POINTER, sizeof( pxARPHeader->ucSenderProtocolAddress ) );
eReturn = eReturnEthernetFrame;
}
break;
case ipARP_REPLY :
iptracePROCESSING_RECEIVED_ARP_REPLY( ulTargetProtocolAddress );
vARPRefreshCacheEntry( &( pxARPHeader->xSenderHardwareAddress ), ulSenderProtocolAddress );
/* Process received ARP frame to see if there is a clash. */
#if( ipconfigARP_USE_CLASH_DETECTION != 0 )
{
if( ulSenderProtocolAddress == *ipLOCAL_IP_ADDRESS_POINTER )
{
xARPHadIPClash = pdTRUE;
memcpy( xARPClashMacAddress.ucBytes, pxARPHeader->xSenderHardwareAddress.ucBytes, sizeof( xARPClashMacAddress.ucBytes ) );
}
}
#endif /* ipconfigARP_USE_CLASH_DETECTION */
break;
default :
/* Invalid. */
break;
}
}
return eReturn;
}
/*-----------------------------------------------------------*/
#if( ipconfigUSE_ARP_REMOVE_ENTRY != 0 )
uint32_t ulARPRemoveCacheEntryByMac( const MACAddress_t * pxMACAddress )
{
BaseType_t x;
uint32_t lResult = 0;
/* For each entry in the ARP cache table. */
for( x = 0; x < ipconfigARP_CACHE_ENTRIES; x++ )
{
if( ( memcmp( xARPCache[ x ].xMACAddress.ucBytes, pxMACAddress->ucBytes, sizeof( pxMACAddress->ucBytes ) ) == 0 ) )
{
lResult = xARPCache[ x ].ulIPAddress;
memset( &xARPCache[ x ], '\0', sizeof( xARPCache[ x ] ) );
break;
}
}
return lResult;
}
#endif /* ipconfigUSE_ARP_REMOVE_ENTRY != 0 */
/*-----------------------------------------------------------*/
void vARPRefreshCacheEntry( const MACAddress_t * pxMACAddress, const uint32_t ulIPAddress )
{
BaseType_t x = 0;
BaseType_t xIpEntry = -1;
BaseType_t xMacEntry = -1;
BaseType_t xUseEntry = 0;
uint8_t ucMinAgeFound = 0U;
#if( ipconfigARP_STORES_REMOTE_ADDRESSES == 0 )
/* Only process the IP address if it is on the local network.
Unless: when '*ipLOCAL_IP_ADDRESS_POINTER' equals zero, the IP-address
and netmask are still unknown. */
if( ( ( ulIPAddress & xNetworkAddressing.ulNetMask ) == ( ( *ipLOCAL_IP_ADDRESS_POINTER ) & xNetworkAddressing.ulNetMask ) ) ||
( *ipLOCAL_IP_ADDRESS_POINTER == 0ul ) )
#else
/* If ipconfigARP_STORES_REMOTE_ADDRESSES is non-zero, IP addresses with
a different netmask will also be stored. After when replying to a UDP
message from a different netmask, the IP address can be looped up and a
reply sent. This option is useful for systems with multiple gateways,
the reply will surely arrive. If ipconfigARP_STORES_REMOTE_ADDRESSES is
zero the the gateway address is the only option. */
if( pdTRUE )
#endif
{
/* Start with the maximum possible number. */
ucMinAgeFound--;
/* For each entry in the ARP cache table. */
for( x = 0; x < ipconfigARP_CACHE_ENTRIES; x++ )
{
/* Does this line in the cache table hold an entry for the IP
address being queried? */
if( xARPCache[ x ].ulIPAddress == ulIPAddress )
{
if( pxMACAddress == NULL )
{
/* In case the parameter pxMACAddress is NULL, an entry will be reserved to
indicate that there is an outstanding ARP request, This entry will have
"ucValid == pdFALSE". */
xIpEntry = x;
break;
}
/* See if the MAC-address also matches. */
if( memcmp( xARPCache[ x ].xMACAddress.ucBytes, pxMACAddress->ucBytes, sizeof( pxMACAddress->ucBytes ) ) == 0 )
{
/* This function will be called for each received packet
As this is by far the most common path the coding standard
is relaxed in this case and a return is permitted as an
optimisation. */
xARPCache[ x ].ucAge = ( uint8_t ) ipconfigMAX_ARP_AGE;
xARPCache[ x ].ucValid = ( uint8_t ) pdTRUE;
return;
}
/* Found an entry containing ulIPAddress, but the MAC address
doesn't match. Might be an entry with ucValid=pdFALSE, waiting
for an ARP reply. Still want to see if there is match with the
given MAC address.ucBytes. If found, either of the two entries
must be cleared. */
xIpEntry = x;
}
else if( ( pxMACAddress != NULL ) && ( memcmp( xARPCache[ x ].xMACAddress.ucBytes, pxMACAddress->ucBytes, sizeof( pxMACAddress->ucBytes ) ) == 0 ) )
{
/* Found an entry with the given MAC-address, but the IP-address
is different. Continue looping to find a possible match with
ulIPAddress. */
#if( ipconfigARP_STORES_REMOTE_ADDRESSES != 0 )
/* If ARP stores the MAC address of IP addresses outside the
network, than the MAC address of the gateway should not be
overwritten. */
BaseType_t bIsLocal[ 2 ];
bIsLocal[ 0 ] = ( ( xARPCache[ x ].ulIPAddress & xNetworkAddressing.ulNetMask ) == ( ( *ipLOCAL_IP_ADDRESS_POINTER ) & xNetworkAddressing.ulNetMask ) );
bIsLocal[ 1 ] = ( ( ulIPAddress & xNetworkAddressing.ulNetMask ) == ( ( *ipLOCAL_IP_ADDRESS_POINTER ) & xNetworkAddressing.ulNetMask ) );
if( bIsLocal[ 0 ] == bIsLocal[ 1 ] )
{
xMacEntry = x;
}
#else
xMacEntry = x;
#endif
}
/* _HT_
Shouldn't we test for xARPCache[ x ].ucValid == pdFALSE here ? */
else if( xARPCache[ x ].ucAge < ucMinAgeFound )
{
/* As the table is traversed, remember the table row that
contains the oldest entry (the lowest age count, as ages are
decremented to zero) so the row can be re-used if this function
needs to add an entry that does not already exist. */
ucMinAgeFound = xARPCache[ x ].ucAge;
xUseEntry = x;
}
}
if( xMacEntry >= 0 )
{
xUseEntry = xMacEntry;
if( xIpEntry >= 0 )
{
/* Both the MAC address as well as the IP address were found in
different locations: clear the entry which matches the
IP-address */
memset( &xARPCache[ xIpEntry ], '\0', sizeof( xARPCache[ xIpEntry ] ) );
}
}
else if( xIpEntry >= 0 )
{
/* An entry containing the IP-address was found, but it had a different MAC address */
xUseEntry = xIpEntry;
}
/* If the entry was not found, we use the oldest entry and set the IPaddress */
xARPCache[ xUseEntry ].ulIPAddress = ulIPAddress;
if( pxMACAddress != NULL )
{
memcpy( xARPCache[ xUseEntry ].xMACAddress.ucBytes, pxMACAddress->ucBytes, sizeof( pxMACAddress->ucBytes ) );
iptraceARP_TABLE_ENTRY_CREATED( ulIPAddress, (*pxMACAddress) );
/* And this entry does not need immediate attention */
xARPCache[ xUseEntry ].ucAge = ( uint8_t ) ipconfigMAX_ARP_AGE;
xARPCache[ xUseEntry ].ucValid = ( uint8_t ) pdTRUE;
}
else if( xIpEntry < 0 )
{
xARPCache[ xUseEntry ].ucAge = ( uint8_t ) ipconfigMAX_ARP_RETRANSMISSIONS;
xARPCache[ xUseEntry ].ucValid = ( uint8_t ) pdFALSE;
}
}
}
/*-----------------------------------------------------------*/
#if( ipconfigUSE_ARP_REVERSED_LOOKUP == 1 )
eARPLookupResult_t eARPGetCacheEntryByMac( MACAddress_t * const pxMACAddress, uint32_t *pulIPAddress )
{
BaseType_t x;
eARPLookupResult_t eReturn = eARPCacheMiss;
/* Loop through each entry in the ARP cache. */
for( x = 0; x < ipconfigARP_CACHE_ENTRIES; x++ )
{
/* Does this row in the ARP cache table hold an entry for the MAC
address being searched? */
if( memcmp( pxMACAddress->ucBytes, xARPCache[ x ].xMACAddress.ucBytes, sizeof( MACAddress_t ) ) == 0 )
{
*pulIPAddress = xARPCache[ x ].ulIPAddress;
eReturn = eARPCacheHit;
break;
}
}
return eReturn;
}
#endif /* ipconfigUSE_ARP_REVERSED_LOOKUP */
/*-----------------------------------------------------------*/
eARPLookupResult_t eARPGetCacheEntry( uint32_t *pulIPAddress, MACAddress_t * const pxMACAddress )
{
eARPLookupResult_t eReturn;
uint32_t ulAddressToLookup;
#if( ipconfigUSE_LLMNR == 1 )
if( *pulIPAddress == ipLLMNR_IP_ADDR ) /* Is in network byte order. */
{
/* The LLMNR IP-address has a fixed virtual MAC address. */
memcpy( pxMACAddress->ucBytes, xLLMNR_MacAdress.ucBytes, sizeof( MACAddress_t ) );
eReturn = eARPCacheHit;
}
else
#endif
if( ( *pulIPAddress == ipBROADCAST_IP_ADDRESS ) || /* Is it the general broadcast address 255.255.255.255? */
( *pulIPAddress == xNetworkAddressing.ulBroadcastAddress ) )/* Or a local broadcast address, eg 192.168.1.255? */
{
/* This is a broadcast so uses the broadcast MAC address. */
memcpy( pxMACAddress->ucBytes, xBroadcastMACAddress.ucBytes, sizeof( MACAddress_t ) );
eReturn = eARPCacheHit;
}
else if( *ipLOCAL_IP_ADDRESS_POINTER == 0UL )
{
/* The IP address has not yet been assigned, so there is nothing that
can be done. */
eReturn = eCantSendPacket;
}
else
{
eReturn = eARPCacheMiss;
if( ( *pulIPAddress & xNetworkAddressing.ulNetMask ) != ( ( *ipLOCAL_IP_ADDRESS_POINTER ) & xNetworkAddressing.ulNetMask ) )
{
#if( ipconfigARP_STORES_REMOTE_ADDRESSES == 1 )
eReturn = prvCacheLookup( *pulIPAddress, pxMACAddress );
if( eReturn == eARPCacheHit )
{
/* The stack is configured to store 'remote IP addresses', i.e. addresses
belonging to a different the netmask. prvCacheLookup() returned a hit, so
the MAC address is known */
}
else
#endif
{
/* The IP address is off the local network, so look up the
hardware address of the router, if any. */
if( xNetworkAddressing.ulGatewayAddress != ( uint32_t )0u )
{
ulAddressToLookup = xNetworkAddressing.ulGatewayAddress;
}
else
{
ulAddressToLookup = *pulIPAddress;
}
}
}
else
{
/* The IP address is on the local network, so lookup the requested
IP address directly. */
ulAddressToLookup = *pulIPAddress;
}
if( eReturn == eARPCacheMiss )
{
if( ulAddressToLookup == 0UL )
{
/* The address is not on the local network, and there is not a
router. */
eReturn = eCantSendPacket;
}
else
{
eReturn = prvCacheLookup( ulAddressToLookup, pxMACAddress );
if( eReturn == eARPCacheMiss )
{
/* It might be that the ARP has to go to the gateway. */
*pulIPAddress = ulAddressToLookup;
}
}
}
}
return eReturn;
}
/*-----------------------------------------------------------*/
static eARPLookupResult_t prvCacheLookup( uint32_t ulAddressToLookup, MACAddress_t * const pxMACAddress )
{
BaseType_t x;
eARPLookupResult_t eReturn = eARPCacheMiss;
/* Loop through each entry in the ARP cache. */
for( x = 0; x < ipconfigARP_CACHE_ENTRIES; x++ )
{
/* Does this row in the ARP cache table hold an entry for the IP address
being queried? */
if( xARPCache[ x ].ulIPAddress == ulAddressToLookup )
{
/* A matching valid entry was found. */
if( xARPCache[ x ].ucValid == ( uint8_t ) pdFALSE )
{
/* This entry is waiting an ARP reply, so is not valid. */
eReturn = eCantSendPacket;
}
else
{
/* A valid entry was found. */
memcpy( pxMACAddress->ucBytes, xARPCache[ x ].xMACAddress.ucBytes, sizeof( MACAddress_t ) );
eReturn = eARPCacheHit;
}
break;
}
}
return eReturn;
}
/*-----------------------------------------------------------*/
void vARPAgeCache( void )
{
BaseType_t x;
TickType_t xTimeNow;
/* Loop through each entry in the ARP cache. */
for( x = 0; x < ipconfigARP_CACHE_ENTRIES; x++ )
{
/* If the entry is valid (its age is greater than zero). */
if( xARPCache[ x ].ucAge > 0U )
{
/* Decrement the age value of the entry in this ARP cache table row.
When the age reaches zero it is no longer considered valid. */
( xARPCache[ x ].ucAge )--;
/* If the entry is not yet valid, then it is waiting an ARP
reply, and the ARP request should be retransmitted. */
if( xARPCache[ x ].ucValid == ( uint8_t ) pdFALSE )
{
FreeRTOS_OutputARPRequest( xARPCache[ x ].ulIPAddress );
}
else if( xARPCache[ x ].ucAge <= ( uint8_t ) arpMAX_ARP_AGE_BEFORE_NEW_ARP_REQUEST )
{
/* This entry will get removed soon. See if the MAC address is
still valid to prevent this happening. */
iptraceARP_TABLE_ENTRY_WILL_EXPIRE( xARPCache[ x ].ulIPAddress );
FreeRTOS_OutputARPRequest( xARPCache[ x ].ulIPAddress );
}
else
{
/* The age has just ticked down, with nothing to do. */
}
if( xARPCache[ x ].ucAge == 0u )
{
/* The entry is no longer valid. Wipe it out. */
iptraceARP_TABLE_ENTRY_EXPIRED( xARPCache[ x ].ulIPAddress );
xARPCache[ x ].ulIPAddress = 0UL;
}
}
}
xTimeNow = xTaskGetTickCount ();
if( ( xLastGratuitousARPTime == ( TickType_t ) 0 ) || ( ( xTimeNow - xLastGratuitousARPTime ) > ( TickType_t ) arpGRATUITOUS_ARP_PERIOD ) )
{
FreeRTOS_OutputARPRequest( *ipLOCAL_IP_ADDRESS_POINTER );
xLastGratuitousARPTime = xTimeNow;
}
}
/*-----------------------------------------------------------*/
void vARPSendGratuitous( void )
{
/* Setting xLastGratuitousARPTime to 0 will force a gratuitous ARP the next
time vARPAgeCache() is called. */
xLastGratuitousARPTime = ( TickType_t ) 0;
/* Let the IP-task call vARPAgeCache(). */
xSendEventToIPTask( eARPTimerEvent );
}
/*-----------------------------------------------------------*/
void FreeRTOS_OutputARPRequest( uint32_t ulIPAddress )
{
NetworkBufferDescriptor_t *pxNetworkBuffer;
/* This is called from the context of the IP event task, so a block time
must not be used. */
pxNetworkBuffer = pxGetNetworkBufferWithDescriptor( sizeof( ARPPacket_t ), ( TickType_t ) 0 );
if( pxNetworkBuffer != NULL )
{
pxNetworkBuffer->ulIPAddress = ulIPAddress;
vARPGenerateRequestPacket( pxNetworkBuffer );
#if defined( ipconfigETHERNET_MINIMUM_PACKET_BYTES )
{
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
xNetworkInterfaceOutput( pxNetworkBuffer, pdTRUE );
}
}
void vARPGenerateRequestPacket( NetworkBufferDescriptor_t * const pxNetworkBuffer )
{
ARPPacket_t *pxARPPacket;
pxARPPacket = ( ARPPacket_t * ) pxNetworkBuffer->pucEthernetBuffer;
/* memcpy the const part of the header information into the correct
location in the packet. This copies:
xEthernetHeader.ulDestinationAddress
xEthernetHeader.usFrameType;
xARPHeader.usHardwareType;
xARPHeader.usProtocolType;
xARPHeader.ucHardwareAddressLength;
xARPHeader.ucProtocolAddressLength;
xARPHeader.usOperation;
xARPHeader.xTargetHardwareAddress;
*/
memcpy( ( void * ) pxARPPacket, ( void * ) xDefaultPartARPPacketHeader, sizeof( xDefaultPartARPPacketHeader ) );
memcpy( ( void * ) pxARPPacket->xEthernetHeader.xSourceAddress.ucBytes , ( void * ) ipLOCAL_MAC_ADDRESS, ( size_t ) ipMAC_ADDRESS_LENGTH_BYTES );
memcpy( ( void * ) pxARPPacket->xARPHeader.xSenderHardwareAddress.ucBytes, ( void * ) ipLOCAL_MAC_ADDRESS, ( size_t ) ipMAC_ADDRESS_LENGTH_BYTES );
memcpy( ( void* )pxARPPacket->xARPHeader.ucSenderProtocolAddress, ( void* )ipLOCAL_IP_ADDRESS_POINTER, sizeof( pxARPPacket->xARPHeader.ucSenderProtocolAddress ) );
pxARPPacket->xARPHeader.ulTargetProtocolAddress = pxNetworkBuffer->ulIPAddress;
pxNetworkBuffer->xDataLength = sizeof( ARPPacket_t );
iptraceCREATING_ARP_REQUEST( pxNetworkBuffer->ulIPAddress );
}
/*-----------------------------------------------------------*/
void FreeRTOS_ClearARP( void )
{
memset( xARPCache, '\0', sizeof( xARPCache ) );
}
/*-----------------------------------------------------------*/
#if( ipconfigHAS_PRINTF != 0 ) || ( ipconfigHAS_DEBUG_PRINTF != 0 )
void FreeRTOS_PrintARPCache( void )
{
BaseType_t x, xCount = 0;
/* Loop through each entry in the ARP cache. */
for( x = 0; x < ipconfigARP_CACHE_ENTRIES; x++ )
{
if( ( xARPCache[ x ].ulIPAddress != 0ul ) && ( xARPCache[ x ].ucAge > 0U ) )
{
/* See if the MAC-address also matches, and we're all happy */
FreeRTOS_printf( ( "Arp %2ld: %3u - %16lxip : %02x:%02x:%02x : %02x:%02x:%02x\n",
x,
xARPCache[ x ].ucAge,
xARPCache[ x ].ulIPAddress,
xARPCache[ x ].xMACAddress.ucBytes[0],
xARPCache[ x ].xMACAddress.ucBytes[1],
xARPCache[ x ].xMACAddress.ucBytes[2],
xARPCache[ x ].xMACAddress.ucBytes[3],
xARPCache[ x ].xMACAddress.ucBytes[4],
xARPCache[ x ].xMACAddress.ucBytes[5] ) );
xCount++;
}
}
FreeRTOS_printf( ( "Arp has %ld entries\n", xCount ) );
}
#endif /* ( ipconfigHAS_PRINTF != 0 ) || ( ipconfigHAS_DEBUG_PRINTF != 0 ) */
/*
* FreeRTOS+TCP V2.0.11
* Copyright (C) 2017 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
*/
/* 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_Sockets.h"
#include "FreeRTOS_IP_Private.h"
#include "FreeRTOS_UDP_IP.h"
#include "FreeRTOS_TCP_IP.h"
#include "FreeRTOS_DHCP.h"
#include "FreeRTOS_ARP.h"
#include "NetworkInterface.h"
#include "NetworkBufferManagement.h"
/* Exclude the entire file if DHCP is not enabled. */
#if( ipconfigUSE_DHCP != 0 )
#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
#define dhcpSERVER_HOST_NAME_LENGTH 64
#define dhcpBOOT_FILE_NAME_LENGTH 128
/* Timer parameters */
#ifndef dhcpINITIAL_DHCP_TX_PERIOD
#define dhcpINITIAL_TIMER_PERIOD ( pdMS_TO_TICKS( 250 ) )
#define dhcpINITIAL_DHCP_TX_PERIOD ( pdMS_TO_TICKS( 5000 ) )
#endif
/* Codes of interest found in the DHCP options field. */
#define dhcpZERO_PAD_OPTION_CODE ( 0u )
#define dhcpSUBNET_MASK_OPTION_CODE ( 1u )
#define dhcpGATEWAY_OPTION_CODE ( 3u )
#define dhcpDNS_SERVER_OPTIONS_CODE ( 6u )
#define dhcpDNS_HOSTNAME_OPTIONS_CODE ( 12u )
#define dhcpREQUEST_IP_ADDRESS_OPTION_CODE ( 50u )
#define dhcpLEASE_TIME_OPTION_CODE ( 51u )
#define dhcpMESSAGE_TYPE_OPTION_CODE ( 53u )
#define dhcpSERVER_IP_ADDRESS_OPTION_CODE ( 54u )
#define dhcpPARAMETER_REQUEST_OPTION_CODE ( 55u )
#define dhcpCLIENT_IDENTIFIER_OPTION_CODE ( 61u )
/* The four DHCP message types of interest. */
#define dhcpMESSAGE_TYPE_DISCOVER ( 1 )
#define dhcpMESSAGE_TYPE_OFFER ( 2 )
#define dhcpMESSAGE_TYPE_REQUEST ( 3 )
#define dhcpMESSAGE_TYPE_ACK ( 5 )
#define dhcpMESSAGE_TYPE_NACK ( 6 )
/* Offsets into the transmitted DHCP options fields at which various parameters
are located. */
#define dhcpCLIENT_IDENTIFIER_OFFSET ( 5 )
#define dhcpREQUESTED_IP_ADDRESS_OFFSET ( 13 )
#define dhcpDHCP_SERVER_IP_ADDRESS_OFFSET ( 19 )
/* Values used in the DHCP packets. */
#define dhcpREQUEST_OPCODE ( 1 )
#define dhcpREPLY_OPCODE ( 2 )
#define dhcpADDRESS_TYPE_ETHERNET ( 1 )
#define dhcpETHERNET_ADDRESS_LENGTH ( 6 )
/* 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 )
/* Don't allow the lease time to be too short. */
#define dhcpMINIMUM_LEASE_TIME ( pdMS_TO_TICKS( 60000UL ) ) /* 60 seconds in ticks. */
/* Marks the end of the variable length options field in the DHCP packet. */
#define dhcpOPTION_END_BYTE 0xffu
/* Offset into a DHCP message at which the first byte of the options is
located. */
#define dhcpFIRST_OPTION_BYTE_OFFSET ( 0xf0 )
/* When walking the variable length options field, the following value is used
to ensure the walk has not gone past the end of the valid options. 2 bytes is
made up of the length byte, and minimum one byte value. */
#define dhcpMAX_OPTION_LENGTH_OF_INTEREST ( 2L )
/* Standard DHCP port numbers and magic cookie value. */
#if( ipconfigBYTE_ORDER == pdFREERTOS_LITTLE_ENDIAN )
#define dhcpCLIENT_PORT 0x4400u
#define dhcpSERVER_PORT 0x4300u
#define dhcpCOOKIE 0x63538263ul
#define dhcpBROADCAST 0x0080u
#else
#define dhcpCLIENT_PORT 0x0044u
#define dhcpSERVER_PORT 0x0043u
#define dhcpCOOKIE 0x63825363ul
#define dhcpBROADCAST 0x8000u
#endif /* ipconfigBYTE_ORDER */
#include "pack_struct_start.h"
struct xDHCPMessage
{
uint8_t ucOpcode;
uint8_t ucAddressType;
uint8_t ucAddressLength;
uint8_t ucHops;
uint32_t ulTransactionID;
uint16_t usElapsedTime;
uint16_t usFlags;
uint32_t ulClientIPAddress_ciaddr;
uint32_t ulYourIPAddress_yiaddr;
uint32_t ulServerIPAddress_siaddr;
uint32_t ulRelayAgentIPAddress_giaddr;
uint8_t ucClientHardwareAddress[ dhcpCLIENT_HARDWARE_ADDRESS_LENGTH ];
uint8_t ucServerHostName[ dhcpSERVER_HOST_NAME_LENGTH ];
uint8_t ucBootFileName[ dhcpBOOT_FILE_NAME_LENGTH ];
uint32_t ulDHCPCookie;
uint8_t ucFirstOptionByte;
}
#include "pack_struct_end.h"
typedef struct xDHCPMessage DHCPMessage_t;
/* DHCP state machine states. */
typedef enum
{
eWaitingSendFirstDiscover = 0, /* Initial state. 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. */
#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;
/* Hold information in between steps in the DHCP state machine. */
struct xDHCP_DATA
{
uint32_t ulTransactionId;
uint32_t ulOfferedIPAddress;
uint32_t ulDHCPServerAddress;
uint32_t ulLeaseTime;
/* Hold information on the current timer state. */
TickType_t xDHCPTxTime;
TickType_t xDHCPTxPeriod;
/* Try both without and with the broadcast flag */
BaseType_t xUseBroadcast;
/* Maintains the DHCP state machine state. */
eDHCPState_t eDHCPState;
/* The UDP socket used for all incoming and outgoing DHCP traffic. */
Socket_t xDHCPSocket;
};
typedef struct xDHCP_DATA DHCPData_t;
#if( ipconfigDHCP_FALL_BACK_AUTO_IP != 0 )
/* Define the Link Layer IP address: 169.254.x.x */
#define LINK_LAYER_ADDRESS_0 169
#define LINK_LAYER_ADDRESS_1 254
/* Define the netmask used: 255.255.0.0 */
#define LINK_LAYER_NETMASK_0 255
#define LINK_LAYER_NETMASK_1 255
#define LINK_LAYER_NETMASK_2 0
#define LINK_LAYER_NETMASK_3 0
#endif
/*
* Generate a DHCP discover message and send it on the DHCP socket.
*/
static void prvSendDHCPDiscover( void );
/*
* Interpret message received on the DHCP socket.
*/
static BaseType_t prvProcessDHCPReplies( BaseType_t xExpectedMessageType );
/*
* Generate a DHCP request packet, and send it on the DHCP socket.
*/
static void prvSendDHCPRequest( void );
/*
* Prepare to start a DHCP transaction. This initialises some state variables
* and creates the DHCP socket if necessary.
*/
static void prvInitialiseDHCP( void );
/*
* Creates the part of outgoing DHCP messages that are common to all outgoing
* DHCP messages.
*/
static uint8_t *prvCreatePartDHCPMessage( struct freertos_sockaddr *pxAddress, BaseType_t xOpcode, const uint8_t * const pucOptionsArray, size_t *pxOptionsArraySize );
/*
* Create the DHCP socket, if it has not been created already.
*/
static void prvCreateDHCPSocket( void );
/*
* After DHCP has failed to answer, prepare everything to start searching
* for (trying-out) LinkLayer IP-addresses, using the random method: Send
* a gratuitous ARP request and wait if another device responds to it.
*/
#if( ipconfigDHCP_FALL_BACK_AUTO_IP != 0 )
static void prvPrepareLinkLayerIPLookUp( void );
#endif
/*-----------------------------------------------------------*/
/* The next DHCP transaction Id to be used. */
static DHCPData_t xDHCPData;
/*-----------------------------------------------------------*/
BaseType_t xIsDHCPSocket( Socket_t xSocket )
{
BaseType_t xReturn;
if( xDHCPData.xDHCPSocket == xSocket )
{
xReturn = pdTRUE;
}
else
{
xReturn = pdFALSE;
}
return xReturn;
}
/*-----------------------------------------------------------*/
void vDHCPProcess( BaseType_t xReset )
{
BaseType_t xGivingUp = pdFALSE;
#if( ipconfigUSE_DHCP_HOOK != 0 )
eDHCPCallbackAnswer_t eAnswer;
#endif /* ipconfigUSE_DHCP_HOOK */
/* Is DHCP starting over? */
if( xReset != pdFALSE )
{
xDHCPData.eDHCPState = eWaitingSendFirstDiscover;
}
switch( xDHCPData.eDHCPState )
{
case eWaitingSendFirstDiscover :
/* Ask the user if a DHCP discovery is required. */
#if( ipconfigUSE_DHCP_HOOK != 0 )
eAnswer = xApplicationDHCPHook( eDHCPPhasePreDiscover, xNetworkAddressing.ulDefaultIPAddress );
if( eAnswer == eDHCPContinue )
#endif /* ipconfigUSE_DHCP_HOOK */
{
/* Initial state. Create the DHCP socket, timer, etc. if they
have not already been created. */
prvInitialiseDHCP();
/* See if prvInitialiseDHCP() has creates a socket. */
if( xDHCPData.xDHCPSocket == NULL )
{
xGivingUp = pdTRUE;
break;
}
*ipLOCAL_IP_ADDRESS_POINTER = 0UL;
/* Send the first discover request. */
if( xDHCPData.xDHCPSocket != NULL )
{
xDHCPData.xDHCPTxTime = xTaskGetTickCount();
prvSendDHCPDiscover( );
xDHCPData.eDHCPState = eWaitingOffer;
}
}
#if( ipconfigUSE_DHCP_HOOK != 0 )
else
{
if( eAnswer == eDHCPUseDefaults )
{
memcpy( &xNetworkAddressing, &xDefaultAddressing, sizeof( xNetworkAddressing ) );
}
/* The user indicates that the DHCP process does not continue. */
xGivingUp = pdTRUE;
}
#endif /* ipconfigUSE_DHCP_HOOK */
break;
case eWaitingOffer :
xGivingUp = pdFALSE;
/* Look for offers coming in. */
if( prvProcessDHCPReplies( dhcpMESSAGE_TYPE_OFFER ) == pdPASS )
{
#if( ipconfigUSE_DHCP_HOOK != 0 )
/* Ask the user if a DHCP request is required. */
eAnswer = xApplicationDHCPHook( eDHCPPhasePreRequest, xDHCPData.ulOfferedIPAddress );
if( eAnswer == eDHCPContinue )
#endif /* ipconfigUSE_DHCP_HOOK */
{
/* An offer has been made, the user wants to continue,
generate the request. */
xDHCPData.xDHCPTxTime = xTaskGetTickCount();
xDHCPData.xDHCPTxPeriod = dhcpINITIAL_DHCP_TX_PERIOD;
prvSendDHCPRequest( );
xDHCPData.eDHCPState = eWaitingAcknowledge;
break;
}
#if( ipconfigUSE_DHCP_HOOK != 0 )
if( eAnswer == eDHCPUseDefaults )
{
memcpy( &xNetworkAddressing, &xDefaultAddressing, sizeof( xNetworkAddressing ) );
}
/* The user indicates that the DHCP process does not continue. */
xGivingUp = pdTRUE;
#endif /* ipconfigUSE_DHCP_HOOK */
}
else if( ( xTaskGetTickCount() - xDHCPData.xDHCPTxTime ) > xDHCPData.xDHCPTxPeriod )
{
/* It is time to send another Discover. Increase the time
period, and if it has not got to the point of giving up - send
another discovery. */
xDHCPData.xDHCPTxPeriod <<= 1;
if( xDHCPData.xDHCPTxPeriod <= ipconfigMAXIMUM_DISCOVER_TX_PERIOD )
{
xDHCPData.ulTransactionId = ipconfigRAND32( );
if( 0 != xDHCPData.ulTransactionId )
{
xDHCPData.xDHCPTxTime = xTaskGetTickCount( );
xDHCPData.xUseBroadcast = !xDHCPData.xUseBroadcast;
prvSendDHCPDiscover( );
FreeRTOS_debug_printf( ( "vDHCPProcess: timeout %lu ticks\n", xDHCPData.xDHCPTxPeriod ) );
}
else
{
FreeRTOS_debug_printf( ( "vDHCPProcess: failed to generate a random Transaction ID\n" ) );
}
}
else
{
FreeRTOS_debug_printf( ( "vDHCPProcess: giving up %lu > %lu ticks\n", xDHCPData.xDHCPTxPeriod, ipconfigMAXIMUM_DISCOVER_TX_PERIOD ) );
#if( ipconfigDHCP_FALL_BACK_AUTO_IP != 0 )
{
/* Only use a fake Ack if the default IP address == 0x00
and the link local addressing is used. Start searching
a free LinkLayer IP-address. Next state will be
'eGetLinkLayerAddress'. */
prvPrepareLinkLayerIPLookUp();
/* Setting an IP address manually so set to not using
leased address mode. */
xDHCPData.eDHCPState = eGetLinkLayerAddress;
}
#else
{
xGivingUp = pdTRUE;
}
#endif /* ipconfigDHCP_FALL_BACK_AUTO_IP */
}
}
break;
case eWaitingAcknowledge :
/* Look for acks coming in. */
if( prvProcessDHCPReplies( dhcpMESSAGE_TYPE_ACK ) == pdPASS )
{
FreeRTOS_debug_printf( ( "vDHCPProcess: acked %lxip\n", FreeRTOS_ntohl( xDHCPData.ulOfferedIPAddress ) ) );
/* DHCP completed. The IP address can now be used, and the
timer set to the lease timeout time. */
*ipLOCAL_IP_ADDRESS_POINTER = xDHCPData.ulOfferedIPAddress;
/* Setting the 'local' broadcast address, something like
'192.168.1.255'. */
xNetworkAddressing.ulBroadcastAddress = ( xDHCPData.ulOfferedIPAddress & xNetworkAddressing.ulNetMask ) | ~xNetworkAddressing.ulNetMask;
xDHCPData.eDHCPState = eLeasedAddress;
iptraceDHCP_SUCCEDEED( xDHCPData.ulOfferedIPAddress );
/* DHCP failed, the default configured IP-address will be used
Now call vIPNetworkUpCalls() to send the network-up event and
start the ARP timer. */
vIPNetworkUpCalls( );
/* Close socket to ensure packets don't queue on it. */
vSocketClose( xDHCPData.xDHCPSocket );
xDHCPData.xDHCPSocket = NULL;
if( xDHCPData.ulLeaseTime == 0UL )
{
xDHCPData.ulLeaseTime = dhcpDEFAULT_LEASE_TIME;
}
else if( xDHCPData.ulLeaseTime < dhcpMINIMUM_LEASE_TIME )
{
xDHCPData.ulLeaseTime = dhcpMINIMUM_LEASE_TIME;
}
else
{
/* The lease time is already valid. */
}
/* Check for clashes. */
vARPSendGratuitous();
vIPReloadDHCPTimer( xDHCPData.ulLeaseTime );
}
else
{
/* Is it time to send another Discover? */
if( ( xTaskGetTickCount() - xDHCPData.xDHCPTxTime ) > xDHCPData.xDHCPTxPeriod )
{
/* Increase the time period, and if it has not got to the
point of giving up - send another request. */
xDHCPData.xDHCPTxPeriod <<= 1;
if( xDHCPData.xDHCPTxPeriod <= ipconfigMAXIMUM_DISCOVER_TX_PERIOD )
{
xDHCPData.xDHCPTxTime = xTaskGetTickCount();
prvSendDHCPRequest( );
}
else
{
/* Give up, start again. */
xDHCPData.eDHCPState = eWaitingSendFirstDiscover;
}
}
}
break;
#if( ipconfigDHCP_FALL_BACK_AUTO_IP != 0 )
case eGetLinkLayerAddress:
if( ( xTaskGetTickCount() - xDHCPData.xDHCPTxTime ) > xDHCPData.xDHCPTxPeriod )
{
if( xARPHadIPClash == pdFALSE )
{
/* ARP OK. proceed. */
iptraceDHCP_SUCCEDEED( xDHCPData.ulOfferedIPAddress );
/* Auto-IP succeeded, the default configured IP-address will
be used. Now call vIPNetworkUpCalls() to send the
network-up event and start the ARP timer. */
vIPNetworkUpCalls( );
xDHCPData.eDHCPState = eNotUsingLeasedAddress;
}
else
{
/* ARP clashed - try another IP address. */
prvPrepareLinkLayerIPLookUp();
/* Setting an IP address manually so set to not using leased
address mode. */
xDHCPData.eDHCPState = eGetLinkLayerAddress;
}
}
break;
#endif /* ipconfigDHCP_FALL_BACK_AUTO_IP */
case eLeasedAddress :
/* Resend the request at the appropriate time to renew the lease. */
prvCreateDHCPSocket();
if( xDHCPData.xDHCPSocket != NULL )
{
xDHCPData.xDHCPTxTime = xTaskGetTickCount();
xDHCPData.xDHCPTxPeriod = dhcpINITIAL_DHCP_TX_PERIOD;
prvSendDHCPRequest( );
xDHCPData.eDHCPState = eWaitingAcknowledge;
/* From now on, we should be called more often */
vIPReloadDHCPTimer( dhcpINITIAL_TIMER_PERIOD );
}
break;
case eNotUsingLeasedAddress:
vIPSetDHCPTimerEnableState( pdFALSE );
break;
default:
break;
}
if( xGivingUp != pdFALSE )
{
/* xGivingUp became true either because of a time-out, or because
xApplicationDHCPHook() returned another value than 'eDHCPContinue',
meaning that the conversion is canceled from here. */
/* Revert to static IP address. */
taskENTER_CRITICAL();
{
*ipLOCAL_IP_ADDRESS_POINTER = xNetworkAddressing.ulDefaultIPAddress;
iptraceDHCP_REQUESTS_FAILED_USING_DEFAULT_IP_ADDRESS( xNetworkAddressing.ulDefaultIPAddress );
}
taskEXIT_CRITICAL();
xDHCPData.eDHCPState = eNotUsingLeasedAddress;
vIPSetDHCPTimerEnableState( pdFALSE );
/* DHCP failed, the default configured IP-address will be used. Now
call vIPNetworkUpCalls() to send the network-up event and start the ARP
timer. */
vIPNetworkUpCalls( );
/* Test if socket was indeed created. */
if( xDHCPData.xDHCPSocket != NULL )
{
/* Close socket to ensure packets don't queue on it. */
vSocketClose( xDHCPData.xDHCPSocket );
xDHCPData.xDHCPSocket = NULL;
}
}
}
/*-----------------------------------------------------------*/
static void prvCreateDHCPSocket( void )
{
struct freertos_sockaddr xAddress;
BaseType_t xReturn;
TickType_t xTimeoutTime = ( TickType_t ) 0;
/* Create the socket, if it has not already been created. */
if( xDHCPData.xDHCPSocket == NULL )
{
xDHCPData.xDHCPSocket = FreeRTOS_socket( FREERTOS_AF_INET, FREERTOS_SOCK_DGRAM, FREERTOS_IPPROTO_UDP );
if( xDHCPData.xDHCPSocket != FREERTOS_INVALID_SOCKET )
{
/* Ensure the Rx and Tx timeouts are zero as the DHCP executes in the
context of the IP task. */
FreeRTOS_setsockopt( xDHCPData.xDHCPSocket, 0, FREERTOS_SO_RCVTIMEO, ( void * ) &xTimeoutTime, sizeof( TickType_t ) );
FreeRTOS_setsockopt( xDHCPData.xDHCPSocket, 0, FREERTOS_SO_SNDTIMEO, ( void * ) &xTimeoutTime, sizeof( TickType_t ) );
/* Bind to the standard DHCP client port. */
xAddress.sin_port = ( uint16_t ) dhcpCLIENT_PORT;
xReturn = vSocketBind( xDHCPData.xDHCPSocket, &xAddress, sizeof( xAddress ), pdFALSE );
if( xReturn != 0 )
{
/* Binding failed, close the socket again. */
vSocketClose( xDHCPData.xDHCPSocket );
xDHCPData.xDHCPSocket = NULL;
}
}
else
{
/* Change to NULL for easier testing. */
xDHCPData.xDHCPSocket = NULL;
}
}
}
/*-----------------------------------------------------------*/
static void prvInitialiseDHCP( void )
{
/* Initialise the parameters that will be set by the DHCP process. Per
https://www.ietf.org/rfc/rfc2131.txt, Transaction ID should be a random
value chosen by the client. */
xDHCPData.ulTransactionId = ipconfigRAND32();
/* Check for random number generator API failure. */
if( 0 != xDHCPData.ulTransactionId )
{
xDHCPData.xUseBroadcast = 0;
xDHCPData.ulOfferedIPAddress = 0UL;
xDHCPData.ulDHCPServerAddress = 0UL;
xDHCPData.xDHCPTxPeriod = dhcpINITIAL_DHCP_TX_PERIOD;
/* Create the DHCP socket if it has not already been created. */
prvCreateDHCPSocket();
FreeRTOS_debug_printf( ( "prvInitialiseDHCP: start after %lu ticks\n", dhcpINITIAL_TIMER_PERIOD ) );
vIPReloadDHCPTimer( dhcpINITIAL_TIMER_PERIOD );
}
}
/*-----------------------------------------------------------*/
static BaseType_t prvProcessDHCPReplies( BaseType_t xExpectedMessageType )
{
uint8_t *pucUDPPayload, *pucLastByte;
struct freertos_sockaddr xClient;
uint32_t xClientLength = sizeof( xClient );
int32_t lBytes;
DHCPMessage_t *pxDHCPMessage;
uint8_t *pucByte, ucOptionCode, ucLength;
uint32_t ulProcessed, ulParameter;
BaseType_t xReturn = pdFALSE;
const uint32_t ulMandatoryOptions = 2ul; /* DHCP server address, and the correct DHCP message type must be present in the options. */
lBytes = FreeRTOS_recvfrom( xDHCPData.xDHCPSocket, ( void * ) &pucUDPPayload, 0ul, FREERTOS_ZERO_COPY, &xClient, &xClientLength );
if( lBytes > 0 )
{
/* Map a DHCP structure onto the received data. */
pxDHCPMessage = ( DHCPMessage_t * ) ( pucUDPPayload );
/* Sanity check. */
if( ( lBytes >= sizeof( DHCPMessage_t ) ) &&
( pxDHCPMessage->ulDHCPCookie == ( uint32_t ) dhcpCOOKIE ) &&
( pxDHCPMessage->ucOpcode == ( uint8_t ) dhcpREPLY_OPCODE ) &&
( pxDHCPMessage->ulTransactionID == FreeRTOS_htonl( xDHCPData.ulTransactionId ) ) )
{
if( memcmp( ( void * ) &( pxDHCPMessage->ucClientHardwareAddress ),
( void * ) ipLOCAL_MAC_ADDRESS,
sizeof( MACAddress_t ) ) == 0 )
{
/* None of the essential options have been processed yet. */
ulProcessed = 0ul;
/* Walk through the options until the dhcpOPTION_END_BYTE byte
is found, taking care not to walk off the end of the options. */
pucByte = &( pxDHCPMessage->ucFirstOptionByte );
pucLastByte = &( pucUDPPayload[ lBytes - dhcpMAX_OPTION_LENGTH_OF_INTEREST ] );
while( pucByte < pucLastByte )
{
ucOptionCode = pucByte[ 0 ];
if( ucOptionCode == dhcpOPTION_END_BYTE )
{
/* Ready, the last byte has been seen. */
break;
}
if( ucOptionCode == dhcpZERO_PAD_OPTION_CODE )
{
/* The value zero is used as a pad byte,
it is not followed by a length byte. */
pucByte += 1;
continue;
}
/* Stop if the response is malformed. */
if( pucByte < pucLastByte - 1 )
{
ucLength = pucByte[ 1 ];
pucByte += 2;
if( pucByte >= pucLastByte - ucLength )
{
break;
}
}
else
{
break;
}
/* In most cases, a 4-byte network-endian parameter follows,
just get it once here and use later. */
if( ucLength >= sizeof( ulParameter ) )
{
memcpy( ( void * ) &( ulParameter ),
( void * ) pucByte,
( size_t ) sizeof( ulParameter ) );
}
else
{
ulParameter = 0;
}
/* Option-specific handling. */
switch( ucOptionCode )
{
case dhcpMESSAGE_TYPE_OPTION_CODE :
if( *pucByte == ( uint8_t ) xExpectedMessageType )
{
/* The message type is the message type the
state machine is expecting. */
ulProcessed++;
}
else if( *pucByte == ( uint8_t ) dhcpMESSAGE_TYPE_NACK )
{
if( xExpectedMessageType == ( BaseType_t ) dhcpMESSAGE_TYPE_ACK )
{
/* Start again. */
xDHCPData.eDHCPState = eWaitingSendFirstDiscover;
}
}
else
{
/* Don't process other message types. */
}
break;
case dhcpSUBNET_MASK_OPTION_CODE :
if( ucLength == sizeof( uint32_t ) )
{
xNetworkAddressing.ulNetMask = ulParameter;
}
break;
case dhcpGATEWAY_OPTION_CODE :
if( ucLength == sizeof( uint32_t ) )
{
/* ulProcessed is not incremented in this case
because the gateway is not essential. */
xNetworkAddressing.ulGatewayAddress = ulParameter;
}
break;
case dhcpDNS_SERVER_OPTIONS_CODE :
/* ulProcessed is not incremented in this case
because the DNS server is not essential. Only the
first DNS server address is taken. */
xNetworkAddressing.ulDNSServerAddress = ulParameter;
break;
case dhcpSERVER_IP_ADDRESS_OPTION_CODE :
if( ucLength == sizeof( uint32_t ) )
{
if( xExpectedMessageType == ( BaseType_t ) dhcpMESSAGE_TYPE_OFFER )
{
/* Offers state the replying server. */
ulProcessed++;
xDHCPData.ulDHCPServerAddress = ulParameter;
}
else
{
/* The ack must come from the expected server. */
if( xDHCPData.ulDHCPServerAddress == ulParameter )
{
ulProcessed++;
}
}
}
break;
case dhcpLEASE_TIME_OPTION_CODE :
if( ucLength == sizeof( xDHCPData.ulLeaseTime ) )
{
/* ulProcessed is not incremented in this case
because the lease time is not essential. */
/* The DHCP parameter is in seconds, convert
to host-endian format. */
xDHCPData.ulLeaseTime = FreeRTOS_ntohl( ulParameter );
/* Divide the lease time by two to ensure a
renew request is sent before the lease actually
expires. */
xDHCPData.ulLeaseTime >>= 1UL;
/* Multiply with configTICK_RATE_HZ to get clock
ticks. */
xDHCPData.ulLeaseTime = configTICK_RATE_HZ * xDHCPData.ulLeaseTime;
}
break;
default :
/* Not interested in this field. */
break;
}
/* Jump over the data to find the next option code. */
if( ucLength == 0u )
{
break;
}
else
{
pucByte += ucLength;
}
}
/* Were all the mandatory options received? */
if( ulProcessed >= ulMandatoryOptions )
{
/* HT:endian: used to be network order */
xDHCPData.ulOfferedIPAddress = pxDHCPMessage->ulYourIPAddress_yiaddr;
FreeRTOS_printf( ( "vDHCPProcess: offer %lxip\n", FreeRTOS_ntohl( xDHCPData.ulOfferedIPAddress ) ) );
xReturn = pdPASS;
}
}
}
FreeRTOS_ReleaseUDPPayloadBuffer( ( void * ) pucUDPPayload );
}
return xReturn;
}
/*-----------------------------------------------------------*/
static uint8_t *prvCreatePartDHCPMessage( struct freertos_sockaddr *pxAddress, BaseType_t xOpcode, const uint8_t * const pucOptionsArray, size_t *pxOptionsArraySize )
{
DHCPMessage_t *pxDHCPMessage;
size_t xRequiredBufferSize = sizeof( DHCPMessage_t ) + *pxOptionsArraySize;
uint8_t *pucUDPPayloadBuffer;
#if( ipconfigDHCP_REGISTER_HOSTNAME == 1 )
const char *pucHostName = pcApplicationHostnameHook ();
size_t xNameLength = strlen( pucHostName );
uint8_t *pucPtr;
xRequiredBufferSize += ( 2 + xNameLength );
#endif
/* Get a buffer. This uses a maximum delay, but the delay will be capped
to ipconfigUDP_MAX_SEND_BLOCK_TIME_TICKS so the return value still needs to
be test. */
do
{
} while( ( pucUDPPayloadBuffer = ( uint8_t * ) FreeRTOS_GetUDPPayloadBuffer( xRequiredBufferSize, portMAX_DELAY ) ) == NULL );
pxDHCPMessage = ( DHCPMessage_t * ) pucUDPPayloadBuffer;
/* Most fields need to be zero. */
memset( ( void * ) pxDHCPMessage, 0x00, sizeof( DHCPMessage_t ) );
/* Create the message. */
pxDHCPMessage->ucOpcode = ( uint8_t ) xOpcode;
pxDHCPMessage->ucAddressType = ( uint8_t ) dhcpADDRESS_TYPE_ETHERNET;
pxDHCPMessage->ucAddressLength = ( uint8_t ) dhcpETHERNET_ADDRESS_LENGTH;
pxDHCPMessage->ulTransactionID = FreeRTOS_htonl( xDHCPData.ulTransactionId );
pxDHCPMessage->ulDHCPCookie = ( uint32_t ) dhcpCOOKIE;
if( xDHCPData.xUseBroadcast != pdFALSE )
{
pxDHCPMessage->usFlags = ( uint16_t ) dhcpBROADCAST;
}
else
{
pxDHCPMessage->usFlags = 0u;
}
memcpy( ( void * ) &( pxDHCPMessage->ucClientHardwareAddress[ 0 ] ), ( void * ) ipLOCAL_MAC_ADDRESS, sizeof( MACAddress_t ) );
/* Copy in the const part of the options options. */
memcpy( ( void * ) &( pucUDPPayloadBuffer[ dhcpFIRST_OPTION_BYTE_OFFSET ] ), ( void * ) pucOptionsArray, *pxOptionsArraySize );
#if( ipconfigDHCP_REGISTER_HOSTNAME == 1 )
{
/* With this option, the hostname can be registered as well which makes
it easier to lookup a device in a router's list of DHCP clients. */
/* Point to where the OPTION_END was stored to add data. */
pucPtr = &( pucUDPPayloadBuffer[ dhcpFIRST_OPTION_BYTE_OFFSET + ( *pxOptionsArraySize - 1 ) ] );
pucPtr[ 0 ] = dhcpDNS_HOSTNAME_OPTIONS_CODE;
pucPtr[ 1 ] = ( uint8_t ) xNameLength;
memcpy( ( void *) ( pucPtr + 2 ), pucHostName, xNameLength );
pucPtr[ 2 + xNameLength ] = dhcpOPTION_END_BYTE;
*pxOptionsArraySize += ( 2 + xNameLength );
}
#endif
/* Map in the client identifier. */
memcpy( ( void * ) &( pucUDPPayloadBuffer[ dhcpFIRST_OPTION_BYTE_OFFSET + dhcpCLIENT_IDENTIFIER_OFFSET ] ),
( void * ) ipLOCAL_MAC_ADDRESS, sizeof( MACAddress_t ) );
/* Set the addressing. */
pxAddress->sin_addr = ipBROADCAST_IP_ADDRESS;
pxAddress->sin_port = ( uint16_t ) dhcpSERVER_PORT;
return pucUDPPayloadBuffer;
}
/*-----------------------------------------------------------*/
static void prvSendDHCPRequest( void )
{
uint8_t *pucUDPPayloadBuffer;
struct freertos_sockaddr xAddress;
static const uint8_t ucDHCPRequestOptions[] =
{
/* Do not change the ordering without also changing
dhcpCLIENT_IDENTIFIER_OFFSET, dhcpREQUESTED_IP_ADDRESS_OFFSET and
dhcpDHCP_SERVER_IP_ADDRESS_OFFSET. */
dhcpMESSAGE_TYPE_OPTION_CODE, 1, dhcpMESSAGE_TYPE_REQUEST, /* Message type option. */
dhcpCLIENT_IDENTIFIER_OPTION_CODE, 6, 0, 0, 0, 0, 0, 0, /* Client identifier. */
dhcpREQUEST_IP_ADDRESS_OPTION_CODE, 4, 0, 0, 0, 0, /* The IP address being requested. */
dhcpSERVER_IP_ADDRESS_OPTION_CODE, 4, 0, 0, 0, 0, /* The IP address of the DHCP server. */
dhcpOPTION_END_BYTE
};
size_t xOptionsLength = sizeof( ucDHCPRequestOptions );
pucUDPPayloadBuffer = prvCreatePartDHCPMessage( &xAddress, dhcpREQUEST_OPCODE, ucDHCPRequestOptions, &xOptionsLength );
/* Copy in the IP address being requested. */
memcpy( ( void * ) &( pucUDPPayloadBuffer[ dhcpFIRST_OPTION_BYTE_OFFSET + dhcpREQUESTED_IP_ADDRESS_OFFSET ] ),
( void * ) &( xDHCPData.ulOfferedIPAddress ), sizeof( xDHCPData.ulOfferedIPAddress ) );
/* Copy in the address of the DHCP server being used. */
memcpy( ( void * ) &( pucUDPPayloadBuffer[ dhcpFIRST_OPTION_BYTE_OFFSET + dhcpDHCP_SERVER_IP_ADDRESS_OFFSET ] ),
( void * ) &( xDHCPData.ulDHCPServerAddress ), sizeof( xDHCPData.ulDHCPServerAddress ) );
FreeRTOS_debug_printf( ( "vDHCPProcess: reply %lxip\n", FreeRTOS_ntohl( xDHCPData.ulOfferedIPAddress ) ) );
iptraceSENDING_DHCP_REQUEST();
if( FreeRTOS_sendto( xDHCPData.xDHCPSocket, pucUDPPayloadBuffer, ( sizeof( DHCPMessage_t ) + xOptionsLength ), FREERTOS_ZERO_COPY, &xAddress, sizeof( xAddress ) ) == 0 )
{
/* The packet was not successfully queued for sending and must be
returned to the stack. */
FreeRTOS_ReleaseUDPPayloadBuffer( pucUDPPayloadBuffer );
}
}
/*-----------------------------------------------------------*/
static void prvSendDHCPDiscover( void )
{
uint8_t *pucUDPPayloadBuffer;
struct freertos_sockaddr xAddress;
static const uint8_t ucDHCPDiscoverOptions[] =
{
/* Do not change the ordering without also changing dhcpCLIENT_IDENTIFIER_OFFSET. */
dhcpMESSAGE_TYPE_OPTION_CODE, 1, dhcpMESSAGE_TYPE_DISCOVER, /* Message type option. */
dhcpCLIENT_IDENTIFIER_OPTION_CODE, 6, 0, 0, 0, 0, 0, 0, /* Client identifier. */
dhcpPARAMETER_REQUEST_OPTION_CODE, 3, dhcpSUBNET_MASK_OPTION_CODE, dhcpGATEWAY_OPTION_CODE, dhcpDNS_SERVER_OPTIONS_CODE, /* Parameter request option. */
dhcpOPTION_END_BYTE
};
size_t xOptionsLength = sizeof( ucDHCPDiscoverOptions );
pucUDPPayloadBuffer = prvCreatePartDHCPMessage( &xAddress, dhcpREQUEST_OPCODE, ucDHCPDiscoverOptions, &xOptionsLength );
FreeRTOS_debug_printf( ( "vDHCPProcess: discover\n" ) );
iptraceSENDING_DHCP_DISCOVER();
if( FreeRTOS_sendto( xDHCPData.xDHCPSocket, pucUDPPayloadBuffer, ( sizeof( DHCPMessage_t ) + xOptionsLength ), FREERTOS_ZERO_COPY, &xAddress, sizeof( xAddress ) ) == 0 )
{
/* The packet was not successfully queued for sending and must be
returned to the stack. */
FreeRTOS_ReleaseUDPPayloadBuffer( pucUDPPayloadBuffer );
}
}
/*-----------------------------------------------------------*/
#if( ipconfigDHCP_FALL_BACK_AUTO_IP != 0 )
static void prvPrepareLinkLayerIPLookUp( void )
{
uint8_t ucLinkLayerIPAddress[ 2 ];
/* After DHCP has failed to answer, prepare everything to start
trying-out LinkLayer IP-addresses, using the random method. */
xDHCPData.xDHCPTxTime = xTaskGetTickCount();
ucLinkLayerIPAddress[ 0 ] = ( uint8_t )1 + ( uint8_t )( ipconfigRAND32() % 0xFDu ); /* get value 1..254 for IP-address 3rd byte of IP address to try. */
ucLinkLayerIPAddress[ 1 ] = ( uint8_t )1 + ( uint8_t )( ipconfigRAND32() % 0xFDu ); /* get value 1..254 for IP-address 4th byte of IP address to try. */
xNetworkAddressing.ulGatewayAddress = FreeRTOS_htonl( 0xA9FE0203 );
/* prepare xDHCPData with data to test. */
xDHCPData.ulOfferedIPAddress =
FreeRTOS_inet_addr_quick( LINK_LAYER_ADDRESS_0, LINK_LAYER_ADDRESS_1, ucLinkLayerIPAddress[ 0 ], ucLinkLayerIPAddress[ 1 ] );
xDHCPData.ulLeaseTime = dhcpDEFAULT_LEASE_TIME; /* don't care about lease time. just put anything. */
xNetworkAddressing.ulNetMask =
FreeRTOS_inet_addr_quick( LINK_LAYER_NETMASK_0, LINK_LAYER_NETMASK_1, LINK_LAYER_NETMASK_2, LINK_LAYER_NETMASK_3 );
/* DHCP completed. The IP address can now be used, and the
timer set to the lease timeout time. */
*ipLOCAL_IP_ADDRESS_POINTER = xDHCPData.ulOfferedIPAddress;
/* Setting the 'local' broadcast address, something like 192.168.1.255' */
xNetworkAddressing.ulBroadcastAddress = ( xDHCPData.ulOfferedIPAddress & xNetworkAddressing.ulNetMask ) | ~xNetworkAddressing.ulNetMask;
/* Close socket to ensure packets don't queue on it. not needed anymore as DHCP failed. but still need timer for ARP testing. */
vSocketClose( xDHCPData.xDHCPSocket );
xDHCPData.xDHCPSocket = NULL;
xDHCPData.xDHCPTxPeriod = pdMS_TO_TICKS( 3000ul + ( ipconfigRAND32() & 0x3fful ) ); /* do ARP test every (3 + 0-1024mS) seconds. */
xARPHadIPClash = pdFALSE; /* reset flag that shows if have ARP clash. */
vARPSendGratuitous();
}
#endif /* ipconfigDHCP_FALL_BACK_AUTO_IP */
/*-----------------------------------------------------------*/
#endif /* ipconfigUSE_DHCP != 0 */
/*
* FreeRTOS+TCP V2.0.11
* Copyright (C) 2017 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
*/
/* Standard includes. */
#include <stdint.h>
/* FreeRTOS includes. */
#include "FreeRTOS.h"
#include "task.h"
#include "queue.h"
#include "list.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_DNS.h"
#include "NetworkBufferManagement.h"
#include "NetworkInterface.h"
#include "IPTraceMacroDefaults.h"
/* Exclude the entire file if DNS is not enabled. */
#if( ipconfigUSE_DNS != 0 )
#if( ipconfigBYTE_ORDER == pdFREERTOS_LITTLE_ENDIAN )
#define dnsDNS_PORT 0x3500
#define dnsONE_QUESTION 0x0100
#define dnsOUTGOING_FLAGS 0x0001 /* Standard query. */
#define dnsRX_FLAGS_MASK 0x0f80 /* The bits of interest in the flags field of incoming DNS messages. */
#define dnsEXPECTED_RX_FLAGS 0x0080 /* Should be a response, without any errors. */
#else
#define dnsDNS_PORT 0x0035
#define dnsONE_QUESTION 0x0001
#define dnsOUTGOING_FLAGS 0x0100 /* Standard query. */
#define dnsRX_FLAGS_MASK 0x800f /* The bits of interest in the flags field of incoming DNS messages. */
#define dnsEXPECTED_RX_FLAGS 0x8000 /* Should be a response, without any errors. */
#endif /* ipconfigBYTE_ORDER */
/* The maximum number of times a DNS request should be sent out if a response
is not received, before giving up. */
#ifndef ipconfigDNS_REQUEST_ATTEMPTS
#define ipconfigDNS_REQUEST_ATTEMPTS 5
#endif
/* 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. */
#define dnsNBNS_FLAGS_RESPONSE 0x8000
#define dnsNBNS_FLAGS_OPCODE_MASK 0x7800
#define dnsNBNS_FLAGS_OPCODE_QUERY 0x0000
#define dnsNBNS_FLAGS_OPCODE_REGISTRATION 0x2800
/* Host types. */
#define dnsTYPE_A_HOST 0x01
#define dnsCLASS_IN 0x01
/* LLMNR constants. */
#define dnsLLMNR_TTL_VALUE 300000
#define dnsLLMNR_FLAGS_IS_REPONSE 0x8000
/* NBNS constants. */
#define dnsNBNS_TTL_VALUE 3600 /* 1 hour valid */
#define dnsNBNS_TYPE_NET_BIOS 0x0020
#define dnsNBNS_CLASS_IN 0x01
#define dnsNBNS_NAME_FLAGS 0x6000
#define dnsNBNS_ENCODED_NAME_LENGTH 32
/* 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 ( 0x8500 )
/* Flag DNS parsing errors in situations where an IPv4 address is the return
type. */
#define dnsPARSE_ERROR 0UL
/*
* 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.
*/
static Socket_t prvCreateDNSSocket( void );
/*
* Create the DNS message in the zero copy buffer passed in the first parameter.
*/
static size_t prvCreateDNSMessage( uint8_t *pucUDPPayloadBuffer, const char *pcHostName, TickType_t xIdentifier );
/*
* Simple routine that jumps over the NAME field of a resource record.
*/
static uint8_t *prvSkipNameField( uint8_t *pucByte, size_t xSourceLen );
/*
* Process a response packet from a DNS server.
*/
static uint32_t prvParseDNSReply( uint8_t *pucUDPPayloadBuffer, size_t xBufferLength, TickType_t xIdentifier );
/*
* Prepare and send a message to a DNS server. 'xReadTimeOut_ms' will be passed as
* zero, in case the user has supplied a call-back function.
*/
static uint32_t prvGetHostByName( const char *pcHostName, TickType_t xIdentifier, TickType_t xReadTimeOut_ms );
/*
* The NBNS and the LLMNR protocol share this reply function.
*/
#if( ( ipconfigUSE_NBNS == 1 ) || ( ipconfigUSE_LLMNR == 1 ) )
static void prvReplyDNSMessage( NetworkBufferDescriptor_t *pxNetworkBuffer, BaseType_t lNetLength );
#endif
#if( ipconfigUSE_NBNS == 1 )
static portINLINE void prvTreatNBNS( uint8_t *pucUDPPayloadBuffer, size_t xBufferLength, uint32_t ulIPAddress );
#endif /* ipconfigUSE_NBNS */
#if( ipconfigUSE_DNS_CACHE == 1 )
static uint8_t *prvReadNameField( uint8_t *pucByte, size_t xSourceLen, char *pcName, size_t xLen );
static void prvProcessDNSCache( const char *pcName, uint32_t *pulIP, uint32_t ulTTL, BaseType_t xLookUp );
typedef struct xDNS_CACHE_TABLE_ROW
{
uint32_t ulIPAddress; /* The IP address of an ARP 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;
} DNSCacheRow_t;
static DNSCacheRow_t xDNSCache[ ipconfigDNS_CACHE_ENTRIES ];
#endif /* ipconfigUSE_DNS_CACHE == 1 */
#if( ipconfigUSE_LLMNR == 1 )
const MACAddress_t xLLMNR_MacAdress = { { 0x01, 0x00, 0x5e, 0x00, 0x00, 0xfc } };
#endif /* ipconfigUSE_LLMNR == 1 */
/*-----------------------------------------------------------*/
#include "pack_struct_start.h"
struct xDNSMessage
{
uint16_t usIdentifier;
uint16_t usFlags;
uint16_t usQuestions;
uint16_t usAnswers;
uint16_t usAuthorityRRs;
uint16_t usAdditionalRRs;
}
#include "pack_struct_end.h"
typedef struct xDNSMessage DNSMessage_t;
/* A DNS query consists of a header, as described in 'struct xDNSMessage'
It is followed by 1 or more queries, each one consisting of a name and a tail,
with two fields: type and class
*/
#include "pack_struct_start.h"
struct xDNSTail
{
uint16_t usType;
uint16_t usClass;
}
#include "pack_struct_end.h"
typedef struct xDNSTail DNSTail_t;
/* DNS answer record header. */
#include "pack_struct_start.h"
struct xDNSAnswerRecord
{
uint16_t usType;
uint16_t usClass;
uint32_t ulTTL;
uint16_t usDataLength;
}
#include "pack_struct_end.h"
typedef struct xDNSAnswerRecord DNSAnswerRecord_t;
#if( ipconfigUSE_LLMNR == 1 )
#include "pack_struct_start.h"
struct xLLMNRAnswer
{
uint8_t ucNameCode;
uint8_t ucNameOffset; /* The name is not repeated in the answer, only the offset is given with "0xc0 <offs>" */
uint16_t usType;
uint16_t usClass;
uint32_t ulTTL;
uint16_t usDataLength;
uint32_t ulIPAddress;
}
#include "pack_struct_end.h"
typedef struct xLLMNRAnswer LLMNRAnswer_t;
#endif /* ipconfigUSE_LLMNR == 1 */
#if( ipconfigUSE_NBNS == 1 )
#include "pack_struct_start.h"
struct xNBNSRequest
{
uint16_t usRequestId;
uint16_t usFlags;
uint16_t ulRequestCount;
uint16_t usAnswerRSS;
uint16_t usAuthRSS;
uint16_t usAdditionalRSS;
uint8_t ucNameSpace;
uint8_t ucName[ dnsNBNS_ENCODED_NAME_LENGTH ];
uint8_t ucNameZero;
uint16_t usType;
uint16_t usClass;
}
#include "pack_struct_end.h"
typedef struct xNBNSRequest NBNSRequest_t;
#include "pack_struct_start.h"
struct xNBNSAnswer
{
uint16_t usType;
uint16_t usClass;
uint32_t ulTTL;
uint16_t usDataLength;
uint16_t usNbFlags; /* NetBIOS flags 0x6000 : IP-address, big-endian */
uint32_t ulIPAddress;
}
#include "pack_struct_end.h"
typedef struct xNBNSAnswer NBNSAnswer_t;
#endif /* ipconfigUSE_NBNS == 1 */
/*-----------------------------------------------------------*/
#if( ipconfigUSE_DNS_CACHE == 1 )
uint32_t FreeRTOS_dnslookup( const char *pcHostName )
{
uint32_t ulIPAddress = 0UL;
prvProcessDNSCache( pcHostName, &ulIPAddress, 0, pdTRUE );
return ulIPAddress;
}
#endif /* ipconfigUSE_DNS_CACHE == 1 */
/*-----------------------------------------------------------*/
#if( ipconfigDNS_USE_CALLBACKS != 0 )
typedef struct xDNS_Callback {
TickType_t xRemaningTime; /* Timeout in ms */
FOnDNSEvent pCallbackFunction; /* Function to be called when the address has been found or when a timeout has beeen reached */
TimeOut_t xTimeoutState;
void *pvSearchID;
struct xLIST_ITEM xListItem;
char pcName[ 1 ];
} DNSCallback_t;
static List_t xCallbackList;
/* Define FreeRTOS_gethostbyname() as a normal blocking call. */
uint32_t FreeRTOS_gethostbyname( const char *pcHostName )
{
return FreeRTOS_gethostbyname_a( pcHostName, ( FOnDNSEvent ) NULL, ( void* )NULL, 0 );
}
/*-----------------------------------------------------------*/
/* Initialise the list of call-back structures. */
void vDNSInitialise( void );
void vDNSInitialise( void )
{
vListInitialise( &xCallbackList );
}
/*-----------------------------------------------------------*/
/* Iterate through the list of call-back structures and remove
old entries which have reached a timeout.
As soon as the list hase become empty, the DNS timer will be stopped
In case pvSearchID is supplied, the user wants to cancel a DNS request
*/
void vDNSCheckCallBack( void *pvSearchID );
void vDNSCheckCallBack( void *pvSearchID )
{
const ListItem_t *pxIterator;
const MiniListItem_t* xEnd = ( const MiniListItem_t* )listGET_END_MARKER( &xCallbackList );
vTaskSuspendAll();
{
for( pxIterator = ( const ListItem_t * ) listGET_NEXT( xEnd );
pxIterator != ( const ListItem_t * ) xEnd;
)
{
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 ) )
{
uxListRemove( &pxCallback->xListItem );
vPortFree( pxCallback );
}
else if( xTaskCheckForTimeOut( &pxCallback->xTimeoutState, &pxCallback->xRemaningTime ) != pdFALSE )
{
pxCallback->pCallbackFunction( pxCallback->pcName, pxCallback->pvSearchID, 0 );
uxListRemove( &pxCallback->xListItem );
vPortFree( ( void * ) pxCallback );
}
}
}
xTaskResumeAll();
if( listLIST_IS_EMPTY( &xCallbackList ) )
{
vIPSetDnsTimerEnableState( pdFALSE );
}
}
/*-----------------------------------------------------------*/
void FreeRTOS_gethostbyname_cancel( void *pvSearchID )
{
/* _HT_ Should better become a new API call to have the IP-task remove the callback */
vDNSCheckCallBack( pvSearchID );
}
/*-----------------------------------------------------------*/
/* FreeRTOS_gethostbyname_a() was called along with callback parameters.
Store them in a list for later reference. */
static void vDNSSetCallBack( const char *pcHostName, void *pvSearchID, FOnDNSEvent pCallbackFunction, TickType_t xTimeout, TickType_t xIdentifier );
static void vDNSSetCallBack( const char *pcHostName, void *pvSearchID, FOnDNSEvent pCallbackFunction, TickType_t xTimeout, TickType_t xIdentifier )
{
size_t lLength = strlen( pcHostName );
DNSCallback_t *pxCallback = ( DNSCallback_t * )pvPortMalloc( sizeof( *pxCallback ) + lLength );
/* Translate from ms to number of clock ticks. */
xTimeout /= portTICK_PERIOD_MS;
if( pxCallback != NULL )
{
if( listLIST_IS_EMPTY( &xCallbackList ) )
{
/* This is the first one, start the DNS timer to check for timeouts */
vIPReloadDNSTimer( FreeRTOS_min_uint32( 1000U, xTimeout ) );
}
strcpy( pxCallback->pcName, pcHostName );
pxCallback->pCallbackFunction = pCallbackFunction;
pxCallback->pvSearchID = pvSearchID;
pxCallback->xRemaningTime = xTimeout;
vTaskSetTimeOutState( &pxCallback->xTimeoutState );
listSET_LIST_ITEM_OWNER( &( pxCallback->xListItem ), ( void* ) pxCallback );
listSET_LIST_ITEM_VALUE( &( pxCallback->xListItem ), xIdentifier );
vTaskSuspendAll();
{
vListInsertEnd( &xCallbackList, &pxCallback->xListItem );
}
xTaskResumeAll();
}
}
/*-----------------------------------------------------------*/
/* A DNS reply was received, see if there is any matching entry and
call the handler. */
static void vDNSDoCallback( TickType_t xIdentifier, const char *pcName, uint32_t ulIPAddress );
static void vDNSDoCallback( TickType_t xIdentifier, const char *pcName, uint32_t ulIPAddress )
{
const ListItem_t *pxIterator;
const MiniListItem_t* xEnd = ( const MiniListItem_t* )listGET_END_MARKER( &xCallbackList );
vTaskSuspendAll();
{
for( pxIterator = ( const ListItem_t * ) listGET_NEXT( xEnd );
pxIterator != ( const ListItem_t * ) xEnd;
pxIterator = ( const ListItem_t * ) listGET_NEXT( pxIterator ) )
{
if( listGET_LIST_ITEM_VALUE( pxIterator ) == xIdentifier )
{
DNSCallback_t *pxCallback = ( DNSCallback_t * ) listGET_LIST_ITEM_OWNER( pxIterator );
pxCallback->pCallbackFunction( pcName, pxCallback->pvSearchID, ulIPAddress );
uxListRemove( &pxCallback->xListItem );
vPortFree( pxCallback );
if( listLIST_IS_EMPTY( &xCallbackList ) )
{
vIPSetDnsTimerEnableState( pdFALSE );
}
break;
}
}
}
xTaskResumeAll();
}
#endif /* ipconfigDNS_USE_CALLBACKS != 0 */
/*-----------------------------------------------------------*/
#if( ipconfigDNS_USE_CALLBACKS == 0 )
uint32_t FreeRTOS_gethostbyname( const char *pcHostName )
#else
uint32_t FreeRTOS_gethostbyname_a( const char *pcHostName, FOnDNSEvent pCallback, void *pvSearchID, TickType_t xTimeout )
#endif
{
uint32_t ulIPAddress = 0UL;
TickType_t xReadTimeOut_ms = ipconfigSOCK_DEFAULT_RECEIVE_BLOCK_TIME;
TickType_t xIdentifier = 0;
/* If the supplied hostname is IP address, convert it to uint32_t
and return. */
#if( ipconfigINCLUDE_FULL_INET_ADDR == 1 )
{
ulIPAddress = FreeRTOS_inet_addr( pcHostName );
}
#endif /* ipconfigINCLUDE_FULL_INET_ADDR == 1 */
/* If a DNS cache is used then check the cache before issuing another DNS
request. */
#if( ipconfigUSE_DNS_CACHE == 1 )
{
if( ulIPAddress == 0UL )
{
ulIPAddress = FreeRTOS_dnslookup( pcHostName );
if( ulIPAddress != 0 )
{
FreeRTOS_debug_printf( ( "FreeRTOS_gethostbyname: found '%s' in cache: %lxip\n", pcHostName, ulIPAddress ) );
}
else
{
/* prvGetHostByName will be called to start a DNS lookup */
}
}
}
#endif /* ipconfigUSE_DNS_CACHE == 1 */
/* Generate a unique identifier. */
if( 0 == ulIPAddress )
{
xIdentifier = ( TickType_t )ipconfigRAND32( );
}
#if( ipconfigDNS_USE_CALLBACKS != 0 )
{
if( pCallback != NULL )
{
if( ulIPAddress == 0UL )
{
/* The user has provided a callback function, so do not block on recvfrom() */
if( 0 != xIdentifier )
{
xReadTimeOut_ms = 0;
vDNSSetCallBack( pcHostName, pvSearchID, pCallback, xTimeout, ( TickType_t )xIdentifier );
}
}
else
{
/* The IP address is known, do the call-back now. */
pCallback( pcHostName, pvSearchID, ulIPAddress );
}
}
}
#endif
if( ( ulIPAddress == 0UL ) && ( 0 != xIdentifier ) )
{
ulIPAddress = prvGetHostByName( pcHostName, xIdentifier, xReadTimeOut_ms );
}
return ulIPAddress;
}
/*-----------------------------------------------------------*/
static uint32_t prvGetHostByName( const char *pcHostName, TickType_t xIdentifier, TickType_t xReadTimeOut_ms )
{
struct freertos_sockaddr xAddress;
Socket_t xDNSSocket;
uint32_t ulIPAddress = 0UL;
uint8_t *pucUDPPayloadBuffer;
uint32_t ulAddressLength = sizeof( struct freertos_sockaddr );
BaseType_t xAttempt;
int32_t lBytes;
size_t xPayloadLength, xExpectedPayloadLength;
TickType_t xWriteTimeOut_ms = ipconfigSOCK_DEFAULT_SEND_BLOCK_TIME;
#if( ipconfigUSE_LLMNR == 1 )
BaseType_t bHasDot = pdFALSE;
#endif /* ipconfigUSE_LLMNR == 1 */
/* If LLMNR is being used then determine if the host name includes a '.' -
if not then LLMNR can be used as the lookup method. */
#if( ipconfigUSE_LLMNR == 1 )
{
const char *pucPtr;
for( pucPtr = pcHostName; *pucPtr; pucPtr++ )
{
if( *pucPtr == '.' )
{
bHasDot = pdTRUE;
break;
}
}
}
#endif /* ipconfigUSE_LLMNR == 1 */
/* Two is added at the end for the count of characters in the first
subdomain part and the string end byte. */
xExpectedPayloadLength = sizeof( DNSMessage_t ) + strlen( pcHostName ) + sizeof( uint16_t ) + sizeof( uint16_t ) + 2u;
xDNSSocket = prvCreateDNSSocket();
if( xDNSSocket != NULL )
{
FreeRTOS_setsockopt( xDNSSocket, 0, FREERTOS_SO_SNDTIMEO, ( void * ) &xWriteTimeOut_ms, sizeof( TickType_t ) );
FreeRTOS_setsockopt( xDNSSocket, 0, FREERTOS_SO_RCVTIMEO, ( void * ) &xReadTimeOut_ms, sizeof( TickType_t ) );
for( xAttempt = 0; xAttempt < ipconfigDNS_REQUEST_ATTEMPTS; xAttempt++ )
{
/* Get a buffer. This uses a maximum delay, but the delay will be
capped to ipconfigUDP_MAX_SEND_BLOCK_TIME_TICKS so the return value
still needs to be tested. */
pucUDPPayloadBuffer = ( uint8_t * ) FreeRTOS_GetUDPPayloadBuffer( xExpectedPayloadLength, portMAX_DELAY );
if( pucUDPPayloadBuffer != NULL )
{
/* Create the message in the obtained buffer. */
xPayloadLength = prvCreateDNSMessage( pucUDPPayloadBuffer, pcHostName, xIdentifier );
iptraceSENDING_DNS_REQUEST();
/* Obtain the DNS server address. */
FreeRTOS_GetAddressConfiguration( NULL, NULL, NULL, &ulIPAddress );
/* Send the DNS message. */
#if( ipconfigUSE_LLMNR == 1 )
if( bHasDot == pdFALSE )
{
/* Use LLMNR addressing. */
( ( DNSMessage_t * ) pucUDPPayloadBuffer) -> usFlags = 0;
xAddress.sin_addr = ipLLMNR_IP_ADDR; /* Is in network byte order. */
xAddress.sin_port = FreeRTOS_ntohs( ipLLMNR_PORT );
}
else
#endif
{
/* Use DNS server. */
xAddress.sin_addr = ulIPAddress;
xAddress.sin_port = dnsDNS_PORT;
}
ulIPAddress = 0UL;
if( FreeRTOS_sendto( xDNSSocket, pucUDPPayloadBuffer, xPayloadLength, FREERTOS_ZERO_COPY, &xAddress, sizeof( xAddress ) ) != 0 )
{
/* Wait for the reply. */
lBytes = FreeRTOS_recvfrom( xDNSSocket, &pucUDPPayloadBuffer, 0, FREERTOS_ZERO_COPY, &xAddress, &ulAddressLength );
if( lBytes > 0 )
{
/* The reply was received. Process it. */
ulIPAddress = prvParseDNSReply( pucUDPPayloadBuffer, lBytes, xIdentifier );
/* Finished with the buffer. The zero copy interface
is being used, so the buffer must be freed by the
task. */
FreeRTOS_ReleaseUDPPayloadBuffer( ( void * ) pucUDPPayloadBuffer );
if( ulIPAddress != 0UL )
{
/* All done. */
break;
}
}
}
else
{
/* The message was not sent so the stack will not be
releasing the zero copy - it must be released here. */
FreeRTOS_ReleaseUDPPayloadBuffer( ( void * ) pucUDPPayloadBuffer );
}
}
}
/* Finished with the socket. */
FreeRTOS_closesocket( xDNSSocket );
}
return ulIPAddress;
}
/*-----------------------------------------------------------*/
static size_t prvCreateDNSMessage( uint8_t *pucUDPPayloadBuffer, const char *pcHostName, TickType_t xIdentifier )
{
DNSMessage_t *pxDNSMessageHeader;
uint8_t *pucStart, *pucByte;
DNSTail_t *pxTail;
static const DNSMessage_t xDefaultPartDNSHeader =
{
0, /* The identifier will be overwritten. */
dnsOUTGOING_FLAGS, /* Flags set for standard query. */
dnsONE_QUESTION, /* One question is being asked. */
0, /* No replies are included. */
0, /* No authorities. */
0 /* No additional authorities. */
};
/* Copy in the const part of the header. */
memcpy( ( void * ) pucUDPPayloadBuffer, ( void * ) &xDefaultPartDNSHeader, sizeof( xDefaultPartDNSHeader ) );
/* Write in a unique identifier. */
pxDNSMessageHeader = ( DNSMessage_t * ) pucUDPPayloadBuffer;
pxDNSMessageHeader->usIdentifier = ( uint16_t ) xIdentifier;
/* Create the resource record at the end of the header. First
find the end of the header. */
pucStart = pucUDPPayloadBuffer + sizeof( xDefaultPartDNSHeader );
/* Leave a gap for the first length bytes. */
pucByte = pucStart + 1;
/* Copy in the host name. */
strcpy( ( char * ) pucByte, pcHostName );
/* Mark the end of the string. */
pucByte += strlen( pcHostName );
*pucByte = 0x00u;
/* Walk the string to replace the '.' characters with byte counts.
pucStart holds the address of the byte count. Walking the string
starts after the byte count position. */
pucByte = pucStart;
do
{
pucByte++;
while( ( *pucByte != 0x00 ) && ( *pucByte != '.' ) )
{
pucByte++;
}
/* Fill in the byte count, then move the pucStart pointer up to
the found byte position. */
*pucStart = ( uint8_t ) ( ( uint32_t ) pucByte - ( uint32_t ) pucStart );
( *pucStart )--;
pucStart = pucByte;
} while( *pucByte != 0x00 );
/* Finish off the record. */
pxTail = (DNSTail_t *)( pucByte + 1 );
vSetField16( pxTail, DNSTail_t, usType, dnsTYPE_A_HOST ); /* Type A: host */
vSetField16( pxTail, DNSTail_t, usClass, dnsCLASS_IN ); /* 1: Class IN */
/* Return the total size of the generated message, which is the space from
the last written byte to the beginning of the buffer. */
return ( ( uint32_t ) pucByte - ( uint32_t ) pucUDPPayloadBuffer + 1 ) + sizeof( *pxTail );
}
/*-----------------------------------------------------------*/
#if( ipconfigUSE_DNS_CACHE == 1 )
static uint8_t *prvReadNameField( uint8_t *pucByte, size_t xSourceLen, char *pcName, size_t xDestLen )
{
size_t xNameLen = 0;
BaseType_t xCount;
if( 0 == xSourceLen )
{
return NULL;
}
/* Determine if the name is the fully coded name, or an offset to the name
elsewhere in the message. */
if( ( *pucByte & dnsNAME_IS_OFFSET ) == dnsNAME_IS_OFFSET )
{
/* Jump over the two byte offset. */
if( xSourceLen > sizeof( uint16_t ) )
{
pucByte += sizeof( uint16_t );
}
else
{
pucByte = NULL;
}
}
else
{
/* pucByte points to the full name. Walk over the string. */
while( ( NULL != pucByte ) && ( *pucByte != 0x00 ) && ( xSourceLen > 1 ) )
{
/* If this is not the first time through the loop, then add a
separator in the output. */
if( ( xNameLen > 0 ) && ( xNameLen < ( xDestLen - 1 ) ) )
{
pcName[ xNameLen++ ] = '.';
}
/* Process the first/next sub-string. */
for( xCount = *(pucByte++), xSourceLen--;
xCount-- && xSourceLen > 1;
pucByte++, xSourceLen-- )
{
if( xNameLen < xDestLen - 1 )
{
pcName[ xNameLen++ ] = *( ( char * )pucByte );
}
else
{
/* DNS name is too big for the provided buffer. */
pucByte = NULL;
break;
}
}
}
/* Confirm that a fully formed name was found. */
if( NULL != pucByte )
{
if( 0x00 == *pucByte )
{
pucByte++;
xSourceLen--;
pcName[ xNameLen++ ] = '\0';
}
else
{
pucByte = NULL;
}
}
}
return pucByte;
}
#endif /* ipconfigUSE_DNS_CACHE == 1 */
/*-----------------------------------------------------------*/
static uint8_t *prvSkipNameField( uint8_t *pucByte, size_t xSourceLen )
{
size_t xChunkLength;
if( 0 == xSourceLen )
{
return NULL;
}
/* Determine if the name is the fully coded name, or an offset to the name
elsewhere in the message. */
if( ( *pucByte & dnsNAME_IS_OFFSET ) == dnsNAME_IS_OFFSET )
{
/* Jump over the two byte offset. */
if( xSourceLen > sizeof( uint16_t ) )
{
pucByte += sizeof( uint16_t );
}
else
{
pucByte = NULL;
}
}
else
{
/* pucByte points to the full name. Walk over the string. */
while( ( *pucByte != 0x00 ) && ( xSourceLen > 1 ) )
{
xChunkLength = *pucByte + 1;
if( xSourceLen > xChunkLength )
{
xSourceLen -= xChunkLength;
pucByte += xChunkLength;
}
else
{
pucByte = NULL;
break;
}
}
/* Confirm that a fully formed name was found. */
if( NULL != pucByte )
{
if( 0x00 == *pucByte )
{
pucByte++;
}
else
{
pucByte = NULL;
}
}
}
return pucByte;
}
/*-----------------------------------------------------------*/
uint32_t ulDNSHandlePacket( NetworkBufferDescriptor_t *pxNetworkBuffer )
{
uint8_t *pucUDPPayloadBuffer;
size_t xPlayloadBufferLength;
DNSMessage_t *pxDNSMessageHeader;
xPlayloadBufferLength = pxNetworkBuffer->xDataLength - sizeof( UDPPacket_t );
if ( xPlayloadBufferLength < sizeof( DNSMessage_t ) )
{
return pdFAIL;
}
pucUDPPayloadBuffer = pxNetworkBuffer->pucEthernetBuffer + sizeof( UDPPacket_t );
pxDNSMessageHeader = ( DNSMessage_t * ) pucUDPPayloadBuffer;
if( pxNetworkBuffer->xDataLength > sizeof( UDPPacket_t ) )
{
prvParseDNSReply( pucUDPPayloadBuffer,
xPlayloadBufferLength,
( uint32_t )pxDNSMessageHeader->usIdentifier );
}
/* The packet was not consumed. */
return pdFAIL;
}
/*-----------------------------------------------------------*/
#if( ipconfigUSE_NBNS == 1 )
uint32_t ulNBNSHandlePacket (NetworkBufferDescriptor_t *pxNetworkBuffer )
{
UDPPacket_t *pxUDPPacket = ( UDPPacket_t * ) pxNetworkBuffer->pucEthernetBuffer;
uint8_t *pucUDPPayloadBuffer = pxNetworkBuffer->pucEthernetBuffer + sizeof( UDPPacket_t );
if( pxNetworkBuffer->xDataLength > sizeof( UDPPacket_t) )
{
prvTreatNBNS( pucUDPPayloadBuffer,
pxNetworkBuffer->xDataLength - sizeof( UDPPacket_t ),
pxUDPPacket->xIPHeader.ulSourceIPAddress );
}
/* The packet was not consumed. */
return pdFAIL;
}
#endif /* ipconfigUSE_NBNS */
/*-----------------------------------------------------------*/
static uint32_t prvParseDNSReply( uint8_t *pucUDPPayloadBuffer, size_t xBufferLength, TickType_t xIdentifier )
{
DNSMessage_t *pxDNSMessageHeader;
DNSAnswerRecord_t *pxDNSAnswerRecord;
uint32_t ulIPAddress = 0UL;
#if( ipconfigUSE_LLMNR == 1 )
char *pcRequestedName = NULL;
#endif
uint8_t *pucByte;
size_t xSourceBytesRemaining;
uint16_t x, usDataLength, usQuestions;
#if( ipconfigUSE_LLMNR == 1 )
uint16_t usType = 0, usClass = 0;
#endif
#if( ipconfigUSE_DNS_CACHE == 1 )
char pcName[ ipconfigDNS_CACHE_NAME_LENGTH ] = "";
#endif
/* Ensure that the buffer is of at least minimal DNS message length. */
if( xBufferLength < sizeof( DNSMessage_t ) )
{
return dnsPARSE_ERROR;
}
else
{
xSourceBytesRemaining = xBufferLength;
}
/* Parse the DNS message header. */
pxDNSMessageHeader = ( DNSMessage_t * ) pucUDPPayloadBuffer;
if( pxDNSMessageHeader->usIdentifier == ( uint16_t ) xIdentifier )
{
/* Start at the first byte after the header. */
pucByte = pucUDPPayloadBuffer + sizeof( DNSMessage_t );
xSourceBytesRemaining -= sizeof( DNSMessage_t );
/* Skip any question records. */
usQuestions = FreeRTOS_ntohs( pxDNSMessageHeader->usQuestions );
for( x = 0; x < usQuestions; x++ )
{
#if( ipconfigUSE_LLMNR == 1 )
{
if( x == 0 )
{
pcRequestedName = ( char * ) pucByte;
}
}
#endif
#if( ipconfigUSE_DNS_CACHE == 1 )
if( x == 0 )
{
pucByte = prvReadNameField( pucByte,
xSourceBytesRemaining,
pcName,
sizeof( pcName ) );
/* Check for a malformed response. */
if( NULL == pucByte )
{
return dnsPARSE_ERROR;
}
else
{
xSourceBytesRemaining = ( pucUDPPayloadBuffer + xBufferLength ) - pucByte;
}
}
else
#endif /* ipconfigUSE_DNS_CACHE */
{
/* Skip the variable length pcName field. */
pucByte = prvSkipNameField( pucByte,
xSourceBytesRemaining );
/* Check for a malformed response. */
if( NULL == pucByte )
{
return dnsPARSE_ERROR;
}
else
{
xSourceBytesRemaining = pucUDPPayloadBuffer + xBufferLength - pucByte;
}
}
/* Check the remaining buffer size. */
if( xSourceBytesRemaining >= sizeof( uint32_t ) )
{
#if( ipconfigUSE_LLMNR == 1 )
{
/* usChar2u16 returns value in host endianness */
usType = usChar2u16( pucByte );
usClass = usChar2u16( pucByte + 2 );
}
#endif /* ipconfigUSE_LLMNR */
/* Skip the type and class fields. */
pucByte += sizeof( uint32_t );
xSourceBytesRemaining -= sizeof( uint32_t );
}
else
{
/* Malformed response. */
return dnsPARSE_ERROR;
}
}
/* Search through the answer records. */
pxDNSMessageHeader->usAnswers = FreeRTOS_ntohs( pxDNSMessageHeader->usAnswers );
if( ( pxDNSMessageHeader->usFlags & dnsRX_FLAGS_MASK ) == dnsEXPECTED_RX_FLAGS )
{
for( x = 0; x < pxDNSMessageHeader->usAnswers; x++ )
{
pucByte = prvSkipNameField( pucByte,
xSourceBytesRemaining );
/* Check for a malformed response. */
if( NULL == pucByte )
{
return dnsPARSE_ERROR;
}
else
{
xSourceBytesRemaining = pucUDPPayloadBuffer + xBufferLength - pucByte;
}
/* Is there enough data for an IPv4 A record answer and, if so,
is this an A record? */
if( xSourceBytesRemaining >= sizeof( DNSAnswerRecord_t ) + sizeof( uint32_t ) &&
usChar2u16( pucByte ) == dnsTYPE_A_HOST )
{
/* This is the required record type and is of sufficient size. */
pxDNSAnswerRecord = ( DNSAnswerRecord_t * )pucByte;
/* Sanity check the data length of an IPv4 answer. */
if( FreeRTOS_ntohs( pxDNSAnswerRecord->usDataLength ) == sizeof( uint32_t ) )
{
/* Copy the IP address out of the record. */
memcpy( &ulIPAddress,
pucByte + sizeof( DNSAnswerRecord_t ),
sizeof( uint32_t ) );
#if( ipconfigUSE_DNS_CACHE == 1 )
{
prvProcessDNSCache( pcName, &ulIPAddress, pxDNSAnswerRecord->ulTTL, pdFALSE );
}
#endif /* ipconfigUSE_DNS_CACHE */
#if( ipconfigDNS_USE_CALLBACKS != 0 )
{
/* See if any asynchronous call was made to FreeRTOS_gethostbyname_a() */
vDNSDoCallback( ( TickType_t ) pxDNSMessageHeader->usIdentifier, pcName, ulIPAddress );
}
#endif /* ipconfigDNS_USE_CALLBACKS != 0 */
}
pucByte += sizeof( DNSAnswerRecord_t ) + sizeof( uint32_t );
xSourceBytesRemaining -= ( sizeof( DNSAnswerRecord_t ) + sizeof( uint32_t ) );
break;
}
else if( xSourceBytesRemaining >= sizeof( DNSAnswerRecord_t ) )
{
/* It's not an A record, so skip it. Get the header location
and then jump over the header. */
pxDNSAnswerRecord = ( DNSAnswerRecord_t * )pucByte;
pucByte += sizeof( DNSAnswerRecord_t );
xSourceBytesRemaining -= sizeof( DNSAnswerRecord_t );
/* Determine the length of the answer data from the header. */
usDataLength = FreeRTOS_ntohs( pxDNSAnswerRecord->usDataLength );
/* Jump over the answer. */
if( xSourceBytesRemaining >= usDataLength )
{
pucByte += usDataLength;
xSourceBytesRemaining -= usDataLength;
}
else
{
/* Malformed response. */
return dnsPARSE_ERROR;
}
}
}
}
#if( ipconfigUSE_LLMNR == 1 )
else if( usQuestions && ( usType == dnsTYPE_A_HOST ) && ( usClass == dnsCLASS_IN ) )
{
/* If this is not a reply to our DNS request, it might an LLMNR
request. */
if( xApplicationDNSQueryHook ( ( pcRequestedName + 1 ) ) )
{
int16_t usLength;
NetworkBufferDescriptor_t *pxNewBuffer = NULL;
NetworkBufferDescriptor_t *pxNetworkBuffer = pxUDPPayloadBuffer_to_NetworkBuffer( pucUDPPayloadBuffer );
LLMNRAnswer_t *pxAnswer;
if( ( xBufferAllocFixedSize == pdFALSE ) && ( pxNetworkBuffer != NULL ) )
{
BaseType_t xDataLength = xBufferLength + sizeof( UDPHeader_t ) + sizeof( EthernetHeader_t ) + sizeof( IPHeader_t );
/* The field xDataLength was set to the length of the UDP payload.
The answer (reply) will be longer than the request, so the packet
must be duplicaed into a bigger buffer */
pxNetworkBuffer->xDataLength = xDataLength;
pxNewBuffer = pxDuplicateNetworkBufferWithDescriptor( pxNetworkBuffer, xDataLength + 16 );
if( pxNewBuffer != NULL )
{
BaseType_t xOffset1, xOffset2;
xOffset1 = ( BaseType_t ) ( pucByte - pucUDPPayloadBuffer );
xOffset2 = ( BaseType_t ) ( ( ( uint8_t * ) pcRequestedName ) - pucUDPPayloadBuffer );
pxNetworkBuffer = pxNewBuffer;
pucUDPPayloadBuffer = pxNetworkBuffer->pucEthernetBuffer + ipUDP_PAYLOAD_OFFSET_IPv4;
pucByte = pucUDPPayloadBuffer + xOffset1;
pcRequestedName = ( char * ) ( pucUDPPayloadBuffer + xOffset2 );
pxDNSMessageHeader = ( DNSMessage_t * ) pucUDPPayloadBuffer;
}
else
{
/* Just to indicate that the message may not be answered. */
pxNetworkBuffer = NULL;
}
}
if( pxNetworkBuffer != NULL )
{
pxAnswer = (LLMNRAnswer_t *)pucByte;
/* We leave 'usIdentifier' and 'usQuestions' untouched */
vSetField16( pxDNSMessageHeader, DNSMessage_t, usFlags, dnsLLMNR_FLAGS_IS_REPONSE ); /* Set the response flag */
vSetField16( pxDNSMessageHeader, DNSMessage_t, usAnswers, 1 ); /* Provide a single answer */
vSetField16( pxDNSMessageHeader, DNSMessage_t, usAuthorityRRs, 0 ); /* No authority */
vSetField16( pxDNSMessageHeader, DNSMessage_t, usAdditionalRRs, 0 ); /* No additional info */
pxAnswer->ucNameCode = dnsNAME_IS_OFFSET;
pxAnswer->ucNameOffset = ( uint8_t )( pcRequestedName - ( char * ) pucUDPPayloadBuffer );
vSetField16( pxAnswer, LLMNRAnswer_t, usType, dnsTYPE_A_HOST ); /* Type A: host */
vSetField16( pxAnswer, LLMNRAnswer_t, usClass, dnsCLASS_IN ); /* 1: Class IN */
vSetField32( pxAnswer, LLMNRAnswer_t, ulTTL, dnsLLMNR_TTL_VALUE );
vSetField16( pxAnswer, LLMNRAnswer_t, usDataLength, 4 );
vSetField32( pxAnswer, LLMNRAnswer_t, ulIPAddress, FreeRTOS_ntohl( *ipLOCAL_IP_ADDRESS_POINTER ) );
usLength = ( int16_t ) ( sizeof( *pxAnswer ) + ( size_t ) ( pucByte - pucUDPPayloadBuffer ) );
prvReplyDNSMessage( pxNetworkBuffer, usLength );
if( pxNewBuffer != NULL )
{
vReleaseNetworkBufferAndDescriptor( pxNewBuffer );
}
}
}
}
#endif /* ipconfigUSE_LLMNR == 1 */
}
return ulIPAddress;
}
/*-----------------------------------------------------------*/
#if( ipconfigUSE_NBNS == 1 )
static void prvTreatNBNS( uint8_t *pucUDPPayloadBuffer, size_t xBufferLength, uint32_t ulIPAddress )
{
uint16_t usFlags, usType, usClass;
uint8_t *pucSource, *pucTarget;
uint8_t ucByte;
uint8_t ucNBNSName[ 17 ];
/* Check for minimum buffer size. */
if( xBufferLength < sizeof( NBNSRequest_t ) )
{
return;
}
/* Read the request flags in host endianness. */
usFlags = usChar2u16( pucUDPPayloadBuffer + offsetof( NBNSRequest_t, usFlags ) );
if( ( usFlags & dnsNBNS_FLAGS_OPCODE_MASK ) == dnsNBNS_FLAGS_OPCODE_QUERY )
{
usType = usChar2u16( pucUDPPayloadBuffer + offsetof( NBNSRequest_t, usType ) );
usClass = usChar2u16( pucUDPPayloadBuffer + offsetof( NBNSRequest_t, usClass ) );
/* Not used for now */
( void )usClass;
/* For NBNS a name is 16 bytes long, written with capitals only.
Make sure that the copy is terminated with a zero. */
pucTarget = ucNBNSName + sizeof(ucNBNSName ) - 2;
pucTarget[ 1 ] = '\0';
/* Start with decoding the last 2 bytes. */
pucSource = pucUDPPayloadBuffer + ( offsetof( NBNSRequest_t, ucName ) + ( dnsNBNS_ENCODED_NAME_LENGTH - 2 ) );
for( ;; )
{
ucByte = ( uint8_t ) ( ( ( pucSource[ 0 ] - 0x41 ) << 4 ) | ( pucSource[ 1 ] - 0x41 ) );
/* Make sure there are no trailing spaces in the name. */
if( ( ucByte == ' ' ) && ( pucTarget[ 1 ] == '\0' ) )
{
ucByte = '\0';
}
*pucTarget = ucByte;
if( pucTarget == ucNBNSName )
{
break;
}
pucTarget -= 1;
pucSource -= 2;
}
#if( ipconfigUSE_DNS_CACHE == 1 )
{
if( ( usFlags & dnsNBNS_FLAGS_RESPONSE ) != 0 )
{
/* If this is a response from another device,
add the name to the DNS cache */
prvProcessDNSCache( ( char * ) ucNBNSName, &ulIPAddress, 0, pdFALSE );
}
}
#else
{
/* Avoid compiler warnings. */
( void ) ulIPAddress;
}
#endif /* ipconfigUSE_DNS_CACHE */
if( ( ( usFlags & dnsNBNS_FLAGS_RESPONSE ) == 0 ) &&
( usType == dnsNBNS_TYPE_NET_BIOS ) &&
( xApplicationDNSQueryHook( ( const char * ) ucNBNSName ) != pdFALSE ) )
{
uint16_t usLength;
DNSMessage_t *pxMessage;
NBNSAnswer_t *pxAnswer;
/* Someone is looking for a device with ucNBNSName,
prepare a positive reply. */
NetworkBufferDescriptor_t *pxNetworkBuffer = pxUDPPayloadBuffer_to_NetworkBuffer( pucUDPPayloadBuffer );
if( ( xBufferAllocFixedSize == pdFALSE ) && ( pxNetworkBuffer != NULL ) )
{
NetworkBufferDescriptor_t *pxNewBuffer;
BaseType_t xDataLength = pxNetworkBuffer->xDataLength + sizeof( UDPHeader_t ) +
sizeof( EthernetHeader_t ) + sizeof( IPHeader_t );
/* The field xDataLength was set to the length of the UDP payload.
The answer (reply) will be longer than the request, so the packet
must be duplicated into a bigger buffer */
pxNetworkBuffer->xDataLength = xDataLength;
pxNewBuffer = pxDuplicateNetworkBufferWithDescriptor( pxNetworkBuffer, xDataLength + 16 );
if( pxNewBuffer != NULL )
{
pucUDPPayloadBuffer = pxNewBuffer->pucEthernetBuffer + sizeof( UDPPacket_t );
pxNetworkBuffer = pxNewBuffer;
}
else
{
/* Just prevent that a reply will be sent */
pxNetworkBuffer = NULL;
}
}
/* Should not occur: pucUDPPayloadBuffer is part of a xNetworkBufferDescriptor */
if( pxNetworkBuffer != NULL )
{
pxMessage = (DNSMessage_t *)pucUDPPayloadBuffer;
/* As the fields in the structures are not word-aligned, we have to
copy the values byte-by-byte using macro's vSetField16() and vSetField32() */
vSetField16( pxMessage, DNSMessage_t, usFlags, dnsNBNS_QUERY_RESPONSE_FLAGS ); /* 0x8500 */
vSetField16( pxMessage, DNSMessage_t, usQuestions, 0 );
vSetField16( pxMessage, DNSMessage_t, usAnswers, 1 );
vSetField16( pxMessage, DNSMessage_t, usAuthorityRRs, 0 );
vSetField16( pxMessage, DNSMessage_t, usAdditionalRRs, 0 );
pxAnswer = (NBNSAnswer_t *)( pucUDPPayloadBuffer + offsetof( NBNSRequest_t, usType ) );
vSetField16( pxAnswer, NBNSAnswer_t, usType, usType ); /* Type */
vSetField16( pxAnswer, NBNSAnswer_t, usClass, dnsNBNS_CLASS_IN ); /* Class */
vSetField32( pxAnswer, NBNSAnswer_t, ulTTL, dnsNBNS_TTL_VALUE );
vSetField16( pxAnswer, NBNSAnswer_t, usDataLength, 6 ); /* 6 bytes including the length field */
vSetField16( pxAnswer, NBNSAnswer_t, usNbFlags, dnsNBNS_NAME_FLAGS );
vSetField32( pxAnswer, NBNSAnswer_t, ulIPAddress, FreeRTOS_ntohl( *ipLOCAL_IP_ADDRESS_POINTER ) );
usLength = ( uint16_t ) ( offsetof( NBNSRequest_t, usType ) + sizeof( NBNSAnswer_t ) );
prvReplyDNSMessage( pxNetworkBuffer, usLength );
}
}
}
}
#endif /* ipconfigUSE_NBNS */
/*-----------------------------------------------------------*/
static Socket_t prvCreateDNSSocket( void )
{
Socket_t xSocket = NULL;
struct freertos_sockaddr xAddress;
BaseType_t xReturn;
TickType_t xTimeoutTime = pdMS_TO_TICKS( 200 );
/* 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 );
/* Auto bind the port. */
xAddress.sin_port = 0u;
xReturn = FreeRTOS_bind( xSocket, &xAddress, sizeof( xAddress ) );
/* Check the bind was successful, and clean up if not. */
if( xReturn != 0 )
{
FreeRTOS_closesocket( xSocket );
xSocket = NULL;
}
else
{
/* Set the send and receive timeouts. */
FreeRTOS_setsockopt( xSocket, 0, FREERTOS_SO_RCVTIMEO, ( void * ) &xTimeoutTime, sizeof( TickType_t ) );
FreeRTOS_setsockopt( xSocket, 0, FREERTOS_SO_SNDTIMEO, ( void * ) &xTimeoutTime, sizeof( TickType_t ) );
}
return xSocket;
}
/*-----------------------------------------------------------*/
#if( ( ipconfigUSE_NBNS == 1 ) || ( ipconfigUSE_LLMNR == 1 ) )
static void prvReplyDNSMessage( NetworkBufferDescriptor_t *pxNetworkBuffer, BaseType_t lNetLength )
{
UDPPacket_t *pxUDPPacket;
IPHeader_t *pxIPHeader;
UDPHeader_t *pxUDPHeader;
pxUDPPacket = (UDPPacket_t *) pxNetworkBuffer->pucEthernetBuffer;
pxIPHeader = &pxUDPPacket->xIPHeader;
pxUDPHeader = &pxUDPPacket->xUDPHeader;
/* HT: started using defines like 'ipSIZE_OF_xxx' */
pxIPHeader->usLength = FreeRTOS_htons( lNetLength + ipSIZE_OF_IPv4_HEADER + ipSIZE_OF_UDP_HEADER );
/* HT:endian: should not be translated, copying from packet to packet */
pxIPHeader->ulDestinationIPAddress = pxIPHeader->ulSourceIPAddress;
pxIPHeader->ulSourceIPAddress = *ipLOCAL_IP_ADDRESS_POINTER;
pxIPHeader->ucTimeToLive = ipconfigUDP_TIME_TO_LIVE;
pxIPHeader->usIdentification = FreeRTOS_htons( usPacketIdentifier );
usPacketIdentifier++;
pxUDPHeader->usLength = FreeRTOS_htons( lNetLength + ipSIZE_OF_UDP_HEADER );
vFlip_16( pxUDPPacket->xUDPHeader.usSourcePort, pxUDPPacket->xUDPHeader.usDestinationPort );
#if( ipconfigDRIVER_INCLUDED_TX_IP_CHECKSUM == 0 )
{
/* calculate the IP header checksum */
pxIPHeader->usHeaderChecksum = 0x00;
pxIPHeader->usHeaderChecksum = usGenerateChecksum( 0UL, ( uint8_t * ) &( pxIPHeader->ucVersionHeaderLength ), ipSIZE_OF_IPv4_HEADER );
pxIPHeader->usHeaderChecksum = ~FreeRTOS_htons( pxIPHeader->usHeaderChecksum );
/* calculate the UDP checksum for outgoing package */
usGenerateProtocolChecksum( ( uint8_t* ) pxUDPPacket, lNetLength, pdTRUE );
}
#endif
/* Important: tell NIC driver how many bytes must be sent */
pxNetworkBuffer->xDataLength = ( size_t ) ( lNetLength + ipSIZE_OF_IPv4_HEADER + ipSIZE_OF_UDP_HEADER + ipSIZE_OF_ETH_HEADER );
/* This function will fill in the eth addresses and send the packet */
vReturnEthernetFrame( pxNetworkBuffer, pdFALSE );
}
#endif /* ipconfigUSE_NBNS == 1 || ipconfigUSE_LLMNR == 1 */
/*-----------------------------------------------------------*/
#if( ipconfigUSE_DNS_CACHE == 1 )
static void prvProcessDNSCache( const char *pcName, uint32_t *pulIP, uint32_t ulTTL, BaseType_t xLookUp )
{
BaseType_t x;
BaseType_t xFound = pdFALSE;
uint32_t ulCurrentTimeSeconds = ( xTaskGetTickCount() / portTICK_PERIOD_MS ) / 1000;
static BaseType_t xFreeEntry = 0;
/* For each entry in the DNS cache table. */
for( x = 0; x < ipconfigDNS_CACHE_ENTRIES; x++ )
{
if( xDNSCache[ x ].pcName[ 0 ] == 0 )
{
break;
}
if( 0 == strcmp( xDNSCache[ x ].pcName, pcName ) )
{
/* Is this function called for a lookup or to add/update an IP address? */
if( xLookUp != pdFALSE )
{
/* Confirm that the record is still fresh. */
if( ulCurrentTimeSeconds < ( xDNSCache[ x ].ulTimeWhenAddedInSeconds + FreeRTOS_ntohl( xDNSCache[ x ].ulTTL ) ) )
{
*pulIP = xDNSCache[ x ].ulIPAddress;
}
else
{
/* Age out the old cached record. */
xDNSCache[ x ].pcName[ 0 ] = 0;
}
}
else
{
xDNSCache[ x ].ulIPAddress = *pulIP;
xDNSCache[ x ].ulTTL = ulTTL;
xDNSCache[ x ].ulTimeWhenAddedInSeconds = ulCurrentTimeSeconds;
}
xFound = pdTRUE;
break;
}
}
if( xFound == pdFALSE )
{
if( xLookUp != pdFALSE )
{
*pulIP = 0;
}
else
{
/* Add or update the item. */
if( strlen( pcName ) < ipconfigDNS_CACHE_NAME_LENGTH )
{
strcpy( xDNSCache[ xFreeEntry ].pcName, pcName );
xDNSCache[ xFreeEntry ].ulIPAddress = *pulIP;
xDNSCache[ xFreeEntry ].ulTTL = ulTTL;
xDNSCache[ xFreeEntry ].ulTimeWhenAddedInSeconds = ulCurrentTimeSeconds;
xFreeEntry++;
if( xFreeEntry == ipconfigDNS_CACHE_ENTRIES )
{
xFreeEntry = 0;
}
}
}
}
if( ( xLookUp == 0 ) || ( *pulIP != 0 ) )
{
FreeRTOS_debug_printf( ( "prvProcessDNSCache: %s: '%s' @ %lxip\n", xLookUp ? "look-up" : "add", pcName, FreeRTOS_ntohl( *pulIP ) ) );
}
}
#endif /* ipconfigUSE_DNS_CACHE */
#endif /* ipconfigUSE_DNS != 0 */
/*-----------------------------------------------------------*/
/* Provide access to private members for testing. */
#ifdef AMAZON_FREERTOS_ENABLE_UNIT_TESTS
#include "aws_freertos_tcp_test_access_dns_define.h"
#endif
/*
* FreeRTOS+TCP V2.0.11
* Copyright (C) 2017 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
*/
/* 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_ARP.h"
#include "FreeRTOS_UDP_IP.h"
#include "FreeRTOS_TCP_IP.h"
#include "FreeRTOS_DHCP.h"
#include "NetworkInterface.h"
#include "NetworkBufferManagement.h"
#include "FreeRTOS_DNS.h"
/* Used to ensure the structure packing is having the desired effect. The
'volatile' is used to prevent compiler warnings about comparing a constant with
a constant. */
#define ipEXPECTED_EthernetHeader_t_SIZE ( ( size_t ) 14 )
#define ipEXPECTED_ARPHeader_t_SIZE ( ( size_t ) 28 )
#define ipEXPECTED_IPHeader_t_SIZE ( ( size_t ) 20 )
#define ipEXPECTED_IGMPHeader__SIZE ( ( size_t ) 8 )
#define ipEXPECTED_ICMPHeader_t_SIZE ( ( size_t ) 8 )
#define ipEXPECTED_UDPHeader_t_SIZE ( ( size_t ) 8 )
#define ipEXPECTED_TCPHeader_t_SIZE ( ( size_t ) 20 )
/* ICMP protocol definitions. */
#define ipICMP_ECHO_REQUEST ( ( uint8_t ) 8 )
#define ipICMP_ECHO_REPLY ( ( uint8_t ) 0 )
/* Time delay between repeated attempts to initialise the network hardware. */
#define ipINITIALISATION_RETRY_DELAY ( pdMS_TO_TICKS( 3000 ) )
/* Defines how often the ARP timer callback function is executed. The time is
shorted in the Windows simulator as simulated time is not real time. */
#ifndef ipARP_TIMER_PERIOD_MS
#ifdef _WINDOWS_
#define ipARP_TIMER_PERIOD_MS ( 500 ) /* For windows simulator builds. */
#else
#define ipARP_TIMER_PERIOD_MS ( 10000 )
#endif
#endif
#ifndef iptraceIP_TASK_STARTING
#define iptraceIP_TASK_STARTING() do {} while( 0 )
#endif
#if( ( ipconfigUSE_TCP == 1 ) && !defined( ipTCP_TIMER_PERIOD_MS ) )
/* When initialising the TCP timer,
give it an initial time-out of 1 second. */
#define ipTCP_TIMER_PERIOD_MS ( 1000 )
#endif
/* If ipconfigETHERNET_DRIVER_FILTERS_FRAME_TYPES is set to 1, then the Ethernet
driver will filter incoming packets and only pass the stack those packets it
considers need processing. In this case ipCONSIDER_FRAME_FOR_PROCESSING() can
be #defined away. If ipconfigETHERNET_DRIVER_FILTERS_FRAME_TYPES is set to 0
then the Ethernet driver will pass all received packets to the stack, and the
stack must do the filtering itself. In this case ipCONSIDER_FRAME_FOR_PROCESSING
needs to call eConsiderFrameForProcessing. */
#if ipconfigETHERNET_DRIVER_FILTERS_FRAME_TYPES == 0
#define ipCONSIDER_FRAME_FOR_PROCESSING( pucEthernetBuffer ) eConsiderFrameForProcessing( ( pucEthernetBuffer ) )
#else
#define ipCONSIDER_FRAME_FOR_PROCESSING( pucEthernetBuffer ) eProcessBuffer
#endif
/* 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'
#if( ipconfigBYTE_ORDER == pdFREERTOS_LITTLE_ENDIAN )
/* The bits in the two byte IP header field that make up the fragment offset value. */
#define ipFRAGMENT_OFFSET_BIT_MASK ( ( uint16_t ) 0xff0f )
#else
/* The bits in the two byte IP header field that make up the fragment offset value. */
#define ipFRAGMENT_OFFSET_BIT_MASK ( ( uint16_t ) 0x0fff )
#endif /* ipconfigBYTE_ORDER */
/* The maximum time the IP task is allowed to remain in the Blocked state if no
events are posted to the network event queue. */
#ifndef ipconfigMAX_IP_TASK_SLEEP_TIME
#define ipconfigMAX_IP_TASK_SLEEP_TIME ( pdMS_TO_TICKS( 10000UL ) )
#endif
/* When a new TCP connection is established, the value of
'ulNextInitialSequenceNumber' will be used as the initial sequence number. It
is very important that at start-up, 'ulNextInitialSequenceNumber' contains a
random value. Also its value must be increased continuously in time, to prevent
a third party guessing the next sequence number and take-over a TCP connection.
It is advised to increment it by 1 ever 4us, which makes about 256 times
per ms: */
#define ipINITIAL_SEQUENCE_NUMBER_FACTOR 256UL
/* 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
/* Returned to indicate a valid checksum when the checksum does not need to be
calculated. */
#define ipCORRECT_CRC 0xffffu
/* Returned as the (invalid) checksum when the length of the data being checked
had an invalid length. */
#define ipINVALID_LENGTH 0x1234u
/*-----------------------------------------------------------*/
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;
TickType_t ulRemainingTime;
TickType_t ulReloadTime;
} IPTimer_t;
/* Used in checksum calculation. */
typedef union _xUnion32
{
uint32_t u32;
uint16_t u16[ 2 ];
uint8_t u8[ 4 ];
} xUnion32;
/* Used in checksum calculation. */
typedef union _xUnionPtr
{
uint32_t *u32ptr;
uint16_t *u16ptr;
uint8_t *u8ptr;
} xUnionPtr;
/*-----------------------------------------------------------*/
/*
* The main TCP/IP stack processing task. This task receives commands/events
* from the network hardware drivers and tasks that are using sockets. It also
* maintains a set of protocol timers.
*/
static void prvIPTask( void *pvParameters );
/*
* Called when new data is available from the network interface.
*/
static void prvProcessEthernetPacket( NetworkBufferDescriptor_t * const pxNetworkBuffer );
/*
* Process incoming IP packets.
*/
static eFrameProcessingResult_t prvProcessIPPacket( IPPacket_t * const pxIPPacket, NetworkBufferDescriptor_t * const pxNetworkBuffer );
#if ( ipconfigREPLY_TO_INCOMING_PINGS == 1 ) || ( ipconfigSUPPORT_OUTGOING_PINGS == 1 )
/*
* Process incoming ICMP packets.
*/
static eFrameProcessingResult_t prvProcessICMPPacket( ICMPPacket_t * const pxICMPPacket );
#endif /* ( ipconfigREPLY_TO_INCOMING_PINGS == 1 ) || ( ipconfigSUPPORT_OUTGOING_PINGS == 1 ) */
/*
* 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 );
#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( ICMPPacket_t * const pxICMPPacket );
#endif /* ipconfigSUPPORT_OUTGOING_PINGS */
/*
* Called to create a network connection when the stack is first started, or
* when the network connection is lost.
*/
static void prvProcessNetworkDownEvent( void );
/*
* Checks the ARP, DHCP and TCP timers to see if any periodic or timeout
* processing is required.
*/
static void prvCheckNetworkTimers( void );
/*
* Determine how long the IP task can sleep for, which depends on when the next
* periodic or timeout processing must be performed.
*/
static TickType_t prvCalculateSleepTime( void );
/*
* The network card driver has received a packet. In the case that it is part
* of a linked packet chain, walk through it to handle every message.
*/
static void prvHandleEthernetPacket( NetworkBufferDescriptor_t *pxBuffer );
/*
* Utility functions for the light weight IP timers.
*/
static void prvIPTimerStart( IPTimer_t *pxTimer, TickType_t xTime );
static BaseType_t prvIPTimerCheck( IPTimer_t *pxTimer );
static void prvIPTimerReload( IPTimer_t *pxTimer, TickType_t xTime );
static eFrameProcessingResult_t prvAllowIPPacket( const IPPacket_t * const pxIPPacket,
NetworkBufferDescriptor_t * const pxNetworkBuffer, UBaseType_t uxHeaderLength );
/*-----------------------------------------------------------*/
/* The queue used to pass events into the IP-task for processing. */
QueueHandle_t xNetworkEventQueue = NULL;
/*_RB_ Requires comment. */
uint16_t usPacketIdentifier = 0U;
/* For convenience, a MAC address of all 0xffs is defined const for quick
reference. */
const MACAddress_t xBroadcastMACAddress = { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff } };
/* Structure that stores the netmask, gateway address and DNS server addresses. */
NetworkAddressingParameters_t xNetworkAddressing = { 0, 0, 0, 0, 0 };
/* Default values for the above struct in case DHCP
does not lead to a confirmed request. */
NetworkAddressingParameters_t xDefaultAddressing = { 0, 0, 0, 0, 0 };
/* Used to ensure network down events cannot be missed when they cannot be
posted to the network event queue because the network event queue is already
full. */
static BaseType_t xNetworkDownEventPending = pdFALSE;
/* Stores the handle of the task that handles the stack. The handle is used
(indirectly) by some utility function to determine if the utility function is
being called by a task (in which case it is ok to block) or by the IP task
itself (in which case it is not ok to block). */
static TaskHandle_t xIPTaskHandle = NULL;
#if( ipconfigUSE_TCP != 0 )
/* Set to a non-zero value if one or more TCP message have been processed
within the last round. */
static BaseType_t xProcessedTCPMessage;
#endif
/* Simple set to pdTRUE or pdFALSE depending on whether the network is up or
down (connected, not connected) respectively. */
static BaseType_t xNetworkUp = pdFALSE;
/*
A timer for each of the following processes, all of which need attention on a
regular basis:
1. ARP, to check its table entries
2. DPHC, to send requests and to renew a reservation
3. TCP, to check for timeouts, resends
4. DNS, to check for timeouts when looking-up a domain.
*/
static IPTimer_t xARPTimer;
#if( ipconfigUSE_DHCP != 0 )
static IPTimer_t xDHCPTimer;
#endif
#if( ipconfigUSE_TCP != 0 )
static IPTimer_t xTCPTimer;
#endif
#if( ipconfigDNS_USE_CALLBACKS != 0 )
static IPTimer_t xDNSTimer;
#endif
/* Set to pdTRUE when the IP task is ready to start processing packets. */
static BaseType_t xIPTaskInitialised = pdFALSE;
#if( ipconfigCHECK_IP_QUEUE_SPACE != 0 )
/* Keep track of the lowest amount of space in 'xNetworkEventQueue'. */
static UBaseType_t uxQueueMinimumSpace = ipconfigEVENT_QUEUE_LENGTH;
#endif
/*-----------------------------------------------------------*/
static void prvIPTask( void *pvParameters )
{
IPStackEvent_t xReceivedEvent;
TickType_t xNextIPSleep;
FreeRTOS_Socket_t *pxSocket;
struct freertos_sockaddr xAddress;
/* Just to prevent compiler warnings about unused parameters. */
( void ) pvParameters;
/* A possibility to set some additional task properties. */
iptraceIP_TASK_STARTING();
/* Generate a dummy message to say that the network connection has gone
down. This will cause this task to initialise the network interface. After
this it is the responsibility of the network interface hardware driver to
send this message if a previously connected network is disconnected. */
FreeRTOS_NetworkDown();
#if( ipconfigUSE_TCP == 1 )
{
/* Initialise the TCP timer. */
prvIPTimerReload( &xTCPTimer, pdMS_TO_TICKS( ipTCP_TIMER_PERIOD_MS ) );
}
#endif
/* Initialisation is complete and events can now be processed. */
xIPTaskInitialised = pdTRUE;
FreeRTOS_debug_printf( ( "prvIPTask started\n" ) );
/* Loop, processing IP events. */
for( ;; )
{
ipconfigWATCHDOG_TIMER();
/* Check the ARP, DHCP and TCP timers to see if there is any periodic
or timeout processing to perform. */
prvCheckNetworkTimers();
/* Calculate the acceptable maximum sleep time. */
xNextIPSleep = prvCalculateSleepTime();
/* Wait until there is something to do. If the following call exits
* due to a time out rather than a message being received, set a
* 'NoEvent' value. */
if ( xQueueReceive( xNetworkEventQueue, ( void * ) &xReceivedEvent, xNextIPSleep ) == pdFALSE )
{
xReceivedEvent.eEventType = eNoEvent;
}
#if( ipconfigCHECK_IP_QUEUE_SPACE != 0 )
{
if( xReceivedEvent.eEventType != eNoEvent )
{
UBaseType_t uxCount;
uxCount = uxQueueSpacesAvailable( xNetworkEventQueue );
if( uxQueueMinimumSpace > uxCount )
{
uxQueueMinimumSpace = uxCount;
}
}
}
#endif /* ipconfigCHECK_IP_QUEUE_SPACE */
iptraceNETWORK_EVENT_RECEIVED( xReceivedEvent.eEventType );
switch( xReceivedEvent.eEventType )
{
case eNetworkDownEvent :
/* Attempt to establish a connection. */
xNetworkUp = pdFALSE;
prvProcessNetworkDownEvent();
break;
case eNetworkRxEvent:
/* The network hardware driver has received a new packet. A
pointer to the received buffer is located in the pvData member
of the received event structure. */
prvHandleEthernetPacket( ( NetworkBufferDescriptor_t * ) ( xReceivedEvent.pvData ) );
break;
case eARPTimerEvent :
/* The ARP timer has expired, process the ARP cache. */
vARPAgeCache();
break;
case eSocketBindEvent:
/* FreeRTOS_bind (a user API) wants the IP-task to bind a socket
to a port. The port number is communicated in the socket field
usLocalPort. vSocketBind() will actually bind the socket and the
API will unblock as soon as the eSOCKET_BOUND event is
triggered. */
pxSocket = ( FreeRTOS_Socket_t * ) ( xReceivedEvent.pvData );
xAddress.sin_addr = 0u; /* For the moment. */
xAddress.sin_port = FreeRTOS_ntohs( pxSocket->usLocalPort );
pxSocket->usLocalPort = 0u;
vSocketBind( pxSocket, &xAddress, sizeof( xAddress ), pdFALSE );
/* Before 'eSocketBindEvent' was sent it was tested that
( xEventGroup != NULL ) so it can be used now to wake up the
user. */
pxSocket->xEventBits |= eSOCKET_BOUND;
vSocketWakeUpUser( pxSocket );
break;
case eSocketCloseEvent :
/* The user API FreeRTOS_closesocket() has sent a message to the
IP-task to actually close a socket. This is handled in
vSocketClose(). As the socket gets closed, there is no way to
report back to the API, so the API won't wait for the result */
vSocketClose( ( FreeRTOS_Socket_t * ) ( xReceivedEvent.pvData ) );
break;
case eStackTxEvent :
/* The network stack has generated a packet to send. A
pointer to the generated buffer is located in the pvData
member of the received event structure. */
vProcessGeneratedUDPPacket( ( NetworkBufferDescriptor_t * ) ( xReceivedEvent.pvData ) );
break;
case eDHCPEvent:
/* The DHCP state machine needs processing. */
#if( ipconfigUSE_DHCP == 1 )
{
vDHCPProcess( pdFALSE );
}
#endif /* ipconfigUSE_DHCP */
break;
case eSocketSelectEvent :
/* FreeRTOS_select() has got unblocked by a socket event,
vSocketSelect() will check which sockets actually have an event
and update the socket field xSocketBits. */
#if( ipconfigSUPPORT_SELECT_FUNCTION == 1 )
{
vSocketSelect( ( SocketSelect_t * ) ( xReceivedEvent.pvData ) );
}
#endif /* ipconfigSUPPORT_SELECT_FUNCTION == 1 */
break;
case eSocketSignalEvent :
#if( ipconfigSUPPORT_SIGNALS != 0 )
{
/* Some task wants to signal the user of this socket in
order to interrupt a call to recv() or a call to select(). */
FreeRTOS_SignalSocket( ( Socket_t ) xReceivedEvent.pvData );
}
#endif /* ipconfigSUPPORT_SIGNALS */
break;
case eTCPTimerEvent :
#if( ipconfigUSE_TCP == 1 )
{
/* Simply mark the TCP timer as expired so it gets processed
the next time prvCheckNetworkTimers() is called. */
xTCPTimer.bExpired = pdTRUE_UNSIGNED;
}
#endif /* ipconfigUSE_TCP */
break;
case eTCPAcceptEvent:
/* The API FreeRTOS_accept() was called, the IP-task will now
check if the listening socket (communicated in pvData) actually
received a new connection. */
#if( ipconfigUSE_TCP == 1 )
{
pxSocket = ( FreeRTOS_Socket_t * ) ( xReceivedEvent.pvData );
if( xTCPCheckNewClient( pxSocket ) != pdFALSE )
{
pxSocket->xEventBits |= eSOCKET_ACCEPT;
vSocketWakeUpUser( pxSocket );
}
}
#endif /* ipconfigUSE_TCP */
break;
case eTCPNetStat:
/* FreeRTOS_netstat() was called to have the IP-task print an
overview of all sockets and their connections */
#if( ( ipconfigUSE_TCP == 1 ) && ( ipconfigHAS_PRINTF == 1 ) )
{
vTCPNetStat();
}
#endif /* ipconfigUSE_TCP */
break;
default :
/* Should not get here. */
break;
}
if( xNetworkDownEventPending != pdFALSE )
{
/* A network down event could not be posted to the network event
queue because the queue was full. Try posting again. */
FreeRTOS_NetworkDown();
}
}
}
/*-----------------------------------------------------------*/
BaseType_t xIsCallingFromIPTask( void )
{
BaseType_t xReturn;
if( xTaskGetCurrentTaskHandle() == xIPTaskHandle )
{
xReturn = pdTRUE;
}
else
{
xReturn = pdFALSE;
}
return xReturn;
}
/*-----------------------------------------------------------*/
static void prvHandleEthernetPacket( NetworkBufferDescriptor_t *pxBuffer )
{
#if( ipconfigUSE_LINKED_RX_MESSAGES == 0 )
{
/* When ipconfigUSE_LINKED_RX_MESSAGES is not set to 0 then only one
buffer will be sent at a time. This is the default way for +TCP to pass
messages from the MAC to the TCP/IP stack. */
prvProcessEthernetPacket( pxBuffer );
}
#else /* ipconfigUSE_LINKED_RX_MESSAGES */
{
NetworkBufferDescriptor_t *pxNextBuffer;
/* An optimisation that is useful when there is high network traffic.
Instead of passing received packets into the IP task one at a time the
network interface can chain received packets together and pass them into
the IP task in one go. The packets are chained using the pxNextBuffer
member. The loop below walks through the chain processing each packet
in the chain in turn. */
do
{
/* Store a pointer to the buffer after pxBuffer for use later on. */
pxNextBuffer = pxBuffer->pxNextBuffer;
/* Make it NULL to avoid using it later on. */
pxBuffer->pxNextBuffer = NULL;
prvProcessEthernetPacket( pxBuffer );
pxBuffer = pxNextBuffer;
/* While there is another packet in the chain. */
} while( pxBuffer != NULL );
}
#endif /* ipconfigUSE_LINKED_RX_MESSAGES */
}
/*-----------------------------------------------------------*/
static TickType_t prvCalculateSleepTime( void )
{
TickType_t xMaximumSleepTime;
/* Start with the maximum sleep time, then check this against the remaining
time in any other timers that are active. */
xMaximumSleepTime = ipconfigMAX_IP_TASK_SLEEP_TIME;
if( xARPTimer.bActive != pdFALSE_UNSIGNED )
{
if( xARPTimer.ulRemainingTime < xMaximumSleepTime )
{
xMaximumSleepTime = xARPTimer.ulReloadTime;
}
}
#if( ipconfigUSE_DHCP == 1 )
{
if( xDHCPTimer.bActive != pdFALSE_UNSIGNED )
{
if( xDHCPTimer.ulRemainingTime < xMaximumSleepTime )
{
xMaximumSleepTime = xDHCPTimer.ulRemainingTime;
}
}
}
#endif /* ipconfigUSE_DHCP */
#if( ipconfigUSE_TCP == 1 )
{
if( xTCPTimer.ulRemainingTime < xMaximumSleepTime )
{
xMaximumSleepTime = xTCPTimer.ulRemainingTime;
}
}
#endif
#if( ipconfigDNS_USE_CALLBACKS != 0 )
{
if( xDNSTimer.bActive != pdFALSE )
{
if( xDNSTimer.ulRemainingTime < xMaximumSleepTime )
{
xMaximumSleepTime = xDNSTimer.ulRemainingTime;
}
}
}
#endif
return xMaximumSleepTime;
}
/*-----------------------------------------------------------*/
static void prvCheckNetworkTimers( void )
{
/* Is it time for ARP processing? */
if( prvIPTimerCheck( &xARPTimer ) != pdFALSE )
{
xSendEventToIPTask( eARPTimerEvent );
}
#if( ipconfigUSE_DHCP == 1 )
{
/* Is it time for DHCP processing? */
if( prvIPTimerCheck( &xDHCPTimer ) != pdFALSE )
{
xSendEventToIPTask( eDHCPEvent );
}
}
#endif /* ipconfigUSE_DHCP */
#if( ipconfigDNS_USE_CALLBACKS != 0 )
{
extern void vDNSCheckCallBack( void *pvSearchID );
/* 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( 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( ( xProcessedTCPMessage != pdFALSE ) && ( 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 );
xProcessedTCPMessage = 0;
}
}
#endif /* ipconfigUSE_TCP == 1 */
}
/*-----------------------------------------------------------*/
static void prvIPTimerStart( IPTimer_t *pxTimer, TickType_t xTime )
{
vTaskSetTimeOutState( &pxTimer->xTimeOut );
pxTimer->ulRemainingTime = xTime;
if( xTime == ( TickType_t ) 0 )
{
pxTimer->bExpired = pdTRUE_UNSIGNED;
}
else
{
pxTimer->bExpired = pdFALSE_UNSIGNED;
}
pxTimer->bActive = pdTRUE_UNSIGNED;
}
/*-----------------------------------------------------------*/
static void prvIPTimerReload( IPTimer_t *pxTimer, TickType_t xTime )
{
pxTimer->ulReloadTime = xTime;
prvIPTimerStart( pxTimer, xTime );
}
/*-----------------------------------------------------------*/
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 != pdFALSE_UNSIGNED ) ||
( xTaskCheckForTimeOut( &( pxTimer->xTimeOut ), &( pxTimer->ulRemainingTime ) ) != pdFALSE ) )
{
prvIPTimerStart( pxTimer, pxTimer->ulReloadTime );
xReturn = pdTRUE;
}
else
{
xReturn = pdFALSE;
}
}
return xReturn;
}
/*-----------------------------------------------------------*/
void FreeRTOS_NetworkDown( void )
{
static const IPStackEvent_t xNetworkDownEvent = { eNetworkDownEvent, NULL };
const TickType_t xDontBlock = ( TickType_t ) 0;
/* Simply send the network task the appropriate event. */
if( xSendEventStructToIPTask( &xNetworkDownEvent, xDontBlock ) != pdPASS )
{
/* Could not send the message, so it is still pending. */
xNetworkDownEventPending = pdTRUE;
}
else
{
/* Message was sent so it is not pending. */
xNetworkDownEventPending = pdFALSE;
}
iptraceNETWORK_DOWN();
}
/*-----------------------------------------------------------*/
BaseType_t FreeRTOS_NetworkDownFromISR( void )
{
static const IPStackEvent_t xNetworkDownEvent = { eNetworkDownEvent, NULL };
BaseType_t xHigherPriorityTaskWoken = pdFALSE;
/* Simply send the network task the appropriate event. */
if( xQueueSendToBackFromISR( xNetworkEventQueue, &xNetworkDownEvent, &xHigherPriorityTaskWoken ) != pdPASS )
{
xNetworkDownEventPending = pdTRUE;
}
else
{
xNetworkDownEventPending = pdFALSE;
}
iptraceNETWORK_DOWN();
return xHigherPriorityTaskWoken;
}
/*-----------------------------------------------------------*/
void *FreeRTOS_GetUDPPayloadBuffer( size_t xRequestedSizeBytes, TickType_t xBlockTimeTicks )
{
NetworkBufferDescriptor_t *pxNetworkBuffer;
void *pvReturn;
/* Cap the block time. The reason for this is explained where
ipconfigUDP_MAX_SEND_BLOCK_TIME_TICKS is defined (assuming an official
FreeRTOSIPConfig.h header file is being used). */
if( xBlockTimeTicks > ipconfigUDP_MAX_SEND_BLOCK_TIME_TICKS )
{
xBlockTimeTicks = ipconfigUDP_MAX_SEND_BLOCK_TIME_TICKS;
}
/* Obtain a network buffer with the required amount of storage. */
pxNetworkBuffer = pxGetNetworkBufferWithDescriptor( sizeof( UDPPacket_t ) + xRequestedSizeBytes, xBlockTimeTicks );
if( pxNetworkBuffer != NULL )
{
/* Set the actual packet size in case a bigger buffer was returned. */
pxNetworkBuffer->xDataLength = sizeof( UDPPacket_t ) + xRequestedSizeBytes;
/* Leave space for the UPD header. */
pvReturn = ( void * ) &( pxNetworkBuffer->pucEthernetBuffer[ ipUDP_PAYLOAD_OFFSET_IPv4 ] );
}
else
{
pvReturn = NULL;
}
return ( void * ) pvReturn;
}
/*-----------------------------------------------------------*/
NetworkBufferDescriptor_t *pxDuplicateNetworkBufferWithDescriptor( NetworkBufferDescriptor_t * const pxNetworkBuffer,
BaseType_t xNewLength )
{
NetworkBufferDescriptor_t * pxNewBuffer;
/* This function is only used when 'ipconfigZERO_COPY_TX_DRIVER' is set to 1.
The transmit routine wants to have ownership of the network buffer
descriptor, because it will pass the buffer straight to DMA. */
pxNewBuffer = pxGetNetworkBufferWithDescriptor( ( size_t ) xNewLength, ( TickType_t ) 0 );
if( pxNewBuffer != NULL )
{
/* Set the actual packet size in case a bigger buffer than requested
was returned. */
pxNewBuffer->xDataLength = xNewLength;
/* Copy the original packet information. */
pxNewBuffer->ulIPAddress = pxNetworkBuffer->ulIPAddress;
pxNewBuffer->usPort = pxNetworkBuffer->usPort;
pxNewBuffer->usBoundPort = pxNetworkBuffer->usBoundPort;
memcpy( pxNewBuffer->pucEthernetBuffer, pxNetworkBuffer->pucEthernetBuffer, pxNetworkBuffer->xDataLength );
}
return pxNewBuffer;
}
/*-----------------------------------------------------------*/
#if( ipconfigZERO_COPY_TX_DRIVER != 0 ) || ( ipconfigZERO_COPY_RX_DRIVER != 0 )
NetworkBufferDescriptor_t *pxPacketBuffer_to_NetworkBuffer( const void *pvBuffer )
{
uint8_t *pucBuffer;
NetworkBufferDescriptor_t *pxResult;
if( pvBuffer == NULL )
{
pxResult = NULL;
}
else
{
/* Obtain the network buffer from the zero copy pointer. */
pucBuffer = ( uint8_t * ) pvBuffer;
/* The input here is a pointer to a payload buffer. Subtract the
size of the header in the network buffer, usually 8 + 2 bytes. */
pucBuffer -= ipBUFFER_PADDING;
/* Here a pointer was placed to the network descriptor. As a
pointer is dereferenced, make sure it is well aligned. */
if( ( ( ( uint32_t ) pucBuffer ) & ( sizeof( pucBuffer ) - ( size_t ) 1 ) ) == ( uint32_t ) 0 )
{
pxResult = * ( ( NetworkBufferDescriptor_t ** ) pucBuffer );
}
else
{
pxResult = NULL;
}
}
return pxResult;
}
#endif /* ipconfigZERO_COPY_TX_DRIVER != 0 */
/*-----------------------------------------------------------*/
NetworkBufferDescriptor_t *pxUDPPayloadBuffer_to_NetworkBuffer( void *pvBuffer )
{
uint8_t *pucBuffer;
NetworkBufferDescriptor_t *pxResult;
if( pvBuffer == NULL )
{
pxResult = NULL;
}
else
{
/* Obtain the network buffer from the zero copy pointer. */
pucBuffer = ( uint8_t * ) pvBuffer;
/* The input here is a pointer to a payload buffer. Subtract
the total size of a UDP/IP header plus the size of the header in
the network buffer, usually 8 + 2 bytes. */
pucBuffer -= ( sizeof( UDPPacket_t ) + ipBUFFER_PADDING );
/* Here a pointer was placed to the network descriptor,
As a pointer is dereferenced, make sure it is well aligned */
if( ( ( ( uint32_t ) pucBuffer ) & ( sizeof( pucBuffer ) - 1 ) ) == 0 )
{
/* The following statement may trigger a:
warning: cast increases required alignment of target type [-Wcast-align].
It has been confirmed though that the alignment is suitable. */
pxResult = * ( ( NetworkBufferDescriptor_t ** ) pucBuffer );
}
else
{
pxResult = NULL;
}
}
return pxResult;
}
/*-----------------------------------------------------------*/
void FreeRTOS_ReleaseUDPPayloadBuffer( void *pvBuffer )
{
vReleaseNetworkBufferAndDescriptor( pxUDPPayloadBuffer_to_NetworkBuffer( pvBuffer ) );
}
/*-----------------------------------------------------------*/
/*_RB_ Should we add an error or assert if the task priorities are set such that the servers won't function as expected? */
/*_HT_ There was a bug in FreeRTOS_TCP_IP.c that only occurred when the applications' priority was too high.
As that bug has been repaired, there is not an urgent reason to warn.
It is better though to use the advised priority scheme. */
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 ] )
{
BaseType_t xReturn = pdFALSE;
/* This function should only be called once. */
configASSERT( xIPIsNetworkTaskReady() == pdFALSE );
configASSERT( xNetworkEventQueue == NULL );
configASSERT( xIPTaskHandle == NULL );
/* Check structure packing is correct. */
configASSERT( sizeof( EthernetHeader_t ) == ipEXPECTED_EthernetHeader_t_SIZE );
configASSERT( sizeof( ARPHeader_t ) == ipEXPECTED_ARPHeader_t_SIZE );
configASSERT( sizeof( IPHeader_t ) == ipEXPECTED_IPHeader_t_SIZE );
configASSERT( sizeof( ICMPHeader_t ) == ipEXPECTED_ICMPHeader_t_SIZE );
configASSERT( sizeof( UDPHeader_t ) == ipEXPECTED_UDPHeader_t_SIZE );
/* Attempt to create the queue used to communicate with the IP task. */
xNetworkEventQueue = xQueueCreate( ( UBaseType_t ) ipconfigEVENT_QUEUE_LENGTH, ( UBaseType_t ) sizeof( IPStackEvent_t ) );
configASSERT( xNetworkEventQueue );
if( xNetworkEventQueue != NULL )
{
#if ( configQUEUE_REGISTRY_SIZE > 0 )
{
/* A queue registry is normally used to assist a kernel aware
debugger. If one is in use then it will be helpful for the debugger
to show information about the network event queue. */
vQueueAddToRegistry( xNetworkEventQueue, "NetEvnt" );
}
#endif /* configQUEUE_REGISTRY_SIZE */
if( xNetworkBuffersInitialise() == pdPASS )
{
/* Store the local IP and MAC address. */
xNetworkAddressing.ulDefaultIPAddress = FreeRTOS_inet_addr_quick( ucIPAddress[ 0 ], ucIPAddress[ 1 ], ucIPAddress[ 2 ], ucIPAddress[ 3 ] );
xNetworkAddressing.ulNetMask = FreeRTOS_inet_addr_quick( ucNetMask[ 0 ], ucNetMask[ 1 ], ucNetMask[ 2 ], ucNetMask[ 3 ] );
xNetworkAddressing.ulGatewayAddress = FreeRTOS_inet_addr_quick( ucGatewayAddress[ 0 ], ucGatewayAddress[ 1 ], ucGatewayAddress[ 2 ], ucGatewayAddress[ 3 ] );
xNetworkAddressing.ulDNSServerAddress = FreeRTOS_inet_addr_quick( ucDNSServerAddress[ 0 ], ucDNSServerAddress[ 1 ], ucDNSServerAddress[ 2 ], ucDNSServerAddress[ 3 ] );
xNetworkAddressing.ulBroadcastAddress = ( xNetworkAddressing.ulDefaultIPAddress & xNetworkAddressing.ulNetMask ) | ~xNetworkAddressing.ulNetMask;
memcpy( &xDefaultAddressing, &xNetworkAddressing, sizeof( xDefaultAddressing ) );
#if ipconfigUSE_DHCP == 1
{
/* The IP address is not set until DHCP completes. */
*ipLOCAL_IP_ADDRESS_POINTER = 0x00UL;
}
#else
{
/* The IP address is set from the value passed in. */
*ipLOCAL_IP_ADDRESS_POINTER = xNetworkAddressing.ulDefaultIPAddress;
/* Added to prevent ARP flood to gateway. Ensure the
gateway is on the same subnet as the IP address. */
configASSERT( ( ( *ipLOCAL_IP_ADDRESS_POINTER ) & xNetworkAddressing.ulNetMask ) == ( xNetworkAddressing.ulGatewayAddress & xNetworkAddressing.ulNetMask ) );
}
#endif /* ipconfigUSE_DHCP == 1 */
/* The MAC address is stored in the start of the default packet
header fragment, which is used when sending UDP packets. */
memcpy( ( void * ) ipLOCAL_MAC_ADDRESS, ( void * ) ucMACAddress, ( size_t ) ipMAC_ADDRESS_LENGTH_BYTES );
/* Prepare the sockets interface. */
xReturn = vNetworkSocketsInit();
if( pdTRUE == xReturn )
{
/* Create the task that processes Ethernet and stack events. */
xReturn = xTaskCreate( prvIPTask, "IP-task", ( uint16_t )ipconfigIP_TASK_STACK_SIZE_WORDS, NULL, ( UBaseType_t )ipconfigIP_TASK_PRIORITY, &xIPTaskHandle );
}
}
else
{
FreeRTOS_debug_printf( ( "FreeRTOS_IPInit: xNetworkBuffersInitialise() failed\n") );
/* Clean up. */
vQueueDelete( xNetworkEventQueue );
xNetworkEventQueue = NULL;
}
}
else
{
FreeRTOS_debug_printf( ( "FreeRTOS_IPInit: Network event queue could not be created\n") );
}
return xReturn;
}
/*-----------------------------------------------------------*/
void FreeRTOS_GetAddressConfiguration( uint32_t *pulIPAddress, uint32_t *pulNetMask, uint32_t *pulGatewayAddress, uint32_t *pulDNSServerAddress )
{
/* Return the address configuration to the caller. */
if( pulIPAddress != NULL )
{
*pulIPAddress = *ipLOCAL_IP_ADDRESS_POINTER;
}
if( pulNetMask != NULL )
{
*pulNetMask = xNetworkAddressing.ulNetMask;
}
if( pulGatewayAddress != NULL )
{
*pulGatewayAddress = xNetworkAddressing.ulGatewayAddress;
}
if( pulDNSServerAddress != NULL )
{
*pulDNSServerAddress = xNetworkAddressing.ulDNSServerAddress;
}
}
/*-----------------------------------------------------------*/
void FreeRTOS_SetAddressConfiguration( const uint32_t *pulIPAddress, const uint32_t *pulNetMask, const uint32_t *pulGatewayAddress, const uint32_t *pulDNSServerAddress )
{
/* Update the address configuration. */
if( pulIPAddress != NULL )
{
*ipLOCAL_IP_ADDRESS_POINTER = *pulIPAddress;
}
if( pulNetMask != NULL )
{
xNetworkAddressing.ulNetMask = *pulNetMask;
}
if( pulGatewayAddress != NULL )
{
xNetworkAddressing.ulGatewayAddress = *pulGatewayAddress;
}
if( pulDNSServerAddress != NULL )
{
xNetworkAddressing.ulDNSServerAddress = *pulDNSServerAddress;
}
}
/*-----------------------------------------------------------*/
#if ( ipconfigSUPPORT_OUTGOING_PINGS == 1 )
BaseType_t FreeRTOS_SendPingRequest( uint32_t ulIPAddress, size_t xNumberOfBytesToSend, TickType_t xBlockTimeTicks )
{
NetworkBufferDescriptor_t *pxNetworkBuffer;
ICMPHeader_t *pxICMPHeader;
BaseType_t xReturn = pdFAIL;
static uint16_t usSequenceNumber = 0;
uint8_t *pucChar;
IPStackEvent_t xStackTxEvent = { eStackTxEvent, NULL };
if( (xNumberOfBytesToSend >= 1 ) && ( xNumberOfBytesToSend < ( ( ipconfigNETWORK_MTU - sizeof( IPHeader_t ) ) - sizeof( ICMPHeader_t ) ) ) && ( uxGetNumberOfFreeNetworkBuffers() >= 3 ) )
{
pxNetworkBuffer = pxGetNetworkBufferWithDescriptor( xNumberOfBytesToSend + sizeof( ICMPPacket_t ), xBlockTimeTicks );
if( pxNetworkBuffer != NULL )
{
pxICMPHeader = ( ICMPHeader_t * ) &( pxNetworkBuffer->pucEthernetBuffer[ ipIP_PAYLOAD_OFFSET ] );
usSequenceNumber++;
/* Fill in the basic header information. */
pxICMPHeader->ucTypeOfMessage = ipICMP_ECHO_REQUEST;
pxICMPHeader->ucTypeOfService = 0;
pxICMPHeader->usIdentifier = usSequenceNumber;
pxICMPHeader->usSequenceNumber = usSequenceNumber;
/* Find the start of the data. */
pucChar = ( uint8_t * ) pxICMPHeader;
pucChar += sizeof( ICMPHeader_t );
/* Just memset the data to a fixed value. */
memset( ( void * ) pucChar, ( int ) ipECHO_DATA_FILL_BYTE, xNumberOfBytesToSend );
/* The message is complete, IP and checksum's are handled by
vProcessGeneratedUDPPacket */
pxNetworkBuffer->pucEthernetBuffer[ ipSOCKET_OPTIONS_OFFSET ] = FREERTOS_SO_UDPCKSUM_OUT;
pxNetworkBuffer->ulIPAddress = ulIPAddress;
pxNetworkBuffer->usPort = ipPACKET_CONTAINS_ICMP_DATA;
pxNetworkBuffer->xDataLength = xNumberOfBytesToSend + sizeof( ICMPHeader_t );
/* Send to the stack. */
xStackTxEvent.pvData = pxNetworkBuffer;
if( xSendEventStructToIPTask( &xStackTxEvent, xBlockTimeTicks) != pdPASS )
{
vReleaseNetworkBufferAndDescriptor( pxNetworkBuffer );
iptraceSTACK_TX_EVENT_LOST( ipSTACK_TX_EVENT );
}
else
{
xReturn = usSequenceNumber;
}
}
}
else
{
/* The requested number of bytes will not fit in the available space
in the network buffer. */
}
return xReturn;
}
#endif /* ipconfigSUPPORT_OUTGOING_PINGS == 1 */
/*-----------------------------------------------------------*/
BaseType_t xSendEventToIPTask( eIPEvent_t eEvent )
{
IPStackEvent_t xEventMessage;
const TickType_t xDontBlock = ( TickType_t ) 0;
xEventMessage.eEventType = eEvent;
xEventMessage.pvData = ( void* )NULL;
return xSendEventStructToIPTask( &xEventMessage, xDontBlock );
}
/*-----------------------------------------------------------*/
BaseType_t xSendEventStructToIPTask( const IPStackEvent_t *pxEvent, TickType_t xTimeout )
{
BaseType_t xReturn, xSendMessage;
if( ( xIPIsNetworkTaskReady() == pdFALSE ) && ( pxEvent->eEventType != eNetworkDownEvent ) )
{
/* Only allow eNetworkDownEvent events if the IP task is not ready
yet. Not going to attempt to send the message so the send failed. */
xReturn = pdFAIL;
}
else
{
xSendMessage = pdTRUE;
#if( ipconfigUSE_TCP == 1 )
{
if( pxEvent->eEventType == eTCPTimerEvent )
{
/* TCP timer events are sent to wake the timer task when
xTCPTimer has expired, but there is no point sending them if the
IP task is already awake processing other message. */
xTCPTimer.bExpired = pdTRUE_UNSIGNED;
if( uxQueueMessagesWaiting( xNetworkEventQueue ) != 0u )
{
/* Not actually going to send the message but this is not a
failure as the message didn't need to be sent. */
xSendMessage = pdFALSE;
}
}
}
#endif /* ipconfigUSE_TCP */
if( xSendMessage != pdFALSE )
{
/* The IP task cannot block itself while waiting for itself to
respond. */
if( ( xIsCallingFromIPTask() == pdTRUE ) && ( xTimeout > ( TickType_t ) 0 ) )
{
xTimeout = ( TickType_t ) 0;
}
xReturn = xQueueSendToBack( xNetworkEventQueue, pxEvent, xTimeout );
if( xReturn == pdFAIL )
{
/* A message should have been sent to the IP task, but wasn't. */
FreeRTOS_debug_printf( ( "xSendEventStructToIPTask: CAN NOT ADD %d\n", pxEvent->eEventType ) );
iptraceSTACK_TX_EVENT_LOST( pxEvent->eEventType );
}
}
else
{
/* It was not necessary to send the message to process the event so
even though the message was not sent the call was successful. */
xReturn = pdPASS;
}
}
return xReturn;
}
/*-----------------------------------------------------------*/
eFrameProcessingResult_t eConsiderFrameForProcessing( const uint8_t * const pucEthernetBuffer )
{
eFrameProcessingResult_t eReturn;
const EthernetHeader_t *pxEthernetHeader;
pxEthernetHeader = ( const EthernetHeader_t * ) pucEthernetBuffer;
if( memcmp( ( void * ) ipLOCAL_MAC_ADDRESS, ( void * ) &( pxEthernetHeader->xDestinationAddress ), sizeof( MACAddress_t ) ) == 0 )
{
/* The packet was directed to this node directly - process it. */
eReturn = eProcessBuffer;
}
else if( memcmp( ( void * ) xBroadcastMACAddress.ucBytes, ( void * ) pxEthernetHeader->xDestinationAddress.ucBytes, sizeof( MACAddress_t ) ) == 0 )
{
/* The packet was a broadcast - process it. */
eReturn = eProcessBuffer;
}
else
#if( ipconfigUSE_LLMNR == 1 )
if( memcmp( ( void * ) xLLMNR_MacAdress.ucBytes, ( void * ) pxEthernetHeader->xDestinationAddress.ucBytes, sizeof( MACAddress_t ) ) == 0 )
{
/* The packet is a request for LLMNR - process it. */
eReturn = eProcessBuffer;
}
else
#endif /* ipconfigUSE_LLMNR */
{
/* The packet was not a broadcast, or for this node, just release
the buffer without taking any other action. */
eReturn = eReleaseBuffer;
}
#if( ipconfigFILTER_OUT_NON_ETHERNET_II_FRAMES == 1 )
{
uint16_t usFrameType;
if( eReturn == eProcessBuffer )
{
usFrameType = pxEthernetHeader->usFrameType;
usFrameType = FreeRTOS_ntohs( usFrameType );
if( usFrameType <= 0x600U )
{
/* Not an Ethernet II frame. */
eReturn = eReleaseBuffer;
}
}
}
#endif /* ipconfigFILTER_OUT_NON_ETHERNET_II_FRAMES == 1 */
return eReturn;
}
/*-----------------------------------------------------------*/
static void prvProcessNetworkDownEvent( void )
{
/* Stop the ARP timer while there is no network. */
xARPTimer.bActive = pdFALSE_UNSIGNED;
#if ipconfigUSE_NETWORK_EVENT_HOOK == 1
{
static BaseType_t xCallEventHook = pdFALSE;
/* The first network down event is generated by the IP stack itself to
initialise the network hardware, so do not call the network down event
the first time through. */
if( xCallEventHook == pdTRUE )
{
vApplicationIPNetworkEventHook( eNetworkDown );
}
xCallEventHook = pdTRUE;
}
#endif
/* Per the ARP Cache Validation section of https://tools.ietf.org/html/rfc1122,
treat network down as a "delivery problem" and flush the ARP cache for this
interface. */
FreeRTOS_ClearARP( );
/* The network has been disconnected (or is being initialised for the first
time). Perform whatever hardware processing is necessary to bring it up
again, or wait for it to be available again. This is hardware dependent. */
if( xNetworkInterfaceInitialise() != pdPASS )
{
/* Ideally the network interface initialisation function will only
return when the network is available. In case this is not the case,
wait a while before retrying the initialisation. */
vTaskDelay( ipINITIALISATION_RETRY_DELAY );
FreeRTOS_NetworkDown();
}
else
{
/* Set remaining time to 0 so it will become active immediately. */
#if ipconfigUSE_DHCP == 1
{
/* The network is not up until DHCP has completed. */
vDHCPProcess( pdTRUE );
xSendEventToIPTask( eDHCPEvent );
}
#else
{
/* Perform any necessary 'network up' processing. */
vIPNetworkUpCalls();
}
#endif
}
}
/*-----------------------------------------------------------*/
void vIPNetworkUpCalls( void )
{
xNetworkUp = pdTRUE;
#if( ipconfigUSE_NETWORK_EVENT_HOOK == 1 )
{
vApplicationIPNetworkEventHook( eNetworkUp );
}
#endif /* ipconfigUSE_NETWORK_EVENT_HOOK */
#if( ipconfigDNS_USE_CALLBACKS != 0 )
{
/* The following function is declared in FreeRTOS_DNS.c and 'private' to
this library */
extern void vDNSInitialise( void );
vDNSInitialise();
}
#endif /* ipconfigDNS_USE_CALLBACKS != 0 */
/* Set remaining time to 0 so it will become active immediately. */
prvIPTimerReload( &xARPTimer, pdMS_TO_TICKS( ipARP_TIMER_PERIOD_MS ) );
}
/*-----------------------------------------------------------*/
static void prvProcessEthernetPacket( NetworkBufferDescriptor_t * const pxNetworkBuffer )
{
EthernetHeader_t *pxEthernetHeader;
eFrameProcessingResult_t eReturned = eReleaseBuffer;
configASSERT( pxNetworkBuffer );
/* Interpret the Ethernet frame. */
if( pxNetworkBuffer->xDataLength >= sizeof( EthernetHeader_t ) )
{
eReturned = ipCONSIDER_FRAME_FOR_PROCESSING( pxNetworkBuffer->pucEthernetBuffer );
pxEthernetHeader = ( EthernetHeader_t * )( pxNetworkBuffer->pucEthernetBuffer );
if( eReturned == eProcessBuffer )
{
/* Interpret the received Ethernet packet. */
switch( pxEthernetHeader->usFrameType )
{
case ipARP_FRAME_TYPE:
/* The Ethernet frame contains an ARP packet. */
if( pxNetworkBuffer->xDataLength >= sizeof( ARPPacket_t ) )
{
eReturned = eARPProcessPacket( ( ARPPacket_t * )pxNetworkBuffer->pucEthernetBuffer );
}
else
{
eReturned = eReleaseBuffer;
}
break;
case ipIPv4_FRAME_TYPE:
/* The Ethernet frame contains an IP packet. */
if( pxNetworkBuffer->xDataLength >= sizeof( IPPacket_t ) )
{
eReturned = prvProcessIPPacket( ( IPPacket_t * )pxNetworkBuffer->pucEthernetBuffer, pxNetworkBuffer );
}
else
{
eReturned = eReleaseBuffer;
}
break;
default:
/* No other packet types are handled. Nothing to do. */
eReturned = eReleaseBuffer;
break;
}
}
}
/* Perform any actions that resulted from processing the Ethernet frame. */
switch( eReturned )
{
case eReturnEthernetFrame :
/* The Ethernet frame will have been updated (maybe it was
an ARP request or a PING request?) and should be sent back to
its source. */
vReturnEthernetFrame( pxNetworkBuffer, pdTRUE );
/* parameter pdTRUE: the buffer must be released once
the frame has been transmitted */
break;
case eFrameConsumed :
/* The frame is in use somewhere, don't release the buffer
yet. */
break;
default :
/* The frame is not being used anywhere, and the
NetworkBufferDescriptor_t structure containing the frame should
just be released back to the list of free buffers. */
vReleaseNetworkBufferAndDescriptor( pxNetworkBuffer );
break;
}
}
/*-----------------------------------------------------------*/
static eFrameProcessingResult_t prvAllowIPPacket( const IPPacket_t * const pxIPPacket,
NetworkBufferDescriptor_t * 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 sparse network buffers. */
uint32_t ulDestinationIPAddress = pxIPHeader->ulDestinationIPAddress;
/* Ensure that the incoming packet is not fragmented (only outgoing
packets can be fragmented) as these are the only handled IP frames
currently. */
if( ( pxIPHeader->usFragmentOffset & ipFRAGMENT_OFFSET_BIT_MASK ) != 0U )
{
/* Can not handle, fragmented packet. */
eReturn = eReleaseBuffer;
}
/* 0x45 means: IPv4 with an IP header of 5 x 4 = 20 bytes
* 0x47 means: IPv4 with an IP header of 7 x 4 = 28 bytes */
else if( ( pxIPHeader->ucVersionHeaderLength < 0x45u ) || ( pxIPHeader->ucVersionHeaderLength > 0x4Fu ) )
{
/* Can not handle, unknown or invalid header version. */
eReturn = eReleaseBuffer;
}
/* Is the packet for this IP address? */
else if( ( ulDestinationIPAddress != *ipLOCAL_IP_ADDRESS_POINTER ) &&
/* Is it the global broadcast address 255.255.255.255 ? */
( ulDestinationIPAddress != ipBROADCAST_IP_ADDRESS ) &&
/* Is it a specific broadcast address 192.168.1.255 ? */
( ulDestinationIPAddress != xNetworkAddressing.ulBroadcastAddress ) &&
#if( ipconfigUSE_LLMNR == 1 )
/* Is it the LLMNR multicast address? */
( ulDestinationIPAddress != ipLLMNR_IP_ADDR ) &&
#endif
/* Or (during DHCP negotiation) we have no IP-address yet? */
( *ipLOCAL_IP_ADDRESS_POINTER != 0UL ) )
{
/* Packet is not for this node, release it */
eReturn = eReleaseBuffer;
}
}
#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? */
if( ( pxIPHeader->ucProtocol != ( uint8_t ) ipPROTOCOL_ICMP ) &&
( usGenerateChecksum( 0UL, ( 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
{
/* to avoid warning unused parameters */
( void ) pxNetworkBuffer;
( void ) uxHeaderLength;
}
#endif /* ipconfigDRIVER_INCLUDED_RX_IP_CHECKSUM == 0 */
return eReturn;
}
/*-----------------------------------------------------------*/
static eFrameProcessingResult_t prvProcessIPPacket( IPPacket_t * const pxIPPacket, NetworkBufferDescriptor_t * const pxNetworkBuffer )
{
eFrameProcessingResult_t eReturn;
IPHeader_t * pxIPHeader = &( pxIPPacket->xIPHeader );
UBaseType_t uxHeaderLength = ( UBaseType_t ) ( ( pxIPHeader->ucVersionHeaderLength & 0x0Fu ) << 2 );
uint8_t ucProtocol;
/* Bound the calculated header length: take away the Ethernet header size,
then check if the IP header is claiming to be longer than the remaining
total packet size. Also check for minimal header field length. */
if( ( uxHeaderLength > ( pxNetworkBuffer->xDataLength - ipSIZE_OF_ETH_HEADER ) ) ||
( uxHeaderLength < ipSIZE_OF_IPv4_HEADER ) )
{
return eReleaseBuffer;
}
ucProtocol = pxIPPacket->xIPHeader.ucProtocol;
/* Check if the IP headers are acceptable and if it has our destination. */
eReturn = prvAllowIPPacket( pxIPPacket, pxNetworkBuffer, uxHeaderLength );
if( eReturn == eProcessBuffer )
{
if( uxHeaderLength > ipSIZE_OF_IPv4_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
* Note: IP options are mostly use in Multi-cast protocols */
const size_t optlen = ( ( size_t ) uxHeaderLength ) - ipSIZE_OF_IPv4_HEADER;
/* From: the previous start of UDP/ICMP/TCP data */
uint8_t *pucSource = ( uint8_t* )(pxNetworkBuffer->pucEthernetBuffer + sizeof( EthernetHeader_t ) + uxHeaderLength);
/* To: the usual start of UDP/ICMP/TCP data at offset 20 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;
memmove( pucTarget, pucSource, xMoveLen );
pxNetworkBuffer->xDataLength -= optlen;
/* Fix-up new version/header length field in IP packet. */
pxIPHeader->ucVersionHeaderLength = ( pxIPHeader->ucVersionHeaderLength & 0xF0 ) | /* High nibble is the version. */
( ( ipSIZE_OF_IPv4_HEADER >> 2 ) & 0x0F ); /* Low nibble is the header size, in bytes, divided by four. */
}
/* Add the IP and MAC addresses to the ARP table if they are not
already there - otherwise refresh the age of the existing
entry. */
if( ucProtocol != ( uint8_t ) ipPROTOCOL_UDP )
{
/* Refresh the ARP cache with the IP/MAC-address of the received packet
* For UDP packets, this will be done later in xProcessReceivedUDPPacket()
* as soon as know that the message will be handled by someone
* This will prevent that the ARP cache will get overwritten
* with the IP-address of useless broadcast packets
*/
vARPRefreshCacheEntry( &( pxIPPacket->xEthernetHeader.xSourceAddress ), pxIPHeader->ulSourceIPAddress );
}
switch( ucProtocol )
{
case ipPROTOCOL_ICMP :
/* The IP packet contained an ICMP frame. Don't bother
checking the ICMP checksum, as if it is wrong then the
wrong data will also be returned, and the source of the
ping will know something went wrong because it will not
be able to validate what it receives. */
#if ( ipconfigREPLY_TO_INCOMING_PINGS == 1 ) || ( ipconfigSUPPORT_OUTGOING_PINGS == 1 )
{
if( pxNetworkBuffer->xDataLength >= sizeof( ICMPPacket_t ) )
{
ICMPPacket_t *pxICMPPacket = ( ICMPPacket_t * )( pxNetworkBuffer->pucEthernetBuffer );
if( pxIPHeader->ulDestinationIPAddress == *ipLOCAL_IP_ADDRESS_POINTER )
{
eReturn = prvProcessICMPPacket( pxICMPPacket );
}
}
else
{
eReturn = eReleaseBuffer;
}
}
#endif /* ( ipconfigREPLY_TO_INCOMING_PINGS == 1 ) || ( ipconfigSUPPORT_OUTGOING_PINGS == 1 ) */
break;
case ipPROTOCOL_UDP :
{
/* The IP packet contained a UDP frame. */
UDPPacket_t *pxUDPPacket = ( UDPPacket_t * ) ( pxNetworkBuffer->pucEthernetBuffer );
/* Only proceed if the payload length indicated in the header
appears to be valid. */
if ( pxNetworkBuffer->xDataLength >= sizeof( UDPPacket_t ) )
{
/* Ensure that downstream UDP packet handling has the lesser
* of: the actual network buffer Ethernet frame length, or
* the sender's UDP packet header payload length, minus the
* size of the UDP header.
*
* The size of the UDP packet structure in this implementation
* includes the size of the Ethernet header, the size of
* the IP header, and the size of the UDP header.
*/
pxNetworkBuffer->xDataLength -= sizeof( UDPPacket_t );
if( ( FreeRTOS_ntohs( pxUDPPacket->xUDPHeader.usLength ) - sizeof( UDPHeader_t ) ) <
pxNetworkBuffer->xDataLength )
{
pxNetworkBuffer->xDataLength = FreeRTOS_ntohs( pxUDPPacket->xUDPHeader.usLength ) - sizeof( UDPHeader_t );
}
/* Fields in pxNetworkBuffer (usPort, ulIPAddress) are network order. */
pxNetworkBuffer->usPort = pxUDPPacket->xUDPHeader.usSourcePort;
pxNetworkBuffer->ulIPAddress = pxUDPPacket->xIPHeader.ulSourceIPAddress;
/* ipconfigDRIVER_INCLUDED_RX_IP_CHECKSUM:
* In some cases, the upper-layer checksum has been calculated
* by the NIC driver.
*
* Pass the packet payload to the UDP sockets implementation. */
if( xProcessReceivedUDPPacket( pxNetworkBuffer,
pxUDPPacket->xUDPHeader.usDestinationPort ) == pdPASS )
{
eReturn = eFrameConsumed;
}
}
else
{
eReturn = eReleaseBuffer;
}
}
break;
#if ipconfigUSE_TCP == 1
case ipPROTOCOL_TCP :
{
if( xProcessReceivedTCPPacket( pxNetworkBuffer ) == pdPASS )
{
eReturn = eFrameConsumed;
}
/* Setting this variable will cause xTCPTimerCheck()
to be called just before the IP-task blocks. */
xProcessedTCPMessage++;
}
break;
#endif
default :
/* Not a supported frame type. */
break;
}
}
return eReturn;
}
/*-----------------------------------------------------------*/
#if ( ipconfigSUPPORT_OUTGOING_PINGS == 1 )
static void prvProcessICMPEchoReply( ICMPPacket_t * const pxICMPPacket )
{
ePingReplyStatus_t eStatus = eSuccess;
uint16_t usDataLength, usCount;
uint8_t *pucByte;
/* Find the total length of the IP packet. */
usDataLength = pxICMPPacket->xIPHeader.usLength;
usDataLength = FreeRTOS_ntohs( usDataLength );
/* Remove the length of the IP headers to obtain the length of the ICMP
message itself. */
usDataLength = ( uint16_t ) ( ( ( uint32_t ) usDataLength ) - ipSIZE_OF_IPv4_HEADER );
/* Remove the length of the ICMP header, to obtain the length of
data contained in the ping. */
usDataLength = ( uint16_t ) ( ( ( uint32_t ) usDataLength ) - ipSIZE_OF_ICMP_HEADER );
/* Checksum has already been checked before in prvProcessIPPacket */
/* Find the first byte of the data within the ICMP packet. */
pucByte = ( uint8_t * ) pxICMPPacket;
pucByte += sizeof( ICMPPacket_t );
/* Check each byte. */
for( usCount = 0; usCount < usDataLength; usCount++ )
{
if( *pucByte != ipECHO_DATA_FILL_BYTE )
{
eStatus = eInvalidData;
break;
}
pucByte++;
}
/* Call back into the application to pass it the result. */
vApplicationPingReplyHook( eStatus, pxICMPPacket->xICMPHeader.usIdentifier );
}
#endif
/*-----------------------------------------------------------*/
#if ( ipconfigREPLY_TO_INCOMING_PINGS == 1 )
static eFrameProcessingResult_t prvProcessICMPEchoRequest( ICMPPacket_t * const pxICMPPacket )
{
ICMPHeader_t *pxICMPHeader;
IPHeader_t *pxIPHeader;
uint16_t usRequest;
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;
pxIPHeader->ulDestinationIPAddress = pxIPHeader->ulSourceIPAddress;
pxIPHeader->ulSourceIPAddress = *ipLOCAL_IP_ADDRESS_POINTER;
/* Update the checksum because the ucTypeOfMessage member in the header
has been changed to ipICMP_ECHO_REPLY. This is faster than calling
usGenerateChecksum(). */
/* due to compiler warning "integer operation result is out of range" */
usRequest = ( uint16_t ) ( ( uint16_t )ipICMP_ECHO_REQUEST << 8 );
if( pxICMPHeader->usChecksum >= FreeRTOS_htons( 0xFFFFu - usRequest ) )
{
pxICMPHeader->usChecksum = ( uint16_t )
( ( ( uint32_t ) pxICMPHeader->usChecksum ) +
FreeRTOS_htons( usRequest + 1UL ) );
}
else
{
pxICMPHeader->usChecksum = ( uint16_t )
( ( ( uint32_t ) pxICMPHeader->usChecksum ) +
FreeRTOS_htons( usRequest ) );
}
return eReturnEthernetFrame;
}
#endif /* ipconfigREPLY_TO_INCOMING_PINGS == 1 */
/*-----------------------------------------------------------*/
#if ( ipconfigREPLY_TO_INCOMING_PINGS == 1 ) || ( ipconfigSUPPORT_OUTGOING_PINGS == 1 )
static eFrameProcessingResult_t prvProcessICMPPacket( ICMPPacket_t * const pxICMPPacket )
{
eFrameProcessingResult_t eReturn = eReleaseBuffer;
iptraceICMP_PACKET_RECEIVED();
switch( pxICMPPacket->xICMPHeader.ucTypeOfMessage )
{
case ipICMP_ECHO_REQUEST :
#if ( ipconfigREPLY_TO_INCOMING_PINGS == 1 )
{
eReturn = prvProcessICMPEchoRequest( pxICMPPacket );
}
#endif /* ( ipconfigREPLY_TO_INCOMING_PINGS == 1 ) */
break;
case ipICMP_ECHO_REPLY :
#if ( ipconfigSUPPORT_OUTGOING_PINGS == 1 )
{
prvProcessICMPEchoReply( pxICMPPacket );
}
#endif /* ipconfigSUPPORT_OUTGOING_PINGS */
break;
default :
break;
}
return eReturn;
}
#endif /* ( ipconfigREPLY_TO_INCOMING_PINGS == 1 ) || ( ipconfigSUPPORT_OUTGOING_PINGS == 1 ) */
/*-----------------------------------------------------------*/
uint16_t usGenerateProtocolChecksum( const uint8_t * const pucEthernetBuffer, size_t uxBufferLength, BaseType_t xOutgoingPacket )
{
uint32_t ulLength;
uint16_t usChecksum, *pusChecksum;
const IPPacket_t * pxIPPacket;
UBaseType_t uxIPHeaderLength;
ProtocolPacket_t *pxProtPack;
uint8_t ucProtocol;
#if( ipconfigHAS_DEBUG_PRINTF != 0 )
const char *pcType;
#endif
/* Check for minimum packet size. */
if( uxBufferLength < sizeof( IPPacket_t ) )
{
return ipINVALID_LENGTH;
}
/* Parse the packet length. */
pxIPPacket = ( const IPPacket_t * ) pucEthernetBuffer;
/* Per https://tools.ietf.org/html/rfc791, the four-bit Internet Header
Length field contains the length of the internet header in 32-bit words. */
uxIPHeaderLength = ( UBaseType_t ) ( sizeof( uint32_t ) * ( pxIPPacket->xIPHeader.ucVersionHeaderLength & 0x0Fu ) );
/* Check for minimum packet size. */
if( uxBufferLength < sizeof( IPPacket_t ) + uxIPHeaderLength - ipSIZE_OF_IPv4_HEADER )
{
return ipINVALID_LENGTH;
}
if( uxBufferLength < FreeRTOS_ntohs( pxIPPacket->xIPHeader.usLength ) )
{
return ipINVALID_LENGTH;
}
/* Identify the next protocol. */
ucProtocol = pxIPPacket->xIPHeader.ucProtocol;
/* N.B., if this IP packet header includes Options, then the following
assignment results in a pointer into the protocol packet with the Ethernet
and IP headers incorrectly aligned. However, either way, the "third"
protocol (Layer 3 or 4) header will be aligned, which is the convenience
of this calculation. */
pxProtPack = ( ProtocolPacket_t * ) ( pucEthernetBuffer + ( uxIPHeaderLength - ipSIZE_OF_IPv4_HEADER ) );
/* Switch on the Layer 3/4 protocol. */
if( ucProtocol == ( uint8_t ) ipPROTOCOL_UDP )
{
if( uxBufferLength < ( uxIPHeaderLength + ipSIZE_OF_ETH_HEADER + ipSIZE_OF_UDP_HEADER ) )
{
return ipINVALID_LENGTH;
}
pusChecksum = ( uint16_t * ) ( &( pxProtPack->xUDPPacket.xUDPHeader.usChecksum ) );
#if( ipconfigHAS_DEBUG_PRINTF != 0 )
{
pcType = "UDP";
}
#endif /* ipconfigHAS_DEBUG_PRINTF != 0 */
}
else if( ucProtocol == ( uint8_t ) ipPROTOCOL_TCP )
{
if( uxBufferLength < ( uxIPHeaderLength + ipSIZE_OF_ETH_HEADER + ipSIZE_OF_TCP_HEADER ) )
{
return ipINVALID_LENGTH;
}
pusChecksum = ( uint16_t * ) ( &( pxProtPack->xTCPPacket.xTCPHeader.usChecksum ) );
#if( ipconfigHAS_DEBUG_PRINTF != 0 )
{
pcType = "TCP";
}
#endif /* ipconfigHAS_DEBUG_PRINTF != 0 */
}
else if( ( ucProtocol == ( uint8_t ) ipPROTOCOL_ICMP ) ||
( ucProtocol == ( uint8_t ) ipPROTOCOL_IGMP ) )
{
if( uxBufferLength < ( uxIPHeaderLength + ipSIZE_OF_ETH_HEADER + ipSIZE_OF_ICMP_HEADER ) )
{
return ipINVALID_LENGTH;
}
pusChecksum = ( uint16_t * ) ( &( pxProtPack->xICMPPacket.xICMPHeader.usChecksum ) );
#if( ipconfigHAS_DEBUG_PRINTF != 0 )
{
if( ucProtocol == ( uint8_t ) ipPROTOCOL_ICMP )
{
pcType = "ICMP";
}
else
{
pcType = "IGMP";
}
}
#endif /* ipconfigHAS_DEBUG_PRINTF != 0 */
}
else
{
/* Unhandled protocol, other than ICMP, IGMP, UDP, or TCP. */
return ipUNHANDLED_PROTOCOL;
}
/* The protocol and checksum field have been identified. Check the direction
of the packet. */
if( xOutgoingPacket != pdFALSE )
{
/* This is an outgoing packet. Before calculating the checksum, set it
to zero. */
*( pusChecksum ) = 0u;
}
else if( ( *pusChecksum == 0u ) && ( ucProtocol == ( uint8_t ) ipPROTOCOL_UDP ) )
{
/* Sender hasn't set the checksum, no use to calculate it. */
return ipCORRECT_CRC;
}
ulLength = ( uint32_t )
( FreeRTOS_ntohs( pxIPPacket->xIPHeader.usLength ) - ( ( uint16_t ) uxIPHeaderLength ) ); /* normally minus 20 */
if( ( ulLength < sizeof( pxProtPack->xUDPPacket.xUDPHeader ) ) ||
( ulLength > ( uint32_t )( ipconfigNETWORK_MTU - uxIPHeaderLength ) ) )
{
#if( ipconfigHAS_DEBUG_PRINTF != 0 )
{
FreeRTOS_debug_printf( ( "usGenerateProtocolChecksum[%s]: len invalid: %lu\n", pcType, ulLength ) );
}
#endif /* ipconfigHAS_DEBUG_PRINTF != 0 */
/* Again, in a 16-bit return value there is no space to indicate an
error. For incoming packets, 0x1234 will cause dropping of the packet.
For outgoing packets, there is a serious problem with the
format/length */
return ipINVALID_LENGTH;
}
if( ucProtocol <= ( uint8_t ) ipPROTOCOL_IGMP )
{
/* ICMP/IGMP do not have a pseudo header for CRC-calculation. */
usChecksum = ( uint16_t )
( ~usGenerateChecksum( 0UL,
( uint8_t * ) &( pxProtPack->xTCPPacket.xTCPHeader ), ( size_t ) ulLength ) );
}
else
{
/* For UDP and TCP, sum the pseudo header, i.e. IP protocol + length
fields */
usChecksum = ( uint16_t ) ( ulLength + ( ( uint16_t ) ucProtocol ) );
/* And then continue at the IPv4 source and destination addresses. */
usChecksum = ( uint16_t )
( ~usGenerateChecksum( ( uint32_t ) usChecksum, ( uint8_t * )&( pxIPPacket->xIPHeader.ulSourceIPAddress ),
( 2u * sizeof( pxIPPacket->xIPHeader.ulSourceIPAddress ) + ulLength ) ) );
/* Sum TCP header and data. */
}
if( xOutgoingPacket == pdFALSE )
{
/* This is in incoming packet. If the CRC is correct, it should be zero. */
if( usChecksum == 0u )
{
usChecksum = ( uint16_t )ipCORRECT_CRC;
}
}
else
{
if( ( usChecksum == 0u ) && ( ucProtocol == ( uint8_t ) ipPROTOCOL_UDP ) )
{
/* In case of UDP, a calculated checksum of 0x0000 is transmitted
as 0xffff. A value of zero would mean that the checksum is not used. */
#if( ipconfigHAS_DEBUG_PRINTF != 0 )
{
if( xOutgoingPacket != pdFALSE )
{
FreeRTOS_debug_printf( ( "usGenerateProtocolChecksum[%s]: crc swap: %04X\n", pcType, usChecksum ) );
}
}
#endif /* ipconfigHAS_DEBUG_PRINTF != 0 */
usChecksum = ( uint16_t )0xffffu;
}
}
usChecksum = FreeRTOS_htons( usChecksum );
if( xOutgoingPacket != pdFALSE )
{
*( pusChecksum ) = usChecksum;
}
#if( ipconfigHAS_DEBUG_PRINTF != 0 )
else if( ( xOutgoingPacket == pdFALSE ) && ( usChecksum != ipCORRECT_CRC ) )
{
FreeRTOS_debug_printf( ( "usGenerateProtocolChecksum[%s]: ID %04X: from %lxip to %lxip bad crc: %04X\n",
pcType,
FreeRTOS_ntohs( pxIPPacket->xIPHeader.usIdentification ),
FreeRTOS_ntohl( pxIPPacket->xIPHeader.ulSourceIPAddress ),
FreeRTOS_ntohl( pxIPPacket->xIPHeader.ulDestinationIPAddress ),
FreeRTOS_ntohs( *pusChecksum ) ) );
}
#endif /* ipconfigHAS_DEBUG_PRINTF != 0 */
return usChecksum;
}
/*-----------------------------------------------------------*/
/**
* This method generates a checksum for a given IPv4 header, per RFC791 (page 14).
* The checksum algorithm is decribed as:
* "[T]he 16 bit one's complement of the one's complement sum of all 16 bit words in the
* header. For purposes of computing the checksum, the value of the checksum field is zero."
*
* In a nutshell, that means that each 16-bit 'word' must be summed, after which
* the number of 'carries' (overflows) is added to the result. If that addition
* produces an overflow, that 'carry' must also be added to the final result. The final checksum
* should be the bitwise 'not' (ones-complement) of the result if the packet is
* meant to be transmitted, but this method simply returns the raw value, probably
* because when a packet is received, the checksum is verified by checking that
* ((received & calculated) == 0) without applying a bitwise 'not' to the 'calculated' checksum.
*
* This logic is optimized for microcontrollers which have limited resources, so the logic looks odd.
* It iterates over the full range of 16-bit words, but it does so by processing several 32-bit
* words at once whenever possible. Its first step is to align the memory pointer to a 32-bit boundary,
* after which it runs a fast loop to process multiple 32-bit words at once and adding their 'carries'.
* Finally, it finishes up by processing any remaining 16-bit words, and adding up all of the 'carries'.
* With 32-bit arithmetic, the number of 16-bit 'carries' produced by sequential additions can be found
* by looking at the 16 most-significant bits of the 32-bit integer, since a 32-bit int will continue
* counting up instead of overflowing after 16 bits. That is why the actual checksum calculations look like:
* union.u32 = ( uint32_t ) union.u16[ 0 ] + union.u16[ 1 ];
*
* Arguments:
* ulSum: This argument provides a value to initialize the progressive summation
* of the header's values to. It is often 0, but protocols like TCP or UDP
* can have pseudo-header fields which need to be included in the checksum.
* pucNextData: This argument contains the address of the first byte which this
* method should process. The method's memory iterator is initialized to this value.
* uxDataLengthBytes: This argument contains the number of bytes that this method
* should process.
*/
uint16_t usGenerateChecksum( uint32_t ulSum, const uint8_t * pucNextData, size_t uxDataLengthBytes )
{
xUnion32 xSum2, xSum, xTerm;
xUnionPtr xSource; /* Points to first byte */
xUnionPtr xLastSource; /* Points to last byte plus one */
uint32_t ulAlignBits, ulCarry = 0ul;
/* Small MCUs often spend up to 30% of the time doing checksum calculations
This function is optimised for 32-bit CPUs; Each time it will try to fetch
32-bits, sums it with an accumulator and counts the number of carries. */
/* Swap the input (little endian platform only). */
xSum.u32 = FreeRTOS_ntohs( ulSum );
xTerm.u32 = 0ul;
xSource.u8ptr = ( uint8_t * ) pucNextData;
ulAlignBits = ( ( ( uint32_t ) pucNextData ) & 0x03u ); /* gives 0, 1, 2, or 3 */
/* If byte (8-bit) aligned... */
if( ( ( ulAlignBits & 1ul ) != 0ul ) && ( uxDataLengthBytes >= ( size_t ) 1 ) )
{
xTerm.u8[ 1 ] = *( xSource.u8ptr );
( xSource.u8ptr )++;
uxDataLengthBytes--;
/* Now xSource is word (16-bit) aligned. */
}
/* If half-word (16-bit) aligned... */
if( ( ( ulAlignBits == 1u ) || ( ulAlignBits == 2u ) ) && ( uxDataLengthBytes >= 2u ) )
{
xSum.u32 += *(xSource.u16ptr);
( xSource.u16ptr )++;
uxDataLengthBytes -= 2u;
/* Now xSource is word (32-bit) aligned. */
}
/* Word (32-bit) aligned, do the most part. */
xLastSource.u32ptr = ( xSource.u32ptr + ( uxDataLengthBytes / 4u ) ) - 3u;
/* In this loop, four 32-bit additions will be done, in total 16 bytes.
Indexing with constants (0,1,2,3) gives faster code than using
post-increments. */
while( xSource.u32ptr < xLastSource.u32ptr )
{
/* Use a secondary Sum2, just to see if the addition produced an
overflow. */
xSum2.u32 = xSum.u32 + xSource.u32ptr[ 0 ];
if( xSum2.u32 < xSum.u32 )
{
ulCarry++;
}
/* Now add the secondary sum to the major sum, and remember if there was
a carry. */
xSum.u32 = xSum2.u32 + xSource.u32ptr[ 1 ];
if( xSum2.u32 > xSum.u32 )
{
ulCarry++;
}
/* And do the same trick once again for indexes 2 and 3 */
xSum2.u32 = xSum.u32 + xSource.u32ptr[ 2 ];
if( xSum2.u32 < xSum.u32 )
{
ulCarry++;
}
xSum.u32 = xSum2.u32 + xSource.u32ptr[ 3 ];
if( xSum2.u32 > xSum.u32 )
{
ulCarry++;
}
/* And finally advance the pointer 4 * 4 = 16 bytes. */
xSource.u32ptr += 4;
}
/* Now add all carries. */
xSum.u32 = ( uint32_t )xSum.u16[ 0 ] + xSum.u16[ 1 ] + ulCarry;
uxDataLengthBytes %= 16u;
xLastSource.u8ptr = ( uint8_t * ) ( xSource.u8ptr + ( uxDataLengthBytes & ~( ( size_t ) 1 ) ) );
/* Half-word aligned. */
while( xSource.u16ptr < xLastSource.u16ptr )
{
/* At least one more short. */
xSum.u32 += xSource.u16ptr[ 0 ];
xSource.u16ptr++;
}
if( ( uxDataLengthBytes & ( size_t ) 1 ) != 0u ) /* Maybe one more ? */
{
xTerm.u8[ 0 ] = xSource.u8ptr[ 0 ];
}
xSum.u32 += xTerm.u32;
/* Now add all carries again. */
xSum.u32 = ( uint32_t ) xSum.u16[ 0 ] + xSum.u16[ 1 ];
/* The previous summation might have given a 16-bit carry. */
xSum.u32 = ( uint32_t ) xSum.u16[ 0 ] + xSum.u16[ 1 ];
if( ( ulAlignBits & 1u ) != 0u )
{
/* Quite unlikely, but pucNextData might be non-aligned, which would
mean that a checksum is calculated starting at an odd position. */
xSum.u32 = ( ( xSum.u32 & 0xffu ) << 8 ) | ( ( xSum.u32 & 0xff00u ) >> 8 );
}
/* swap the output (little endian platform only). */
return FreeRTOS_htons( ( (uint16_t) xSum.u32 ) );
}
/*-----------------------------------------------------------*/
void vReturnEthernetFrame( NetworkBufferDescriptor_t * pxNetworkBuffer, BaseType_t xReleaseAfterSend )
{
EthernetHeader_t *pxEthernetHeader;
#if( ipconfigZERO_COPY_TX_DRIVER != 0 )
NetworkBufferDescriptor_t *pxNewBuffer;
#endif
#if defined( ipconfigETHERNET_MINIMUM_PACKET_BYTES )
{
if( pxNetworkBuffer->xDataLength < ( size_t ) ipconfigETHERNET_MINIMUM_PACKET_BYTES )
{
BaseType_t xIndex;
FreeRTOS_printf( ( "vReturnEthernetFrame: length %lu\n", ( uint32_t )pxNetworkBuffer->xDataLength ) );
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( ipconfigZERO_COPY_TX_DRIVER != 0 )
if( xReleaseAfterSend == pdFALSE )
{
pxNewBuffer = pxDuplicateNetworkBufferWithDescriptor( pxNetworkBuffer, ( BaseType_t ) pxNetworkBuffer->xDataLength );
xReleaseAfterSend = pdTRUE;
pxNetworkBuffer = pxNewBuffer;
}
if( pxNetworkBuffer != NULL )
#endif
{
pxEthernetHeader = ( EthernetHeader_t * ) ( pxNetworkBuffer->pucEthernetBuffer );
/* Swap source and destination MAC addresses. */
memcpy( ( void * ) &( pxEthernetHeader->xDestinationAddress ), ( void * ) &( pxEthernetHeader->xSourceAddress ), sizeof( pxEthernetHeader->xDestinationAddress ) );
memcpy( ( void * ) &( pxEthernetHeader->xSourceAddress) , ( void * ) ipLOCAL_MAC_ADDRESS, ( size_t ) ipMAC_ADDRESS_LENGTH_BYTES );
/* Send! */
xNetworkInterfaceOutput( pxNetworkBuffer, xReleaseAfterSend );
}
}
/*-----------------------------------------------------------*/
uint32_t FreeRTOS_GetIPAddress( void )
{
/* Returns the IP address of the NIC. */
return *ipLOCAL_IP_ADDRESS_POINTER;
}
/*-----------------------------------------------------------*/
void FreeRTOS_SetIPAddress( uint32_t ulIPAddress )
{
/* Sets the IP address of the NIC. */
*ipLOCAL_IP_ADDRESS_POINTER = ulIPAddress;
}
/*-----------------------------------------------------------*/
uint32_t FreeRTOS_GetGatewayAddress( void )
{
return xNetworkAddressing.ulGatewayAddress;
}
/*-----------------------------------------------------------*/
uint32_t FreeRTOS_GetDNSServerAddress( void )
{
return xNetworkAddressing.ulDNSServerAddress;
}
/*-----------------------------------------------------------*/
uint32_t FreeRTOS_GetNetmask( void )
{
return xNetworkAddressing.ulNetMask;
}
/*-----------------------------------------------------------*/
void FreeRTOS_UpdateMACAddress( const uint8_t ucMACAddress[ipMAC_ADDRESS_LENGTH_BYTES] )
{
/* Copy the MAC address at the start of the default packet header fragment. */
memcpy( ( void * )ipLOCAL_MAC_ADDRESS, ( void * )ucMACAddress, ( size_t )ipMAC_ADDRESS_LENGTH_BYTES );
}
/*-----------------------------------------------------------*/
const uint8_t * FreeRTOS_GetMACAddress( void )
{
return ipLOCAL_MAC_ADDRESS;
}
/*-----------------------------------------------------------*/
void FreeRTOS_SetNetmask ( uint32_t ulNetmask )
{
xNetworkAddressing.ulNetMask = ulNetmask;
}
/*-----------------------------------------------------------*/
void FreeRTOS_SetGatewayAddress ( uint32_t ulGatewayAddress )
{
xNetworkAddressing.ulGatewayAddress = ulGatewayAddress;
}
/*-----------------------------------------------------------*/
#if( ipconfigUSE_DHCP == 1 )
void vIPSetDHCPTimerEnableState( BaseType_t xEnableState )
{
if( xEnableState != pdFALSE )
{
xDHCPTimer.bActive = pdTRUE_UNSIGNED;
}
else
{
xDHCPTimer.bActive = pdFALSE_UNSIGNED;
}
}
#endif /* ipconfigUSE_DHCP */
/*-----------------------------------------------------------*/
#if( ipconfigUSE_DHCP == 1 )
void vIPReloadDHCPTimer( uint32_t ulLeaseTime )
{
prvIPTimerReload( &xDHCPTimer, ulLeaseTime );
}
#endif /* ipconfigUSE_DHCP */
/*-----------------------------------------------------------*/
#if( ipconfigDNS_USE_CALLBACKS == 1 )
void vIPSetDnsTimerEnableState( BaseType_t xEnableState )
{
if( xEnableState != 0 )
{
xDNSTimer.bActive = pdTRUE;
}
else
{
xDNSTimer.bActive = pdFALSE;
}
}
#endif /* ipconfigUSE_DHCP */
/*-----------------------------------------------------------*/
#if( ipconfigDNS_USE_CALLBACKS != 0 )
void vIPReloadDNSTimer( uint32_t ulCheckTime )
{
prvIPTimerReload( &xDNSTimer, ulCheckTime );
}
#endif /* ipconfigDNS_USE_CALLBACKS != 0 */
/*-----------------------------------------------------------*/
BaseType_t xIPIsNetworkTaskReady( void )
{
return xIPTaskInitialised;
}
/*-----------------------------------------------------------*/
BaseType_t FreeRTOS_IsNetworkUp( void )
{
return xNetworkUp;
}
/*-----------------------------------------------------------*/
#if( ipconfigCHECK_IP_QUEUE_SPACE != 0 )
UBaseType_t uxGetMinimumIPQueueSpace( void )
{
return uxQueueMinimumSpace;
}
#endif
/*-----------------------------------------------------------*/