3 Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
5 Permission is hereby granted, free of charge, to any person obtaining a copy of
6 this software and associated documentation files (the "Software"), to deal in
7 the Software without restriction, including without limitation the rights to
8 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9 the Software, and to permit persons to whom the Software is furnished to do so,
10 subject to the following conditions:
12 The above copyright notice and this permission notice shall be included in all
13 copies or substantial portions of the Software.
15 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
17 FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18 COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19 IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20 CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 http://aws.amazon.com/freertos
23 http://www.FreeRTOS.org
26 /* WinPCap includes. */
30 /* FreeRTOS includes. */
35 /* FreeRTOS+TCP includes. */
36 #include "FreeRTOS_IP.h"
37 #include "FreeRTOS_IP_Private.h"
38 #include "NetworkBufferManagement.h"
40 /* Thread-safe circular buffers are being used to pass data to and from the PCAP
42 #include "Win32-Extensions.h"
43 #include "FreeRTOS_Stream_Buffer.h"
45 /* Sizes of the thread safe circular buffers used to pass data to and from the
46 WinPCAP Windows threads. */
47 #define xSEND_BUFFER_SIZE 32768
48 #define xRECV_BUFFER_SIZE 32768
50 /* If ipconfigETHERNET_DRIVER_FILTERS_FRAME_TYPES is set to 1, then the Ethernet
51 driver will filter incoming packets and only pass the stack those packets it
52 considers need processing. */
53 #if( ipconfigETHERNET_DRIVER_FILTERS_FRAME_TYPES == 0 )
54 #define ipCONSIDER_FRAME_FOR_PROCESSING( pucEthernetBuffer ) eProcessBuffer
56 #define ipCONSIDER_FRAME_FOR_PROCESSING( pucEthernetBuffer ) eConsiderFrameForProcessing( ( pucEthernetBuffer ) )
59 /* Used to insert test code only. */
60 #define niDISRUPT_PACKETS 0
62 /*-----------------------------------------------------------*/
65 * Windows threads that are outside of the control of the FreeRTOS simulator are
66 * used to interface with the WinPCAP libraries.
68 DWORD WINAPI prvWinPcapRecvThread( void *pvParam );
69 DWORD WINAPI prvWinPcapSendThread( void *pvParam );
72 * Print out a numbered list of network interfaces that are available on the
75 static pcap_if_t * prvPrintAvailableNetworkInterfaces( void );
78 * Open the network interface. The number of the interface to be opened is set
79 * by the configNETWORK_INTERFACE_TO_USE constant in FreeRTOSConfig.h.
81 static void prvOpenSelectedNetworkInterface( pcap_if_t *pxAllNetworkInterfaces );
82 static int prvOpenInterface( const char *pucName );
85 * Configure the capture filter to allow blocking reads, and to filter out
86 * packets that are not of interest to this demo.
88 static void prvConfigureCaptureBehaviour( void );
91 * A function that simulates Ethernet interrupts by periodically polling the
92 * WinPCap interface for new data.
94 static void prvInterruptSimulatorTask( void *pvParameters );
97 * Create the buffers that are used to pass data between the FreeRTOS simulator
98 * and the Win32 threads that manage WinPCAP.
100 static void prvCreateThreadSafeBuffers( void );
103 * Utility function used to format print messages only.
105 static const char *prvRemoveSpaces( char *pcBuffer, int aBuflen, const char *pcMessage );
107 /*-----------------------------------------------------------*/
109 /* Required by the WinPCap library. */
110 static char cErrorBuffer[ PCAP_ERRBUF_SIZE ];
112 /* An event used to wake up the Win32 thread that sends data through the WinPCAP
114 static void *pvSendEvent = NULL;
116 /* _HT_ made the PCAP interface number configurable through the program's
117 parameters in order to test in different machines. */
118 static BaseType_t xConfigNetworkInterfaceToUse = configNETWORK_INTERFACE_TO_USE;
120 /* Handles to the Windows threads that handle the PCAP IO. */
121 static HANDLE vWinPcapRecvThreadHandle = NULL;
122 static HANDLE vWinPcapSendThreadHandle = NULL;;
124 /* The interface being used by WinPCap. */
125 static pcap_t *pxOpenedInterfaceHandle = NULL;
127 /* Circular buffers used by the PCAP Win32 threads. */
128 static StreamBuffer_t *xSendBuffer = NULL;
129 static StreamBuffer_t *xRecvBuffer = NULL;
131 /* The MAC address initially set to the constants defined in FreeRTOSConfig.h. */
132 extern uint8_t ucMACAddress[ 6 ];
134 /* Logs the number of WinPCAP send failures, for viewing in the debugger only. */
135 static volatile uint32_t ulWinPCAPSendFailures = 0;
137 /*-----------------------------------------------------------*/
139 BaseType_t xNetworkInterfaceInitialise( void )
141 BaseType_t xReturn = pdFALSE;
142 pcap_if_t *pxAllNetworkInterfaces;
144 /* Query the computer the simulation is being executed on to find the
145 network interfaces it has installed. */
146 pxAllNetworkInterfaces = prvPrintAvailableNetworkInterfaces();
148 /* Open the network interface. The number of the interface to be opened is
149 set by the configNETWORK_INTERFACE_TO_USE constant in FreeRTOSConfig.h.
150 Calling this function will set the pxOpenedInterfaceHandle variable. If,
151 after calling this function, pxOpenedInterfaceHandle is equal to NULL, then
152 the interface could not be opened. */
153 if( pxAllNetworkInterfaces != NULL )
155 prvOpenSelectedNetworkInterface( pxAllNetworkInterfaces );
158 if( pxOpenedInterfaceHandle != NULL )
165 /*-----------------------------------------------------------*/
167 static void prvCreateThreadSafeBuffers( void )
169 /* The buffer used to pass data to be transmitted from a FreeRTOS task to
170 the Win32 thread that sends via the WinPCAP library. */
171 if( xSendBuffer == NULL)
173 xSendBuffer = ( StreamBuffer_t * ) malloc( sizeof( *xSendBuffer ) - sizeof( xSendBuffer->ucArray ) + xSEND_BUFFER_SIZE + 1 );
174 configASSERT( xSendBuffer );
175 memset( xSendBuffer, '\0', sizeof( *xSendBuffer ) - sizeof( xSendBuffer->ucArray ) );
176 xSendBuffer->LENGTH = xSEND_BUFFER_SIZE + 1;
179 /* The buffer used to pass received data from the Win32 thread that receives
180 via the WinPCAP library to the FreeRTOS task. */
181 if( xRecvBuffer == NULL)
183 xRecvBuffer = ( StreamBuffer_t * ) malloc( sizeof( *xRecvBuffer ) - sizeof( xRecvBuffer->ucArray ) + xRECV_BUFFER_SIZE + 1 );
184 configASSERT( xRecvBuffer );
185 memset( xRecvBuffer, '\0', sizeof( *xRecvBuffer ) - sizeof( xRecvBuffer->ucArray ) );
186 xRecvBuffer->LENGTH = xRECV_BUFFER_SIZE + 1;
189 /*-----------------------------------------------------------*/
191 BaseType_t xNetworkInterfaceOutput( NetworkBufferDescriptor_t * const pxNetworkBuffer, BaseType_t bReleaseAfterSend )
195 iptraceNETWORK_INTERFACE_TRANSMIT();
196 configASSERT( xIsCallingFromIPTask() == pdTRUE );
198 /* Both the length of the data being sent and the actual data being sent
199 are placed in the thread safe buffer used to pass data between the FreeRTOS
200 tasks and the Win32 thread that sends data via the WinPCAP library. Drop
201 the packet if there is insufficient space in the buffer to hold both. */
202 xSpace = uxStreamBufferGetSpace( xSendBuffer );
204 if( ( pxNetworkBuffer->xDataLength <= ( ipconfigNETWORK_MTU + ipSIZE_OF_ETH_HEADER ) ) &&
205 ( xSpace >= ( pxNetworkBuffer->xDataLength + sizeof( pxNetworkBuffer->xDataLength ) ) ) )
207 /* First write in the length of the data, then write in the data
209 uxStreamBufferAdd( xSendBuffer, 0, ( const uint8_t * ) &( pxNetworkBuffer->xDataLength ), sizeof( pxNetworkBuffer->xDataLength ) );
210 uxStreamBufferAdd( xSendBuffer, 0, ( const uint8_t * ) pxNetworkBuffer->pucEthernetBuffer, pxNetworkBuffer->xDataLength );
214 FreeRTOS_debug_printf( ( "xNetworkInterfaceOutput: send buffers full to store %lu\n", pxNetworkBuffer->xDataLength ) );
217 /* Kick the Tx task in either case in case it doesn't know the buffer is
219 SetEvent( pvSendEvent );
221 /* The buffer has been sent so can be released. */
222 if( bReleaseAfterSend != pdFALSE )
224 vReleaseNetworkBufferAndDescriptor( pxNetworkBuffer );
229 /*-----------------------------------------------------------*/
231 static pcap_if_t * prvPrintAvailableNetworkInterfaces( void )
233 pcap_if_t * pxAllNetworkInterfaces = NULL, *xInterface;
234 int32_t lInterfaceNumber = 1;
236 static BaseType_t xInvalidInterfaceDetected = pdFALSE;
238 if( xInvalidInterfaceDetected == pdFALSE )
240 if( pcap_findalldevs_ex( PCAP_SRC_IF_STRING, NULL, &pxAllNetworkInterfaces, cErrorBuffer ) == -1 )
242 printf( "Could not obtain a list of network interfaces\n%s\n", cErrorBuffer );
243 pxAllNetworkInterfaces = NULL;
247 printf( "\r\n\r\nThe following network interfaces are available:\r\n\r\n" );
250 if( pxAllNetworkInterfaces != NULL )
252 /* Print out the list of network interfaces. The first in the list
253 is interface '1', not interface '0'. */
254 for( xInterface = pxAllNetworkInterfaces; xInterface != NULL; xInterface = xInterface->next )
256 /* The descriptions of the devices can be full of spaces, clean them
257 a little. printf() can only be used here because the network is not
258 up yet - so no other network tasks will be running. */
259 printf( "Interface %d - %s\n", lInterfaceNumber, prvRemoveSpaces( cBuffer, sizeof( cBuffer ), xInterface->name ) );
260 printf( " (%s)\n", prvRemoveSpaces(cBuffer, sizeof( cBuffer ), xInterface->description ? xInterface->description : "No description" ) );
266 if( lInterfaceNumber == 1 )
268 /* The interface number was never incremented, so the above for() loop
269 did not execute meaning no interfaces were found. */
270 printf( " \nNo network interfaces were found.\n" );
271 pxAllNetworkInterfaces = NULL;
274 printf( "\r\nThe interface that will be opened is set by " );
275 printf( "\"configNETWORK_INTERFACE_TO_USE\", which\r\nshould be defined in FreeRTOSConfig.h\r\n" );
277 if( ( xConfigNetworkInterfaceToUse < 1L ) || ( xConfigNetworkInterfaceToUse >= lInterfaceNumber ) )
279 printf( "\r\nERROR: configNETWORK_INTERFACE_TO_USE is set to %d, which is an invalid value.\r\n", xConfigNetworkInterfaceToUse );
280 printf( "Please set configNETWORK_INTERFACE_TO_USE to one of the interface numbers listed above,\r\n" );
281 printf( "then re-compile and re-start the application. Only Ethernet (as opposed to WiFi)\r\n" );
282 printf( "interfaces are supported.\r\n\r\nHALTING\r\n\r\n\r\n" );
283 xInvalidInterfaceDetected = pdTRUE;
285 if( pxAllNetworkInterfaces != NULL )
287 /* Free the device list, as no devices are going to be opened. */
288 pcap_freealldevs( pxAllNetworkInterfaces );
289 pxAllNetworkInterfaces = NULL;
294 printf( "Attempting to open interface number %d.\n", xConfigNetworkInterfaceToUse );
298 return pxAllNetworkInterfaces;
300 /*-----------------------------------------------------------*/
302 static int prvOpenInterface( const char *pucName )
304 static char pucInterfaceName[ 256 ];
306 if( pucName != NULL )
308 strncpy( pucInterfaceName, pucName, sizeof( pucInterfaceName ) );
311 pxOpenedInterfaceHandle = pcap_open( pucInterfaceName, /* The name of the selected interface. */
312 ipTOTAL_ETHERNET_FRAME_SIZE, /* The size of the packet to capture. */
313 PCAP_OPENFLAG_PROMISCUOUS, /* Open in promiscuous mode as the MAC and
314 IP address is going to be "simulated", and
315 not be the real MAC and IP address. This allows
316 traffic to the simulated IP address to be routed
317 to uIP, and traffic to the real IP address to be
318 routed to the Windows TCP/IP stack. */
320 NULL, /* No authentication is required as this is
321 not a remote capture session. */
325 if ( pxOpenedInterfaceHandle == NULL )
327 printf( "\n%s is not supported by WinPcap and cannot be opened\n", pucInterfaceName );
332 /* Configure the capture filter to allow blocking reads, and to filter
333 out packets that are not of interest to this demo. */
334 prvConfigureCaptureBehaviour();
338 /*-----------------------------------------------------------*/
340 static void prvOpenSelectedNetworkInterface( pcap_if_t *pxAllNetworkInterfaces )
342 pcap_if_t *pxInterface;
345 /* Walk the list of devices until the selected device is located. */
346 pxInterface = pxAllNetworkInterfaces;
347 for( x = 0L; x < ( xConfigNetworkInterfaceToUse - 1L ); x++ )
349 pxInterface = pxInterface->next;
352 /* Open the selected interface. */
353 if( prvOpenInterface( pxInterface->name ) == 0 )
355 printf( "Successfully opened interface number %d.\n", x + 1 );
359 printf( "Failed to open interface number %d.\n", x + 1 );
362 /* The device list is no longer required. */
363 pcap_freealldevs( pxAllNetworkInterfaces );
365 /*-----------------------------------------------------------*/
367 static void prvConfigureCaptureBehaviour( void )
369 struct bpf_program xFilterCode;
372 /* Set up a filter so only the packets of interest are passed to the IP
373 stack. cErrorBuffer is used for convenience to create the string. Don't
374 confuse this with an error message. */
375 sprintf( cErrorBuffer, "broadcast or multicast or ether host %x:%x:%x:%x:%x:%x",
376 ucMACAddress[0], ucMACAddress[1], ucMACAddress[2], ucMACAddress[3], ucMACAddress[4], ucMACAddress[5] );
378 ulNetMask = ( configNET_MASK3 << 24UL ) | ( configNET_MASK2 << 16UL ) | ( configNET_MASK1 << 8L ) | configNET_MASK0;
380 if( pcap_compile( pxOpenedInterfaceHandle, &xFilterCode, cErrorBuffer, 1, ulNetMask ) < 0 )
382 printf( "\nThe packet filter string is invalid\n" );
386 if( pcap_setfilter( pxOpenedInterfaceHandle, &xFilterCode ) < 0 )
388 printf( "\nAn error occurred setting the packet filter.\n" );
390 /* When pcap_compile() succeeds, it allocates memory for the memory pointed to by the bpf_program struct
391 parameter.pcap_freecode() will free that memory. */
392 pcap_freecode( &xFilterCode );
395 /* Create the buffers used to pass packets between the FreeRTOS simulator
396 and the Win32 threads that are handling WinPCAP. */
397 prvCreateThreadSafeBuffers();
399 if( pvSendEvent == NULL )
401 /* Create event used to signal the Win32 WinPCAP Tx thread. */
402 pvSendEvent = CreateEvent( NULL, FALSE, TRUE, NULL );
404 /* Create the Win32 thread that handles WinPCAP Rx. */
405 vWinPcapRecvThreadHandle = CreateThread(
406 NULL, /* Pointer to thread security attributes. */
407 0, /* Initial thread stack size, in bytes. */
408 prvWinPcapRecvThread, /* Pointer to thread function. */
409 NULL, /* Argument for new thread. */
410 0, /* Creation flags. */
413 /* Use the cores that are not used by the FreeRTOS tasks. */
414 SetThreadAffinityMask( vWinPcapRecvThreadHandle, ~0x01u );
416 /* Create the Win32 thread that handlers WinPCAP Tx. */
417 vWinPcapSendThreadHandle = CreateThread(
418 NULL, /* Pointer to thread security attributes. */
419 0, /* initial thread stack size, in bytes. */
420 prvWinPcapSendThread, /* Pointer to thread function. */
421 NULL, /* Argument for new thread. */
422 0, /* Creation flags. */
425 /* Use the cores that are not used by the FreeRTOS tasks. */
426 SetThreadAffinityMask( vWinPcapSendThreadHandle, ~0x01u );
428 /* Create a task that simulates an interrupt in a real system. This will
429 block waiting for packets, then send a message to the IP task when data
431 xTaskCreate( prvInterruptSimulatorTask, "MAC_ISR", configMINIMAL_STACK_SIZE, NULL, configMAC_ISR_SIMULATOR_PRIORITY, NULL );
434 /*-----------------------------------------------------------*/
436 /* WinPCAP function. */
437 void pcap_callback( u_char *user, const struct pcap_pkthdr *pkt_header, const u_char *pkt_data )
441 /* THIS IS CALLED FROM A WINDOWS THREAD - DO NOT ATTEMPT ANY FREERTOS CALLS
442 OR TO PRINT OUT MESSAGES HERE. */
444 /* Pass data to the FreeRTOS simulator on a thread safe circular buffer. */
445 if( ( pkt_header->caplen <= ( ipconfigNETWORK_MTU + ipSIZE_OF_ETH_HEADER ) ) &&
446 ( uxStreamBufferGetSpace( xRecvBuffer ) >= ( ( ( size_t ) pkt_header->caplen ) + sizeof( *pkt_header ) ) ) )
448 uxStreamBufferAdd( xRecvBuffer, 0, ( const uint8_t* ) pkt_header, sizeof( *pkt_header ) );
449 uxStreamBufferAdd( xRecvBuffer, 0, ( const uint8_t* ) pkt_data, ( size_t ) pkt_header->caplen );
452 /*-----------------------------------------------------------*/
454 DWORD WINAPI prvWinPcapRecvThread ( void *pvParam )
458 /* THIS IS A WINDOWS THREAD - DO NOT ATTEMPT ANY FREERTOS CALLS OR TO PRINT
459 OUT MESSAGES HERE. */
463 pcap_dispatch( pxOpenedInterfaceHandle, 1, pcap_callback, ( u_char * ) "mydata" );
466 /*-----------------------------------------------------------*/
468 DWORD WINAPI prvWinPcapSendThread( void *pvParam )
471 uint8_t ucBuffer[ ipconfigNETWORK_MTU + ipSIZE_OF_ETH_HEADER ];
472 static char cErrorMessage[ 1024 ];
473 const DWORD xMaxMSToWait = 1000;
475 /* THIS IS A WINDOWS THREAD - DO NOT ATTEMPT ANY FREERTOS CALLS OR TO PRINT
476 OUT MESSAGES HERE. */
478 /* Remove compiler warnings about unused parameters. */
483 /* Wait until notified of something to send. */
484 WaitForSingleObject( pvSendEvent, xMaxMSToWait );
486 /* Is there more than the length value stored in the circular buffer
487 used to pass data from the FreeRTOS simulator into this Win32 thread? */
488 while( uxStreamBufferGetSize( xSendBuffer ) > sizeof( xLength ) )
490 uxStreamBufferGet( xSendBuffer, 0, ( uint8_t * ) &xLength, sizeof( xLength ), pdFALSE );
491 uxStreamBufferGet( xSendBuffer, 0, ( uint8_t* ) ucBuffer, xLength, pdFALSE );
492 if( pcap_sendpacket( pxOpenedInterfaceHandle, ucBuffer, xLength ) != 0 )
494 ulWinPCAPSendFailures++;
499 /*-----------------------------------------------------------*/
501 static void prvInterruptSimulatorTask( void *pvParameters )
503 struct pcap_pkthdr xHeader;
504 static struct pcap_pkthdr *pxHeader;
505 const uint8_t *pucPacketData;
506 uint8_t ucRecvBuffer[ ipconfigNETWORK_MTU + ipSIZE_OF_ETH_HEADER ];
507 NetworkBufferDescriptor_t *pxNetworkBuffer;
508 IPStackEvent_t xRxEvent = { eNetworkRxEvent, NULL };
509 eFrameProcessingResult_t eResult;
511 /* Remove compiler warnings about unused parameters. */
512 ( void ) pvParameters;
516 /* Does the circular buffer used to pass data from the Win32 thread that
517 handles WinPCAP Rx into the FreeRTOS simulator contain another packet? */
518 if( uxStreamBufferGetSize( xRecvBuffer ) > sizeof( xHeader ) )
520 /* Get the next packet. */
521 uxStreamBufferGet( xRecvBuffer, 0, (uint8_t*)&xHeader, sizeof( xHeader ), pdFALSE );
522 uxStreamBufferGet( xRecvBuffer, 0, (uint8_t*)ucRecvBuffer, ( size_t ) xHeader.len, pdFALSE );
523 pucPacketData = ucRecvBuffer;
526 iptraceNETWORK_INTERFACE_RECEIVE();
528 /* Check for minimal size. */
529 if( pxHeader->len >= sizeof( EthernetHeader_t ) )
531 eResult = ipCONSIDER_FRAME_FOR_PROCESSING( pucPacketData );
535 eResult = eReleaseBuffer;
538 if( eResult == eProcessBuffer )
540 /* Will the data fit into the frame buffer? */
541 if( pxHeader->len <= ipTOTAL_ETHERNET_FRAME_SIZE )
543 /* Obtain a buffer into which the data can be placed. This
544 is only an interrupt simulator, not a real interrupt, so it
545 is ok to call the task level function here, but note that
546 some buffer implementations cannot be called from a real
548 pxNetworkBuffer = pxGetNetworkBufferWithDescriptor( pxHeader->len, 0 );
550 if( pxNetworkBuffer != NULL )
552 memcpy( pxNetworkBuffer->pucEthernetBuffer, pucPacketData, pxHeader->len );
553 pxNetworkBuffer->xDataLength = ( size_t ) pxHeader->len;
555 #if( niDISRUPT_PACKETS == 1 )
557 pxNetworkBuffer = vRxFaultInjection( pxNetworkBuffer, pucPacketData );
559 #endif /* niDISRUPT_PACKETS */
561 if( pxNetworkBuffer != NULL )
563 xRxEvent.pvData = ( void * ) pxNetworkBuffer;
565 /* Data was received and stored. Send a message to
566 the IP task to let it know. */
567 if( xSendEventStructToIPTask( &xRxEvent, ( TickType_t ) 0 ) == pdFAIL )
569 /* The buffer could not be sent to the stack so
570 must be released again. This is only an
571 interrupt simulator, not a real interrupt, so it
572 is ok to use the task level function here, but
573 note no all buffer implementations will allow
574 this function to be executed from a real
576 vReleaseNetworkBufferAndDescriptor( pxNetworkBuffer );
577 iptraceETHERNET_RX_EVENT_LOST();
582 /* The packet was already released or stored inside
583 vRxFaultInjection(). Don't release it here. */
588 iptraceETHERNET_RX_EVENT_LOST();
593 /* Log that a packet was dropped because it would have
594 overflowed the buffer, but there may be more buffers to
601 /* There is no real way of simulating an interrupt. Make sure
602 other tasks can run. */
603 vTaskDelay( configWINDOWS_MAC_INTERRUPT_SIMULATOR_DELAY );
607 /*-----------------------------------------------------------*/
609 static const char *prvRemoveSpaces( char *pcBuffer, int aBuflen, const char *pcMessage )
611 char *pcTarget = pcBuffer;
613 /* Utility function used to formap messages being printed only. */
614 while( ( *pcMessage != 0 ) && ( pcTarget < ( pcBuffer + aBuflen - 1 ) ) )
616 *( pcTarget++ ) = *pcMessage;
618 if( isspace( *pcMessage ) != pdFALSE )
620 while( isspace( *pcMessage ) != pdFALSE )