Repository navigation
Expand file tree
/
Copy pathbaseproxy.cpp
More file actions
1573 lines (1196 loc) · 49.8 KB
/
Copy pathbaseproxy.cpp
File metadata and controls
1573 lines (1196 loc) · 49.8 KB
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
/*
Socle Library Ecosystem
Copyright (c) 2014, Ales Stibal <astib@mag0.net>, All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3.0 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library.
*/
#include <vector>
#include <string>
#include <unistd.h>
#include <sys/socket.h>
#include <cstring>
#include <cerrno>
#include <ctime>
#include <baseproxy.hpp>
#include <hostcx.hpp>
#include <log/logger.hpp>
#include "udpcom.hpp"
#include <vars.hpp>
baseProxy::~baseProxy() {
try {
baseProxy::shutdown();
}
catch(std::exception const& e) {
_err("Proxy: d-tor exception: %s", e.what());
}
if (com_ != nullptr) {
_dum("Proxy: deleting com");
delete com_;
}
}
void baseProxy::ladd(baseHostCX* cs) {
cs->unblock();
int s = cs->socket();
com()->set_poll_handler(s,this);
com()->set_monitor(s);
left_sockets.push_back(cs);
cs->parent_proxy(this, 'L');
_dia("baseProxy::ladd: added socket: %s", cs->c_type());
}
void baseProxy::radd(baseHostCX* cs) {
cs->unblock();
//int s = cs->com()->translate_socket(cs->socket());
int s = cs->socket();
com()->set_poll_handler(s,this);
com()->set_monitor(s);
right_sockets.push_back(cs);
cs->parent_proxy(this, 'R');
_dia("baseProxy::radd: added socket: %s", cs->c_type());
}
void baseProxy::lbadd(baseHostCX* cs) {
int s = cs->com()->translate_socket(cs->socket());
com()->set_monitor(s);
com()->set_poll_handler(s,this);
left_bind_sockets.push_back(cs);
cs->parent_proxy(this, 'L');
_dia("baseProxy::lbadd: added bound socket: %s", cs->c_type());
}
void baseProxy::rbadd(baseHostCX* cs) {
int s = cs->com()->translate_socket(cs->socket());
com()->set_monitor(s);
com()->set_poll_handler(s,this);
right_bind_sockets.push_back(cs);
cs->parent_proxy(this, 'R');
_dia("baseProxy::rbadd: added bound socket: %s", cs->c_type());
}
void baseProxy::lpcadd(baseHostCX* cx) {
cx->permanent(true);
int s = cx->com()->translate_socket(cx->socket());
com()->set_poll_handler(s,this);
com()->set_monitor(s);
if (cx->opening()) com()->set_write_monitor(s);
left_pc_cx.push_back(cx);
cx->parent_proxy(this, 'L');
_dia("baseProxy::lpcadd: added perma socket: %s", cx->c_type());
}
void baseProxy::rpcadd(baseHostCX* cx) {
cx->permanent(true);
int s = cx->com()->translate_socket(cx->socket());
com()->set_poll_handler(s,this);
com()->set_monitor(s);
if (cx->opening()) com()->set_write_monitor(s);
right_pc_cx.push_back(cx);
cx->parent_proxy(this,'R');
_dia("baseProxy::rpcadd: added perma socket %s", cx->c_type());
}
void baseProxy::ldaadd(baseHostCX* cs) {
cs->unblock();
int s = cs->com()->translate_socket(cs->socket());
com()->set_monitor(s);
com()->set_poll_handler(s,this);
left_delayed_accepts.push_back(cs);
cs->parent_proxy(this,'l');
_dia("baseProxy::ldaadd: added delayed socket: %s", cs->c_type());
}
void baseProxy::rdaadd(baseHostCX* cs) {
cs->unblock();
int s = cs->com()->translate_socket(cs->socket());
com()->set_monitor(s);
com()->set_poll_handler(s,this);
right_delayed_accepts.push_back(cs);
cs->parent_proxy(this,'r');
_dia("baseProxy::rdaadd: added delayed socket: %s", cs->c_type());
}
void baseProxy::drop_cx(baseHostCX* cx) {
cx->peer(nullptr);
trashcan.emplace_back(cx);
}
void baseProxy::left_shutdown() {
auto lb = left_bind_sockets.size();
auto ls = left_sockets.size();
auto lp = left_pc_cx.size();
auto ld = left_delayed_accepts.size();
for(auto* ii: left_bind_sockets) { ii->shutdown(); }
for(auto* ii: left_sockets) { ii->shutdown(); }
for(auto* ii: left_pc_cx) { ii->shutdown(); }
for(auto* ii: left_delayed_accepts) { ii->shutdown(); }
for(auto* ii: left_bind_sockets) { drop_cx(ii); }
left_bind_sockets.clear();
for(auto* ii: left_sockets) { drop_cx(ii); }
left_sockets.clear();
for(auto* ii: left_pc_cx) { drop_cx(ii); }
left_pc_cx.clear();
for(auto* ii: left_delayed_accepts) { drop_cx(ii); }
left_delayed_accepts.clear();
_deb("baseProxy::left_shutdown: bind=%d(delayed=%d), sock=%d, perm=%d", lb, ld, ls, lp);
}
void baseProxy::right_shutdown() {
auto rb = right_bind_sockets.size();
auto rs = right_sockets.size();
auto rp = right_pc_cx.size();
auto rd = right_delayed_accepts.size();
for(auto ii: right_bind_sockets) { ii->shutdown(); }
for(auto ii: right_sockets) { ii->shutdown(); }
for(auto ii: right_pc_cx) { ii->shutdown(); }
for(auto ii: right_delayed_accepts) { ii->shutdown(); }
for(auto ii: right_bind_sockets) { drop_cx(ii); }
right_bind_sockets.clear();
for(auto ii: right_sockets) { drop_cx(ii); }
right_sockets.clear();
for(auto ii: right_pc_cx) { drop_cx(ii); }
right_pc_cx.clear();
for(auto ii: right_delayed_accepts) { drop_cx(ii); }
right_delayed_accepts.clear();
_deb("baseProxy::right_shutdown: bind=%d(delayed=%d), sock=%d, perm=%d", rb, rd, rs, rp);
}
void baseProxy::shutdown() {
_dia("baseProxy::shutdown");
left_shutdown();
right_shutdown();
_deb("baseProxy::shutdown finished");
}
int baseProxy::lsize() {
return (left_sockets.size()+left_bind_sockets.size()+left_pc_cx.size()+left_delayed_accepts.size());
}
int baseProxy::rsize() {
return (right_sockets.size()+right_bind_sockets.size()+right_pc_cx.size()+right_delayed_accepts.size());
}
bool baseProxy::on_cx_timer(baseHostCX* cx) {
cx->on_timer();
return true;
}
// return true if clicked, false otherwise.
bool baseProxy::clicker::reset_timer() {
time(&clock_);
if(clock_ < last_tick_) {
last_tick_ = clock_;
return false;
}
if(std::difftime(clock_, last_tick_) >= timer_interval) {
time(&last_tick_);
return true;
}
return false;
}
// (re)set socket set and calculate max socket no
bool baseProxy::run_timers () {
if(clicker_.reset_timer()) {
auto cx_check = [&](auto* cx, bool idle_check=false) {
on_cx_timer(cx);
if(idle_check && cx->idle_timeout()) {
state().dead(true);
_dia("%s: timed out!", hr().c_str());
}
};
auto for_each_check = [&](auto what, bool idle_check=false) {
for(auto it: what) {
cx_check(it, idle_check);
}
};
for_each_check(left_sockets, true);
for_each_check(left_delayed_accepts, true);
for_each_check(left_bind_sockets);
for_each_check(left_pc_cx, true);
for_each_check(right_sockets, true);
for_each_check(right_delayed_accepts, true);
for_each_check(right_bind_sockets);
for_each_check(right_pc_cx, true);
return true;
}
return false;
}
// (re)set socket set and calculate max socket no
int baseProxy::prepare_sockets(baseCom* fdset_owner) {
int max = 1;
return max;
}
bool baseProxy::handle_cx_events(unsigned char side, baseHostCX* cx) {
auto handle_terminal = [&]() {
// A permanent callback reconnects synchronously. Retire the failed
// descriptor first so the generic terminal path cannot immediately
// shut down the replacement socket.
if(side == 'x' || side == 'y') {
cx->shutdown();
if(side == 'x') on_left_pc_error(cx);
else on_right_pc_error(cx);
} else {
if(side == 'l') on_left_error(cx);
else on_right_error(cx);
cx->shutdown();
}
};
// treat non-blocking still opening sockets
if( cx->opening_timeout() ) {
_dia("baseProxy::handle_cx_events[%d]: opening timeout!", cx->socket());
handle_terminal();
return false;
}
if( cx->idle_timeout() ) {
_dia("baseProxy::handle_cx_events[%d]: idle timeout!", cx->socket());
handle_terminal();
return false;
}
if( cx->error() ) {
_dia("baseProxy::handle_cx_events[%d]: error!", cx->socket());
handle_terminal();
return false;
}
//process new messages before waiting_for_peercom check
if( cx->new_message() ) {
_dia("baseProxy::handle_cx_events[%d]: new message!", cx->socket());
if (side == 'l') { on_left_message(cx); }
else if(side == 'r') { on_right_message(cx); }
else if(side == 'x') { on_left_message(cx); }
else if(side == 'y') { on_right_message(cx); }
return false;
}
return true;
}
bool baseProxy::handle_cx_read(unsigned char side, baseHostCX* cx,
bool cross_direction_retry) {
_ext("%c in R fdset: %d", side, cx->socket());
bool proceed = cx->readable();
if(cross_direction_retry && cx->com()->forced_read_on_write_reset()) {
_dia("baseProxy::handle_cx_read[%c]: read overridden on write socket event", side);
proceed = true;
}
if (proceed && !cx->read_eof()) {
_ext("%c in R fdset and readable: %d", side, cx->socket());
int red = cx->read();
auto handle_eof = [&]() -> bool {
if(side == 'l' || side == 'x') {
handle_last_status |= HANDLE_LEFT_ERROR;
state().error_on_left_read = true;
} else {
handle_last_status |= HANDLE_RIGHT_ERROR;
state().error_on_right_read = true;
}
// Permanent/reconnecting contexts use EOF as a reconnect signal,
// not an end-to-end stream half-close.
if(side == 'x' || side == 'y') {
cx->shutdown();
if(side == 'x') on_left_pc_error(cx);
else on_right_pc_error(cx);
return false;
}
if(side == 'l') on_left_error(cx);
else on_right_error(cx);
// A read EOF is a half-close, not permission to destroy the write
// half of the same full-duplex stream. Stop read readiness while
// retaining any independent queued/protocol-level output.
if(!state().dead() && cx->socket() != 0) {
if((cx->opening() && cx->com()->opening_write_event_pending()) ||
!cx->writebuf()->empty() || cx->com()->write_event_pending()) {
cx->com()->set_write_monitor_only(cx->socket());
} else {
cx->com()->unset_monitor(cx->socket());
}
} else {
cx->shutdown();
}
_deb("baseProxy::handle_cx_read[%c]: EOF processed", side);
return !state().dead();
};
if (red == 0) {
return handle_eof();
}
if (red > 0) {
stats_.last_read += red;
if (side == 'l') { on_left_bytes(cx); }
else if(side == 'r') { on_right_bytes(cx); }
else if(side == 'x') { on_left_bytes(cx); }
else if(side == 'y') { on_right_bytes(cx); }
_deb("baseProxy::handle_cx_read[%c]: %d bytes processed", side, red);
// Preserve the final application bytes when EOF follows them in
// the same drain batch, then transition to half-closed state.
if(cx->read_eof() && !handle_eof()) return false;
}
}
return true;
}
bool baseProxy::handle_cx_write(unsigned char side, baseHostCX* cx,
bool cross_direction_retry) {
_ext("baseProxy::handle_cx_write[%c]: in write fdset: %d",side, cx->socket());
bool proceed = cx->writable();
if(cross_direction_retry && cx->com()->forced_write_on_read_reset()) {
_dia("baseProxy::handle_cx_read[%c]: write overridden on read socket event", side);
proceed = true;
}
if (proceed) {
_ext("baseProxy::handle_cx_write[%c]: writable: %d", side, cx->socket());
int wrt = cx->write();
if (wrt < 0) {
cx->shutdown();
//left_sockets.erase(i);
if(side == 'l' || side == 'x') {
handle_last_status |= HANDLE_LEFT_ERROR;
state().error_on_left_write = true;
} else {
handle_last_status |= HANDLE_RIGHT_ERROR;
state().error_on_right_write = true;
}
if (side == 'l') { on_left_error(cx); }
else if(side == 'r') { on_right_error(cx); }
else if(side == 'x') { on_left_pc_error(cx); }
else if(side == 'y') { on_right_pc_error(cx); }
_deb("baseProxy::handle_cx_write[%c]: error processed", side);
return false;
} else {
stats_.last_write += wrt;
if(auto* owner = parent(); owner != nullptr && wrt > 0) {
if(side == 'l' || side == 'x') {
owner->stats().count_bytes_down(wrt);
} else if(side == 'r' || side == 'y') {
owner->stats().count_bytes_up(wrt);
}
}
if(wrt > 0 and stats_.do_rate_meter) {
if (stats_.do_rate_meter) {
if (side == 'l' or side == 'x') {
stats_.mtr_down.update(wrt);
} else if (side == 'r' or side == 'y') {
stats_.mtr_up.update(wrt);
}
}
_deb("baseProxy::handle_cx_write[%c]: %d bytes processed", side, wrt);
}
}
}
return true;
}
bool baseProxy::handle_cx_read_once(unsigned char side, baseCom* xcom, baseHostCX* cx) {
bool ret = true;
bool dont_read = false;
const bool waiting_for_peer = cx->socket() != 0 &&
cx->read_waiting_for_peercom();
_ext("%c: %d",side, cx->socket());
if(cx->socket() == 0) {
_dia("baseProxy::handle_cx_read_once[%c]: monitored socket changed to zero - terminating.", side);
cx->error(true);
ret = false;
goto failure;
}
if ((side == 'l' || side == 'x') && state().write_right_bottleneck()) dont_read = true;
else {
if ((side == 'r' || side == 'y') && state().write_left_bottleneck()) dont_read = true;
}
if(dont_read){
_dia("baseProxy::handle_cx_read_once[%c]: bottleneck, not reading", side);
}
// waiting_for_peercom cx is subject to timeout only, no r/w is done on it ( it would return -1/0 anyway, so spare some cycles)
if((!waiting_for_peer) && (!dont_read)) {
bool forced_read = cx->com()->forced_read_reset();
bool in_read_set = xcom->in_readset(cx->socket());
if(in_read_set || forced_read) {
if(forced_read) {
if(! in_read_set) {
_dia("baseProxy::handle_cx_read_once[%c]: forced read, NOT in read set", side);
} else {
_deb("baseProxy::handle_cx_read_once[%c]: forced read, but in read set too", side);
}
}
if(! handle_cx_read(side,cx)) {
ret = false;
goto failure;
}
if(cx->com()->forced_write_on_read()) {
_dia("baseProxy::handle_cx_read_once[%c]: write on read enforced on socket %d", side, cx->socket());
if(! handle_cx_write(side, cx, true)) {
ret = false;
goto failure;
}
}
}
} else {
const bool ready = xcom->in_readset(cx->socket());
_dia("baseProxy::handle_cx_read_once[%c]: deferred read in cx with socket %d, in read_set: %s", side, cx->socket(),
ready ? "yes" : "no");
// A deferred level-triggered event (including EPOLLRDHUP) must leave
// the immediate poll set or it will spin until the read is resumed.
// Rescanning removes the descriptor from both current result sets.
// Let an already-delivered write event advance the protocol first;
// the write dispatcher reapplies the read pause afterwards.
if(ready && !xcom->in_writeset(cx->socket())) {
cx->defer_read_readiness();
}
}
// on failure, skip all operations and go here
failure:
// errors are products of operations above. Act on them.
if(not handle_cx_events(side, cx))
ret = false;
return ret;
}
// Iterate vector and set monitoring for each cx->socket() according to ifread (read monitor), and ifwrite (write monitor).
// Tricky one:
// paused_* arguments: 0 - don't change anything pausing
// greater than 0 - pause read or write
// lesser than 0 - unpause read or write
unsigned int baseProxy::change_monitor_for_cx_vec(std::vector<baseHostCX*>* cx_vec, bool ifread, bool ifwrite,
int pause_read, int pause_write,
bool preserve_connection_write) {
unsigned int sockets_changed = 0;
// do reference
if(cx_vec) {
std::vector<baseHostCX *>& nnn = *cx_vec;
for(auto cx: nnn) {
// Pausing reads for backpressure must not discard an independent
// write already queued on the same full-duplex connection. That
// used to remove EPOLLOUT as a side effect and could delay the
// opposite direction until an unrelated event or timer tick.
auto const monitor_write = ifwrite ||
(preserve_connection_write &&
(cx->opening() || !cx->writebuf()->empty() || cx->com()->write_event_pending()));
if(ifread && monitor_write) {
cx->com()->change_monitor(cx->socket(),EPOLLIN|EPOLLOUT);
} else {
if (ifread) {
cx->com()->change_monitor(cx->socket(), EPOLLIN);
} else if (monitor_write) {
cx->com()->change_monitor(cx->socket(), EPOLLOUT);
} else {
cx->com()->unset_monitor(cx->socket());
}
}
if(pause_read != 0) {
cx->read_waiting_for_peercom(pause_read > 0);
}
if(pause_write != 0) {
cx->write_waiting_for_peercom(pause_write > 0);
}
sockets_changed++;
}
}
return sockets_changed;
}
unsigned int baseProxy::change_side_monitoring(unsigned char side, bool ifread, bool ifwrite, int pause_read, int pause_write) {
std::string str_side = "unknown";
std::vector<baseHostCX*>* normal = nullptr;
std::vector<baseHostCX*>* bound = nullptr;
if (side == 'l' || side == 'x') {
str_side = "left";
normal = &ls();
bound = &lbs();
}
if (side == 'r' || side == 'y') {
str_side = "right";
normal = &rs();
bound = &rbs();
}
unsigned int sockets_changed = 0;
if(normal) {
sockets_changed += change_monitor_for_cx_vec(normal,ifread,ifwrite, pause_read, pause_write);
}
if(bound) {
// Listening sockets never carry proxy output. Their `opening` flag is
// not a reason to subscribe to EPOLLOUT (which would stay ready and
// spin the event loop while the peer side is backpressured).
sockets_changed += change_monitor_for_cx_vec(bound,ifread,ifwrite, pause_read, pause_write, false);
}
_inf("side-wide monitor change for side %c|%s [r %d:w %d - pr %d: pw %d]: %d sockets changed.",
side,str_side.c_str(),
ifread, ifwrite,
pause_read, pause_write, sockets_changed);
return sockets_changed;
}
bool baseProxy::handle_cx_write_once(unsigned char side, baseCom* xcom, baseHostCX* cx) {
if(cx->socket() == 0) {
_dia("baseProxy::handle_cx_write_once[%c]: monitored socket changed to zero - terminating.",side);
cx->error(true);
handle_cx_events(side,cx);
return false;
}
if(cx->write_waiting_for_peercom()) {
return handle_cx_events(side,cx);
}
bool in_writeset = xcom->in_writeset(cx->socket());
bool in_force_writeset = cx->com()->forced_write_reset();
bool const write_dispatched = in_writeset || in_force_writeset || !cx->writebuf()->empty();
if(write_dispatched) {
bool side_left = side == 'l' || side == 'L' || side == 'x' || side == 'X';
bool side_right = side == 'r' || side == 'R' || side == 'y' || side == 'Y';
auto orig_bytes_sz = cx->writebuf()->size();
auto pending_bytes_sz = orig_bytes_sz;
// The write handler already owns classification of a fatal write.
// Feeding the same failure through the generic path invokes a
// permanent reconnect callback twice.
if(!handle_cx_write(side, cx)) {
return false;
}
if(cx->error()) {
handle_cx_events(side,cx);
return false;
}
pending_bytes_sz = cx->writebuf()->size();
auto written_sz = orig_bytes_sz - pending_bytes_sz;
if(cx->com()->forced_read_on_write()) {
_dia("baseProxy::handle_cx_write_once[%c]: read on write enforced on socket %d", side, cx->socket());
if(! handle_cx_read(side, cx, true)) {
handle_cx_events(side,cx);
return false;
}
}
// if we wanted to write something, but after write we have some left-overs
if (orig_bytes_sz > 0) {
if (pending_bytes_sz > 0) {
// on bottleneck, we monitor write on this socket to flush buffered data
cx->com()->set_write_monitor(cx->socket());
if (side_left) {
_dia("left write bottleneck %s, written %d, pending %d bytes!", state().write_left_bottleneck() ? "continuing" : "start", written_sz, pending_bytes_sz);
state().write_left_bottleneck(true);
change_side_monitoring('r', false, false, 1, 0);
change_side_monitoring('l', true, true, -1, -1);
} else if (side_right) {
_dia("right write bottleneck %s, written %d, pending %d bytes!", state().write_right_bottleneck() ? "continuing" : "start", written_sz, pending_bytes_sz);
state().write_right_bottleneck(true);
change_side_monitoring('l', false, false, 1, 0);
change_side_monitoring('r', true, true, -1, -1);
}
} else {
if (state().write_left_bottleneck() && side_left) {
_dia("left write bottleneck stop!");
state().write_left_bottleneck(false);
change_side_monitoring('r', true, false, -1, 0); //NOTE: write monitor enable?
} else if (state().write_right_bottleneck() && side_right) {
_dia("right write bottleneck stop!");
state().write_right_bottleneck(false);
change_side_monitoring('l', true, false, -1, 0); //NOTE: write monitor enable?
}
}
}
}
// A write may publish a context message. Dispatch it before changing
// readiness monitoring, since another socket event may never arrive.
if(cx->new_message()) {
return handle_cx_events(side, cx);
}
// Inspect the pause without advancing the peer's transport state machine.
// A completed write must not re-arm a deferred level-triggered read.
bool const read_bottleneck =
((side == 'l' || side == 'x') && state().write_right_bottleneck()) ||
((side == 'r' || side == 'y') && state().write_left_bottleneck());
if(write_dispatched && (cx->read_paused_for_peer() || read_bottleneck)) {
cx->defer_read_readiness();
} else if(cx->read_eof()) {
if((cx->opening() && cx->com()->opening_write_event_pending()) ||
!cx->writebuf()->empty() || cx->com()->write_event_pending()) {
cx->com()->set_write_monitor_only(cx->socket());
} else {
cx->com()->unset_monitor(cx->socket());
}
}
return true;
}
bool baseProxy::handle_sockets_accept(unsigned char side, baseCom* xcom, baseHostCX* thiscx) {
sockaddr_storage clientInfo{};
socklen_t addrlen = sizeof(clientInfo);
int client = com()->accept(thiscx->socket(), (sockaddr*)&clientInfo, &addrlen);
if(client < 0) {
_dia("baseProxy::handle_sockets_accept[%c]: bound socket accept failed: %s", side, string_error(errno).c_str());
// Return false and make proxy reattempt later. Reporting error as the success is always a bad idea.
return false;
}
if(new_raw()) {
_deb("baseProxy::handle_sockets_accept[%c]: raw processing on %d", side, client);
if (side == 'l') { on_left_new_raw(client); }
else if(side == 'r') { on_right_new_raw(client); }
}
else {
auto cx = std::unique_ptr<baseHostCX>(new_cx(client));
if(not cx) {
com()->close(client);
return false;
}
if(!cx->read_waiting_for_peercom()) {
_dia("baseProxy::handle_sockets_accept[%c]: new unpaused socket %d -> accepting", side, client);
cx->on_accept_socket(client);
} else {
_dia("baseProxy::handle_sockets_accept[%c]: new waiting_for_peercom socket %d -> delaying", side, client);
cx->on_delay_socket(client);
}
if (side == 'l') { on_left_new(std::move(cx)); }
else if(side == 'r') { on_right_new(std::move(cx)); }
}
return true;
}
unsigned int baseProxy::handle_sockets_accept_batch(unsigned char side, baseCom* xcom, baseHostCX* thiscx) {
// Drain a ready listener instead of deferring queued connections to later
// poll cycles, but keep a bound so a sustained flood cannot starve other FDs.
// Only stream transports have an accept queue. UDPCom::accept() returns the
// bound socket itself and its raw callback drains the datagram queue, so
// repeating it would only issue empty receive probes.
constexpr unsigned int accept_batch_limit = 256;
auto const batch_limit = com()->master()->l4_proto() == SOCK_STREAM
? accept_batch_limit
: 1U;
unsigned int accepted = 0;
while(accepted < batch_limit && handle_sockets_accept(side, xcom, thiscx)) {
++accepted;
}
return accepted;
}
int baseProxy::handle_sockets_once(baseCom* xcom) {
run_timers();
stats_.last_read = 0;
stats_.last_write = 0;
state().error_on_left_read = false;
state().error_on_left_write = false;
state().error_on_right_read = false;
state().error_on_right_write = false;
if ( xcom->poll_result >= 0) {
// READS
if(! left_sockets.empty() ) {
for (auto i: left_sockets) {
if (!handle_cx_read_once('l', xcom, i)) {
break;
}
}
}
if(! right_sockets.empty() ) {
for (auto i: right_sockets) {
if (!handle_cx_read_once('r', xcom, i)) {
break;
}
}
}
//WRITES
if( ! left_sockets.empty() ) {
for (auto i: left_sockets) {
if (!handle_cx_write_once('l', xcom, i)) {
break;
}
}
}
if( ! right_sockets.empty() ) {
for(auto i: right_sockets) {
if(! handle_cx_write_once('r',xcom, i)) {
break;
}
}
}
// now operate permanent-connect sockets to create accepted sockets
if(! left_pc_cx.empty() ) {
for (auto i: left_pc_cx) {
//READS
// if socket is already in error, don't read, instead just raise again error, if we should reconnect
if (i->error() and i->should_reconnect_now()) {
on_left_pc_error(i);
break;
} else if (i->error()) {
break;
}
if (!handle_cx_read_once('x', xcom, i)) {
handle_last_status |= HANDLE_LEFT_PC_ERROR;
state().error_on_left_read = true;
break;
}
//WRITES
// if socket is already in error, don't read, instead just raise again error, if we should reconnect
if (i->error() and i->should_reconnect_now()) {
on_left_pc_error(i);
break;
} else if (i->error()) {
break;
}
bool const was_opening = i->opening();
if(was_opening && xcom->in_writeset(i->socket()) && i->is_connected()) {
i->opening(false);
}
if (!handle_cx_write_once('x', xcom, i)) {
handle_last_status |= HANDLE_LEFT_PC_ERROR;
state().error_on_left_write = true;
break;
} else if (was_opening && !i->opening()) {
on_left_pc_restore(i);
}
}
}
if(! right_pc_cx.empty() ) {
for (auto i: right_pc_cx) {
// READS
// if socket is already in error, don't read, instead just raise again error, if we should reconnect
if (i->error() and i->should_reconnect_now()) {
on_right_pc_error(i);
break;
} else if (i->error()) {
break;
}
if (!handle_cx_read_once('y', xcom, i)) {
handle_last_status |= HANDLE_RIGHT_PC_ERROR;
state().error_on_right_read = true;
break;
}
// // WRITES
// if socket is already in error, don't read, instead just raise again error, if we should reconnect
if (i->error() and i->should_reconnect_now()) {
on_right_pc_error(i);
break;
} else if (i->error()) {
break;
}
bool const was_opening = i->opening();
if(was_opening && xcom->in_writeset(i->socket()) && i->is_connected()) {
i->opening(false);
}
if (!handle_cx_write_once('y', xcom, i)) {
handle_last_status |= HANDLE_RIGHT_PC_ERROR;
state().error_on_right_write = true;
break;
} else if (was_opening && !i->opening()) {
on_right_pc_restore(i);
}
}
}
// no socket is really ready to be processed; while it make sense to check 'connecting' sockets, it makes
// no sense to loop through bound sockets.
if (xcom->poll_result > 0) {
auto accepted = [xcom] (baseHostCX *p, auto action) -> bool {
if (!p->read_waiting_for_peercom()) {
p->on_accept_socket(p->socket());
action(p);
return true;
}
// Delayed TLS accepts intentionally leave ClientHello queued
// until the origin side is ready. Its readable edge must wake
// the peer's write-driven handshake; EPOLLIN on the origin
// cannot consume bytes which are waiting on this socket.