forked from FreeRTOS/FreeRTOS-Plus-TCP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
FreeRTOS_Sockets.c
4925 lines (4220 loc) · 183 KB
/
FreeRTOS_Sockets.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* FreeRTOS+TCP V2.3.3
* Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
/**
* @file FreeRTOS_Sockets.c
* @brief Implements the Sockets API based on Berkeley sockets for the FreeRTOS+TCP network stack.
* Sockets are used by the application processes to interact with the IP-task which in turn
* interacts with the hardware.
*/
/* Standard includes. */
#include <stdint.h>
#include <stdio.h>
/* FreeRTOS includes. */
#include "FreeRTOS.h"
#include "task.h"
#include "queue.h"
#include "semphr.h"
/* FreeRTOS+TCP includes. */
#include "FreeRTOS_UDP_IP.h"
#include "FreeRTOS_IP.h"
#include "FreeRTOS_Sockets.h"
#include "FreeRTOS_IP_Private.h"
#include "FreeRTOS_DNS.h"
#include "NetworkBufferManagement.h"
/* The ItemValue of the sockets xBoundSocketListItem member holds the socket's
* port number. */
/** @brief Set the port number for the socket in the xBoundSocketListItem. */
#define socketSET_SOCKET_PORT( pxSocket, usPort ) listSET_LIST_ITEM_VALUE( ( &( ( pxSocket )->xBoundSocketListItem ) ), ( usPort ) )
/** @brief Get the port number for the socket in the xBoundSocketListItem. */
#define socketGET_SOCKET_PORT( pxSocket ) listGET_LIST_ITEM_VALUE( ( &( ( pxSocket )->xBoundSocketListItem ) ) )
/** @brief Test if a socket it bound which means it is either included in
* xBoundUDPSocketsList or xBoundTCPSocketsList
*/
#define socketSOCKET_IS_BOUND( pxSocket ) ( listLIST_ITEM_CONTAINER( &( pxSocket )->xBoundSocketListItem ) != NULL )
/** @brief If FreeRTOS_sendto() is called on a socket that is not bound to a port
* number then, depending on the FreeRTOSIPConfig.h settings, it might be
* that a port number is automatically generated for the socket.
* Automatically generated port numbers will be between
* socketAUTO_PORT_ALLOCATION_START_NUMBER and 0xffff.
*
* @note Per https://tools.ietf.org/html/rfc6056, "the dynamic ports consist of
* the range 49152-65535. However, ephemeral port selection algorithms should
* use the whole range 1024-65535" excluding those already in use (inbound
* or outbound).
*/
#if !defined( socketAUTO_PORT_ALLOCATION_START_NUMBER )
#define socketAUTO_PORT_ALLOCATION_START_NUMBER ( ( uint16_t ) 0x0400 )
#endif
/** @brief Maximum value of port number which can be auto assigned. */
#define socketAUTO_PORT_ALLOCATION_MAX_NUMBER ( ( uint16_t ) 0xffff )
/** @brief The number of octets that make up an IP address. */
#define socketMAX_IP_ADDRESS_OCTETS 4U
/** @brief A block time of 0 simply means "don't block". */
#define socketDONT_BLOCK ( ( TickType_t ) 0 )
/** @brief TCP timer period in milliseconds. */
#if ( ( ipconfigUSE_TCP == 1 ) && !defined( ipTCP_TIMER_PERIOD_MS ) )
#define ipTCP_TIMER_PERIOD_MS ( 1000U )
#endif
/* Some helper macro's for defining the 20/80 % limits of uxLittleSpace / uxEnoughSpace. */
#define sock20_PERCENT 20U /**< 20% of the defined limit. */
#define sock80_PERCENT 80U /**< 80% of the defined limit. */
#define sock100_PERCENT 100U /**< 100% of the defined limit. */
#if ( ipconfigUSE_CALLBACKS != 0 )
static portINLINE ipDECL_CAST_PTR_FUNC_FOR_TYPE( F_TCP_UDP_Handler_t )
{
return ( F_TCP_UDP_Handler_t * ) pvArgument;
}
/*-----------------------------------------------------------*/
static portINLINE ipDECL_CAST_CONST_PTR_FUNC_FOR_TYPE( F_TCP_UDP_Handler_t )
{
return ( const F_TCP_UDP_Handler_t * ) pvArgument;
}
/*-----------------------------------------------------------*/
#endif /* if ( ipconfigUSE_CALLBACKS != 0 ) */
/**
* @brief Utility function to cast pointer of a type to pointer of type NetworkBufferDescriptor_t.
*
* @return The casted pointer.
*/
static portINLINE ipDECL_CAST_PTR_FUNC_FOR_TYPE( NetworkBufferDescriptor_t )
{
return ( NetworkBufferDescriptor_t * ) pvArgument;
}
/*-----------------------------------------------------------*/
/**
* @brief Utility function to cast pointer of a type to pointer of type StreamBuffer_t.
*
* @return The casted pointer.
*/
static portINLINE ipDECL_CAST_PTR_FUNC_FOR_TYPE( StreamBuffer_t )
{
return ( StreamBuffer_t * ) pvArgument;
}
/*-----------------------------------------------------------*/
/*
* Allocate the next port number from the private allocation range.
* TCP and UDP each have their own series of port numbers
* ulProtocol is either ipPROTOCOL_UDP or ipPROTOCOL_TCP
*/
static uint16_t prvGetPrivatePortNumber( BaseType_t xProtocol );
/*
* Return the list item from within pxList that has an item value of
* xWantedItemValue. If there is no such list item return NULL.
*/
static const ListItem_t * pxListFindListItemWithValue( const List_t * pxList,
TickType_t xWantedItemValue );
/*
* Return pdTRUE only if pxSocket is valid and bound, as far as can be
* determined.
*/
static BaseType_t prvValidSocket( const FreeRTOS_Socket_t * pxSocket,
BaseType_t xProtocol,
BaseType_t xIsBound );
#if ( ipconfigUSE_TCP == 1 )
/*
* Internal function prvSockopt_so_buffer(): sets FREERTOS_SO_SNDBUF or
* FREERTOS_SO_RCVBUF properties of a socket.
*/
static BaseType_t prvSockopt_so_buffer( FreeRTOS_Socket_t * pxSocket,
int32_t lOptionName,
const void * pvOptionValue );
#endif /* ipconfigUSE_TCP == 1 */
/*
* Before creating a socket, check the validity of the parameters used
* and find the size of the socket space, which is different for UDP and TCP
*/
static BaseType_t prvDetermineSocketSize( BaseType_t xDomain,
BaseType_t xType,
BaseType_t xProtocol,
size_t * pxSocketSize );
#if ( ipconfigUSE_TCP == 1 )
/*
* Create a txStream or a rxStream, depending on the parameter 'xIsInputStream'
*/
static StreamBuffer_t * prvTCPCreateStream( FreeRTOS_Socket_t * pxSocket,
BaseType_t xIsInputStream );
#endif /* ipconfigUSE_TCP == 1 */
#if ( ipconfigUSE_TCP == 1 )
/*
* Called from FreeRTOS_send(): some checks which will be done before
* sending a TCP packed.
*/
static int32_t prvTCPSendCheck( FreeRTOS_Socket_t * pxSocket,
size_t uxDataLength );
#endif /* ipconfigUSE_TCP */
#if ( ipconfigUSE_TCP == 1 )
/*
* When a child socket gets closed, make sure to update the child-count of the parent
*/
static void prvTCPSetSocketCount( FreeRTOS_Socket_t const * pxSocketToDelete );
#endif /* ipconfigUSE_TCP == 1 */
#if ( ipconfigUSE_TCP == 1 )
/*
* Called from FreeRTOS_connect(): make some checks and if allowed, send a
* message to the IP-task to start connecting to a remote socket
*/
static BaseType_t prvTCPConnectStart( FreeRTOS_Socket_t * pxSocket,
struct freertos_sockaddr const * pxAddress );
#endif /* ipconfigUSE_TCP */
#if ( ipconfigUSE_TCP == 1 )
/*
* Check if it makes any sense to wait for a connect event.
* It may return: -EINPROGRESS, -EAGAIN, or 0 for OK.
*/
static BaseType_t bMayConnect( FreeRTOS_Socket_t const * pxSocket );
#endif /* ipconfigUSE_TCP */
#if ( ipconfigSUPPORT_SELECT_FUNCTION == 1 )
/* Executed by the IP-task, it will check all sockets belonging to a set */
static void prvFindSelectedSocket( SocketSelect_t * pxSocketSet );
#endif /* ipconfigSUPPORT_SELECT_FUNCTION == 1 */
/*-----------------------------------------------------------*/
/** @brief The list that contains mappings between sockets and port numbers.
* Accesses to this list must be protected by critical sections of
* some kind.
*/
List_t xBoundUDPSocketsList;
#if ipconfigUSE_TCP == 1
/** @brief The list that contains mappings between sockets and port numbers.
* Accesses to this list must be protected by critical sections of
* some kind.
*/
List_t xBoundTCPSocketsList;
#endif /* ipconfigUSE_TCP == 1 */
/*-----------------------------------------------------------*/
/**
* @brief Check whether the socket is valid or not.
*
* @param[in] pxSocket: The socket being checked.
* @param[in] xProtocol: The protocol for which the socket was created.
* @param[in] xIsBound: pdTRUE when the socket should be bound, otherwise pdFALSE.
*
* @return If the socket is valid, then pdPASS is returned or else, pdFAIL
* is returned.
*/
static BaseType_t prvValidSocket( const FreeRTOS_Socket_t * pxSocket,
BaseType_t xProtocol,
BaseType_t xIsBound )
{
BaseType_t xReturn;
if( ( pxSocket == NULL ) || ( pxSocket == FREERTOS_INVALID_SOCKET ) )
{
xReturn = pdFALSE;
}
else if( ( xIsBound != pdFALSE ) && !socketSOCKET_IS_BOUND( pxSocket ) )
{
/* The caller expects the socket to be bound, but it isn't. */
xReturn = pdFALSE;
}
else if( pxSocket->ucProtocol != ( uint8_t ) xProtocol )
{
/* Socket has a wrong type (UDP != TCP). */
xReturn = pdFALSE;
}
else
{
xReturn = pdTRUE;
}
return xReturn;
}
/*-----------------------------------------------------------*/
/**
* @brief Initialise the bound TCP/UDP socket lists.
*/
void vNetworkSocketsInit( void )
{
vListInitialise( &xBoundUDPSocketsList );
#if ( ipconfigUSE_TCP == 1 )
{
vListInitialise( &xBoundTCPSocketsList );
}
#endif /* ipconfigUSE_TCP == 1 */
}
/*-----------------------------------------------------------*/
/**
* @brief Determine the socket size for the given protocol.
*
* @param[in] xDomain: The domain for which the size of socket is being determined.
* @param[in] xType: Is this a datagram socket or a stream socket.
* @param[in] xProtocol: The protocol being used.
* @param[out] pxSocketSize: Pointer to a variable in which the size shall be returned
* if all checks pass.
*
* @return pdPASS if socket size was determined and put in the parameter pxSocketSize
* correctly, else pdFAIL.
*/
static BaseType_t prvDetermineSocketSize( BaseType_t xDomain,
BaseType_t xType,
BaseType_t xProtocol,
size_t * pxSocketSize )
{
BaseType_t xReturn = pdPASS;
FreeRTOS_Socket_t const * pxSocket = NULL;
/* Asserts must not appear before it has been determined that the network
* task is ready - otherwise the asserts will fail. */
if( xIPIsNetworkTaskReady() == pdFALSE )
{
xReturn = pdFAIL;
}
else
{
/* Only Ethernet is currently supported. */
configASSERT( xDomain == FREERTOS_AF_INET );
/* Check if the UDP socket-list has been initialised. */
configASSERT( listLIST_IS_INITIALISED( &xBoundUDPSocketsList ) );
#if ( ipconfigUSE_TCP == 1 )
{
/* Check if the TCP socket-list has been initialised. */
configASSERT( listLIST_IS_INITIALISED( &xBoundTCPSocketsList ) );
}
#endif /* ipconfigUSE_TCP == 1 */
if( xProtocol == FREERTOS_IPPROTO_UDP )
{
if( xType != FREERTOS_SOCK_DGRAM )
{
xReturn = pdFAIL;
configASSERT( xReturn == pdPASS );
}
/* In case a UDP socket is created, do not allocate space for TCP data. */
*pxSocketSize = ( sizeof( *pxSocket ) - sizeof( pxSocket->u ) ) + sizeof( pxSocket->u.xUDP );
}
#if ( ipconfigUSE_TCP == 1 )
else if( xProtocol == FREERTOS_IPPROTO_TCP )
{
if( xType != FREERTOS_SOCK_STREAM )
{
xReturn = pdFAIL;
configASSERT( xReturn == pdPASS );
}
*pxSocketSize = ( sizeof( *pxSocket ) - sizeof( pxSocket->u ) ) + sizeof( pxSocket->u.xTCP );
}
#endif /* ipconfigUSE_TCP == 1 */
else
{
xReturn = pdFAIL;
configASSERT( xReturn == pdPASS );
}
}
/* In case configASSERT() is not used */
( void ) xDomain;
( void ) pxSocket; /* Was only used for sizeof. */
return xReturn;
}
/*-----------------------------------------------------------*/
/**
* @brief allocate and initialise a socket.
*
* @param[in] xDomain: The domain in which the socket should be created.
* @param[in] xType: The type of the socket.
* @param[in] xProtocol: The protocol of the socket.
*
* @return FREERTOS_INVALID_SOCKET if the allocation failed, or if there was
* a parameter error, otherwise a valid socket.
*/
Socket_t FreeRTOS_socket( BaseType_t xDomain,
BaseType_t xType,
BaseType_t xProtocol )
{
FreeRTOS_Socket_t * pxSocket;
/* Note that this value will be over-written by the call to prvDetermineSocketSize. */
size_t uxSocketSize = 1;
EventGroupHandle_t xEventGroup;
Socket_t xReturn;
if( prvDetermineSocketSize( xDomain, xType, xProtocol, &uxSocketSize ) == pdFAIL )
{
xReturn = FREERTOS_INVALID_SOCKET;
}
else
{
/* Allocate the structure that will hold the socket information. The
* size depends on the type of socket: UDP sockets need less space. A
* define 'pvPortMallocSocket' will used to allocate the necessary space.
* By default it points to the FreeRTOS function 'pvPortMalloc()'. */
pxSocket = ipCAST_PTR_TO_TYPE_PTR( FreeRTOS_Socket_t, pvPortMallocSocket( uxSocketSize ) );
if( pxSocket == NULL )
{
xReturn = FREERTOS_INVALID_SOCKET;
iptraceFAILED_TO_CREATE_SOCKET();
}
else
{
xEventGroup = xEventGroupCreate();
if( xEventGroup == NULL )
{
vPortFreeSocket( pxSocket );
xReturn = FREERTOS_INVALID_SOCKET;
iptraceFAILED_TO_CREATE_EVENT_GROUP();
}
else
{
if( xProtocol == FREERTOS_IPPROTO_UDP )
{
iptraceMEM_STATS_CREATE( tcpSOCKET_UDP, pxSocket, uxSocketSize + sizeof( StaticEventGroup_t ) );
}
else
{
/* Lint wants at least a comment, in case the macro is empty. */
iptraceMEM_STATS_CREATE( tcpSOCKET_TCP, pxSocket, uxSocketSize + sizeof( StaticEventGroup_t ) );
}
/* Clear the entire space to avoid nulling individual entries. */
( void ) memset( pxSocket, 0, uxSocketSize );
pxSocket->xEventGroup = xEventGroup;
/* Initialise the socket's members. The semaphore will be created
* if the socket is bound to an address, for now the pointer to the
* semaphore is just set to NULL to show it has not been created. */
if( xProtocol == FREERTOS_IPPROTO_UDP )
{
vListInitialise( &( pxSocket->u.xUDP.xWaitingPacketsList ) );
#if ( ipconfigUDP_MAX_RX_PACKETS > 0U )
{
pxSocket->u.xUDP.uxMaxPackets = ( UBaseType_t ) ipconfigUDP_MAX_RX_PACKETS;
}
#endif /* ipconfigUDP_MAX_RX_PACKETS > 0 */
}
vListInitialiseItem( &( pxSocket->xBoundSocketListItem ) );
listSET_LIST_ITEM_OWNER( &( pxSocket->xBoundSocketListItem ), ipPOINTER_CAST( void *, pxSocket ) );
pxSocket->xReceiveBlockTime = ipconfigSOCK_DEFAULT_RECEIVE_BLOCK_TIME;
pxSocket->xSendBlockTime = ipconfigSOCK_DEFAULT_SEND_BLOCK_TIME;
pxSocket->ucSocketOptions = ( uint8_t ) FREERTOS_SO_UDPCKSUM_OUT;
pxSocket->ucProtocol = ( uint8_t ) xProtocol; /* protocol: UDP or TCP */
#if ( ipconfigUSE_TCP == 1 )
{
if( xProtocol == FREERTOS_IPPROTO_TCP )
{
/* StreamSize is expressed in number of bytes */
/* Round up buffer sizes to nearest multiple of MSS */
pxSocket->u.xTCP.usCurMSS = ( uint16_t ) ipconfigTCP_MSS;
pxSocket->u.xTCP.usInitMSS = ( uint16_t ) ipconfigTCP_MSS;
pxSocket->u.xTCP.uxRxStreamSize = ( size_t ) ipconfigTCP_RX_BUFFER_LENGTH;
pxSocket->u.xTCP.uxTxStreamSize = ( size_t ) FreeRTOS_round_up( ipconfigTCP_TX_BUFFER_LENGTH, ipconfigTCP_MSS );
/* Use half of the buffer size of the TCP windows */
#if ( ipconfigUSE_TCP_WIN == 1 )
{
pxSocket->u.xTCP.uxRxWinSize = FreeRTOS_max_uint32( 1UL, ( uint32_t ) ( pxSocket->u.xTCP.uxRxStreamSize / 2U ) / ipconfigTCP_MSS );
pxSocket->u.xTCP.uxTxWinSize = FreeRTOS_max_uint32( 1UL, ( uint32_t ) ( pxSocket->u.xTCP.uxTxStreamSize / 2U ) / ipconfigTCP_MSS );
}
#else
{
pxSocket->u.xTCP.uxRxWinSize = 1U;
pxSocket->u.xTCP.uxTxWinSize = 1U;
}
#endif
/* The above values are just defaults, and can be overridden by
* calling FreeRTOS_setsockopt(). No buffers will be allocated until a
* socket is connected and data is exchanged. */
}
}
#endif /* ipconfigUSE_TCP == 1 */
xReturn = pxSocket;
}
}
}
/* Remove compiler warnings in the case the configASSERT() is not defined. */
( void ) xDomain;
return xReturn;
}
/*-----------------------------------------------------------*/
#if ( ipconfigSUPPORT_SELECT_FUNCTION == 1 )
/**
* @brief Create a socket set.
*
* @return The new socket set which was created, or NULL when allocation has failed.
*/
SocketSet_t FreeRTOS_CreateSocketSet( void )
{
SocketSelect_t * pxSocketSet;
pxSocketSet = ipCAST_PTR_TO_TYPE_PTR( SocketSelect_t, pvPortMalloc( sizeof( *pxSocketSet ) ) );
if( pxSocketSet != NULL )
{
( void ) memset( pxSocketSet, 0, sizeof( *pxSocketSet ) );
pxSocketSet->xSelectGroup = xEventGroupCreate();
if( pxSocketSet->xSelectGroup == NULL )
{
vPortFree( pxSocketSet );
pxSocketSet = NULL;
}
else
{
/* Lint wants at least a comment, in case the macro is empty. */
iptraceMEM_STATS_CREATE( tcpSOCKET_SET, pxSocketSet, sizeof( *pxSocketSet ) + sizeof( StaticEventGroup_t ) );
}
}
return ( SocketSet_t ) pxSocketSet;
}
#endif /* ipconfigSUPPORT_SELECT_FUNCTION == 1 */
/*-----------------------------------------------------------*/
#if ( ipconfigSUPPORT_SELECT_FUNCTION == 1 )
/**
* @brief Delete a given socket set.
*
* @param[in] xSocketSet: The socket set being deleted.
*/
void FreeRTOS_DeleteSocketSet( SocketSet_t xSocketSet )
{
IPStackEvent_t xCloseEvent;
xCloseEvent.eEventType = eSocketSetDeleteEvent;
xCloseEvent.pvData = ( void * ) xSocketSet;
if( xSendEventStructToIPTask( &xCloseEvent, ( TickType_t ) portMAX_DELAY ) == pdFAIL )
{
FreeRTOS_printf( ( "FreeRTOS_DeleteSocketSet: xSendEventStructToIPTask failed\n" ) );
}
}
#endif /* ipconfigSUPPORT_SELECT_FUNCTION == 1 */
/*-----------------------------------------------------------*/
#if ( ipconfigSUPPORT_SELECT_FUNCTION == 1 )
/**
* @brief Add a socket to a set.
*
* @param[in] xSocket: The socket being added.
* @param[in] xSocketSet: The socket set being added to.
* @param[in] xBitsToSet: The event bits to set, a combination of the values defined
* in 'eSelectEvent_t', for read, write, exception, etc.
*/
void FreeRTOS_FD_SET( Socket_t xSocket,
SocketSet_t xSocketSet,
EventBits_t xBitsToSet )
{
FreeRTOS_Socket_t * pxSocket = ( FreeRTOS_Socket_t * ) xSocket;
SocketSelect_t * pxSocketSet = ( SocketSelect_t * ) xSocketSet;
configASSERT( pxSocket != NULL );
configASSERT( xSocketSet != NULL );
/* Make sure we're not adding bits which are reserved for internal use,
* such as eSELECT_CALL_IP */
pxSocket->xSelectBits |= xBitsToSet & ( ( EventBits_t ) eSELECT_ALL );
if( ( pxSocket->xSelectBits & ( ( EventBits_t ) eSELECT_ALL ) ) != ( EventBits_t ) 0U )
{
/* Adding a socket to a socket set. */
pxSocket->pxSocketSet = ( SocketSelect_t * ) xSocketSet;
/* Now have the IP-task call vSocketSelect() to see if the set contains
* any sockets which are 'ready' and set the proper bits. */
prvFindSelectedSocket( pxSocketSet );
}
}
#endif /* ipconfigSUPPORT_SELECT_FUNCTION == 1 */
/*-----------------------------------------------------------*/
#if ( ipconfigSUPPORT_SELECT_FUNCTION == 1 )
/**
* @brief Clear select bits for a socket. If the mask becomes 0,
* remove the socket from the set.
*
* @param[in] xSocket: The socket whose select bits are being cleared.
* @param[in] xSocketSet: The socket set of the socket.
* @param[in] xBitsToClear: The bits to be cleared. Every '1' means that the
* corresponding bit will be cleared. See 'eSelectEvent_t' for
* the possible values.
*/
void FreeRTOS_FD_CLR( Socket_t xSocket,
SocketSet_t xSocketSet,
EventBits_t xBitsToClear )
{
FreeRTOS_Socket_t * pxSocket = ( FreeRTOS_Socket_t * ) xSocket;
configASSERT( pxSocket != NULL );
configASSERT( xSocketSet != NULL );
pxSocket->xSelectBits &= ~( xBitsToClear & ( ( EventBits_t ) eSELECT_ALL ) );
if( ( pxSocket->xSelectBits & ( ( EventBits_t ) eSELECT_ALL ) ) != ( EventBits_t ) 0U )
{
pxSocket->pxSocketSet = ( SocketSelect_t * ) xSocketSet;
}
else
{
/* disconnect it from the socket set */
pxSocket->pxSocketSet = NULL;
}
}
#endif /* ipconfigSUPPORT_SELECT_FUNCTION == 1 */
/*-----------------------------------------------------------*/
#if ( ipconfigSUPPORT_SELECT_FUNCTION == 1 )
/**
* @brief Test if a socket belongs to a socket-set and if so, which event bit(s)
* are set.
*
* @param[in] xSocket: The socket of interest.
* @param[in] xSocketSet: The socket set to which the socket belongs.
*
* @return If the socket belongs to the socket set: the event bits, otherwise zero.
*/
EventBits_t FreeRTOS_FD_ISSET( Socket_t xSocket,
SocketSet_t xSocketSet )
{
EventBits_t xReturn;
const FreeRTOS_Socket_t * pxSocket = ( const FreeRTOS_Socket_t * ) xSocket;
configASSERT( pxSocket != NULL );
configASSERT( xSocketSet != NULL );
if( xSocketSet == ( SocketSet_t ) pxSocket->pxSocketSet )
{
/* Make sure we're not adding bits which are reserved for internal
* use. */
xReturn = pxSocket->xSocketBits & ( ( EventBits_t ) eSELECT_ALL );
}
else
{
xReturn = 0;
}
return xReturn;
}
#endif /* ipconfigSUPPORT_SELECT_FUNCTION == 1 */
/*-----------------------------------------------------------*/
#if ( ipconfigSUPPORT_SELECT_FUNCTION == 1 )
/**
* @brief The select() statement: wait for an event to occur on any of the sockets
* included in a socket set.
*
* @param[in] xSocketSet: The socket set including the sockets on which we are
* waiting for an event to occur.
* @param[in] xBlockTimeTicks: Maximum time ticks to wait for an event to occur.
* If the value is 'portMAX_DELAY' then the function will wait
* indefinitely for an event to occur.
*
* @return The socket which might have triggered the event bit.
*/
BaseType_t FreeRTOS_select( SocketSet_t xSocketSet,
TickType_t xBlockTimeTicks )
{
TimeOut_t xTimeOut;
TickType_t xRemainingTime;
SocketSelect_t * pxSocketSet = ( SocketSelect_t * ) xSocketSet;
EventBits_t uxResult;
configASSERT( xSocketSet != NULL );
/* Only in the first round, check for non-blocking */
xRemainingTime = xBlockTimeTicks;
/* Fetch the current time */
vTaskSetTimeOutState( &xTimeOut );
for( ; ; )
{
/* Find a socket which might have triggered the bit
* This function might return immediately or block for a limited time */
uxResult = xEventGroupWaitBits( pxSocketSet->xSelectGroup, ( ( EventBits_t ) eSELECT_ALL ), pdFALSE, pdFALSE, xRemainingTime );
#if ( ipconfigSUPPORT_SIGNALS != 0 )
{
if( ( uxResult & ( ( EventBits_t ) eSELECT_INTR ) ) != 0U )
{
( void ) xEventGroupClearBits( pxSocketSet->xSelectGroup, ( EventBits_t ) eSELECT_INTR );
FreeRTOS_debug_printf( ( "FreeRTOS_select: interrupted\n" ) );
break;
}
}
#endif /* ipconfigSUPPORT_SIGNALS */
/* Have the IP-task find the socket which had an event */
prvFindSelectedSocket( pxSocketSet );
uxResult = xEventGroupGetBits( pxSocketSet->xSelectGroup );
if( uxResult != 0U )
{
break;
}
/* Has the timeout been reached? */
if( xTaskCheckForTimeOut( &xTimeOut, &xRemainingTime ) != pdFALSE )
{
break;
}
}
return ( BaseType_t ) uxResult;
}
#endif /* ipconfigSUPPORT_SELECT_FUNCTION */
/*-----------------------------------------------------------*/
#if ( ipconfigSUPPORT_SELECT_FUNCTION == 1 )
/**
* @brief Send a message to the IP-task to have it check all sockets belonging to
* 'pxSocketSet'
*
* @param[in] pxSocketSet: The socket set being asked to check.
*/
static void prvFindSelectedSocket( SocketSelect_t * pxSocketSet )
{
IPStackEvent_t xSelectEvent;
#if ( ipconfigSELECT_USES_NOTIFY != 0 )
SocketSelectMessage_t xSelectMessage;
#endif
xSelectEvent.eEventType = eSocketSelectEvent;
#if ( ipconfigSELECT_USES_NOTIFY != 0 )
{
xSelectMessage.pxSocketSet = pxSocketSet;
xSelectMessage.xTaskhandle = xTaskGetCurrentTaskHandle();
xSelectEvent.pvData = &( xSelectMessage );
}
#else
{
xSelectEvent.pvData = pxSocketSet;
/* while the IP-task works on the request, the API will block on
* 'eSELECT_CALL_IP'. So clear it first. */
( void ) xEventGroupClearBits( pxSocketSet->xSelectGroup, ( BaseType_t ) eSELECT_CALL_IP );
}
#endif /* if ( ipconfigSELECT_USES_NOTIFY != 0 ) */
/* Now send the socket select event */
if( xSendEventStructToIPTask( &xSelectEvent, ( TickType_t ) portMAX_DELAY ) == pdFAIL )
{
/* Oops, we failed to wake-up the IP task. No use to wait for it. */
FreeRTOS_debug_printf( ( "prvFindSelectedSocket: failed\n" ) );
}
else
{
/* As soon as the IP-task is ready, it will set 'eSELECT_CALL_IP' to
* wakeup the calling API */
#if ( ipconfigSELECT_USES_NOTIFY != 0 )
{
( void ) ulTaskNotifyTake( pdFALSE, portMAX_DELAY );
}
#else
{
( void ) xEventGroupWaitBits( pxSocketSet->xSelectGroup, ( BaseType_t ) eSELECT_CALL_IP, pdTRUE, pdFALSE, portMAX_DELAY );
}
#endif
}
}
#endif /* ipconfigSUPPORT_SELECT_FUNCTION == 1 */
/*-----------------------------------------------------------*/
/**
* @brief Receive data from a bound socket. In this library, the function
* can only be used with connection-less sockets (UDP). For TCP sockets,
* please use FreeRTOS_recv().
*
* @param[in] xSocket: The socket to which the data is sent i.e. the
* listening socket.
* @param[out] pvBuffer: The buffer in which the data being received is to
* be stored.
* @param[in] uxBufferLength: The length of the buffer.
* @param[in] xFlags: The flags to indicate preferences while calling this function.
* @param[out] pxSourceAddress: The source address from which the data is being sent.
* @param[out] pxSourceAddressLength: This parameter is used only to adhere to Berkeley
* sockets standard. It is not used internally.
*
* @return The number of bytes received. Or else, an error code is returned. When it
* returns a negative value, the cause can be looked-up in
* 'FreeRTOS_errno_TCP.h'.
*/
int32_t FreeRTOS_recvfrom( Socket_t xSocket,
void * pvBuffer,
size_t uxBufferLength,
BaseType_t xFlags,
struct freertos_sockaddr * pxSourceAddress,
socklen_t * pxSourceAddressLength )
{
BaseType_t lPacketCount;
NetworkBufferDescriptor_t * pxNetworkBuffer;
const void * pvCopySource;
FreeRTOS_Socket_t const * pxSocket = xSocket;
TickType_t xRemainingTime = ( TickType_t ) 0; /* Obsolete assignment, but some compilers output a warning if its not done. */
BaseType_t xTimed = pdFALSE;
TimeOut_t xTimeOut;
int32_t lReturn;
EventBits_t xEventBits = ( EventBits_t ) 0;
size_t uxPayloadLength;
if( prvValidSocket( pxSocket, FREERTOS_IPPROTO_UDP, pdTRUE ) == pdFALSE )
{
lReturn = -pdFREERTOS_ERRNO_EINVAL;
}
else
{
lPacketCount = ( BaseType_t ) listCURRENT_LIST_LENGTH( &( pxSocket->u.xUDP.xWaitingPacketsList ) );
/* The function prototype is designed to maintain the expected Berkeley
* sockets standard, but this implementation does not use all the parameters. */
( void ) pxSourceAddressLength;
while( lPacketCount == 0 )
{
if( xTimed == pdFALSE )
{
/* Check to see if the socket is non blocking on the first
* iteration. */
xRemainingTime = pxSocket->xReceiveBlockTime;
if( xRemainingTime == ( TickType_t ) 0 )
{
#if ( ipconfigSUPPORT_SIGNALS != 0 )
{
/* Just check for the interrupt flag. */
xEventBits = xEventGroupWaitBits( pxSocket->xEventGroup, ( EventBits_t ) eSOCKET_INTR,
pdTRUE /*xClearOnExit*/, pdFALSE /*xWaitAllBits*/, socketDONT_BLOCK );
}
#endif /* ipconfigSUPPORT_SIGNALS */
break;
}
if( ( ( ( UBaseType_t ) xFlags ) & ( ( UBaseType_t ) FREERTOS_MSG_DONTWAIT ) ) != 0U )
{
break;
}
/* To ensure this part only executes once. */
xTimed = pdTRUE;
/* Fetch the current time. */
vTaskSetTimeOutState( &xTimeOut );
}
/* Wait for arrival of data. While waiting, the IP-task may set the
* 'eSOCKET_RECEIVE' bit in 'xEventGroup', if it receives data for this
* socket, thus unblocking this API call. */
xEventBits = xEventGroupWaitBits( pxSocket->xEventGroup, ( ( EventBits_t ) eSOCKET_RECEIVE ) | ( ( EventBits_t ) eSOCKET_INTR ),
pdTRUE /*xClearOnExit*/, pdFALSE /*xWaitAllBits*/, xRemainingTime );
#if ( ipconfigSUPPORT_SIGNALS != 0 )
{
if( ( xEventBits & ( EventBits_t ) eSOCKET_INTR ) != 0U )
{
if( ( xEventBits & ( EventBits_t ) eSOCKET_RECEIVE ) != 0U )
{
/* Shouldn't have cleared the eSOCKET_RECEIVE flag. */
( void ) xEventGroupSetBits( pxSocket->xEventGroup, ( EventBits_t ) eSOCKET_RECEIVE );
}
break;
}
}
#else /* if ( ipconfigSUPPORT_SIGNALS != 0 ) */
{
( void ) xEventBits;
}
#endif /* ipconfigSUPPORT_SIGNALS */
lPacketCount = ( BaseType_t ) listCURRENT_LIST_LENGTH( &( pxSocket->u.xUDP.xWaitingPacketsList ) );
if( lPacketCount != 0 )
{
break;
}
/* Has the timeout been reached ? */
if( xTaskCheckForTimeOut( &xTimeOut, &xRemainingTime ) != pdFALSE )
{
break;
}
} /* while( lPacketCount == 0 ) */
if( lPacketCount != 0 )
{
taskENTER_CRITICAL();
{
/* The owner of the list item is the network buffer. */
pxNetworkBuffer = ipCAST_PTR_TO_TYPE_PTR( NetworkBufferDescriptor_t, listGET_OWNER_OF_HEAD_ENTRY( &( pxSocket->u.xUDP.xWaitingPacketsList ) ) );
if( ( ( UBaseType_t ) xFlags & ( UBaseType_t ) FREERTOS_MSG_PEEK ) == 0U )
{
/* Remove the network buffer from the list of buffers waiting to
* be processed by the socket. */
( void ) uxListRemove( &( pxNetworkBuffer->xBufferListItem ) );
}
}
taskEXIT_CRITICAL();
/* The returned value is the length of the payload data, which is
* calculated at the total packet size minus the headers.
* The validity of `xDataLength` prvProcessIPPacket has been confirmed
* in 'prvProcessIPPacket()'. */
uxPayloadLength = pxNetworkBuffer->xDataLength - sizeof( UDPPacket_t );
lReturn = ( int32_t ) uxPayloadLength;
if( pxSourceAddress != NULL )
{
pxSourceAddress->sin_port = pxNetworkBuffer->usPort;
pxSourceAddress->sin_addr = pxNetworkBuffer->ulIPAddress;
}
if( ( ( UBaseType_t ) xFlags & ( UBaseType_t ) FREERTOS_ZERO_COPY ) == 0U )
{
/* The zero copy flag is not set. Truncate the length if it won't
* fit in the provided buffer. */
if( lReturn > ( int32_t ) uxBufferLength )
{
iptraceRECVFROM_DISCARDING_BYTES( ( uxBufferLength - lReturn ) );
lReturn = ( int32_t ) uxBufferLength;
}
/* Copy the received data into the provided buffer, then release the
* network buffer. */
pvCopySource = ( const void * ) &pxNetworkBuffer->pucEthernetBuffer[ ipUDP_PAYLOAD_OFFSET_IPv4 ];
( void ) memcpy( pvBuffer, pvCopySource, ( size_t ) lReturn );
if( ( ( UBaseType_t ) xFlags & ( UBaseType_t ) FREERTOS_MSG_PEEK ) == 0U )
{
vReleaseNetworkBufferAndDescriptor( pxNetworkBuffer );
}
}
else
{
/* The zero copy flag was set. pvBuffer is not a buffer into which
* the received data can be copied, but a pointer that must be set to
* point to the buffer in which the received data has already been
* placed. */
*( ( void ** ) pvBuffer ) = ipPOINTER_CAST( void *, &( pxNetworkBuffer->pucEthernetBuffer[ ipUDP_PAYLOAD_OFFSET_IPv4 ] ) );
}
}
#if ( ipconfigSUPPORT_SIGNALS != 0 )
else if( ( xEventBits & ( EventBits_t ) eSOCKET_INTR ) != 0U )
{
lReturn = -pdFREERTOS_ERRNO_EINTR;
iptraceRECVFROM_INTERRUPTED();
}
#endif /* ipconfigSUPPORT_SIGNALS */
else