This repository has been archived by the owner on Jun 22, 2023. It is now read-only.
forked from scylladb/seastar
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtcp.hh
2084 lines (1926 loc) · 72.5 KB
/
tcp.hh
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
/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. You may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright (C) 2014 Cloudius Systems, Ltd.
*/
#ifndef TCP_HH_
#define TCP_HH_
#include "core/shared_ptr.hh"
#include "core/queue.hh"
#include "core/semaphore.hh"
#include "core/print.hh"
#include "core/byteorder.hh"
#include "core/metrics.hh"
#include "net.hh"
#include "ip_checksum.hh"
#include "ip.hh"
#include "const.hh"
#include "packet-util.hh"
#include <unordered_map>
#include <map>
#include <functional>
#include <deque>
#include <chrono>
#include <experimental/optional>
#include <random>
#include <stdexcept>
#include <system_error>
#define CRYPTOPP_ENABLE_NAMESPACE_WEAK 1
#include <cryptopp/md5.h>
namespace seastar {
using namespace std::chrono_literals;
namespace net {
class tcp_hdr;
inline auto tcp_error(int err) {
return std::system_error(err, std::system_category());
}
inline auto tcp_reset_error() {
return tcp_error(ECONNRESET);
};
inline auto tcp_connect_error() {
return tcp_error(ECONNABORTED);
}
inline auto tcp_refused_error() {
return tcp_error(ECONNREFUSED);
};
enum class tcp_state : uint16_t {
CLOSED = (1 << 0),
LISTEN = (1 << 1),
SYN_SENT = (1 << 2),
SYN_RECEIVED = (1 << 3),
ESTABLISHED = (1 << 4),
FIN_WAIT_1 = (1 << 5),
FIN_WAIT_2 = (1 << 6),
CLOSE_WAIT = (1 << 7),
CLOSING = (1 << 8),
LAST_ACK = (1 << 9),
TIME_WAIT = (1 << 10)
};
inline tcp_state operator|(tcp_state s1, tcp_state s2) {
return tcp_state(uint16_t(s1) | uint16_t(s2));
}
template <typename... Args>
void tcp_debug(const char* fmt, Args&&... args) {
#if TCP_DEBUG
print(fmt, std::forward<Args>(args)...);
#endif
}
struct tcp_option {
// The kind and len field are fixed and defined in TCP protocol
enum class option_kind: uint8_t { mss = 2, win_scale = 3, sack = 4, timestamps = 8, nop = 1, eol = 0 };
enum class option_len: uint8_t { mss = 4, win_scale = 3, sack = 2, timestamps = 10, nop = 1, eol = 1 };
static void write(char* p, option_kind kind, option_len len) {
p[0] = static_cast<uint8_t>(kind);
if (static_cast<uint8_t>(len) > 1) {
p[1] = static_cast<uint8_t>(len);
}
}
struct mss {
static constexpr option_kind kind = option_kind::mss;
static constexpr option_len len = option_len::mss;
uint16_t mss;
static tcp_option::mss read(const char* p) {
tcp_option::mss x;
x.mss = read_be<uint16_t>(p + 2);
return x;
}
void write(char* p) const {
tcp_option::write(p, kind, len);
write_be<uint16_t>(p + 2, mss);
}
};
struct win_scale {
static constexpr option_kind kind = option_kind::win_scale;
static constexpr option_len len = option_len::win_scale;
uint8_t shift;
static tcp_option::win_scale read(const char* p) {
tcp_option::win_scale x;
x.shift = p[2];
return x;
}
void write(char* p) const {
tcp_option::write(p, kind, len);
p[2] = shift;
}
};
struct sack {
static constexpr option_kind kind = option_kind::sack;
static constexpr option_len len = option_len::sack;
static tcp_option::sack read(const char* p) {
return {};
}
void write(char* p) const {
tcp_option::write(p, kind, len);
}
};
struct timestamps {
static constexpr option_kind kind = option_kind::timestamps;
static constexpr option_len len = option_len::timestamps;
uint32_t t1;
uint32_t t2;
static tcp_option::timestamps read(const char* p) {
tcp_option::timestamps ts;
ts.t1 = read_be<uint32_t>(p + 2);
ts.t2 = read_be<uint32_t>(p + 6);
return ts;
}
void write(char* p) const {
tcp_option::write(p, kind, len);
write_be<uint32_t>(p + 2, t1);
write_be<uint32_t>(p + 6, t2);
}
};
struct nop {
static constexpr option_kind kind = option_kind::nop;
static constexpr option_len len = option_len::nop;
void write(char* p) const {
tcp_option::write(p, kind, len);
}
};
struct eol {
static constexpr option_kind kind = option_kind::eol;
static constexpr option_len len = option_len::eol;
void write(char* p) const {
tcp_option::write(p, kind, len);
}
};
static const uint8_t align = 4;
void parse(uint8_t* beg, uint8_t* end);
uint8_t fill(void* h, const tcp_hdr* th, uint8_t option_size);
uint8_t get_size(bool syn_on, bool ack_on);
// For option negotiattion
bool _mss_received = false;
bool _win_scale_received = false;
bool _timestamps_received = false;
bool _sack_received = false;
// Option data
uint16_t _remote_mss = 536;
uint16_t _local_mss;
uint8_t _remote_win_scale = 0;
uint8_t _local_win_scale = 0;
};
inline char*& operator+=(char*& x, tcp_option::option_len len) { x += uint8_t(len); return x; }
inline const char*& operator+=(const char*& x, tcp_option::option_len len) { x += uint8_t(len); return x; }
inline uint8_t& operator+=(uint8_t& x, tcp_option::option_len len) { x += uint8_t(len); return x; }
struct tcp_seq {
uint32_t raw;
};
inline tcp_seq ntoh(tcp_seq s) {
return tcp_seq { ntoh(s.raw) };
}
inline tcp_seq hton(tcp_seq s) {
return tcp_seq { hton(s.raw) };
}
inline
std::ostream& operator<<(std::ostream& os, tcp_seq s) {
return os << s.raw;
}
inline tcp_seq make_seq(uint32_t raw) { return tcp_seq{raw}; }
inline tcp_seq& operator+=(tcp_seq& s, int32_t n) { s.raw += n; return s; }
inline tcp_seq& operator-=(tcp_seq& s, int32_t n) { s.raw -= n; return s; }
inline tcp_seq operator+(tcp_seq s, int32_t n) { return s += n; }
inline tcp_seq operator-(tcp_seq s, int32_t n) { return s -= n; }
inline int32_t operator-(tcp_seq s, tcp_seq q) { return s.raw - q.raw; }
inline bool operator==(tcp_seq s, tcp_seq q) { return s.raw == q.raw; }
inline bool operator!=(tcp_seq s, tcp_seq q) { return !(s == q); }
inline bool operator<(tcp_seq s, tcp_seq q) { return s - q < 0; }
inline bool operator>(tcp_seq s, tcp_seq q) { return q < s; }
inline bool operator<=(tcp_seq s, tcp_seq q) { return !(s > q); }
inline bool operator>=(tcp_seq s, tcp_seq q) { return !(s < q); }
struct tcp_hdr {
static constexpr size_t len = 20;
uint16_t src_port;
uint16_t dst_port;
tcp_seq seq;
tcp_seq ack;
uint8_t rsvd1 : 4;
uint8_t data_offset : 4;
uint8_t f_fin : 1;
uint8_t f_syn : 1;
uint8_t f_rst : 1;
uint8_t f_psh : 1;
uint8_t f_ack : 1;
uint8_t f_urg : 1;
uint8_t rsvd2 : 2;
uint16_t window;
uint16_t checksum;
uint16_t urgent;
static tcp_hdr read(const char* p) {
tcp_hdr h;
h.src_port = read_be<uint16_t>(p + 0);
h.dst_port = read_be<uint16_t>(p + 2);
h.seq = tcp_seq{read_be<uint32_t>(p + 4)};
h.ack = tcp_seq{read_be<uint32_t>(p + 8)};
h.rsvd1 = p[12] & 15;
h.data_offset = uint8_t(p[12]) >> 4;
h.f_fin = (uint8_t(p[13]) >> 0) & 1;
h.f_syn = (uint8_t(p[13]) >> 1) & 1;
h.f_rst = (uint8_t(p[13]) >> 2) & 1;
h.f_psh = (uint8_t(p[13]) >> 3) & 1;
h.f_ack = (uint8_t(p[13]) >> 4) & 1;
h.f_urg = (uint8_t(p[13]) >> 5) & 1;
h.rsvd2 = (uint8_t(p[13]) >> 6) & 3;
h.window = read_be<uint16_t>(p + 14);
h.checksum = read_be<uint16_t>(p + 16);
h.urgent = read_be<uint16_t>(p + 18);
return h;
}
void write(char* p) const {
write_be<uint16_t>(p + 0, src_port);
write_be<uint16_t>(p + 2, dst_port);
write_be<uint32_t>(p + 4, seq.raw);
write_be<uint32_t>(p + 8, ack.raw);
p[12] = rsvd1 | (data_offset << 4);
p[13] = (f_fin << 0)
| (f_syn << 1)
| (f_rst << 2)
| (f_psh << 3)
| (f_ack << 4)
| (f_urg << 5)
| (rsvd2 << 6);
write_be<uint16_t>(p + 14, window);
write_be<uint16_t>(p + 16, checksum);
write_be<uint16_t>(p + 18, urgent);
}
static void write_nbo_checksum(char* p, uint16_t checksum_in_network_byte_order) {
std::copy_n(reinterpret_cast<const char*>(&checksum_in_network_byte_order), 2, p + 16);
}
};
struct tcp_tag {};
using tcp_packet_merger = packet_merger<tcp_seq, tcp_tag>;
template <typename InetTraits>
class tcp {
public:
using ipaddr = typename InetTraits::address_type;
using inet_type = typename InetTraits::inet_type;
using connid = l4connid<InetTraits>;
using connid_hash = typename connid::connid_hash;
class connection;
class listener;
private:
class tcb;
class tcb : public enable_lw_shared_from_this<tcb> {
using clock_type = lowres_clock;
static constexpr tcp_state CLOSED = tcp_state::CLOSED;
static constexpr tcp_state LISTEN = tcp_state::LISTEN;
static constexpr tcp_state SYN_SENT = tcp_state::SYN_SENT;
static constexpr tcp_state SYN_RECEIVED = tcp_state::SYN_RECEIVED;
static constexpr tcp_state ESTABLISHED = tcp_state::ESTABLISHED;
static constexpr tcp_state FIN_WAIT_1 = tcp_state::FIN_WAIT_1;
static constexpr tcp_state FIN_WAIT_2 = tcp_state::FIN_WAIT_2;
static constexpr tcp_state CLOSE_WAIT = tcp_state::CLOSE_WAIT;
static constexpr tcp_state CLOSING = tcp_state::CLOSING;
static constexpr tcp_state LAST_ACK = tcp_state::LAST_ACK;
static constexpr tcp_state TIME_WAIT = tcp_state::TIME_WAIT;
tcp_state _state = CLOSED;
tcp& _tcp;
connection* _conn = nullptr;
promise<> _connect_done;
ipaddr _local_ip;
ipaddr _foreign_ip;
uint16_t _local_port;
uint16_t _foreign_port;
struct unacked_segment {
packet p;
uint16_t data_len;
unsigned nr_transmits;
clock_type::time_point tx_time;
};
struct send {
tcp_seq unacknowledged;
tcp_seq next;
uint32_t window;
uint8_t window_scale;
uint16_t mss;
tcp_seq urgent;
tcp_seq wl1;
tcp_seq wl2;
tcp_seq initial;
std::deque<unacked_segment> data;
std::deque<packet> unsent;
uint32_t unsent_len = 0;
bool closed = false;
promise<> _window_opened;
// Wait for all data are acked
std::experimental::optional<promise<>> _all_data_acked_promise;
// Limit number of data queued into send queue
size_t max_queue_space = 212992;
size_t current_queue_space = 0;
// wait for there is at least one byte available in the queue
std::experimental::optional<promise<>> _send_available_promise;
// Round-trip time variation
std::chrono::milliseconds rttvar;
// Smoothed round-trip time
std::chrono::milliseconds srtt;
bool first_rto_sample = true;
clock_type::time_point syn_tx_time;
// Congestion window
uint32_t cwnd;
// Slow start threshold
uint32_t ssthresh;
// Duplicated ACKs
uint16_t dupacks = 0;
unsigned syn_retransmit = 0;
unsigned fin_retransmit = 0;
uint32_t limited_transfer = 0;
uint32_t partial_ack = 0;
tcp_seq recover;
bool window_probe = false;
} _snd;
struct receive {
tcp_seq next;
uint32_t window;
uint8_t window_scale;
uint16_t mss;
tcp_seq urgent;
tcp_seq initial;
std::deque<packet> data;
tcp_packet_merger out_of_order;
std::experimental::optional<promise<>> _data_received_promise;
} _rcv;
tcp_option _option;
timer<lowres_clock> _delayed_ack;
// Retransmission timeout
std::chrono::milliseconds _rto{1000};
std::chrono::milliseconds _persist_time_out{1000};
static constexpr std::chrono::milliseconds _rto_min{1000};
static constexpr std::chrono::milliseconds _rto_max{60000};
// Clock granularity
static constexpr std::chrono::milliseconds _rto_clk_granularity{1};
static constexpr uint16_t _max_nr_retransmit{5};
timer<lowres_clock> _retransmit;
timer<lowres_clock> _persist;
uint16_t _nr_full_seg_received = 0;
struct isn_secret {
// 512 bits secretkey for ISN generating
uint32_t key[16];
isn_secret () {
std::random_device rd;
std::default_random_engine e(rd());
std::uniform_int_distribution<uint32_t> dist{};
for (auto& k : key) {
k = dist(e);
}
}
};
static isn_secret _isn_secret;
tcp_seq get_isn();
circular_buffer<typename InetTraits::l4packet> _packetq;
bool _poll_active = false;
public:
tcb(tcp& t, connid id);
void input_handle_listen_state(tcp_hdr* th, packet p);
void input_handle_syn_sent_state(tcp_hdr* th, packet p);
void input_handle_other_state(tcp_hdr* th, packet p);
void output_one(bool data_retransmit = false);
future<> wait_for_data();
void abort_reader();
future<> wait_for_all_data_acked();
future<> wait_send_available();
future<> send(packet p);
void connect();
packet read();
void close();
void remove_from_tcbs() {
auto id = connid{_local_ip, _foreign_ip, _local_port, _foreign_port};
_tcp._tcbs.erase(id);
}
std::experimental::optional<typename InetTraits::l4packet> get_packet();
void output() {
if (!_poll_active) {
_poll_active = true;
_tcp.poll_tcb(_foreign_ip, this->shared_from_this()).then_wrapped([this] (auto&& f) {
try {
f.get();
} catch(arp_queue_full_error& ex) {
// retry later
_poll_active = false;
this->start_retransmit_timer();
} catch(arp_timeout_error& ex) {
if (this->in_state(SYN_SENT)) {
_connect_done.set_exception(ex);
this->cleanup();
}
// in other states connection should time out
}
});
}
}
future<> connect_done() {
return _connect_done.get_future();
}
tcp_state& state() {
return _state;
}
private:
void respond_with_reset(tcp_hdr* th);
bool merge_out_of_order();
void insert_out_of_order(tcp_seq seq, packet p);
void trim_receive_data_after_window();
bool should_send_ack(uint16_t seg_len);
void clear_delayed_ack();
packet get_transmit_packet();
void retransmit_one() {
bool data_retransmit = true;
output_one(data_retransmit);
}
void start_retransmit_timer() {
auto now = clock_type::now();
start_retransmit_timer(now);
};
void start_retransmit_timer(clock_type::time_point now) {
auto tp = now + _rto;
_retransmit.rearm(tp);
};
void stop_retransmit_timer() {
_retransmit.cancel();
};
void start_persist_timer() {
auto now = clock_type::now();
start_persist_timer(now);
};
void start_persist_timer(clock_type::time_point now) {
auto tp = now + _persist_time_out;
_persist.rearm(tp);
};
void stop_persist_timer() {
_persist.cancel();
};
void persist();
void retransmit();
void fast_retransmit();
void update_rto(clock_type::time_point tx_time);
void update_cwnd(uint32_t acked_bytes);
void cleanup();
uint32_t can_send() {
if (_snd.window_probe) {
return 1;
}
// Can not send more than advertised window allows
auto x = std::min(uint32_t(_snd.unacknowledged + _snd.window - _snd.next), _snd.unsent_len);
// Can not send more than congestion window allows
x = std::min(_snd.cwnd, x);
if (_snd.dupacks == 1 || _snd.dupacks == 2) {
// RFC5681 Step 3.1
// Send cwnd + 2 * smss per RFC3042
auto flight = flight_size();
auto max = _snd.cwnd + 2 * _snd.mss;
x = flight <= max ? std::min(x, max - flight) : 0;
_snd.limited_transfer += x;
} else if (_snd.dupacks >= 3) {
// RFC5681 Step 3.5
// Sent 1 full-sized segment at most
x = std::min(uint32_t(_snd.mss), x);
}
return x;
}
uint32_t flight_size() {
uint32_t size = 0;
std::for_each(_snd.data.begin(), _snd.data.end(), [&] (unacked_segment& seg) { size += seg.p.len(); });
return size;
}
uint16_t local_mss() {
return _tcp.hw_features().mtu - net::tcp_hdr_len_min - InetTraits::ip_hdr_len_min;
}
void queue_packet(packet p) {
_packetq.emplace_back(typename InetTraits::l4packet{_foreign_ip, std::move(p)});
}
void signal_data_received() {
if (_rcv._data_received_promise) {
_rcv._data_received_promise->set_value();
_rcv._data_received_promise = {};
}
}
void signal_all_data_acked() {
if (_snd._all_data_acked_promise && _snd.unsent_len == 0) {
_snd._all_data_acked_promise->set_value();
_snd._all_data_acked_promise = {};
}
}
void signal_send_available() {
if (_snd._send_available_promise && _snd.max_queue_space > _snd.current_queue_space) {
_snd._send_available_promise->set_value();
_snd._send_available_promise = {};
}
}
void do_syn_sent() {
_state = SYN_SENT;
_snd.syn_tx_time = clock_type::now();
// Send <SYN> to remote
output();
}
void do_syn_received() {
_state = SYN_RECEIVED;
_snd.syn_tx_time = clock_type::now();
// Send <SYN,ACK> to remote
output();
}
void do_established() {
_state = ESTABLISHED;
update_rto(_snd.syn_tx_time);
_connect_done.set_value();
}
void do_reset() {
_state = CLOSED;
cleanup();
if (_rcv._data_received_promise) {
_rcv._data_received_promise->set_exception(tcp_reset_error());
_rcv._data_received_promise = std::experimental::nullopt;
}
if (_snd._all_data_acked_promise) {
_snd._all_data_acked_promise->set_exception(tcp_reset_error());
_snd._all_data_acked_promise = std::experimental::nullopt;
}
if (_snd._send_available_promise) {
_snd._send_available_promise->set_exception(tcp_reset_error());
_snd._send_available_promise = std::experimental::nullopt;
}
}
void do_time_wait() {
// FIXME: Implement TIME_WAIT state timer
_state = TIME_WAIT;
cleanup();
}
void do_closed() {
_state = CLOSED;
cleanup();
}
void do_setup_isn() {
_snd.initial = get_isn();
_snd.unacknowledged = _snd.initial;
_snd.next = _snd.initial + 1;
_snd.recover = _snd.initial;
}
void do_local_fin_acked() {
_snd.unacknowledged += 1;
_snd.next += 1;
}
bool syn_needs_on() {
return in_state(SYN_SENT | SYN_RECEIVED);
}
bool fin_needs_on() {
return in_state(FIN_WAIT_1 | CLOSING | LAST_ACK) && _snd.closed &&
_snd.unsent_len == 0;
}
bool ack_needs_on() {
return !in_state(CLOSED | LISTEN | SYN_SENT);
}
bool foreign_will_not_send() {
return in_state(CLOSING | TIME_WAIT | CLOSE_WAIT | LAST_ACK | CLOSED);
}
bool in_state(tcp_state state) {
return uint16_t(_state) & uint16_t(state);
}
void exit_fast_recovery() {
_snd.dupacks = 0;
_snd.limited_transfer = 0;
_snd.partial_ack = 0;
}
uint32_t data_segment_acked(tcp_seq seg_ack);
bool segment_acceptable(tcp_seq seg_seq, unsigned seg_len);
void init_from_options(tcp_hdr* th, uint8_t* opt_start, uint8_t* opt_end);
friend class connection;
};
inet_type& _inet;
std::unordered_map<connid, lw_shared_ptr<tcb>, connid_hash> _tcbs;
std::unordered_map<uint16_t, listener*> _listening;
std::random_device _rd;
std::default_random_engine _e;
std::uniform_int_distribution<uint16_t> _port_dist{41952, 65535};
circular_buffer<std::pair<lw_shared_ptr<tcb>, ethernet_address>> _poll_tcbs;
// queue for packets that do not belong to any tcb
circular_buffer<ipv4_traits::l4packet> _packetq;
semaphore _queue_space = {212992};
metrics::metric_groups _metrics;
public:
class connection {
lw_shared_ptr<tcb> _tcb;
public:
explicit connection(lw_shared_ptr<tcb> tcbp) : _tcb(std::move(tcbp)) { _tcb->_conn = this; }
connection(const connection&) = delete;
connection(connection&& x) noexcept : _tcb(std::move(x._tcb)) {
_tcb->_conn = this;
}
~connection();
void operator=(const connection&) = delete;
connection& operator=(connection&& x) {
if (this != &x) {
this->~connection();
new (this) connection(std::move(x));
}
return *this;
}
future<> connected() {
return _tcb->connect_done();
}
future<> send(packet p) {
return _tcb->send(std::move(p));
}
future<> wait_for_data() {
return _tcb->wait_for_data();
}
packet read() {
return _tcb->read();
}
ipaddr foreign_ip() {
return _tcb->_foreign_ip;
}
uint16_t foreign_port() {
return _tcb->_foreign_port;
}
void shutdown_connect();
void close_read();
void close_write();
};
class listener {
tcp& _tcp;
uint16_t _port;
queue<connection> _q;
size_t _pending = 0;
private:
listener(tcp& t, uint16_t port, size_t queue_length)
: _tcp(t), _port(port), _q(queue_length) {
_tcp._listening.emplace(_port, this);
}
public:
listener(listener&& x)
: _tcp(x._tcp), _port(x._port), _q(std::move(x._q)) {
_tcp._listening[_port] = this;
x._port = 0;
}
~listener() {
if (_port) {
_tcp._listening.erase(_port);
}
}
future<connection> accept() {
return _q.not_empty().then([this] {
return make_ready_future<connection>(_q.pop());
});
}
void abort_accept() {
_q.abort(std::make_exception_ptr(std::system_error(ECONNABORTED, std::system_category())));
}
bool full() { return _pending + _q.size() >= _q.max_size(); }
void inc_pending() { _pending++; }
void dec_pending() { _pending--; }
friend class tcp;
};
public:
explicit tcp(inet_type& inet);
void received(packet p, ipaddr from, ipaddr to);
bool forward(forward_hash& out_hash_data, packet& p, size_t off);
listener listen(uint16_t port, size_t queue_length = 100);
connection connect(socket_address sa);
const net::hw_features& hw_features() const { return _inet._inet.hw_features(); }
future<> poll_tcb(ipaddr to, lw_shared_ptr<tcb> tcb);
void add_connected_tcb(lw_shared_ptr<tcb> tcbp, uint16_t local_port) {
auto it = _listening.find(local_port);
if (it != _listening.end()) {
it->second->_q.push(connection(tcbp));
it->second->dec_pending();
}
}
private:
void send_packet_without_tcb(ipaddr from, ipaddr to, packet p);
void respond_with_reset(tcp_hdr* rth, ipaddr local_ip, ipaddr foreign_ip);
friend class listener;
};
template <typename InetTraits>
tcp<InetTraits>::tcp(inet_type& inet)
: _inet(inet)
, _e(_rd()) {
namespace sm = metrics;
_metrics.add_group("tcp", {
sm::make_derive("linearizations", [] { return tcp_packet_merger::linearizations(); },
sm::description("Counts a number of times a buffer linearization was invoked during the buffers merge process. "
"Divide it by a total TCP receive packet rate to get an everage number of lineraizations per TCP packet."))
});
_inet.register_packet_provider([this, tcb_polled = 0u] () mutable {
std::experimental::optional<typename InetTraits::l4packet> l4p;
auto c = _poll_tcbs.size();
if (!_packetq.empty() && (!(tcb_polled % 128) || c == 0)) {
l4p = std::move(_packetq.front());
_packetq.pop_front();
_queue_space.signal(l4p.value().p.len());
} else {
while (c--) {
tcb_polled++;
lw_shared_ptr<tcb> tcb;
ethernet_address dst;
std::tie(tcb, dst) = std::move(_poll_tcbs.front());
_poll_tcbs.pop_front();
l4p = tcb->get_packet();
if (l4p) {
l4p.value().e_dst = dst;
break;
}
}
}
return l4p;
});
}
template <typename InetTraits>
future<> tcp<InetTraits>::poll_tcb(ipaddr to, lw_shared_ptr<tcb> tcb) {
return _inet.get_l2_dst_address(to).then([this, tcb = std::move(tcb)] (ethernet_address dst) {
_poll_tcbs.emplace_back(std::move(tcb), dst);
});
}
template <typename InetTraits>
auto tcp<InetTraits>::listen(uint16_t port, size_t queue_length) -> listener {
return listener(*this, port, queue_length);
}
template <typename InetTraits>
auto tcp<InetTraits>::connect(socket_address sa) -> connection {
uint16_t src_port;
connid id;
auto src_ip = _inet._inet.host_address();
auto dst_ip = ipv4_address(sa);
auto dst_port = net::ntoh(sa.u.in.sin_port);
do {
src_port = _port_dist(_e);
id = connid{src_ip, dst_ip, src_port, dst_port};
} while (_inet._inet.netif()->hw_queues_count() > 1 &&
(_inet._inet.netif()->hash2cpu(id.hash(_inet._inet.netif()->rss_key())) != engine().cpu_id()
|| _tcbs.find(id) != _tcbs.end()));
auto tcbp = make_lw_shared<tcb>(*this, id);
_tcbs.insert({id, tcbp});
tcbp->connect();
return connection(tcbp);
}
template <typename InetTraits>
bool tcp<InetTraits>::forward(forward_hash& out_hash_data, packet& p, size_t off) {
auto th = p.get_header(off, tcp_hdr::len);
if (th) {
// src_port, dst_port in network byte order
out_hash_data.push_back(uint8_t(th[0]));
out_hash_data.push_back(uint8_t(th[1]));
out_hash_data.push_back(uint8_t(th[2]));
out_hash_data.push_back(uint8_t(th[3]));
}
return true;
}
template <typename InetTraits>
void tcp<InetTraits>::received(packet p, ipaddr from, ipaddr to) {
auto th = p.get_header(0, tcp_hdr::len);
if (!th) {
return;
}
// data_offset is correct even before ntoh()
auto data_offset = uint8_t(th[12]) >> 4;
if (size_t(data_offset * 4) < tcp_hdr::len) {
return;
}
if (!hw_features().rx_csum_offload) {
checksummer csum;
InetTraits::tcp_pseudo_header_checksum(csum, from, to, p.len());
csum.sum(p);
if (csum.get() != 0) {
return;
}
}
auto h = tcp_hdr::read(th);
auto id = connid{to, from, h.dst_port, h.src_port};
auto tcbi = _tcbs.find(id);
lw_shared_ptr<tcb> tcbp;
if (tcbi == _tcbs.end()) {
auto listener = _listening.find(id.local_port);
if (listener == _listening.end() || listener->second->full()) {
// 1) In CLOSE state
// 1.1 all data in the incoming segment is discarded. An incoming
// segment containing a RST is discarded. An incoming segment not
// containing a RST causes a RST to be sent in response.
// FIXME:
// if ACK off: <SEQ=0><ACK=SEG.SEQ+SEG.LEN><CTL=RST,ACK>
// if ACK on: <SEQ=SEG.ACK><CTL=RST>
return respond_with_reset(&h, id.local_ip, id.foreign_ip);
} else {
// 2) In LISTEN state
// 2.1 first check for an RST
if (h.f_rst) {
// An incoming RST should be ignored
return;
}
// 2.2 second check for an ACK
if (h.f_ack) {
// Any acknowledgment is bad if it arrives on a connection
// still in the LISTEN state.
// <SEQ=SEG.ACK><CTL=RST>
return respond_with_reset(&h, id.local_ip, id.foreign_ip);
}
// 2.3 third check for a SYN
if (h.f_syn) {
// check the security
// NOTE: Ignored for now
tcbp = make_lw_shared<tcb>(*this, id);
_tcbs.insert({id, tcbp});
// TODO: we need to remove the tcb and decrease the pending if
// it stays SYN_RECEIVED state forever.
listener->second->inc_pending();
return tcbp->input_handle_listen_state(&h, std::move(p));
}
// 2.4 fourth other text or control
// So you are unlikely to get here, but if you do, drop the
// segment, and return.
return;
}
} else {
tcbp = tcbi->second;
if (tcbp->state() == tcp_state::SYN_SENT) {
// 3) In SYN_SENT State
return tcbp->input_handle_syn_sent_state(&h, std::move(p));
} else {
// 4) In other state, can be one of the following:
// SYN_RECEIVED, ESTABLISHED, FIN_WAIT_1, FIN_WAIT_2
// CLOSE_WAIT, CLOSING, LAST_ACK, TIME_WAIT
return tcbp->input_handle_other_state(&h, std::move(p));
}
}
}
// Send packet does not belong to any tcb
template <typename InetTraits>
void tcp<InetTraits>::send_packet_without_tcb(ipaddr from, ipaddr to, packet p) {
if (_queue_space.try_wait(p.len())) { // drop packets that do not fit the queue
_inet.get_l2_dst_address(to).then([this, to, p = std::move(p)] (ethernet_address e_dst) mutable {
_packetq.emplace_back(ipv4_traits::l4packet{to, std::move(p), e_dst, ip_protocol_num::tcp});
});
}
}
template <typename InetTraits>
tcp<InetTraits>::connection::~connection() {
if (_tcb) {
_tcb->_conn = nullptr;
close_read();
close_write();
}
}
template <typename InetTraits>
tcp<InetTraits>::tcb::tcb(tcp& t, connid id)
: _tcp(t)
, _local_ip(id.local_ip)
, _foreign_ip(id.foreign_ip)
, _local_port(id.local_port)
, _foreign_port(id.foreign_port)
, _delayed_ack([this] { _nr_full_seg_received = 0; output(); })
, _retransmit([this] { retransmit(); })
, _persist([this] { persist(); }) {
}
template <typename InetTraits>
void tcp<InetTraits>::tcb::respond_with_reset(tcp_hdr* rth) {
_tcp.respond_with_reset(rth, _local_ip, _foreign_ip);
}
template <typename InetTraits>
void tcp<InetTraits>::respond_with_reset(tcp_hdr* rth, ipaddr local_ip, ipaddr foreign_ip) {
if (rth->f_rst) {
return;
}
packet p;
auto th = p.prepend_uninitialized_header(tcp_hdr::len);
auto h = tcp_hdr{};
h.src_port = rth->dst_port;
h.dst_port = rth->src_port;
if (rth->f_ack) {
h.seq = rth->ack;
}
// If this RST packet is in response to a SYN packet. We ACK the ISN.
if (rth->f_syn) {
h.ack = rth->seq + 1;
h.f_ack = true;
}
h.f_rst = true;
h.data_offset = tcp_hdr::len / 4;
h.checksum = 0;
h.write(th);
checksummer csum;
offload_info oi;
InetTraits::tcp_pseudo_header_checksum(csum, local_ip, foreign_ip, tcp_hdr::len);
uint16_t checksum;
if (hw_features().tx_csum_l4_offload) {
checksum = ~csum.get();
oi.needs_csum = true;
} else {
csum.sum(p);
checksum = csum.get();
oi.needs_csum = false;
}
tcp_hdr::write_nbo_checksum(th, checksum);
oi.protocol = ip_protocol_num::tcp;
oi.tcp_hdr_len = tcp_hdr::len;
p.set_offload_info(oi);
send_packet_without_tcb(local_ip, foreign_ip, std::move(p));
}
template <typename InetTraits>
uint32_t tcp<InetTraits>::tcb::data_segment_acked(tcp_seq seg_ack) {
uint32_t total_acked_bytes = 0;
// Full ACK of segment
while (!_snd.data.empty()
&& (_snd.unacknowledged + _snd.data.front().p.len() <= seg_ack)) {
auto acked_bytes = _snd.data.front().p.len();
_snd.unacknowledged += acked_bytes;
// Ignore retransmitted segments when setting the RTO
if (_snd.data.front().nr_transmits == 0) {
update_rto(_snd.data.front().tx_time);
}
update_cwnd(acked_bytes);
total_acked_bytes += acked_bytes;
_snd.current_queue_space -= _snd.data.front().data_len;
signal_send_available();
_snd.data.pop_front();
}
// Partial ACK of segment
if (_snd.unacknowledged < seg_ack) {
auto acked_bytes = seg_ack - _snd.unacknowledged;
if (!_snd.data.empty()) {
auto& unacked_seg = _snd.data.front();
unacked_seg.p.trim_front(acked_bytes);
}
_snd.unacknowledged = seg_ack;