-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFreeRTOS_Sockets.c
3377 lines (2879 loc) · 101 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 Labs Build 150406 (C) 2015 Real Time Engineers ltd.
* Authors include Hein Tibosch and Richard Barry
*
*******************************************************************************
***** NOTE ******* NOTE ******* NOTE ******* NOTE ******* NOTE ******* NOTE ***
*** ***
*** ***
*** FREERTOS+TCP IS STILL IN THE LAB: ***
*** ***
*** This product is functional and is already being used in commercial ***
*** products. Be aware however that we are still refining its design, ***
*** the source code does not yet fully conform to the strict coding and ***
*** style standards mandated by Real Time Engineers ltd., and the ***
*** documentation and testing is not necessarily complete. ***
*** ***
*** PLEASE REPORT EXPERIENCES USING THE SUPPORT RESOURCES FOUND ON THE ***
*** URL: http://www.FreeRTOS.org/contact Active early adopters may, at ***
*** the sole discretion of Real Time Engineers Ltd., be offered versions ***
*** under a license other than that described below. ***
*** ***
*** ***
***** NOTE ******* NOTE ******* NOTE ******* NOTE ******* NOTE ******* NOTE ***
*******************************************************************************
*
* - Open source licensing -
* While FreeRTOS+TCP is in the lab it is provided only under version two of the
* GNU General Public License (GPL) (which is different to the standard FreeRTOS
* license). FreeRTOS+TCP is free to download, use and distribute under the
* terms of that license provided the copyright notice and this text are not
* altered or removed from the source files. The GPL V2 text is available on
* the gnu.org web site, and on the following
* URL: http://www.FreeRTOS.org/gpl-2.0.txt. Active early adopters may, and
* solely at the discretion of Real Time Engineers Ltd., be offered versions
* under a license other then the GPL.
*
* FreeRTOS+TCP is distributed in the hope that it will be useful. You cannot
* use FreeRTOS+TCP unless you agree that you use the software 'as is'.
* FreeRTOS+TCP is provided WITHOUT ANY WARRANTY; without even the implied
* warranties of NON-INFRINGEMENT, MERCHANTABILITY or FITNESS FOR A PARTICULAR
* PURPOSE. Real Time Engineers Ltd. disclaims all conditions and terms, be they
* implied, expressed, or statutory.
*
* 1 tab == 4 spaces!
*
* http://www.FreeRTOS.org
* http://www.FreeRTOS.org/plus
* http://www.FreeRTOS.org/labs
*
*/
/* 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. */
#define socketSET_SOCKET_PORT( pxSocket, usPort ) listSET_LIST_ITEM_VALUE( ( &( ( pxSocket )->xBoundSocketListItem ) ), ( usPort ) )
#define socketGET_SOCKET_PORT( pxSocket ) listGET_LIST_ITEM_VALUE( ( &( ( pxSocket )->xBoundSocketListItem ) ) )
/* 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 )
/* 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. */
/* _HT_ thinks that the default of 0xc000 is pretty high */
#if !defined( socketAUTO_PORT_ALLOCATION_START_NUMBER )
#define socketAUTO_PORT_ALLOCATION_START_NUMBER ( ( uint16_t ) 0xc000 )
#endif
/* When the automatically generated port numbers overflow, the next value used
is not set back to socketAUTO_PORT_ALLOCATION_START_NUMBER because it is likely
that the first few automatically generated ports will still be in use. Instead
it is reset back to the value defined by this constant. */
#define socketAUTO_PORT_ALLOCATION_RESET_NUMBER ( ( uint16_t ) 0xc100 )
#define socketAUTO_PORT_ALLOCATION_MAX_NUMBER ( ( uint16_t ) 0xff00 )
/* The number of octets that make up an IP address. */
#define socketMAX_IP_ADDRESS_OCTETS 4
/*-----------------------------------------------------------*/
/*
* 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 ulProtocol );
/*
* 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( xFreeRTOS_Socket_t *pxSocket, BaseType_t ucProtocol, BaseType_t ucIsBound );
/*
* 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 'bInput'
*/
static xStreamBuffer *prvTcpCreateStream (xFreeRTOS_Socket_t *pxSocket, BaseType_t bInput);
#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( xFreeRTOS_Socket_t *pxSocket, size_t xDataLength );
#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( xFreeRTOS_Socket_t *pxSocket );
#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( xFreeRTOS_Socket_t *pxSocket, struct freertos_sockaddr *pxAddress );
#endif /* ipconfigUSE_TCP */
#if( ipconfigSUPPORT_SELECT_FUNCTION == 1 )
/* Executed by the IP-task, it will check all sockets belonging to a set */
static xFreeRTOS_Socket_t *prvFindSelectedSocket( xSocketSelect_t *pxSocketSet );
#endif /* ipconfigSUPPORT_SELECT_FUNCTION == 1 */
/*-----------------------------------------------------------*/
/* The list that contains mappings between sockets and port numbers. Accesses
to this list must be protected by critical sections of one kind or another. */
List_t xBoundUdpSocketsList;
#if ipconfigUSE_TCP == 1
List_t xBoundTcpSocketsList;
#endif /* ipconfigUSE_TCP == 1 */
static uint16_t usNextPortToUse[] =
{
socketAUTO_PORT_ALLOCATION_START_NUMBER, /* next port for UDP */
#define NXT_UDP_PORT_IDX 0 /* index for UDP port numbers */
#if ipconfigUSE_TCP == 1
socketAUTO_PORT_ALLOCATION_START_NUMBER, /* next port for TCP */
#define NXT_TCP_PORT_IDX 1 /* index for TCP port numbers */
#endif /* ipconfigUSE_TCP == 1 */
};
/*-----------------------------------------------------------*/
static BaseType_t prvValidSocket( xFreeRTOS_Socket_t *pxSocket, BaseType_t ucProtocol, BaseType_t ucIsBound )
{
BaseType_t xReturn = pdTRUE;
if( ( pxSocket == NULL ) || ( pxSocket == FREERTOS_INVALID_SOCKET ) )
{
xReturn = pdFALSE;
}
else if( ( ucIsBound != 0 ) && ( socketSOCKET_IS_BOUND( pxSocket ) == pdFALSE ) )
{
/* The caller expects the socket to be bound, but it isn't */
xReturn = pdFALSE;
}
else if( pxSocket->ucProtocol != ucProtocol )
{
xReturn = pdFALSE;
}
return xReturn;
}
/*-----------------------------------------------------------*/
void vNetworkSocketsInit( void )
{
vListInitialise( &xBoundUdpSocketsList );
/* Determine the first anonymous UDP port number to get assigned. Give it
a random value in order to avoid confusion about port numbers being used
earlier, before rebooting the device */
usNextPortToUse[ NXT_UDP_PORT_IDX ] = ( uint16_t )
( socketAUTO_PORT_ALLOCATION_START_NUMBER +
( ipconfigRAND32() % ( socketAUTO_PORT_ALLOCATION_MAX_NUMBER - socketAUTO_PORT_ALLOCATION_RESET_NUMBER ) ) );
#if( ipconfigUSE_TCP == 1 )
{
extern uint32_t ulNextInitialSequenceNumber;
ulNextInitialSequenceNumber = ipconfigRAND32();
/* Determine the first anonymous TCP port number to get assigned. */
usNextPortToUse[NXT_TCP_PORT_IDX] = ( uint16_t )
( socketAUTO_PORT_ALLOCATION_START_NUMBER +
( ipconfigRAND32() % ( socketAUTO_PORT_ALLOCATION_MAX_NUMBER - socketAUTO_PORT_ALLOCATION_RESET_NUMBER ) ) );
vListInitialise( &xBoundTcpSocketsList );
}
#endif /* ipconfigUSE_TCP == 1 */
}
/*-----------------------------------------------------------*/
static BaseType_t prvDetermineSocketSize( BaseType_t xDomain, BaseType_t xType, BaseType_t xProtocol, size_t *pxSocketSize )
{
BaseType_t xReturn = pdPASS;
xFreeRTOS_Socket_t *pxSocket;
/* 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 );
configASSERT( listLIST_IS_INITIALISED( &xBoundUdpSocketsList ) );
#if( ipconfigUSE_TCP == 1 )
{
configASSERT( listLIST_IS_INITIALISED( &xBoundTcpSocketsList ) );
}
#endif /* ipconfigUSE_TCP == 1 */
if( xProtocol == FREERTOS_IPPROTO_UDP )
{
if( xType != FREERTOS_SOCK_DGRAM )
{
xReturn = pdFAIL;
}
/* 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;
}
*pxSocketSize = ( sizeof( *pxSocket ) - sizeof( pxSocket->u ) ) + sizeof( pxSocket->u.xTcp );
}
#endif /* ipconfigUSE_TCP == 1 */
else
{
xReturn = pdFAIL;
}
}
/* In case configASSERT() is not used */
( void )xDomain;
return xReturn;
}
/*-----------------------------------------------------------*/
/* FreeRTOS_socket() allocates and initiates a socket */
xSocket_t FreeRTOS_socket( BaseType_t xDomain, BaseType_t xType, BaseType_t xProtocol )
{
xFreeRTOS_Socket_t *pxSocket;
size_t uxSocketSize;
EventGroupHandle_t xEventGroup;
xSocket_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 = ( xFreeRTOS_Socket_t * ) pvPortMallocSocket( uxSocketSize );
if( pxSocket == NULL )
{
pxSocket = ( xFreeRTOS_Socket_t * ) FREERTOS_INVALID_SOCKET;
iptraceFAILED_TO_CREATE_SOCKET();
}
else if( ( xEventGroup = xEventGroupCreate() ) == NULL )
{
vPortFreeSocket( pxSocket );
pxSocket = ( xFreeRTOS_Socket_t * ) FREERTOS_INVALID_SOCKET;
iptraceFAILED_TO_CREATE_EVENT_GROUP();
}
else
{
/* Clear the entire space to avoid nulling individual entries */
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 > 0 )
{
pxSocket->u.xUdp.xMaxPackets = ipconfigUDP_MAX_RX_PACKETS;
}
#endif /* ipconfigUDP_MAX_RX_PACKETS > 0 */
}
vListInitialiseItem( &( pxSocket->xBoundSocketListItem ) );
listSET_LIST_ITEM_OWNER( &( pxSocket->xBoundSocketListItem ), ( void * ) pxSocket );
pxSocket->xReceiveBlockTime = ipconfigSOCK_DEFAULT_RECEIVE_BLOCK_TIME;
pxSocket->xSendBlockTime = ipconfigSOCK_DEFAULT_SEND_BLOCK_TIME;
pxSocket->ucSocketOptions = 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.usInitMSS = pxSocket->u.xTcp.usCurMSS = ipconfigTCP_MSS;
pxSocket->u.xTcp.rxStreamSize = ipconfigTCP_RX_BUF_LEN;
pxSocket->u.xTcp.txStreamSize = ( int32_t ) FreeRTOS_round_up( ipconfigTCP_TX_BUF_LEN, ipconfigTCP_MSS );
/* Use half of the buffer size of the TCP windows */
#if ( ipconfigUSE_TCP_WIN == 1 )
{
pxSocket->u.xTcp.ulRxWinSize = FreeRTOS_max_uint32( 1UL, ( uint32_t ) ( pxSocket->u.xTcp.rxStreamSize / 2 ) / ipconfigTCP_MSS );
pxSocket->u.xTcp.ulTxWinSize = FreeRTOS_max_uint32( 1UL, ( uint32_t ) ( pxSocket->u.xTcp.txStreamSize / 2 ) / ipconfigTCP_MSS );
}
#else
{
pxSocket->u.xTcp.ulRxWinSize = 1;
pxSocket->u.xTcp.ulTxWinSize = 1;
}
#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 = ( xSocket_t ) pxSocket;
}
/* Remove compiler warnings in the case the configASSERT() is not defined. */
( void ) xDomain;
return xReturn;
}
/*-----------------------------------------------------------*/
#if( ipconfigSUPPORT_SELECT_FUNCTION == 1 )
xSocketSet_t FreeRTOS_CreateSocketSet( void )
{
xSocketSelect_t *pxSocketSet;
pxSocketSet = ( xSocketSelect_t * ) pvPortMalloc( sizeof( *pxSocketSet ) );
if( pxSocketSet != NULL )
{
memset( pxSocketSet, '\0', sizeof( *pxSocketSet ) );
pxSocketSet->xSelectGroup = xEventGroupCreate();
if( pxSocketSet->xSelectGroup == NULL )
{
vPortFree( ( void* ) pxSocketSet );
pxSocketSet = NULL;
}
}
return ( xSocketSet_t * ) pxSocketSet;
}
#endif /* ipconfigSUPPORT_SELECT_FUNCTION == 1 */
/*-----------------------------------------------------------*/
#if( ipconfigSUPPORT_SELECT_FUNCTION == 1 )
void FreeRTOS_DeleteSocketSet( xSocketSet_t xSocketSet )
{
xSocketSelect_t *pxSocketSet = ( xSocketSelect_t*) xSocketSet;
vEventGroupDelete( pxSocketSet->xSelectGroup );
vPortFree( ( void* ) pxSocketSet );
}
#endif /* ipconfigSUPPORT_SELECT_FUNCTION == 1 */
/*-----------------------------------------------------------*/
#if( ipconfigSUPPORT_SELECT_FUNCTION == 1 )
/* Add a socket to a set */
void FreeRTOS_FD_SET( xSocket_t xSocket, xSocketSet_t xSocketSet, EventBits_t xSelectBits )
{
xFreeRTOS_Socket_t *pxSocket = ( xFreeRTOS_Socket_t * ) xSocket;
xSocketSelect_t *pxSocketSet = ( xSocketSelect_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 |= ( xSelectBits & eSELECT_ALL );
if( ( pxSocket->xSelectBits & eSELECT_ALL ) != 0 )
{
/* Adding a socket to a socket set. */
pxSocket->pxSocketSet = ( xSocketSelect_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.
By setting 'bApiCalled = false', vSocketSelect() knows that it was
not called from a user API */
pxSocketSet->bApiCalled = pdFALSE;
prvFindSelectedSocket( pxSocketSet );
}
}
#endif /* ipconfigSUPPORT_SELECT_FUNCTION == 1 */
/*-----------------------------------------------------------*/
#if( ipconfigSUPPORT_SELECT_FUNCTION == 1 )
/* Clear select bits for a socket
If the mask becomes 0, remove the socket from the set */
void FreeRTOS_FD_CLR( xSocket_t xSocket, xSocketSet_t xSocketSet, EventBits_t xSelectBits )
{
xFreeRTOS_Socket_t *pxSocket = ( xFreeRTOS_Socket_t * ) xSocket;
configASSERT( pxSocket != NULL );
configASSERT( xSocketSet != NULL );
pxSocket->xSelectBits &= ~( xSelectBits & eSELECT_ALL );
if( ( pxSocket->xSelectBits & eSELECT_ALL ) != 0 )
{
pxSocket->pxSocketSet = ( xSocketSelect_t *)xSocketSet;
}
else
{
/* disconnect it from the socket set */
pxSocket->pxSocketSet = ( xSocketSelect_t *)NULL;
}
}
#endif /* ipconfigSUPPORT_SELECT_FUNCTION == 1 */
/*-----------------------------------------------------------*/
#if( ipconfigSUPPORT_SELECT_FUNCTION == 1 )
/* Test if a socket belongs to a socket-set */
EventBits_t FreeRTOS_FD_ISSET( xSocket_t xSocket, xSocketSet_t xSocketSet )
{
EventBits_t xReturn;
xFreeRTOS_Socket_t *pxSocket = ( xFreeRTOS_Socket_t * ) xSocket;
configASSERT( pxSocket != NULL );
configASSERT( xSocketSet != NULL );
if( xSocketSet == ( xSocketSet_t ) pxSocket->pxSocketSet )
{
/* Make sure we're not adding bits which are reserved for internal
use. */
xReturn = pxSocket->xSocketBits & eSELECT_ALL;
}
else
{
xReturn = 0;
}
return xReturn;
}
#endif /* ipconfigSUPPORT_SELECT_FUNCTION == 1 */
/*-----------------------------------------------------------*/
#if( ipconfigSUPPORT_SELECT_FUNCTION == 1 )
/* The select() statement: wait for an event to occur on any of the sockets
included in a socket set */
BaseType_t FreeRTOS_select( xSocketSet_t xSocketSet, TickType_t xBlockTimeTicks )
{
TimeOut_t xTimeOut;
TickType_t xRemainingTime;
xSocketSelect_t *pxSocketSet = ( xSocketSelect_t*) xSocketSet;
BaseType_t xResult;
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 */
xEventGroupWaitBits( pxSocketSet->xSelectGroup, eSELECT_ALL, pdFALSE, pdFALSE, xRemainingTime );
/* Have the IP-task find the socket which had an event */
pxSocketSet->bApiCalled = pdTRUE;
prvFindSelectedSocket( pxSocketSet );
xResult = ( BaseType_t ) xEventGroupGetBits( pxSocketSet->xSelectGroup );
if( xResult != 0 )
{
break;
}
/* Has the timeout been reached? */
if( xTaskCheckForTimeOut( &xTimeOut, &xRemainingTime ) != pdFALSE )
{
break;
}
}
return xResult;
}
#endif /* ipconfigSUPPORT_SELECT_FUNCTION */
/*-----------------------------------------------------------*/
#if( ipconfigSUPPORT_SELECT_FUNCTION == 1 )
/* Send a message to the IP-task to have it check all sockets belonging to
'pxSocketSet' */
static xFreeRTOS_Socket_t *prvFindSelectedSocket( xSocketSelect_t *pxSocketSet )
{
xIPStackEvent_t xSelectEvent;
xFreeRTOS_Socket_t *xReturn;
xSelectEvent.eEventType = eSocketSelectEvent;
xSelectEvent.pvData = ( void * ) pxSocketSet;
/* while the IP-task works on the request, the API will block on
'eSELECT_CALL_IP'. So clear it first. */
xEventGroupClearBits( pxSocketSet->xSelectGroup, eSELECT_CALL_IP );
/* 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" ) );
xReturn = NULL;
}
else
{
/* As soon as the IP-task is ready, it will set 'eSELECT_CALL_IP' to
wakeup the calling API */
xEventGroupWaitBits( pxSocketSet->xSelectGroup, eSELECT_CALL_IP, pdTRUE, pdFALSE, portMAX_DELAY );
/* Return 'pxSocket' which is set by the IP-task */
xReturn = pxSocketSet->pxSocket;
}
return xReturn;
}
#endif /* ipconfigSUPPORT_SELECT_FUNCTION == 1 */
/*-----------------------------------------------------------*/
/*
* FreeRTOS_recvfrom: receive data from a bound socket
* In this library, the function can only be used with connectionsless sockets
* (UDP)
*/
int32_t FreeRTOS_recvfrom( xSocket_t xSocket, void *pvBuffer, size_t xBufferLength, uint32_t ulFlags, struct freertos_sockaddr *pxSourceAddress, socklen_t *pxSourceAddressLength )
{
BaseType_t lPacketCount = 0;
xNetworkBufferDescriptor_t *pxNetworkBuffer;
xFreeRTOS_Socket_t *pxSocket = ( xFreeRTOS_Socket_t * ) xSocket;
TickType_t xRemainingTime = 0; /* Obsolete assignment, but some compilers output a warning if its not done. */
BaseType_t xTimed = pdFALSE;
TimeOut_t xTimeOut;
int32_t lReturn;
if( prvValidSocket( pxSocket, FREERTOS_IPPROTO_UDP, pdTRUE ) == pdFALSE )
{
return -pdFREERTOS_ERRNO_EINVAL;
}
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 )
{
/* Only in the first round, check for non-blocking */
xRemainingTime = pxSocket->xReceiveBlockTime;
if( xRemainingTime == 0 )
{
break;
}
if( ( ulFlags & FREERTOS_MSG_DONTWAIT ) != 0 )
{
break;
}
/* Don't get here a second time. */
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. */
xEventGroupWaitBits( pxSocket->xEventGroup, eSOCKET_RECEIVE, pdTRUE /*xClearOnExit*/, pdFALSE /*xWaitAllBits*/, xRemainingTime );
lPacketCount = ( BaseType_t ) listCURRENT_LIST_LENGTH( &( pxSocket->u.xUdp.xWaitingPacketsList ) );
if( lPacketCount != 0 )
{
break;
}
/* Has the timeout been reached ? */
if( xTaskCheckForTimeOut( &xTimeOut, &xRemainingTime ) )
{
break;
}
}
if( lPacketCount != 0 )
{
taskENTER_CRITICAL();
{
/* The owner of the list item is the network buffer. */
pxNetworkBuffer = ( xNetworkBufferDescriptor_t * ) listGET_OWNER_OF_HEAD_ENTRY( &( pxSocket->u.xUdp.xWaitingPacketsList ) );
/* Remove the network buffer from the list of buffers waiting to
be processed by the socket. */
uxListRemove( &( pxNetworkBuffer->xBufferListItem ) );
}
taskEXIT_CRITICAL();
/* The returned value is the data length, which may have been capped to
the receive buffer size. */
lReturn = ( int32_t ) pxNetworkBuffer->xDataLength;
if( pxSourceAddress != NULL )
{
pxSourceAddress->sin_port = pxNetworkBuffer->usPort;
pxSourceAddress->sin_addr = pxNetworkBuffer->ulIPAddress;
}
if( ( ulFlags & FREERTOS_ZERO_COPY ) == 0 )
{
/* The zero copy flag is not set. Truncate the length if it won't
fit in the provided buffer. */
if( lReturn > ( int32_t ) xBufferLength )
{
iptraceRECVFROM_DISCARDING_BYTES( ( xBufferLength - lReturn ) );
lReturn = ( int32_t )xBufferLength;
}
/* Copy the received data into the provided buffer, then release the
network buffer. */
memcpy( pvBuffer, ( void * ) &( pxNetworkBuffer->pucEthernetBuffer[ ipUDP_PAYLOAD_OFFSET ] ), ( size_t )lReturn );
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 ) = ( void * ) ( &( pxNetworkBuffer->pucEthernetBuffer[ ipUDP_PAYLOAD_OFFSET ] ) );
}
}
else
{
lReturn = -pdFREERTOS_ERRNO_EWOULDBLOCK;
iptraceRECVFROM_TIMEOUT();
}
return lReturn;
}
/*-----------------------------------------------------------*/
int32_t FreeRTOS_sendto( xSocket_t xSocket, const void *pvBuffer, size_t xTotalDataLength, uint32_t ulFlags, const struct freertos_sockaddr *pxDestinationAddress, socklen_t xDestinationAddressLength )
{
xNetworkBufferDescriptor_t *pxNetworkBuffer;
xIPStackEvent_t xStackTxEvent = { eStackTxEvent, NULL };
TimeOut_t xTimeOut;
TickType_t xTicksToWait;
int32_t lReturn = 0;
xFreeRTOS_Socket_t *pxSocket;
pxSocket = ( xFreeRTOS_Socket_t * ) xSocket;
/* The function prototype is designed to maintain the expected Berkeley
sockets standard, but this implementation does not use all the
parameters. */
( void ) xDestinationAddressLength;
configASSERT( pvBuffer );
if( xTotalDataLength <= ipMAX_UDP_PAYLOAD_LENGTH )
{
/* If the socket is not already bound to an address, bind it now.
Passing NULL as the address parameter tells FreeRTOS_bind() to select
the address to bind to. */
if( ( socketSOCKET_IS_BOUND( pxSocket ) != pdFALSE ) ||
( FreeRTOS_bind( xSocket, NULL, 0 ) == 0 ) )
{
xTicksToWait = pxSocket->xSendBlockTime;
#if( ipconfigUSE_CALLBACKS != 0 )
{
if( xIsCallingFromIPTask() != pdFALSE )
{
/* If this send function is called from within a call-back
handler it may not block, otherwise chances would be big to
get a deadlock: the IP-task waiting for itself. */
xTicksToWait = 0;
}
}
#endif /* ipconfigUSE_CALLBACKS */
if( ( ulFlags & FREERTOS_MSG_DONTWAIT ) != 0 )
{
xTicksToWait = 0;
}
if( ( ulFlags & FREERTOS_ZERO_COPY ) == 0 )
{
/* Zero copy is not set, so obtain a network buffer into
which the payload will be copied. */
vTaskSetTimeOutState( &xTimeOut );
/* Block until a buffer becomes available, or until a
timeout has been reached */
pxNetworkBuffer = pxGetNetworkBufferWithDescriptor( xTotalDataLength + sizeof( xUDPPacket_t ), xTicksToWait );
if( pxNetworkBuffer != NULL )
{
memcpy( ( void * ) &( pxNetworkBuffer->pucEthernetBuffer[ ipUDP_PAYLOAD_OFFSET ] ), ( void * ) pvBuffer, xTotalDataLength );
if( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) == pdTRUE )
{
/* The entire block time has been used up. */
xTicksToWait = 0;
}
}
}
else
{
/* When zero copy is used, pvBuffer is a pointer to the
payload of a buffer that has already been obtained from the
stack. Obtain the network buffer pointer from the buffer. */
pxNetworkBuffer = pxUDPPayloadBuffer_to_NetworkBuffer( (void*)pvBuffer );
}
if( pxNetworkBuffer != NULL )
{
pxNetworkBuffer->xDataLength = xTotalDataLength;
pxNetworkBuffer->usPort = pxDestinationAddress->sin_port;
pxNetworkBuffer->usBoundPort = ( uint16_t ) socketGET_SOCKET_PORT( pxSocket );
pxNetworkBuffer->ulIPAddress = pxDestinationAddress->sin_addr;
/* The socket options are passed to the IP layer in the
space that will eventually get used by the Ethernet header. */
pxNetworkBuffer->pucEthernetBuffer[ ipSOCKET_OPTIONS_OFFSET ] = pxSocket->ucSocketOptions;
/* Tell the networking task that the packet needs sending. */
xStackTxEvent.pvData = pxNetworkBuffer;
/* Ask the IP-task to send this packet */
if( xSendEventStructToIPTask( &xStackTxEvent, xTicksToWait ) == pdPASS )
{
/* The packet was successfully sent to the IP task. */
lReturn = ( int32_t ) xTotalDataLength;
#if( ipconfigUSE_CALLBACKS == 1 )
{
if( ipconfigIS_VALID_PROG_ADDRESS( pxSocket->u.xUdp.pHndSent ) )
{
pxSocket->u.xUdp.pHndSent( (xSocket_t *)pxSocket, xTotalDataLength );
}
}
#endif /* ipconfigUSE_CALLBACKS */
}
else
{
/* If the buffer was allocated in this function, release
it. */
if( ( ulFlags & FREERTOS_ZERO_COPY ) == 0 )
{
vReleaseNetworkBufferAndDescriptor( pxNetworkBuffer );
}
iptraceSTACK_TX_EVENT_LOST( ipSTACK_TX_EVENT );
}
}
else
{
/* If errno was available, errno would be set to
FREERTOS_ENOPKTS. As it is, the function must return the
number of transmitted bytes, so the calling function knows
how much data was actually sent. */
iptraceNO_BUFFER_FOR_SENDTO();
}
}
else
{
iptraceSENDTO_SOCKET_NOT_BOUND();
}
}
else
{
/* The data is longer than the available buffer space. */
iptraceSENDTO_DATA_TOO_LONG();
}
return lReturn;
} /* Tested */
/*-----------------------------------------------------------*/
/*
* FreeRTOS_bind() : binds a sockt to a local port number
* If port 0 is provided, a system provided port number will be assigned
* Function can be used for both UDP and TCP sockets
* The actual binding will be performed by the IP-task to avoid mutual access
* to the bound-socket-lists (xBoundUdpSocketsList cq xBoundTcpSocketsList)
*/
BaseType_t FreeRTOS_bind( xSocket_t xSocket, struct freertos_sockaddr * pxAddress, socklen_t xAddressLength )
{
xIPStackEvent_t xBindEvent;
xFreeRTOS_Socket_t *pxSocket = (xFreeRTOS_Socket_t *)xSocket;
BaseType_t xReturn = 0;
( void ) xAddressLength;
/* Once a socket is bound to a port, it can not be bound to a different
port number */
if( socketSOCKET_IS_BOUND( pxSocket) != pdFALSE )
{
/* The socket is already bound. */
FreeRTOS_debug_printf( ( "vSocketBind: Socket already bound to %d\n", pxSocket->usLocPort ) );
xReturn = -pdFREERTOS_ERRNO_EINVAL;
}
else
{
/* Prepare a messages to the IP-task in order to perform the binding.
The desired port number will be passed in 'usLocPort */
xBindEvent.eEventType = eSocketBindEvent;
xBindEvent.pvData = ( void * ) xSocket;
if( pxAddress != NULL )
{
pxSocket->usLocPort = FreeRTOS_ntohs( pxAddress->sin_port );
}
else
{
/* Caller wants to bind to a random port number. */
pxSocket->usLocPort = 0;
}
/* portMAX_DELAY is used as a the time-out parameter, as binding *must*
succeed before the socket can be used. */
if( xSendEventStructToIPTask( &xBindEvent, ( TickType_t ) portMAX_DELAY ) == pdFAIL )
{
/* Failed to wake-up the IP-task, no use to wait for it */
FreeRTOS_debug_printf( ( "FreeRTOS_bind: send event failed\n" ) );
xReturn = -pdFREERTOS_ERRNO_ECANCELED;
}
else
{
/* The IP-task will set the 'eSOCKET_BOUND' bit when it has done its
job. */
xEventGroupWaitBits( pxSocket->xEventGroup, eSOCKET_BOUND, pdTRUE /*xClearOnExit*/, pdFALSE /*xWaitAllBits*/, portMAX_DELAY );
if( socketSOCKET_IS_BOUND( pxSocket ) == pdFALSE )
{
xReturn = -pdFREERTOS_ERRNO_EINVAL;
}
}
}
return xReturn;
}
/*
* vSocketBind(): internal version of bind(), should not be called directly
* 'ulInternal' is used for TCP sockets only: it allows to have several (connected) child sockets
* bound to the same server port
*/
BaseType_t vSocketBind( xFreeRTOS_Socket_t *pxSocket, struct freertos_sockaddr * pxAddress, BaseType_t xAddressLength, BaseType_t ulInternal )
{
BaseType_t xReturn = 0; /* In Berkeley sockets, 0 means pass for bind(). */
List_t *pxSocketList;
#if ipconfigALLOW_SOCKET_SEND_WITHOUT_BIND == 1
struct freertos_sockaddr xAddress;
#endif /* ipconfigALLOW_SOCKET_SEND_WITHOUT_BIND */
#if ipconfigUSE_TCP == 1
if( pxSocket->ucProtocol == FREERTOS_IPPROTO_TCP )
{
pxSocketList = &xBoundTcpSocketsList;
}
else
#endif /* ipconfigUSE_TCP == 1 */
{
pxSocketList = &xBoundUdpSocketsList;
}
/* The function prototype is designed to maintain the expected Berkeley
sockets standard, but this implementation does not use all the parameters. */
( void ) xAddressLength;
configASSERT( pxSocket );
configASSERT( pxSocket != FREERTOS_INVALID_SOCKET );
#if ipconfigALLOW_SOCKET_SEND_WITHOUT_BIND == 1
{
/* pxAddress will be NULL if sendto() was called on a socket without the
socket being bound to an address. In this case, automatically allocate
an address to the socket. There is a very tiny chance that the allocated
port will already be in use - if that is the case, then the check below
[pxListFindListItemWithValue()] will result in an error being returned. */
if( pxAddress == NULL )
{
pxAddress = &xAddress;
/* For now, put it to zero, will be assigned later */
pxAddress->sin_port = 0;
}
}
#endif /* ipconfigALLOW_SOCKET_SEND_WITHOUT_BIND == 1 */
/* Sockets must be bound before calling FreeRTOS_sendto() if
ipconfigALLOW_SOCKET_SEND_WITHOUT_BIND is not set to 1. */
configASSERT( pxAddress );
if( pxAddress != NULL )
{
if( pxAddress->sin_port == 0 )
{
pxAddress->sin_port = prvGetPrivatePortNumber( pxSocket->ucProtocol );
}
/* If vSocketBind() is called from the API FreeRTOS_bind() it has been
confirmed that the socket was not yet bound to a port. If it is called
from the IP-task, no such check is necessary. */
/* Check to ensure the port is not already in use. If the bind is
called internally, a port MAY be used by more than one socket. */
if( ( ulInternal == pdFALSE || ( pxSocket->ucProtocol != FREERTOS_IPPROTO_TCP ) ) &&
( pxListFindListItemWithValue( pxSocketList, ( TickType_t ) pxAddress->sin_port ) != NULL ) )
{
FreeRTOS_debug_printf( ( "vSocketBind: %sP port %d in use\n",
pxSocket->ucProtocol == FREERTOS_IPPROTO_TCP ? "TC" : "UD",
FreeRTOS_ntohs( pxAddress->sin_port ) ) );
xReturn = -pdFREERTOS_ERRNO_EADDRINUSE;
}
else
{
/* Allocate the port number to the socket.
This macro will set 'xBoundSocketListItem->xItemValue' */
socketSET_SOCKET_PORT( pxSocket, pxAddress->sin_port );