-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFreeRTOS_TCP_IP.c
3140 lines (2760 loc) · 110 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 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
*
*/
/*
* FreeRTOS_TCP_IP.c
* 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_TCP_IP.h"
#include "FreeRTOS_DHCP.h"
#include "NetworkInterface.h"
#include "NetworkBufferManagement.h"
#include "FreeRTOS_ARP.h"
#include "FreeRTOS_TCP_WIN.h"
/* Just make sure the contents doesn't get compiled if TCP is not enabled. */
#if ipconfigUSE_TCP == 1
/*
* The meaning of the TCP flags:
*/
#define ipTCP_FLAG_FIN 0x0001 /* No more data from sender */
#define ipTCP_FLAG_SYN 0x0002 /* Synchronize sequence numbers */
#define ipTCP_FLAG_RST 0x0004 /* Reset the connection */
#define ipTCP_FLAG_PSH 0x0008 /* Push function: please push buffered data to the recv application */
#define ipTCP_FLAG_ACK 0x0010 /* Acknowledgment field is significant */
#define ipTCP_FLAG_URG 0x0020 /* Urgent pointer field is significant */
#define ipTCP_FLAG_ECN 0x0040 /* ECN-Echo */
#define ipTCP_FLAG_CWR 0x0080 /* Congestion Window Reduced */
#define ipTCP_FLAG_NS 0x0100 /* ECN-nonce concealment protection */
#define ipTCP_FLAG_RSV 0x0E00 /* Reserved, keep 0 */
/* A mask to filter all protocol flags. */
#define ipTCP_FLAG_CTRL 0x001f
/*
* A few values of the TCP options:
*/
#define TCP_OPT_END 0 /* End of TCP options list */
#define TCP_OPT_NOOP 1 /* "No-operation" TCP option */
#define TCP_OPT_MSS 2 /* Maximum segment size TCP option */
#define TCP_OPT_WSOPT 3 /* TCP Window Scale Option (3-byte long) */
#define TCP_OPT_SACK_P 4 /* Advertize that SACK is permitted */
#define TCP_OPT_SACK_A 5 /* SACK option with first/last */
#define TCP_OPT_TIMESTAMP 8 /* Time-stamp option */
#define TCP_OPT_MSS_LEN 4 /* Length of TCP MSS option. */
#define TCP_OPT_TIMESTAMP_LEN 10 /* fixed length of the time-stamp option */
/*
* The macro NOW_CONNECTED() is use to determine if the connection makes a
* transition from connected to non-connected and vice versa.
* NOW_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 NOW_CONNECTED( status )\
( ( status >= eESTABLISHED ) && ( status != eCLOSE_WAIT ) )
/*
* The highest 4 bits in the TCP offset byte indicate the total length of the
* TCP header, divided by 4.
*/
#define VALID_BITS_IN_TCP_OFFSET_BYTE ( 0xF0 )
/*
* 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 DELAYED_ACK_SHORT_DELAY_MS ( 2 )
#define DELAYED_ACK_LONGER_DELAY_MS ( 20 )
/*
* 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 REDUCED_MSS_THROUGH_INTERNET ( 1400 )
/*
* Each time a new TCP connection is being made, a new Initial Sequence Number shall be used.
* The variable 'ulNextInitialSequenceNumber' will be incremented with a recommended value
* of 0x102.
*/
#define INITIAL_SEQUENCE_NUMBER_INCREMENT ( 0x102UL )
/*
* When there are no TCP options, the TCP offset equals 20 bytes, which is stored as
* the number 5 (words) in the higher niblle of the TCP-offset byte.
*/
#define TCP_OFFSET_LENGTH_BITS ( 0xf0 )
#define TCP_OFFSET_STANDARD_LENGTH ( 0x50 )
/*
* 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 ) */
/*
* The names of the different TCP states may be useful in logging.
*/
#if( ( ipconfigHAS_DEBUG_PRINTF != 0 ) || ( ipconfigHAS_PRINTF != 0 ) )
static const char *pcStateNames[] = {
"eCLOSED",
"eTCP_LISTEN",
"eCONNECT_SYN",
"eSYN_FIRST",
"eSYN_RECEIVED",
"eESTABLISHED",
"eFIN_WAIT_1",
"eFIN_WAIT_2",
"eCLOSE_WAIT",
"eCLOSING",
"eLAST_ACK",
"eTIME_WAIT",
"eUNKNOWN",
};
#endif /* ( ipconfigHAS_DEBUG_PRINTF != 0 ) || ( ipconfigHAS_PRINTF != 0 ) */
/*
* Returns true if the socket must be checked. Non-active sockets are waiting
* for user action, either connect() or close().
*/
static BaseType_t prvTCPSocketIsActive( BaseType_t lStatus );
/*
* Either sends a SYN or calls prvTCPSendRepeated (for regular messages).
*/
static int prvTCPSendPacket( xFreeRTOS_Socket_t *pxSocket );
/*
* Try to send a series of messages.
*/
static BaseType_t prvTCPSendRepeated( xFreeRTOS_Socket_t *pxSocket, xNetworkBufferDescriptor_t **ppxNetworkBuffer );
/*
* Return or send a packet to the other party.
*/
static void prvTCPReturnPacket( xFreeRTOS_Socket_t *pxSocket, xNetworkBufferDescriptor_t *pxNetworkBuffer,
uint32_t ulLen, BaseType_t xReleaseAfterSend );
/*
* Initialise the data structures which keep track of the TCP windowing system.
*/
static void prvTCPCreateWindow( xFreeRTOS_Socket_t *pxSocket );
/*
* Let ARP look-up the MAC-address of the peer and initialise the first SYN
* packet.
*/
static BaseType_t prvTCPPrepareConnect( xFreeRTOS_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( xFreeRTOS_Socket_t *pxSocket, xNetworkBufferDescriptor_t *pxNetworkBuffer );
/*
* 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 BaseType_t prvSetSynAckOptions( xFreeRTOS_Socket_t *pxSocket, xTCPPacket_t * pxTCPPacket );
/*
* 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( xFreeRTOS_Socket_t *pxSocket );
/*
* Prepare an outgoing message, if anything has to be sent.
*/
static int32_t prvTCPPrepareSend( xFreeRTOS_Socket_t *pxSocket, xNetworkBufferDescriptor_t **ppxNetworkBuffer, BaseType_t uxOptionsLength );
/*
* Calculate when this socket needs to be checked to do (re-)transmissions.
*/
static TickType_t prvTCPNextTimeout( xFreeRTOS_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( xFreeRTOS_Socket_t *pxSocket );
/*
* Called to handle the closure of a TCP connection.
*/
static BaseType_t prvTCPHandleFin( xFreeRTOS_Socket_t *pxSocket, xNetworkBufferDescriptor_t *pxNetworkBuffer );
#if( ipconfigUSE_TCP_TIMESTAMPS == 1 )
static BaseType_t prvTCPSetTimeStamp( BaseType_t lOffset, xFreeRTOS_Socket_t *pxSocket, xTCPHeader_t *pxTCPHeader );
#endif
/*
* Called from prvTCPHandleState(). Find the TCP payload data and check and
* return its length.
*/
static BaseType_t prvCheckRxData( xNetworkBufferDescriptor_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( xFreeRTOS_Socket_t *pxSocket, uint8_t *pucRecvData,
xNetworkBufferDescriptor_t *pxNetworkBuffer, uint32_t ulReceiveLength );
/*
* Set the TCP options (if any) for the outgoing packet.
*/
static BaseType_t prvSetOptions( xFreeRTOS_Socket_t *pxSocket, xNetworkBufferDescriptor_t *pxNetworkBuffer );
/*
* Called from prvTCPHandleState() as long as the TCP status is eSYN_RECEIVED to
* eCONNECT_SYN.
*/
static BaseType_t prvHandleSynReceived( xFreeRTOS_Socket_t *pxSocket, xNetworkBufferDescriptor_t **ppxNetworkBuffer,
uint32_t ulReceiveLength, BaseType_t xOptionsLength );
/*
* Called from prvTCPHandleState() as long as the TCP status is eESTABLISHED.
*/
static BaseType_t prvHandleEstablished( xFreeRTOS_Socket_t *pxSocket, xNetworkBufferDescriptor_t **ppxNetworkBuffer,
uint32_t ulReceiveLength, BaseType_t xOptionsLength );
/*
* 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( xFreeRTOS_Socket_t *pxSocket, xNetworkBufferDescriptor_t **ppxNetworkBuffer,
uint32_t ulReceiveLength, BaseType_t xSendLength );
/*
* The heart of all: check incoming packet for valid data and acks and do what
* is necessary in each state.
*/
static BaseType_t prvTCPHandleState( xFreeRTOS_Socket_t *pxSocket, xNetworkBufferDescriptor_t **ppxNetworkBuffer );
/*
* Reply to a peer with the RST flag on, in case a packet can not be handled.
*/
static BaseType_t prvTCPSendReset( xNetworkBufferDescriptor_t *pxNetworkBuffer );
/*
* Set the initial value for MSS (Maximum Segment Size) to be used.
*/
static void prvSocketSetMSS( xFreeRTOS_Socket_t *pxSocket );
/*
* Return either a newly created socket, or the current socket in a connected
* state (depends on the 'bReuseSocket' flag).
*/
static xFreeRTOS_Socket_t *prvHandleListen( xFreeRTOS_Socket_t *pxSocket, xNetworkBufferDescriptor_t *pxNetworkBuffer );
/*
* After a listening socket receives a new connection, it may duplicate itself.
* The copying takes place in prvTCPSocketCopy.
*/
static BaseType_t prvTCPSocketCopy( xFreeRTOS_Socket_t *pxNewSocket, xFreeRTOS_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( xFreeRTOS_Socket_t *pxSocket );
#endif
/*-----------------------------------------------------------*/
/* Initial Sequence Number, i.e. the next initial sequence number that will be
used when a new connection is opened. The value should be randomized to prevent
attacks from outside (spoofing). */
uint32_t ulNextInitialSequenceNumber = 0;
/*-----------------------------------------------------------*/
/* prvTCPSocketIsActive() returns true if the socket must be checked.
* Non-active sockets are waiting for user action, either connect()
* or close(). */
static BaseType_t prvTCPSocketIsActive( BaseType_t lStatus )
{
switch( lStatus )
{
case eCLOSED:
case eCLOSE_WAIT:
case eFIN_WAIT_2:
case eCLOSING:
case eTIME_WAIT:
return pdFALSE;
default:
return pdTRUE;
}
}
/*-----------------------------------------------------------*/
#if( ipconfigTCP_HANG_PROTECTION == 1 )
static BaseType_t prvTCPStatusAgeCheck( xFreeRTOS_Socket_t *pxSocket )
{
BaseType_t xResult;
switch( pxSocket->u.xTcp.ucTcpState )
{
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;
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 > ( ipconfigTCP_HANG_PROTECTION_TIME * configTICK_RATE_HZ ) )
{
#if( ipconfigHAS_DEBUG_PRINTF == 1 )
{
FreeRTOS_debug_printf( ( "Inactive socket closed: port %u rem %lxip:%u status %s\n",
pxSocket->usLocPort,
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 )
{
if( pxSocket->u.xTcp.bits.bReuseSocket == pdFALSE )
{
/* As it did not get connected, and the user can never
accept() it anymore, it will be deleted now. Called from
the IP-task, so it's safe to call the internal Close
function: vSocketClose(). */
vSocketClose( pxSocket );
}
/* Return a negative value to tell to inform the caller
xTCPTimerCheck()
that the socket got closed and may not be accessed anymore. */
xResult = -1;
}
}
}
return xResult;
}
/*-----------------------------------------------------------*/
#endif
/*
* As soon as a TCP socket timer expires, this function xTCPSocketCheck
* will be called (from xTCPTimerCheck)
* It can send a delayed ACK or new data
* 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( xFreeRTOS_Socket_t *pxSocket )
{
BaseType_t xResult = 0;
BaseType_t xReady = pdFALSE;
if( ( pxSocket->u.xTcp.ucTcpState >= 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 to 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 == 0 )
{
/* 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 != eCLOSED )
{
if( xTCPWindowLoggingLevel > 1 && ipconfigTCP_MAY_LOG_PORT( pxSocket->usLocPort ) )
{
FreeRTOS_debug_printf( ( "Send[%u->%u] del ACK %lu SEQ %lu (len %u)\n",
pxSocket->usLocPort,
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,
ipSIZE_OF_IP_HEADER + ipSIZE_OF_TCP_HEADER ) );
}
prvTCPReturnPacket( pxSocket, pxSocket->u.xTcp.pxAckMessage, ipSIZE_OF_IP_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 ) > 1 )
{
/* 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 >= eESTABLISHED ) ||
( pxSocket->u.xTcp.ucTcpState == eCONNECT_SYN ) )
{
prvTCPSendPacket( pxSocket );
}
/* Set the time-out for the next wakeup for this socket. */
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;
}
/*-----------------------------------------------------------*/
/*
* prvTCPSendPacket() will be called when the socket time-out has been reached.
* It is only called by xTCPSocketCheck().
*/
static int prvTCPSendPacket( xFreeRTOS_Socket_t *pxSocket )
{
BaseType_t lResult = 0;
BaseType_t xOptionsLength;
xTCPPacket_t *pxTCPPacket;
xNetworkBufferDescriptor_t *pxNetworkBuffer;
if( pxSocket->u.xTcp.ucTcpState != eCONNECT_SYN )
{
/* The connection is in s 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 >= 3 )
{
/* 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 ) || ( prvTCPPrepareConnect( pxSocket ) == pdTRUE ) )
{
/* Or else, if the connection has been prepared, or can be prepared
now, proceed to send the packet with the SYN flag.
prvTCPPrepareConnect() prepares 'lastPacket' and returns pdTRUE if
the Ethernet address of the peer or the gateway is found. */
pxTCPPacket = ( xTCPPacket_t * )pxSocket->u.xTcp.lastPacket;
#if( ipconfigUSE_TCP_TIMESTAMPS == 1 )
{
/* When TCP time stamps are enabled, but they will only be applied
if the peer is outside the netmask, usually on the internet.
Packages sent on a LAN are usually too big to carry time stamps. */
if( ( ( pxSocket->u.xTcp.ulRemoteIP ^ FreeRTOS_ntohl( *ipLOCAL_IP_ADDRESS_POINTER ) ) & xNetworkAddressing.ulNetMask ) != 0ul )
{
pxSocket->u.xTcp.xTcpWindow.u.bits.bTimeStamps = 1;
}
}
#endif
/* About to send a SYN packet. Call prvSetSynAckOptions() to set
the proper options: The size of MSS and whether SACK's are
allowed. */
xOptionsLength = prvSetSynAckOptions( pxSocket, pxTCPPacket );
/* Return the number of bytes to be sent. */
lResult = ipSIZE_OF_IP_HEADER + ipSIZE_OF_TCP_HEADER + xOptionsLength;
/* Set the TCP offset field: ipSIZE_OF_TCP_HEADER equals 20 and
xOptionsLength is always a multiple of 4. The complete expression
would be:
ucTcpOffset = ( ( ipSIZE_OF_TCP_HEADER + xOptionsLength ) / 4 ) << 4 */
pxTCPPacket->xTCPHeader.ucTcpOffset = ( uint8_t )( ( ipSIZE_OF_TCP_HEADER + xOptionsLength ) << 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 'lastPacket'. It will be wrapped in a
pseudo network buffer descriptor before it will be sent. */
prvTCPReturnPacket( pxSocket, NULL, ( uint32_t ) lResult, pdFALSE );
}
}
/* Return the total number of bytes sent. */
return lResult;
}
/*-----------------------------------------------------------*/
/*
* 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.
*/
static BaseType_t prvTCPSendRepeated( xFreeRTOS_Socket_t *pxSocket, xNetworkBufferDescriptor_t **ppxNetworkBuffer )
{
BaseType_t lIndex;
BaseType_t lResult = 0;
BaseType_t xOptionsLength = 0;
BaseType_t xSendLength;
/* While sending data, uxGetRxEventCount() will be called to see if the NIC
has received any new message. If so, sending will stop immediately to give
priority to receiving new packets. */
for( lIndex = 0; ( lIndex < SEND_REPEATED_COUNT ) && ( uxGetRxEventCount() == 0 ); lIndex++ )
{
/* prvTCPPrepareSend() might allocate a network buffer if there is data
to be sent. */
xSendLength = prvTCPPrepareSend( pxSocket, ppxNetworkBuffer, xOptionsLength );
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;
}
/*-----------------------------------------------------------*/
/*
* Return (or send) a packet the 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.lastPacket'. A temporary xNetworkBuffer will be used to pass
* the data to the NIC.
*/
static void prvTCPReturnPacket( xFreeRTOS_Socket_t *pxSocket, xNetworkBufferDescriptor_t *pxNetworkBuffer, uint32_t ulLen, BaseType_t xReleaseAfterSend )
{
xTCPPacket_t * pxTCPPacket;
xIPHeader_t *pxIPHeader;
xEthernetHeader_t *pxEthernetHeader;
uint32_t ulFrontSpace, ulSpace;
TCPWindow_t *pxTcpWindow;
xNetworkBufferDescriptor_t xTempBuffer;
/* For sending, a pseudo network buffer will be used, as explained above. */
if( pxNetworkBuffer == NULL )
{
pxNetworkBuffer = &xTempBuffer;
#if( ipconfigUSE_LINKED_RX_MESSAGES != 0 )
{
xTempBuffer.pxNextBuffer = NULL;
}
#endif
xTempBuffer.pucEthernetBuffer = pxSocket->u.xTcp.lastPacket;
xTempBuffer.xDataLength = sizeof pxSocket->u.xTcp.lastPacket;
xReleaseAfterSend = pdFALSE;
}
#if( ipconfigZERO_COPY_TX_DRIVER != 0 )
{
if( xReleaseAfterSend == pdFALSE )
{
pxNetworkBuffer = pxDuplicateNetworkBufferWithDescriptor( pxNetworkBuffer, pxNetworkBuffer->xDataLength );
if( pxNetworkBuffer == NULL )
{
FreeRTOS_debug_printf( ( "prvTCPReturnPacket: duplicate failed\n" ) );
}
xReleaseAfterSend = pdTRUE;
}
}
#endif /* ipconfigZERO_COPY_TX_DRIVER */
if( pxNetworkBuffer != NULL )
{
pxTCPPacket = ( xTCPPacket_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 ) lStreamBufferFrontSpace( pxSocket->u.xTcp.rxStream );
}
else
{
/* No RX stream has been created, the full stream size is
available. */
ulFrontSpace = ( uint32_t ) pxSocket->u.xTcp.rxStreamSize;
}
/* Take the minimum of the RX buffer space and the RX window size. */
ulSpace = FreeRTOS_min_uint32( pxSocket->u.xTcp.ulRxCurWinSize, pxTcpWindow->xSize.ulRxWindowLength );
if( ( pxSocket->u.xTcp.bits.bLowWater != 0 ) || ( pxSocket->u.xTcp.bits.bRxStopped != 0 ) )
{
/* 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 = 0;
}
/* 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( ulSpace > 0xfffcUL )
{
ulSpace = 0xfffcUL;
}
pxTCPPacket->xTCPHeader.usWindow = FreeRTOS_htons( ( uint16_t ) ulSpace );
#if( ipconfigHAS_DEBUG_PRINTF != 0 )
{
if( ipconfigTCP_MAY_LOG_PORT( pxSocket->usLocPort ) != pdFALSE )
{
if( ( xTCPWindowLoggingLevel != 0 ) && ( pxSocket->u.xTcp.bits.bWinChange != pdFALSE ) )
{
int32_t lFrontSpace = pxSocket->u.xTcp.rxStream ? lStreamBufferFrontSpace( pxSocket->u.xTcp.rxStream ) : 0;
FreeRTOS_debug_printf( ( "%s: %lxip:%u: [%lu < %lu] winSize %ld\n",
pxSocket->u.xTcp.bits.bLowWater ? "STOP" : "GO ",
pxSocket->u.xTcp.ulRemoteIP,
pxSocket->u.xTcp.usRemotePort,
pxSocket->u.xTcp.bits.bLowWater ? pxSocket->u.xTcp.lLittleSpace : lFrontSpace, pxSocket->u.xTcp.lEnoughSpace,
(int32_t) ( pxTcpWindow->rx.ulHighestSequenceNumber - pxTcpWindow->rx.ulCurrentSequenceNumber ) ) );
}
}
}
#endif /* ipconfigHAS_DEBUG_PRINTF != 0 */
/* The new window size has been advertised, switch off the flag. */
pxSocket->u.xTcp.bits.bWinChange = pdFALSE;
/* 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 != 0 )
{
/* Sending a keep-alive packet, send the current sequence number
minus 1, which will be recognised as a keep-alive packet an
responded to by acknowledging the last byte. */
pxSocket->u.xTcp.bits.bSendKeepAlive = pdFALSE;
pxSocket->u.xTcp.bits.bWaitKeepAlive = pdTRUE;
pxTCPPacket->xTCPHeader.ulSequenceNumber = pxSocket->u.xTcp.xTcpWindow.ulOurSequenceNumber - 1;
pxTCPPacket->xTCPHeader.ulSequenceNumber = FreeRTOS_htonl( pxTCPPacket->xTCPHeader.ulSequenceNumber );
}
else
#endif
{
pxTCPPacket->xTCPHeader.ulSequenceNumber = FreeRTOS_htonl( pxSocket->u.xTcp.xTcpWindow.ulOurSequenceNumber );
if( ( pxTCPPacket->xTCPHeader.ucTcpFlags & ipTCP_FLAG_FIN ) != 0 )
{
/* Suppress FIN in case this packet carries earlier data to be
retransmitted. */
uint32_t ulDataLen = ( uint32_t ) ( ulLen - ( ipSIZE_OF_TCP_HEADER + ipSIZE_OF_IP_HEADER ) );
if( ( pxTcpWindow->ulOurSequenceNumber + ulDataLen ) != pxTcpWindow->tx.ulFINSequenceNumber )
{
pxTCPPacket->xTCPHeader.ucTcpFlags &= ( ( uint8_t ) ~ipTCP_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 = ipconfigTCP_TIME_TO_LIVE;
pxIPHeader->usLength = FreeRTOS_htons( ulLen );
pxIPHeader->ulDestinationIPAddress = pxIPHeader->ulSourceIPAddress;
pxIPHeader->ulSourceIPAddress = *ipLOCAL_IP_ADDRESS_POINTER;
vFlip_16( pxTCPPacket->xTCPHeader.usSourcePort, pxTCPPacket->xTCPHeader.usDestinationPort );
/* Just an increasing number. */
pxIPHeader->usIdentification = FreeRTOS_htons( usPacketIdentifier );
usPacketIdentifier++;
pxIPHeader->usFragmentOffset = 0;
#if( ipconfigDRIVER_INCLUDED_TX_IP_CHECKSUM == 0 )
{
/* calculate the IP header checksum, in case the driver won't do that. */
pxIPHeader->usHeaderChecksum = 0x00;
pxIPHeader->usHeaderChecksum = usGenerateChecksum( 0UL, ( uint8_t * ) &( pxIPHeader->ucVersionHeaderLength ), ipSIZE_OF_IP_HEADER );
pxIPHeader->usHeaderChecksum = ~FreeRTOS_htons( pxIPHeader->usHeaderChecksum );
/* calculate the TCP checksum for an outgoing packet. */
usGenerateProtocolChecksum( (uint8_t*)pxTCPPacket, pdTRUE );
/* A calculated checksum of 0 must be inverted as 0 means the checksum
is disabled. */
if( pxTCPPacket->xTCPHeader.usChecksum == 0x00 )
{
pxTCPPacket->xTCPHeader.usChecksum = 0xffffU;
}
}
#endif
#if( ipconfigUSE_LINKED_RX_MESSAGES != 0 )
pxNetworkBuffer->pxNextBuffer = NULL;
#endif
/* Important: tell NIC driver how many bytes must be sent. */
pxNetworkBuffer->xDataLength = ulLen + ipSIZE_OF_ETH_HEADER;
/* Fill in the destination MAC addresses. */
memcpy( ( void * ) &( pxEthernetHeader->xDestinationAddress ), ( void * ) &( pxEthernetHeader->xSourceAddress ),
sizeof( pxEthernetHeader->xDestinationAddress ) );
/* The source MAC addresses is fixed to 'ipLOCAL_MAC_ADDRESS'. */
memcpy( ( void * ) &( pxEthernetHeader->xSourceAddress) , ( void * ) ipLOCAL_MAC_ADDRESS, ( size_t ) ipMAC_ADDRESS_LENGTH_BYTES );
/* Send! */
xNetworkInterfaceOutput( pxNetworkBuffer, xReleaseAfterSend );
if( xReleaseAfterSend == pdFALSE )
{
/* Swap-back some fields, as pxBuffer probably points to a socket field
containing the packet header. */
vFlip_16( pxTCPPacket->xTCPHeader.usSourcePort, pxTCPPacket->xTCPHeader.usDestinationPort);
pxTCPPacket->xIPHeader.ulSourceIPAddress = pxTCPPacket->xIPHeader.ulDestinationIPAddress;
memcpy( pxEthernetHeader->xSourceAddress.ucBytes, pxEthernetHeader->xDestinationAddress.ucBytes, 6);
}
else
{
/* Nothing to do: the buffer has been passed to DMA and will be released after use */
}
}
}
/*-----------------------------------------------------------*/
/*
* The SYN event is very important: the sequence numbers, which have a kind of
* random starting value, are being synchronised. The sliding window manager
* (in FreeRTOS_TCP_WIN.c) needs to know them, along with the Maximum Segment
* Size (MSS) in use.
*/
static void prvTCPCreateWindow( xFreeRTOS_Socket_t *pxSocket )
{
if( xTCPWindowLoggingLevel )
FreeRTOS_debug_printf( ( "Limits (using): TCP Win size %lu Water %lu <= %lu <= %lu\n",
pxSocket->u.xTcp.ulRxWinSize * ipconfigTCP_MSS,
pxSocket->u.xTcp.lLittleSpace ,
pxSocket->u.xTcp.lEnoughSpace,
pxSocket->u.xTcp.rxStreamSize ) );
vTCPWindowCreate(
&pxSocket->u.xTcp.xTcpWindow,
ipconfigTCP_MSS * pxSocket->u.xTcp.ulRxWinSize,
ipconfigTCP_MSS * pxSocket->u.xTcp.ulTxWinSize,
pxSocket->u.xTcp.xTcpWindow.rx.ulCurrentSequenceNumber,
pxSocket->u.xTcp.xTcpWindow.ulOurSequenceNumber,
pxSocket->u.xTcp.usInitMSS);
}
/*-----------------------------------------------------------*/
/*
* Connecting sockets have a special state: eCONNECT_SYN. In this phase,
* the Ethernet address of the target will be found using ARP. In case the
* target IP address is not within the netmask, the hardware address of the
* gateway will be used.
*/
static BaseType_t prvTCPPrepareConnect( xFreeRTOS_Socket_t *pxSocket )
{
xTCPPacket_t *pxTCPPacket;
xIPHeader_t *pxIPHeader;
eARPLookupResult_t eReturned;
uint32_t ulRemoteIP;
xMACAddress_t xEthAddress;
BaseType_t xReturn = pdTRUE;
#if( ipconfigHAS_PRINTF != 0 )
{
/* Only necessary for nicer logging. */
memset( xEthAddress.ucBytes, '\0', sizeof( xEthAddress.ucBytes ) );
}
#endif /* ipconfigHAS_PRINTF != 0 */
ulRemoteIP = FreeRTOS_htonl( pxSocket->u.xTcp.ulRemoteIP );
/* Determine the ARP cache status for the requested IP address. */
eReturned = eARPGetCacheEntry( &( ulRemoteIP ), &( xEthAddress ) );
switch( eReturned )
{
case eARPCacheHit: /* An ARP table lookup found a valid entry. */
break; /* We can now prepare the SYN packet. */
case eARPCacheMiss: /* An ARP table lookup did not find a valid entry. */
case eCantSendPacket: /* There is no IP address, or an ARP is still in progress. */
default:
/* Count the number of times it couldn't find the ARP address. */
pxSocket->u.xTcp.ucRepCount++;
FreeRTOS_debug_printf( ( "ARP for %lxip (using %lxip): rc=%d %02X:%02X:%02X %02X:%02X:%02X\n",
pxSocket->u.xTcp.ulRemoteIP,
FreeRTOS_htonl( ulRemoteIP ),
eReturned,
xEthAddress.ucBytes[ 0 ],
xEthAddress.ucBytes[ 1 ],
xEthAddress.ucBytes[ 2 ],
xEthAddress.ucBytes[ 3 ],
xEthAddress.ucBytes[ 4 ],
xEthAddress.ucBytes[ 5 ] ) );
/* And issue a (new) ARP request */
FreeRTOS_OutputARPRequest( ulRemoteIP );
xReturn = pdFALSE;
}
if( xReturn != pdFALSE )
{
/* The MAC-address of the peer (or gateway) has been found,
now prepare the initial TCP packet and some fields in the socket. */
pxTCPPacket = ( xTCPPacket_t * )pxSocket->u.xTcp.lastPacket;
pxIPHeader = &pxTCPPacket->xIPHeader;