forked from FreeRTOS/FreeRTOS-Plus-TCP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
FreeRTOS_TCP_IP.c
4015 lines (3514 loc) · 182 KB
/
FreeRTOS_TCP_IP.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_TCP_IP.c
* @brief Module which handles the TCP connections for FreeRTOS+TCP.
* It depends on FreeRTOS_TCP_WIN.c, which handles the TCP windowing
* schemes.
*
* Endianness: in this module all ports and IP addresses are stored in
* host byte-order, except fields in the IP-packets
*/
/* Standard includes. */
#include <stdint.h>
#include <stdio.h>
/* FreeRTOS includes. */
#include "FreeRTOS.h"
#include "task.h"
#include "queue.h"
#include "semphr.h"
/* FreeRTOS+TCP includes. */
#include "FreeRTOS_IP.h"
#include "FreeRTOS_Sockets.h"
#include "FreeRTOS_IP_Private.h"
#include "FreeRTOS_UDP_IP.h"
#include "FreeRTOS_DHCP.h"
#include "NetworkInterface.h"
#include "NetworkBufferManagement.h"
#include "FreeRTOS_ARP.h"
/* Just make sure the contents doesn't get compiled if TCP is not enabled. */
#if ipconfigUSE_TCP == 1
/*lint -e750 local macro not referenced [MISRA 2012 Rule 2.5, advisory] */
/*
* The meaning of the TCP flags:
*/
#define tcpTCP_FLAG_FIN ( ( uint8_t ) 0x01U ) /**< No more data from sender. */
#define tcpTCP_FLAG_SYN ( ( uint8_t ) 0x02U ) /**< Synchronize sequence numbers. */
#define tcpTCP_FLAG_RST ( ( uint8_t ) 0x04U ) /**< Reset the connection. */
#define tcpTCP_FLAG_PSH ( ( uint8_t ) 0x08U ) /**< Push function: please push buffered data to the recv application. */
#define tcpTCP_FLAG_ACK ( ( uint8_t ) 0x10U ) /**< Acknowledgment field is significant. */
#define tcpTCP_FLAG_URG ( ( uint8_t ) 0x20U ) /**< Urgent pointer field is significant. */
#define tcpTCP_FLAG_ECN ( ( uint8_t ) 0x40U ) /**< ECN-Echo. */
#define tcpTCP_FLAG_CWR ( ( uint8_t ) 0x80U ) /**< Congestion Window Reduced. */
#define tcpTCP_FLAG_CTRL ( ( uint8_t ) 0x1FU ) /**< A mask to filter all protocol flags. */
/*
* A few values of the TCP options:
*/
#define tcpTCP_OPT_END 0U /**< End of TCP options list. */
#define tcpTCP_OPT_NOOP 1U /**< "No-operation" TCP option. */
#define tcpTCP_OPT_MSS 2U /**< Maximum segment size TCP option. */
#define tcpTCP_OPT_WSOPT 3U /**< TCP Window Scale Option (3-byte long). */
#define tcpTCP_OPT_SACK_P 4U /**< Advertise that SACK is permitted. */
#define tcpTCP_OPT_SACK_A 5U /**< SACK option with first/last. */
#define tcpTCP_OPT_TIMESTAMP 8U /**< Time-stamp option. */
#define tcpTCP_OPT_MSS_LEN 4U /**< Length of TCP MSS option. */
#define tcpTCP_OPT_WSOPT_LEN 3U /**< Length of TCP WSOPT option. */
#define tcpTCP_OPT_TIMESTAMP_LEN 10 /**< fixed length of the time-stamp option. */
#ifndef ipconfigTCP_ACK_EARLIER_PACKET
#define ipconfigTCP_ACK_EARLIER_PACKET 1 /**< Acknowledge an earlier packet. */
#endif
/** @brief
* The macro tcpNOW_CONNECTED() is use to determine if the connection makes a
* transition from connected to non-connected and vice versa.
* tcpNOW_CONNECTED() returns true when the status has one of these values:
* eESTABLISHED, eFIN_WAIT_1, eFIN_WAIT_2, eCLOSING, eLAST_ACK, eTIME_WAIT
* Technically the connection status is closed earlier, but the library wants
* to prevent that the socket will be deleted before the last ACK has been
* and thus causing a 'RST' packet on either side.
*/
#define tcpNOW_CONNECTED( status ) \
( ( ( ( status ) >= ( BaseType_t ) eESTABLISHED ) && ( ( status ) != ( BaseType_t ) eCLOSE_WAIT ) ) ? 1 : 0 )
/** @brief
* The highest 4 bits in the TCP offset byte indicate the total length of the
* TCP header, divided by 4.
*/
#define tcpVALID_BITS_IN_TCP_OFFSET_BYTE ( 0xF0U )
/*
* Acknowledgements to TCP data packets may be delayed as long as more is being expected.
* A normal delay would be 200ms. Here a much shorter delay of 20 ms is being used to
* gain performance.
*/
#define tcpDELAYED_ACK_SHORT_DELAY_MS ( 2 ) /**< Should not become smaller than 1. */
#define tcpDELAYED_ACK_LONGER_DELAY_MS ( 20 ) /**< Longer delay for ACK. */
/** @brief
* The MSS (Maximum Segment Size) will be taken as large as possible. However, packets with
* an MSS of 1460 bytes won't be transported through the internet. The MSS will be reduced
* to 1400 bytes.
*/
#define tcpREDUCED_MSS_THROUGH_INTERNET ( 1400 )
/** @brief
* When there are no TCP options, the TCP offset equals 20 bytes, which is stored as
* the number 5 (words) in the higher nibble of the TCP-offset byte.
*/
#define tcpTCP_OFFSET_LENGTH_BITS ( 0xf0U )
#define tcpTCP_OFFSET_STANDARD_LENGTH ( 0x50U ) /**< Standard TCP packet offset. */
/** @brief
* Each TCP socket is checked regularly to see if it can send data packets.
* By default, the maximum number of packets sent during one check is limited to 8.
* This amount may be further limited by setting the socket's TX window size.
*/
#if ( !defined( SEND_REPEATED_COUNT ) )
#define SEND_REPEATED_COUNT ( 8 )
#endif /* !defined( SEND_REPEATED_COUNT ) */
/** @brief
* Define a maximum period of time (ms) to leave a TCP-socket unattended.
* When a TCP timer expires, retries and keep-alive messages will be checked.
*/
#ifndef tcpMAXIMUM_TCP_WAKEUP_TIME_MS
#define tcpMAXIMUM_TCP_WAKEUP_TIME_MS 20000U
#endif
/* Two macro's that were introduced to work with both IPv4 and IPv6. */
#define xIPHeaderSize( pxNetworkBuffer ) ( ipSIZE_OF_IPv4_HEADER ) /**< Size of IP Header. */
#define uxIPHeaderSizeSocket( pxSocket ) ( ipSIZE_OF_IPv4_HEADER ) /**< Size of IP Header socket. */
/*
* Returns true if the socket must be checked. Non-active sockets are waiting
* for user action, either connect() or close().
*/
static BaseType_t prvTCPSocketIsActive( eIPTCPState_t xStatus );
/*
* Either sends a SYN or calls prvTCPSendRepeated (for regular messages).
*/
static int32_t prvTCPSendPacket( FreeRTOS_Socket_t * pxSocket );
/*
* Try to send a series of messages.
*/
static int32_t prvTCPSendRepeated( FreeRTOS_Socket_t * pxSocket,
NetworkBufferDescriptor_t ** ppxNetworkBuffer );
/*
* Return or send a packet to the other party.
*/
static void prvTCPReturnPacket( FreeRTOS_Socket_t * pxSocket,
NetworkBufferDescriptor_t * pxDescriptor,
uint32_t ulLen,
BaseType_t xReleaseAfterSend );
/*
* Initialise the data structures which keep track of the TCP windowing system.
*/
static void prvTCPCreateWindow( FreeRTOS_Socket_t * pxSocket );
/*
* Let ARP look-up the MAC-address of the peer and initialise the first SYN
* packet.
*/
static BaseType_t prvTCPPrepareConnect( FreeRTOS_Socket_t * pxSocket );
#if ( ipconfigHAS_DEBUG_PRINTF != 0 )
/*
* For logging and debugging: make a string showing the TCP flags.
*/
static const char * prvTCPFlagMeaning( UBaseType_t xFlags );
#endif /* ipconfigHAS_DEBUG_PRINTF != 0 */
/*
* Parse the TCP option(s) received, if present.
*/
_static void prvCheckOptions( FreeRTOS_Socket_t * pxSocket,
const NetworkBufferDescriptor_t * pxNetworkBuffer );
/*
* Identify and deal with a single TCP header option, advancing the pointer to
* the header. This function returns pdTRUE or pdFALSE depending on whether the
* caller should continue to parse more header options or break the loop.
*/
_static size_t prvSingleStepTCPHeaderOptions( const uint8_t * const pucPtr,
size_t uxTotalLength,
FreeRTOS_Socket_t * const pxSocket,
BaseType_t xHasSYNFlag );
#if ( ipconfigUSE_TCP_WIN == 1 )
/*
* Skip past TCP header options when doing Selective ACK, until there are no
* more options left.
*/
_static void prvReadSackOption( const uint8_t * const pucPtr,
size_t uxIndex,
FreeRTOS_Socket_t * const pxSocket );
#endif /* ( ipconfigUSE_TCP_WIN == 1 ) */
/*
* Set the initial properties in the options fields, like the preferred
* value of MSS and whether SACK allowed. Will be transmitted in the state
* 'eCONNECT_SYN'.
*/
static UBaseType_t prvSetSynAckOptions( FreeRTOS_Socket_t * pxSocket,
TCPHeader_t * pxTCPHeader );
/*
* For anti-hang protection and TCP keep-alive messages. Called in two places:
* after receiving a packet and after a state change. The socket's alive timer
* may be reset.
*/
static void prvTCPTouchSocket( FreeRTOS_Socket_t * pxSocket );
/*
* Prepare an outgoing message, if anything has to be sent.
*/
static int32_t prvTCPPrepareSend( FreeRTOS_Socket_t * pxSocket,
NetworkBufferDescriptor_t ** ppxNetworkBuffer,
UBaseType_t uxOptionsLength );
/*
* Calculate when this socket needs to be checked to do (re-)transmissions.
*/
static TickType_t prvTCPNextTimeout( FreeRTOS_Socket_t * pxSocket );
/*
* The API FreeRTOS_send() adds data to the TX stream. Add
* this data to the windowing system to it can be transmitted.
*/
static void prvTCPAddTxData( FreeRTOS_Socket_t * pxSocket );
/*
* Called to handle the closure of a TCP connection.
*/
static BaseType_t prvTCPHandleFin( FreeRTOS_Socket_t * pxSocket,
const NetworkBufferDescriptor_t * pxNetworkBuffer );
/*
* Called from prvTCPHandleState(). Find the TCP payload data and check and
* return its length.
*/
static BaseType_t prvCheckRxData( const NetworkBufferDescriptor_t * pxNetworkBuffer,
uint8_t ** ppucRecvData );
/*
* Called from prvTCPHandleState(). Check if the payload data may be accepted.
* If so, it will be added to the socket's reception queue.
*/
static BaseType_t prvStoreRxData( FreeRTOS_Socket_t * pxSocket,
const uint8_t * pucRecvData,
NetworkBufferDescriptor_t * pxNetworkBuffer,
uint32_t ulReceiveLength );
/*
* Set the TCP options (if any) for the outgoing packet.
*/
static UBaseType_t prvSetOptions( FreeRTOS_Socket_t * pxSocket,
const NetworkBufferDescriptor_t * pxNetworkBuffer );
/*
* Called from prvTCPHandleState() as long as the TCP status is eSYN_RECEIVED to
* eCONNECT_SYN.
*/
static BaseType_t prvHandleSynReceived( FreeRTOS_Socket_t * pxSocket,
const NetworkBufferDescriptor_t * pxNetworkBuffer,
uint32_t ulReceiveLength,
UBaseType_t uxOptionsLength );
/*
* Called from prvTCPHandleState() as long as the TCP status is eESTABLISHED.
*/
static BaseType_t prvHandleEstablished( FreeRTOS_Socket_t * pxSocket,
NetworkBufferDescriptor_t ** ppxNetworkBuffer,
uint32_t ulReceiveLength,
UBaseType_t uxOptionsLength );
/*
* Called from prvTCPHandleState(). There is data to be sent.
* If ipconfigUSE_TCP_WIN is defined, and if only an ACK must be sent, it will
* be checked if it would better be postponed for efficiency.
*/
static BaseType_t prvSendData( FreeRTOS_Socket_t * pxSocket,
NetworkBufferDescriptor_t ** ppxNetworkBuffer,
uint32_t ulReceiveLength,
BaseType_t xByteCount );
/*
* The heart of all: check incoming packet for valid data and acks and do what
* is necessary in each state.
*/
static BaseType_t prvTCPHandleState( FreeRTOS_Socket_t * pxSocket,
NetworkBufferDescriptor_t ** ppxNetworkBuffer );
/*
* Common code for sending a TCP protocol control packet (i.e. no options, no
* payload, just flags).
*/
static BaseType_t prvTCPSendSpecialPacketHelper( NetworkBufferDescriptor_t * pxNetworkBuffer,
uint8_t ucTCPFlags );
/*
* A "challenge ACK" is as per https://tools.ietf.org/html/rfc5961#section-3.2,
* case #3. In summary, an RST was received with a sequence number that is
* unexpected but still within the window.
*/
static BaseType_t prvTCPSendChallengeAck( NetworkBufferDescriptor_t * pxNetworkBuffer );
/*
* Reply to a peer with the RST flag on, in case a packet can not be handled.
*/
static BaseType_t prvTCPSendReset( NetworkBufferDescriptor_t * pxNetworkBuffer );
/*
* Set the initial value for MSS (Maximum Segment Size) to be used.
*/
static void prvSocketSetMSS( FreeRTOS_Socket_t * pxSocket );
/*
* Return either a newly created socket, or the current socket in a connected
* state (depends on the 'bReuseSocket' flag).
*/
static FreeRTOS_Socket_t * prvHandleListen( FreeRTOS_Socket_t * pxSocket,
NetworkBufferDescriptor_t * pxNetworkBuffer );
/*
* After a listening socket receives a new connection, it may duplicate itself.
* The copying takes place in prvTCPSocketCopy.
*/
static BaseType_t prvTCPSocketCopy( FreeRTOS_Socket_t * pxNewSocket,
FreeRTOS_Socket_t * pxSocket );
/*
* prvTCPStatusAgeCheck() will see if the socket has been in a non-connected
* state for too long. If so, the socket will be closed, and -1 will be
* returned.
*/
#if ( ipconfigTCP_HANG_PROTECTION == 1 )
static BaseType_t prvTCPStatusAgeCheck( FreeRTOS_Socket_t * pxSocket );
#endif
static NetworkBufferDescriptor_t * prvTCPBufferResize( const FreeRTOS_Socket_t * pxSocket,
NetworkBufferDescriptor_t * pxNetworkBuffer,
int32_t lDataLen,
UBaseType_t uxOptionsLength );
#if ( ipconfigUSE_TCP_WIN != 0 )
static uint8_t prvWinScaleFactor( const FreeRTOS_Socket_t * pxSocket );
#endif
/*-----------------------------------------------------------*/
/**
* @brief Check whether the socket is active or not.
*
* @param[in] xStatus: The status of the socket.
*
* @return pdTRUE if the socket must be checked. Non-active sockets
* are waiting for user action, either connect() or close().
*/
static BaseType_t prvTCPSocketIsActive( eIPTCPState_t xStatus )
{
BaseType_t xResult;
switch( xStatus )
{
case eCLOSED:
case eCLOSE_WAIT:
case eFIN_WAIT_2:
case eCLOSING:
case eTIME_WAIT:
xResult = pdFALSE;
break;
case eTCP_LISTEN:
case eCONNECT_SYN:
case eSYN_FIRST:
case eSYN_RECEIVED:
case eESTABLISHED:
case eFIN_WAIT_1:
case eLAST_ACK:
default:
xResult = pdTRUE;
break;
}
return xResult;
}
/*-----------------------------------------------------------*/
/** @brief Close the socket another time.
*
* @param[in] pxSocket: The socket to be checked.
*/
void vSocketCloseNextTime( FreeRTOS_Socket_t * pxSocket )
{
static FreeRTOS_Socket_t * xPreviousSocket = NULL;
if( ( xPreviousSocket != NULL ) && ( xPreviousSocket != pxSocket ) )
{
vSocketClose( xPreviousSocket );
}
xPreviousSocket = pxSocket;
}
/*-----------------------------------------------------------*/
#if ( ipconfigTCP_HANG_PROTECTION == 1 )
/**
* @brief Some of the TCP states may only last a certain amount of time.
* This function checks if the socket is 'hanging', i.e. staying
* too long in the same state.
*
* @param[in] The socket to be checked.
*
* @return pdFALSE if no checks are needed, pdTRUE if checks were done, or negative
* in case the socket has reached a critical time-out. The socket will go to
* the eCLOSE_WAIT state.
*/
static BaseType_t prvTCPStatusAgeCheck( FreeRTOS_Socket_t * pxSocket )
{
BaseType_t xResult;
eIPTCPState_t eState = ipNUMERIC_CAST( eIPTCPState_t, pxSocket->u.xTCP.ucTCPState );
switch( eState )
{
case eESTABLISHED:
/* If the 'ipconfigTCP_KEEP_ALIVE' option is enabled, sockets in
* state ESTABLISHED can be protected using keep-alive messages. */
xResult = pdFALSE;
break;
case eCLOSED:
case eTCP_LISTEN:
case eCLOSE_WAIT:
/* These 3 states may last for ever, up to the owner. */
xResult = pdFALSE;
break;
case eCONNECT_SYN:
case eSYN_FIRST:
case eSYN_RECEIVED:
case eFIN_WAIT_1:
case eFIN_WAIT_2:
case eCLOSING:
case eLAST_ACK:
case eTIME_WAIT:
default:
/* All other (non-connected) states will get anti-hanging
* protection. */
xResult = pdTRUE;
break;
}
if( xResult != pdFALSE )
{
/* How much time has past since the last active moment which is
* defined as A) a state change or B) a packet has arrived. */
TickType_t xAge = xTaskGetTickCount() - pxSocket->u.xTCP.xLastActTime;
/* ipconfigTCP_HANG_PROTECTION_TIME is in units of seconds. */
if( xAge > ( ( TickType_t ) ipconfigTCP_HANG_PROTECTION_TIME * ( TickType_t ) configTICK_RATE_HZ ) )
{
#if ( ipconfigHAS_DEBUG_PRINTF == 1 )
{
FreeRTOS_debug_printf( ( "Inactive socket closed: port %u rem %lxip:%u status %s\n",
pxSocket->usLocalPort,
pxSocket->u.xTCP.ulRemoteIP,
pxSocket->u.xTCP.usRemotePort,
FreeRTOS_GetTCPStateName( ( UBaseType_t ) pxSocket->u.xTCP.ucTCPState ) ) );
}
#endif /* ipconfigHAS_DEBUG_PRINTF */
/* Move to eCLOSE_WAIT, user may close the socket. */
vTCPStateChange( pxSocket, eCLOSE_WAIT );
/* When 'bPassQueued' true, this socket is an orphan until it
* gets connected. */
if( pxSocket->u.xTCP.bits.bPassQueued != pdFALSE_UNSIGNED )
{
/* vTCPStateChange() has called vSocketCloseNextTime()
* in case the socket is not yet owned by the application.
* Return a negative value to inform the caller that
* the socket will be closed in the next cycle. */
xResult = -1;
}
}
}
return xResult;
}
/*-----------------------------------------------------------*/
#endif /* if ( ipconfigTCP_HANG_PROTECTION == 1 ) */
/**
* @brief As soon as a TCP socket timer expires, this function will be called
* (from xTCPTimerCheck). It can send a delayed ACK or new data.
*
* @param[in] pxSocket: socket to be checked.
*
* @return 0 on success, a negative error code on failure. A negative value will be
* returned in case the hang-protection has put the socket in a wait-close state.
*
* @note Sequence of calling (normally) :
* IP-Task:
* xTCPTimerCheck() // Check all sockets ( declared in FreeRTOS_Sockets.c )
* xTCPSocketCheck() // Either send a delayed ACK or call prvTCPSendPacket()
* prvTCPSendPacket() // Either send a SYN or call prvTCPSendRepeated ( regular messages )
* prvTCPSendRepeated() // Send at most 8 messages on a row
* prvTCPReturnPacket() // Prepare for returning
* xNetworkInterfaceOutput() // Sends data to the NIC ( declared in portable/NetworkInterface/xxx )
*/
BaseType_t xTCPSocketCheck( FreeRTOS_Socket_t * pxSocket )
{
BaseType_t xResult = 0;
BaseType_t xReady = pdFALSE;
if( ( pxSocket->u.xTCP.ucTCPState >= ( uint8_t ) eESTABLISHED ) && ( pxSocket->u.xTCP.txStream != NULL ) )
{
/* The API FreeRTOS_send() might have added data to the TX stream. Add
* this data to the windowing system so it can be transmitted. */
prvTCPAddTxData( pxSocket );
}
#if ( ipconfigUSE_TCP_WIN == 1 )
{
if( pxSocket->u.xTCP.pxAckMessage != NULL )
{
/* The first task of this regular socket check is to send-out delayed
* ACK's. */
if( pxSocket->u.xTCP.bits.bUserShutdown == pdFALSE_UNSIGNED )
{
/* Earlier data was received but not yet acknowledged. This
* function is called when the TCP timer for the socket expires, the
* ACK may be sent now. */
if( pxSocket->u.xTCP.ucTCPState != ( uint8_t ) eCLOSED )
{
if( ( xTCPWindowLoggingLevel > 1 ) && ipconfigTCP_MAY_LOG_PORT( pxSocket->usLocalPort ) )
{
FreeRTOS_debug_printf( ( "Send[%u->%u] del ACK %lu SEQ %lu (len %u)\n",
pxSocket->usLocalPort,
pxSocket->u.xTCP.usRemotePort,
pxSocket->u.xTCP.xTCPWindow.rx.ulCurrentSequenceNumber - pxSocket->u.xTCP.xTCPWindow.rx.ulFirstSequenceNumber,
pxSocket->u.xTCP.xTCPWindow.ulOurSequenceNumber - pxSocket->u.xTCP.xTCPWindow.tx.ulFirstSequenceNumber,
( unsigned ) ipSIZE_OF_IPv4_HEADER + ipSIZE_OF_TCP_HEADER ) );
}
prvTCPReturnPacket( pxSocket, pxSocket->u.xTCP.pxAckMessage, ipSIZE_OF_IPv4_HEADER + ipSIZE_OF_TCP_HEADER, ipconfigZERO_COPY_TX_DRIVER );
#if ( ipconfigZERO_COPY_TX_DRIVER != 0 )
{
/* The ownership has been passed to the SEND routine,
* clear the pointer to it. */
pxSocket->u.xTCP.pxAckMessage = NULL;
}
#endif /* ipconfigZERO_COPY_TX_DRIVER */
}
if( prvTCPNextTimeout( pxSocket ) > 1U )
{
/* Tell the code below that this function is ready. */
xReady = pdTRUE;
}
}
else
{
/* The user wants to perform an active shutdown(), skip sending
* the delayed ACK. The function prvTCPSendPacket() will send the
* FIN along with the ACK's. */
}
if( pxSocket->u.xTCP.pxAckMessage != NULL )
{
vReleaseNetworkBufferAndDescriptor( pxSocket->u.xTCP.pxAckMessage );
pxSocket->u.xTCP.pxAckMessage = NULL;
}
}
}
#endif /* ipconfigUSE_TCP_WIN */
if( xReady == pdFALSE )
{
/* The second task of this regular socket check is sending out data. */
if( ( pxSocket->u.xTCP.ucTCPState >= ( uint8_t ) eESTABLISHED ) ||
( pxSocket->u.xTCP.ucTCPState == ( uint8_t ) eCONNECT_SYN ) )
{
( void ) prvTCPSendPacket( pxSocket );
}
/* Set the time-out for the next wakeup for this socket. */
( void ) prvTCPNextTimeout( pxSocket );
#if ( ipconfigTCP_HANG_PROTECTION == 1 )
{
/* In all (non-connected) states in which keep-alive messages can not be sent
* the anti-hang protocol will close sockets that are 'hanging'. */
xResult = prvTCPStatusAgeCheck( pxSocket );
}
#endif
}
return xResult;
}
/*-----------------------------------------------------------*/
/**
* @brief prvTCPSendPacket() will be called when the socket time-out has been reached.
*
* @param[in] pxSocket: The socket owning the connection.
*
* @return Number of bytes to be sent.
*
* @note It is only called by xTCPSocketCheck().
*/
static int32_t prvTCPSendPacket( FreeRTOS_Socket_t * pxSocket )
{
int32_t lResult = 0;
UBaseType_t uxOptionsLength, uxIntermediateResult = 0;
NetworkBufferDescriptor_t * pxNetworkBuffer;
if( pxSocket->u.xTCP.ucTCPState != ( uint8_t ) eCONNECT_SYN )
{
/* The connection is in a state other than SYN. */
pxNetworkBuffer = NULL;
/* prvTCPSendRepeated() will only create a network buffer if necessary,
* i.e. when data must be sent to the peer. */
lResult = prvTCPSendRepeated( pxSocket, &pxNetworkBuffer );
if( pxNetworkBuffer != NULL )
{
vReleaseNetworkBufferAndDescriptor( pxNetworkBuffer );
}
}
else
{
if( pxSocket->u.xTCP.ucRepCount >= 3U )
{
/* The connection is in the SYN status. The packet will be repeated
* to most 3 times. When there is no response, the socket get the
* status 'eCLOSE_WAIT'. */
FreeRTOS_debug_printf( ( "Connect: giving up %lxip:%u\n",
pxSocket->u.xTCP.ulRemoteIP, /* IP address of remote machine. */
pxSocket->u.xTCP.usRemotePort ) ); /* Port on remote machine. */
vTCPStateChange( pxSocket, eCLOSE_WAIT );
}
else if( ( pxSocket->u.xTCP.bits.bConnPrepared != pdFALSE_UNSIGNED ) || ( prvTCPPrepareConnect( pxSocket ) == pdTRUE ) )
{
ProtocolHeaders_t * pxProtocolHeaders;
const UBaseType_t uxHeaderSize = ipSIZE_OF_IPv4_HEADER;
/* Or else, if the connection has been prepared, or can be prepared
* now, proceed to send the packet with the SYN flag.
* prvTCPPrepareConnect() prepares 'xPacket' and returns pdTRUE if
* the Ethernet address of the peer or the gateway is found. */
pxProtocolHeaders = ipCAST_PTR_TO_TYPE_PTR( ProtocolHeaders_t, &( pxSocket->u.xTCP.xPacket.u.ucLastPacket[ ipSIZE_OF_ETH_HEADER + uxHeaderSize ] ) );
/* About to send a SYN packet. Call prvSetSynAckOptions() to set
* the proper options: The size of MSS and whether SACK's are
* allowed. */
uxOptionsLength = prvSetSynAckOptions( pxSocket, &( pxProtocolHeaders->xTCPHeader ) );
/* Return the number of bytes to be sent. */
uxIntermediateResult = uxIPHeaderSizeSocket( pxSocket ) + ipSIZE_OF_TCP_HEADER + uxOptionsLength;
lResult = ( int32_t ) uxIntermediateResult;
/* Set the TCP offset field: ipSIZE_OF_TCP_HEADER equals 20 and
* uxOptionsLength is always a multiple of 4. The complete expression
* would be:
* ucTCPOffset = ( ( ipSIZE_OF_TCP_HEADER + uxOptionsLength ) / 4 ) << 4 */
pxProtocolHeaders->xTCPHeader.ucTCPOffset = ( uint8_t ) ( ( ipSIZE_OF_TCP_HEADER + uxOptionsLength ) << 2 );
/* Repeat Count is used for a connecting socket, to limit the number
* of tries. */
pxSocket->u.xTCP.ucRepCount++;
/* Send the SYN message to make a connection. The messages is
* stored in the socket field 'xPacket'. It will be wrapped in a
* pseudo network buffer descriptor before it will be sent. */
prvTCPReturnPacket( pxSocket, NULL, ( uint32_t ) lResult, pdFALSE );
}
else
{
/* Nothing to do. */
}
}
/* Return the total number of bytes sent. */
return lResult;
}
/*-----------------------------------------------------------*/
/**
* @brief prvTCPSendRepeated will try to send a series of messages, as
* long as there is data to be sent and as long as the transmit
* window isn't full.
*
* @param[in] pxSocket: The socket owning the connection.
* @param[in,out] ppxNetworkBuffer: Pointer to pointer to the network buffer.
*
* @return Total number of bytes sent.
*/
static int32_t prvTCPSendRepeated( FreeRTOS_Socket_t * pxSocket,
NetworkBufferDescriptor_t ** ppxNetworkBuffer )
{
UBaseType_t uxIndex;
int32_t lResult = 0;
UBaseType_t uxOptionsLength = 0U;
int32_t xSendLength;
for( uxIndex = 0U; uxIndex < ( UBaseType_t ) SEND_REPEATED_COUNT; uxIndex++ )
{
/* prvTCPPrepareSend() might allocate a network buffer if there is data
* to be sent. */
xSendLength = prvTCPPrepareSend( pxSocket, ppxNetworkBuffer, uxOptionsLength );
if( xSendLength <= 0 )
{
break;
}
/* And return the packet to the peer. */
prvTCPReturnPacket( pxSocket, *ppxNetworkBuffer, ( uint32_t ) xSendLength, ipconfigZERO_COPY_TX_DRIVER );
#if ( ipconfigZERO_COPY_TX_DRIVER != 0 )
{
*ppxNetworkBuffer = NULL;
}
#endif /* ipconfigZERO_COPY_TX_DRIVER */
lResult += xSendLength;
}
/* Return the total number of bytes sent. */
return lResult;
}
/*-----------------------------------------------------------*/
/**
* @brief Return (or send) a packet to the peer. The data is stored in pxBuffer,
* which may either point to a real network buffer or to a TCP socket field
* called 'xTCP.xPacket'. A temporary xNetworkBuffer will be used to pass
* the data to the NIC.
*
* @param[in] pxSocket: The socket owning the connection.
* @param[in] pxDescriptor: The network buffer descriptor carrying the packet.
* @param[in] ulLen: Length of the packet being sent.
* @param[in] xReleaseAfterSend: pdTRUE if the ownership of the descriptor is
* transferred to the network interface.
*/
static void prvTCPReturnPacket( FreeRTOS_Socket_t * pxSocket,
NetworkBufferDescriptor_t * pxDescriptor,
uint32_t ulLen,
BaseType_t xReleaseAfterSend )
{
TCPPacket_t * pxTCPPacket;
IPHeader_t * pxIPHeader;
BaseType_t xDoRelease = xReleaseAfterSend;
EthernetHeader_t * pxEthernetHeader;
uint32_t ulFrontSpace, ulSpace, ulSourceAddress, ulWinSize;
const TCPWindow_t * pxTCPWindow;
NetworkBufferDescriptor_t * pxNetworkBuffer = pxDescriptor;
NetworkBufferDescriptor_t xTempBuffer;
/* memcpy() helper variables for MISRA Rule 21.15 compliance*/
const void * pvCopySource;
void * pvCopyDest;
/* For sending, a pseudo network buffer will be used, as explained above. */
if( pxNetworkBuffer == NULL )
{
pxNetworkBuffer = &xTempBuffer;
#if ( ipconfigUSE_LINKED_RX_MESSAGES != 0 )
{
pxNetworkBuffer->pxNextBuffer = NULL;
}
#endif
pxNetworkBuffer->pucEthernetBuffer = pxSocket->u.xTCP.xPacket.u.ucLastPacket;
pxNetworkBuffer->xDataLength = sizeof( pxSocket->u.xTCP.xPacket.u.ucLastPacket );
xDoRelease = pdFALSE;
}
#if ( ipconfigZERO_COPY_TX_DRIVER != 0 )
{
if( xDoRelease == pdFALSE )
{
pxNetworkBuffer = pxDuplicateNetworkBufferWithDescriptor( pxNetworkBuffer, ( size_t ) pxNetworkBuffer->xDataLength );
if( pxNetworkBuffer != NULL )
{
xDoRelease = pdTRUE;
}
else
{
FreeRTOS_debug_printf( ( "prvTCPReturnPacket: duplicate failed\n" ) );
}
}
}
#endif /* ipconfigZERO_COPY_TX_DRIVER */
#ifndef __COVERITY__
if( pxNetworkBuffer != NULL )
#endif
{
/* Map the ethernet buffer onto a TCPPacket_t struct for easy access to the fields. */
pxTCPPacket = ipCAST_PTR_TO_TYPE_PTR( TCPPacket_t, pxNetworkBuffer->pucEthernetBuffer );
pxIPHeader = &pxTCPPacket->xIPHeader;
pxEthernetHeader = &pxTCPPacket->xEthernetHeader;
/* Fill the packet, using hton translations. */
if( pxSocket != NULL )
{
/* Calculate the space in the RX buffer in order to advertise the
* size of this socket's reception window. */
pxTCPWindow = &( pxSocket->u.xTCP.xTCPWindow );
if( pxSocket->u.xTCP.rxStream != NULL )
{
/* An RX stream was created already, see how much space is
* available. */
ulFrontSpace = ( uint32_t ) uxStreamBufferFrontSpace( pxSocket->u.xTCP.rxStream );
}
else
{
/* No RX stream has been created, the full stream size is
* available. */
ulFrontSpace = ( uint32_t ) pxSocket->u.xTCP.uxRxStreamSize;
}
/* Take the minimum of the RX buffer space and the RX window size. */
ulSpace = FreeRTOS_min_uint32( pxTCPWindow->xSize.ulRxWindowLength, ulFrontSpace );
if( ( pxSocket->u.xTCP.bits.bLowWater != pdFALSE_UNSIGNED ) || ( pxSocket->u.xTCP.bits.bRxStopped != pdFALSE_UNSIGNED ) )
{
/* The low-water mark was reached, meaning there was little
* space left. The socket will wait until the application has read
* or flushed the incoming data, and 'zero-window' will be
* advertised. */
ulSpace = 0U;
}
/* If possible, advertise an RX window size of at least 1 MSS, otherwise
* the peer might start 'zero window probing', i.e. sending small packets
* (1, 2, 4, 8... bytes). */
if( ( ulSpace < pxSocket->u.xTCP.usCurMSS ) && ( ulFrontSpace >= pxSocket->u.xTCP.usCurMSS ) )
{
ulSpace = pxSocket->u.xTCP.usCurMSS;
}
/* Avoid overflow of the 16-bit win field. */
#if ( ipconfigUSE_TCP_WIN != 0 )
{
ulWinSize = ( ulSpace >> pxSocket->u.xTCP.ucMyWinScaleFactor );
}
#else
{
ulWinSize = ulSpace;
}
#endif
if( ulWinSize > 0xfffcUL )
{
ulWinSize = 0xfffcUL;
}
pxTCPPacket->xTCPHeader.usWindow = FreeRTOS_htons( ( uint16_t ) ulWinSize );
/* The new window size has been advertised, switch off the flag. */
pxSocket->u.xTCP.bits.bWinChange = pdFALSE_UNSIGNED;
/* Later on, when deciding to delay an ACK, a precise estimate is needed
* of the free RX space. At this moment, 'ulHighestRxAllowed' would be the
* highest sequence number minus 1 that the socket will accept. */
pxSocket->u.xTCP.ulHighestRxAllowed = pxTCPWindow->rx.ulCurrentSequenceNumber + ulSpace;
#if ( ipconfigTCP_KEEP_ALIVE == 1 )
if( pxSocket->u.xTCP.bits.bSendKeepAlive != pdFALSE_UNSIGNED )
{
/* Sending a keep-alive packet, send the current sequence number
* minus 1, which will be recognised as a keep-alive packet and
* responded to by acknowledging the last byte. */
pxSocket->u.xTCP.bits.bSendKeepAlive = pdFALSE_UNSIGNED;
pxSocket->u.xTCP.bits.bWaitKeepAlive = pdTRUE_UNSIGNED;
pxTCPPacket->xTCPHeader.ulSequenceNumber = pxSocket->u.xTCP.xTCPWindow.ulOurSequenceNumber - 1UL;
pxTCPPacket->xTCPHeader.ulSequenceNumber = FreeRTOS_htonl( pxTCPPacket->xTCPHeader.ulSequenceNumber );
}
else
#endif /* if ( ipconfigTCP_KEEP_ALIVE == 1 ) */
{
pxTCPPacket->xTCPHeader.ulSequenceNumber = FreeRTOS_htonl( pxSocket->u.xTCP.xTCPWindow.ulOurSequenceNumber );
if( ( pxTCPPacket->xTCPHeader.ucTCPFlags & ( uint8_t ) tcpTCP_FLAG_FIN ) != 0U )
{
/* Suppress FIN in case this packet carries earlier data to be
* retransmitted. */
uint32_t ulDataLen = ( uint32_t ) ( ulLen - ( ipSIZE_OF_TCP_HEADER + ipSIZE_OF_IPv4_HEADER ) );
if( ( pxTCPWindow->ulOurSequenceNumber + ulDataLen ) != pxTCPWindow->tx.ulFINSequenceNumber )
{
pxTCPPacket->xTCPHeader.ucTCPFlags &= ( ( uint8_t ) ~tcpTCP_FLAG_FIN );
FreeRTOS_debug_printf( ( "Suppress FIN for %lu + %lu < %lu\n",
pxTCPWindow->ulOurSequenceNumber - pxTCPWindow->tx.ulFirstSequenceNumber,
ulDataLen,
pxTCPWindow->tx.ulFINSequenceNumber - pxTCPWindow->tx.ulFirstSequenceNumber ) );
}
}
}
/* Tell which sequence number is expected next time */
pxTCPPacket->xTCPHeader.ulAckNr = FreeRTOS_htonl( pxTCPWindow->rx.ulCurrentSequenceNumber );
}
else
{
/* Sending data without a socket, probably replying with a RST flag
* Just swap the two sequence numbers. */
vFlip_32( pxTCPPacket->xTCPHeader.ulSequenceNumber, pxTCPPacket->xTCPHeader.ulAckNr );
}
pxIPHeader->ucTimeToLive = ( uint8_t ) ipconfigTCP_TIME_TO_LIVE;
pxIPHeader->usLength = FreeRTOS_htons( ulLen );
if( ( pxSocket == NULL ) || ( *ipLOCAL_IP_ADDRESS_POINTER == 0UL ) )
{
/* When pxSocket is NULL, this function is called by prvTCPSendReset()
* and the IP-addresses must be swapped.
* Also swap the IP-addresses in case the IP-tack doesn't have an
* IP-address yet, i.e. when ( *ipLOCAL_IP_ADDRESS_POINTER == 0UL ). */
ulSourceAddress = pxIPHeader->ulDestinationIPAddress;
}
else
{
ulSourceAddress = *ipLOCAL_IP_ADDRESS_POINTER;
}
pxIPHeader->ulDestinationIPAddress = pxIPHeader->ulSourceIPAddress;
pxIPHeader->ulSourceIPAddress = ulSourceAddress;
vFlip_16( pxTCPPacket->xTCPHeader.usSourcePort, pxTCPPacket->xTCPHeader.usDestinationPort );
/* Just an increasing number. */
pxIPHeader->usIdentification = FreeRTOS_htons( usPacketIdentifier );
usPacketIdentifier++;
/* The stack doesn't support fragments, so the fragment offset field must always be zero.
* The header was never memset to zero, so set both the fragment offset and fragmentation flags in one go.
*/
#if ( ipconfigFORCE_IP_DONT_FRAGMENT != 0 )
pxIPHeader->usFragmentOffset = ipFRAGMENT_FLAGS_DONT_FRAGMENT;
#else
pxIPHeader->usFragmentOffset = 0U;
#endif
/* Important: tell NIC driver how many bytes must be sent. */
pxNetworkBuffer->xDataLength = ulLen + ipSIZE_OF_ETH_HEADER;
#if ( ipconfigDRIVER_INCLUDED_TX_IP_CHECKSUM == 0 )
{
/* calculate the IP header checksum, in case the driver won't do that. */
pxIPHeader->usHeaderChecksum = 0x00U;