-
Notifications
You must be signed in to change notification settings - Fork 64
/
Copy pathchannel_io_stream.cpp
executable file
·2013 lines (1658 loc) · 69.2 KB
/
channel_io_stream.cpp
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
/**
* @brief 所有channel文件的模式均为 c + channel<br />
* 使用c的模式是为了简单、结构清晰并且避免异常<br />
* 附带c++的部分是为了避免命名空间污染并且c++的跨平台适配更加简单
*/
#include <assert.h>
#include <stdint.h>
#include <cstddef>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <memory>
#include <vector>
#ifndef _MSC_VER
# include <sys/stat.h>
# include <sys/types.h>
# include <unistd.h>
#endif
#include "detail/libatbus_config.h"
#if defined(ATBUS_MACRO_WITH_UNIX_SOCK) && ATBUS_MACRO_WITH_UNIX_SOCK
# include <sys/socket.h>
# include <sys/un.h>
#endif
#include "common/file_system.h"
#include "common/string_oprs.h"
#include "config/atframe_utils_build_feature.h"
#include "config/compile_optimize.h"
#include "config/compiler_features.h"
#include "algorithm/murmur_hash.h"
#include "detail/buffer.h"
#include "detail/libatbus_channel_export.h"
#include "detail/libatbus_error.h"
#ifdef ATBUS_MACRO_ENABLE_STATIC_ASSERT
# include <detail/libatbus_channel_types.h>
# include <type_traits>
#endif
#define ATBUS_MACRO_TLS_MERGE_BUFFER_LEN (ATBUS_MACRO_MSG_LIMIT - ATBUS_MACRO_DATA_ALIGN_SIZE - sizeof(uv_write_t))
#if !(defined(ATFRAMEWORK_UTILS_THREAD_TLS_USE_PTHREAD) && ATFRAMEWORK_UTILS_THREAD_TLS_USE_PTHREAD) && \
defined(UTIL_CONFIG_THREAD_LOCAL)
namespace atbus {
namespace channel {
namespace detail {
static char *io_stream_get_msg_buffer() {
static UTIL_CONFIG_THREAD_LOCAL char ret[ATBUS_MACRO_TLS_MERGE_BUFFER_LEN];
return ret;
}
} // namespace detail
} // namespace channel
} // namespace atbus
#else
# include <pthread.h>
namespace atbus {
namespace channel {
namespace detail {
static pthread_once_t gt_io_stream_get_msg_buffer_tls_once = PTHREAD_ONCE_INIT;
static pthread_key_t gt_io_stream_get_msg_buffer_tls_key;
static void dtor_pthread_io_stream_get_msg_buffer_tls(void *p) {
char *res = reinterpret_cast<char *>(p);
if (nullptr != res) {
delete[] res;
}
}
static void init_pthread_io_stream_get_msg_buffer_tls() {
(void)pthread_key_create(>_io_stream_get_msg_buffer_tls_key, dtor_pthread_io_stream_get_msg_buffer_tls);
}
static char *io_stream_get_msg_buffer() {
(void)pthread_once(>_io_stream_get_msg_buffer_tls_once, init_pthread_io_stream_get_msg_buffer_tls);
char *ret = reinterpret_cast<char *>(pthread_getspecific(gt_io_stream_get_msg_buffer_tls_key));
if (nullptr == ret) {
ret = new char[ATBUS_MACRO_TLS_MERGE_BUFFER_LEN];
pthread_setspecific(gt_io_stream_get_msg_buffer_tls_key, ret);
}
return ret;
}
struct gt_io_stream_get_msg_buffer_tls_main_thread_dtor_t {
char *buffer_ptr;
gt_io_stream_get_msg_buffer_tls_main_thread_dtor_t() { buffer_ptr = io_stream_get_msg_buffer(); }
~gt_io_stream_get_msg_buffer_tls_main_thread_dtor_t() {
pthread_setspecific(gt_io_stream_get_msg_buffer_tls_key, nullptr);
dtor_pthread_io_stream_get_msg_buffer_tls(buffer_ptr);
}
};
static gt_io_stream_get_msg_buffer_tls_main_thread_dtor_t gt_io_stream_get_msg_buffer_tls_main_thread_dtor;
} // namespace detail
} // namespace channel
} // namespace atbus
#endif
namespace atbus {
namespace channel {
#ifdef ATBUS_MACRO_ENABLE_STATIC_ASSERT
# if ((defined(_MSVC_LANG) && _MSVC_LANG >= 201402L)) || \
(defined(__cplusplus) && __cplusplus >= 201402L && \
!(!defined(__clang__) && defined(__GNUC__) && defined(__GNUC_MINOR__) && \
__GNUC__ * 100 + __GNUC_MINOR__ <= 409))
static_assert(std::is_trivially_copyable<io_stream_conf>::value, "io_stream_conf should be trivially copyable");
# elif (defined(__cplusplus) && __cplusplus >= 201103L) || ((defined(_MSVC_LANG) && _MSVC_LANG >= 201103L))
static_assert(std::is_trivial<io_stream_conf>::value, "io_stream_conf should be trivially");
# else
static_assert(std::is_pod<io_stream_conf>::value, "io_stream_conf should be a pod type");
# endif
static_assert(io_stream_channel::EN_CF_MAX <= sizeof(int) * 8,
"io_stream_channel::flag_t should has no more bits than io_stream_channel::flags");
#endif
namespace {
union io_stream_sockaddr_switcher {
sockaddr base;
sockaddr_in ipv4;
sockaddr_in6 ipv6;
};
struct UTIL_SYMBOL_LOCAL io_stream_flag_guard {
int *flags;
int watch;
bool is_active;
io_stream_flag_guard(int &f, int v) : flags(&f), watch(v) {
if (ATBUS_CHANNEL_IOS_CHECK_FLAG(*flags, watch)) {
is_active = false;
} else {
ATBUS_CHANNEL_IOS_SET_FLAG(*flags, watch);
is_active = true;
}
}
~io_stream_flag_guard() {
if (is_active) {
ATBUS_CHANNEL_IOS_UNSET_FLAG(*flags, watch);
}
}
io_stream_flag_guard(const io_stream_flag_guard &other);
io_stream_flag_guard &operator=(const io_stream_flag_guard &other);
};
static int io_stream_disconnect_internal(io_stream_channel *channel, io_stream_connection *connection,
io_stream_callback_t callback, bool force);
static inline void io_stream_channel_callback(io_stream_callback_evt_t::mem_fn_t fn, io_stream_channel *channel,
io_stream_callback_t async_callback, io_stream_connection *connection,
int status, int errcode, void *priv_data, size_t s) {
if (nullptr != channel) {
channel->error_code = status;
}
if (nullptr != channel && nullptr != channel->evt.callbacks[fn]) {
channel->evt.callbacks[fn](channel, connection, errcode, priv_data, s);
}
if (nullptr != async_callback) {
async_callback(channel, connection, errcode, priv_data, s);
}
}
static inline void io_stream_channel_callback(io_stream_callback_evt_t::mem_fn_t fn, io_stream_channel *channel,
io_stream_connection *conn_evt, io_stream_connection *connection,
int status, int errcode, void *priv_data, size_t s) {
io_stream_callback_t async_callback =
(nullptr != conn_evt && nullptr != conn_evt->evt.callbacks[fn]) ? conn_evt->evt.callbacks[fn] : nullptr;
io_stream_channel_callback(fn, channel, async_callback, connection, status, errcode, priv_data, s);
}
static inline void io_stream_channel_callback(io_stream_callback_evt_t::mem_fn_t fn, io_stream_channel *channel,
io_stream_connection *connection, int status, int errcode,
void *priv_data, size_t s) {
io_stream_channel_callback(fn, channel, connection, connection, status, errcode, priv_data, s);
}
struct UTIL_SYMBOL_LOCAL io_stream_connect_async_data {
uv_connect_t req;
channel_address_t addr;
io_stream_channel *channel;
io_stream_callback_t callback;
std::shared_ptr<adapter::stream_t> stream;
bool pipe;
void *priv_data;
size_t priv_size;
};
// listen 接口传入域名时的回调异步数据
struct UTIL_SYMBOL_LOCAL io_stream_dns_async_data {
io_stream_channel *channel;
channel_address_t addr;
io_stream_callback_t callback;
uv_getaddrinfo_t req;
void *priv_data;
size_t priv_size;
};
struct UTIL_SYMBOL_LOCAL io_stream_handle_private_data {
io_stream_connection *connection = nullptr;
std::shared_ptr<adapter::stream_t> stream_lifetime;
std::unique_ptr<io_stream_connect_async_data> connect_async_lifetime;
inline io_stream_handle_private_data() noexcept {}
};
template <class HandleType>
static io_stream_handle_private_data *io_stream_handle_get_private_data_internal(HandleType *handle) {
if (nullptr == handle) {
return nullptr;
}
return reinterpret_cast<io_stream_handle_private_data *>(handle->data);
}
static io_stream_handle_private_data *io_stream_handle_get_private_data(adapter::handle_t *handle) {
return io_stream_handle_get_private_data_internal(handle);
}
static void io_stream_handle_remove_private_data(adapter::handle_t *handle) {
if (nullptr == handle) {
return;
}
if (nullptr == handle->data) {
return;
}
io_stream_handle_private_data *private_data = reinterpret_cast<io_stream_handle_private_data *>(handle->data);
handle->data = nullptr;
delete private_data;
}
template <class HandleType>
static io_stream_handle_private_data *io_stream_handle_mutable_private_data_internal(HandleType *handle) {
if (nullptr == handle) {
return nullptr;
}
if (nullptr != handle->data) {
return reinterpret_cast<io_stream_handle_private_data *>(handle->data);
}
io_stream_handle_private_data *ret = new io_stream_handle_private_data();
if (nullptr == ret) {
return nullptr;
}
handle->data = reinterpret_cast<void *>(ret);
return ret;
}
static io_stream_handle_private_data *io_stream_handle_mutable_private_data(adapter::stream_t *handle) {
return io_stream_handle_mutable_private_data_internal(handle);
}
static bool io_stream_handle_set_connection(adapter::stream_t *handle, io_stream_connection *conn) {
io_stream_handle_private_data *private_data = io_stream_handle_mutable_private_data(handle);
if (nullptr == private_data) {
return false;
}
private_data->connection = conn;
return true;
}
static bool io_stream_handle_set_connection(uv_write_t *req, io_stream_connection *conn) {
if (nullptr == req) {
return false;
}
req->data = conn;
return true;
}
static io_stream_connection *io_stream_handle_get_connection(adapter::handle_t *handle) {
io_stream_handle_private_data *private_data = io_stream_handle_get_private_data(handle);
if (nullptr == private_data) {
return nullptr;
}
return private_data->connection;
}
static io_stream_connection *io_stream_handle_get_connection(adapter::stream_t *handle) {
io_stream_handle_private_data *private_data = io_stream_handle_mutable_private_data(handle);
if (nullptr == private_data) {
return nullptr;
}
return private_data->connection;
}
static io_stream_connection *io_stream_handle_get_connection(uv_write_t *req) {
if (nullptr == req) {
return nullptr;
}
return reinterpret_cast<io_stream_connection *>(req->data);
}
} // namespace
void io_stream_init_configure(io_stream_conf *conf) {
if (nullptr == conf) {
return;
}
conf->keepalive = 60;
conf->is_noblock = true;
conf->is_nodelay = true;
conf->send_buffer_static = 0; // 默认动态缓冲区
conf->recv_buffer_static = 0; // 默认动态缓冲区
conf->send_buffer_max_size = 0;
conf->send_buffer_limit_size =
ATBUS_MACRO_MSG_LIMIT +
::atbus::detail::buffer_block::padding_size(sizeof(uv_write_t) + sizeof(uint32_t) + 16); // 预留header长度
conf->recv_buffer_max_size =
ATBUS_MACRO_MSG_LIMIT * 2; // 最大接收缓冲区2个最大包体够了,一般一个正在处理的和一个正在接收的
conf->recv_buffer_limit_size = ATBUS_MACRO_MSG_LIMIT;
conf->backlog = ATBUS_MACRO_CONNECTION_BACKLOG;
conf->confirm_timeout = 10;
conf->max_read_net_eagain_count = 256;
conf->max_read_check_block_size_failed_count = 10;
conf->max_read_check_hash_failed_count = 10;
}
static adapter::loop_t *io_stream_get_loop(io_stream_channel *channel) {
if (nullptr == channel) {
return nullptr;
}
if (nullptr == channel->ev_loop) {
channel->ev_loop = reinterpret_cast<adapter::loop_t *>(malloc(sizeof(adapter::loop_t)));
if (nullptr != channel->ev_loop) {
uv_loop_init(channel->ev_loop);
ATBUS_CHANNEL_IOS_SET_FLAG(channel->flags, io_stream_channel::EN_CF_IS_LOOP_OWNER);
}
}
return channel->ev_loop;
}
int io_stream_init(io_stream_channel *channel, adapter::loop_t *ev_loop, const io_stream_conf *conf) {
if (nullptr == channel) {
return EN_ATBUS_ERR_PARAMS;
}
if (nullptr == conf) {
io_stream_conf default_conf;
io_stream_init_configure(&default_conf);
return io_stream_init(channel, ev_loop, &default_conf);
}
channel->conf = *conf;
channel->ev_loop = ev_loop;
ATBUS_CHANNEL_IOS_CLEAR_FLAG(channel->flags);
memset(channel->evt.callbacks, 0, sizeof(channel->evt.callbacks));
channel->error_code = 0;
channel->read_net_eagain_count = 0;
channel->read_check_block_size_failed_count = 0;
channel->read_check_hash_failed_count = 0;
return EN_ATBUS_ERR_SUCCESS;
}
int io_stream_close(io_stream_channel *channel) {
if (nullptr == channel) {
return EN_ATBUS_ERR_PARAMS;
}
io_stream_flag_guard flag_guard(channel->flags, io_stream_channel::EN_CF_CLOSING);
// 不允许在回调中关闭
if (ATBUS_CHANNEL_IOS_CHECK_FLAG(channel->flags, io_stream_channel::EN_CF_IN_CALLBACK)) {
abort();
}
// 释放所有连接
{
std::vector<io_stream_connection *> pending_release;
pending_release.reserve(channel->conn_pool.size());
for (io_stream_channel::conn_pool_t::iterator iter = channel->conn_pool.begin(); iter != channel->conn_pool.end();
++iter) {
pending_release.push_back(iter->second.get());
}
for (size_t i = 0; i < pending_release.size(); ++i) {
io_stream_disconnect(channel, pending_release[i], nullptr);
}
}
// 必须保证这个接口过后channel内的数据可以正常释放
// 所以必须等待相关的回调全部完成
// 当然也可以用另一种方法强行结束掉所有req,但是这样会造成丢失回调
// 并且这会要求逻辑层设计相当完善,否则可能导致内存泄漏。所以为了简化逻辑层设计,还是block并销毁所有数据
if (ATBUS_CHANNEL_IOS_CHECK_FLAG(channel->flags, io_stream_channel::EN_CF_IS_LOOP_OWNER) &&
nullptr != channel->ev_loop) {
// 先清理掉所有可以完成的事件
while (uv_run(channel->ev_loop, UV_RUN_NOWAIT)) {
uv_run(channel->ev_loop, UV_RUN_ONCE);
}
// 停止时阻塞操作,保证资源正常释放
while (UV_EBUSY == uv_loop_close(channel->ev_loop)) {
uv_run(channel->ev_loop, UV_RUN_ONCE);
}
free(channel->ev_loop);
} else {
// both connection and pending gc connection should all be erased
while (!channel->conn_pool.empty() || !channel->conn_gc_pool.empty()) {
uv_run(channel->ev_loop, UV_RUN_ONCE);
}
// 必须等待所有pending的request完成
// 不能简单地用uv_loop_t的active状态判定,因为可能内部会维护uv_async_t来
while (ATBUS_CHANNEL_REQ_ACTIVE(channel)) {
uv_run(channel->ev_loop, UV_RUN_ONCE);
}
}
channel->ev_loop = nullptr;
return EN_ATBUS_ERR_SUCCESS;
}
int io_stream_run(io_stream_channel *channel, adapter::run_mode_t mode) {
if (nullptr == channel) {
return EN_ATBUS_ERR_PARAMS;
}
channel->error_code = uv_run(io_stream_get_loop(channel), static_cast<uv_run_mode>(mode));
if (0 != channel->error_code) {
return EN_ATBUS_ERR_EV_RUN;
}
return EN_ATBUS_ERR_SUCCESS;
}
static void io_stream_on_recv_alloc_fn(uv_handle_t *handle, size_t /*suggested_size*/, uv_buf_t *buf) {
assert(handle);
if (nullptr == handle) {
return;
}
io_stream_connection *conn_raw_ptr = io_stream_handle_get_connection(handle);
assert(conn_raw_ptr && conn_raw_ptr->channel);
if (nullptr == conn_raw_ptr->channel) {
return;
}
io_stream_flag_guard flag_guard(conn_raw_ptr->channel->flags, io_stream_channel::EN_CF_IN_CALLBACK);
// 如果正处于关闭阶段,忽略所有数据
if (io_stream_connection::EN_ST_CONNECTED != conn_raw_ptr->status) {
buf->base = nullptr;
buf->len = 0;
return;
}
void *data = nullptr;
size_t sread = 0, swrite = 0;
conn_raw_ptr->read_buffers.back(data, sread, swrite);
// 正在读取vint时,指定缓冲区为head内存块
if (nullptr == data || 0 == swrite) {
buf->len = static_cast<decltype(buf->len)>(sizeof(conn_raw_ptr->read_head.buffer) - conn_raw_ptr->read_head.len);
if (0 == buf->len) {
// 理论上这里不会走到,因为如果必然会先收取一次header的大小,这时候已经可以解出msg的大小
// 如果msg超过限制大小并低于缓冲区大小,则会发出大小错误回调并会减少header的占用量,
// 那么下一次这个回调函数调用时buf->len必然大于0
// 如果msg超过缓冲区大小,则会出错回调并立即断开连接,不会再有下一次调用
buf->base = nullptr;
} else {
buf->base = &conn_raw_ptr->read_head.buffer[conn_raw_ptr->read_head.len];
}
return;
}
// 否则指定为大内存块缓冲区
buf->base = reinterpret_cast<char *>(data);
buf->len = static_cast<decltype(buf->len)>(swrite);
}
static void io_stream_on_recv_read_fn(uv_stream_t *stream, ssize_t nread, const uv_buf_t * /*buf*/) {
io_stream_connection *conn_raw_ptr = io_stream_handle_get_connection(stream);
assert(conn_raw_ptr);
io_stream_channel *channel = conn_raw_ptr->channel;
assert(channel);
io_stream_flag_guard flag_guard(channel->flags, io_stream_channel::EN_CF_IN_CALLBACK);
// 如果正处于关闭阶段,忽略所有数据
if (io_stream_connection::EN_ST_CONNECTED != conn_raw_ptr->status) {
uv_read_stop(conn_raw_ptr->handle.get());
return;
}
// 读取完或EAGAIN或signal中断,直接忽略即可
if (0 == nread || UV_EAGAIN == nread || UV_EAI_AGAIN == nread || UV_EINTR == nread) {
++channel->read_net_eagain_count;
if (channel->read_net_eagain_count > channel->conf.max_read_net_eagain_count) {
// eagain for too many times, just close
io_stream_disconnect(channel, conn_raw_ptr, nullptr);
}
return;
}
// 网络错误
if (nread < 0) {
io_stream_channel_callback(io_stream_callback_evt_t::EN_FN_RECVED, channel, conn_raw_ptr, static_cast<int>(nread),
EN_ATBUS_ERR_READ_FAILED, nullptr, 0);
// 任何非重试的错误则关闭
// 注意libuv有个特殊的错误码 UV_ENOBUFS 表示缓冲区不足
// 理论上除非配置错误,否则不应该会出现,并且可能会导致header数据无法缩减。所以也直接关闭连接
io_stream_disconnect_internal(channel, conn_raw_ptr, nullptr, nread == UV_ECONNRESET);
return;
}
void *data = nullptr;
size_t sread = 0, swrite = 0;
conn_raw_ptr->read_buffers.back(data, sread, swrite);
bool is_free = false;
// head 阶段
if (nullptr == data || 0 == swrite) {
assert(static_cast<size_t>(nread) <= sizeof(conn_raw_ptr->read_head.buffer) - conn_raw_ptr->read_head.len);
conn_raw_ptr->read_head.len += static_cast<size_t>(nread); // 写数据计数
// 尝试解出所有的head数据
char *buff_start = conn_raw_ptr->read_head.buffer;
size_t buff_left_len = conn_raw_ptr->read_head.len;
// 可能包含多条消息
while (buff_left_len > sizeof(uint32_t)) {
uint64_t msg_len = 0;
// 前4 字节为32位hash
size_t vint_len =
::atbus::detail::fn::read_vint(msg_len, buff_start + sizeof(uint32_t), buff_left_len - sizeof(uint32_t));
// 剩余数据不足以解动态长度整数,直接中断退出
if (0 == vint_len) {
break;
}
// 如果读取vint成功,判定是否有小数据包。并对小数据包直接回调
if (buff_left_len >= sizeof(uint32_t) + vint_len + msg_len) {
channel->error_code = 0;
uint32_t check_hash = atfw::util::hash::murmur_hash3_x86_32(buff_start + sizeof(uint32_t) + vint_len,
static_cast<int>(msg_len), 0);
uint32_t expect_hash;
memcpy(&expect_hash, buff_start, sizeof(uint32_t));
int errcode = EN_ATBUS_ERR_SUCCESS;
if (check_hash != expect_hash) {
errcode = EN_ATBUS_ERR_BAD_DATA;
++channel->read_check_hash_failed_count;
if (channel->read_check_hash_failed_count > channel->conf.max_read_check_hash_failed_count) {
is_free = true;
}
} else if (channel->conf.recv_buffer_limit_size > 0 && msg_len > channel->conf.recv_buffer_limit_size) {
errcode = EN_ATBUS_ERR_INVALID_SIZE;
++channel->read_check_block_size_failed_count;
if (channel->read_check_block_size_failed_count > channel->conf.max_read_check_block_size_failed_count) {
is_free = true;
}
}
io_stream_channel_callback(io_stream_callback_evt_t::EN_FN_RECVED, channel, conn_raw_ptr, 0, errcode,
buff_start + sizeof(uint32_t) + vint_len,
// 这里的地址未对齐,所以buffer不能直接保存内存数据
msg_len);
// 32bits hash+vint+buffer
buff_start += sizeof(uint32_t) + vint_len + msg_len;
buff_left_len -= sizeof(uint32_t) + vint_len + msg_len;
} else {
// 大数据包,使用缓冲区,并且剩余数据一定是在一个包内
// 32位hash 也暂存在这里
if (EN_ATBUS_ERR_SUCCESS == conn_raw_ptr->read_buffers.push_back(data, sizeof(uint32_t) + msg_len)) {
memcpy(data, buff_start, sizeof(uint32_t)); // 32位hash
memcpy(reinterpret_cast<char *>(data) + sizeof(uint32_t), buff_start + sizeof(uint32_t) + vint_len,
buff_left_len - sizeof(uint32_t) - vint_len);
conn_raw_ptr->read_buffers.pop_back(buff_left_len - vint_len, false); // vint_len不用保存
buff_start += buff_left_len;
buff_left_len = 0; // 循环退出
} else {
// 追加大缓冲区失败,可能是到达缓冲区限制
// 读缓冲区一般只有一个正在处理的数据包,如果发生创建失败则是数据错误或者这个包就是超出大小限制的
is_free = true;
buff_start += sizeof(uint32_t) + vint_len;
buff_left_len -= sizeof(uint32_t) + vint_len;
++channel->read_check_block_size_failed_count;
break;
}
}
}
// 后续数据前移
if (buff_start != conn_raw_ptr->read_head.buffer && buff_left_len > 0) {
memmove(conn_raw_ptr->read_head.buffer, buff_start, buff_left_len);
}
conn_raw_ptr->read_head.len = buff_left_len;
} else {
size_t nread_s = static_cast<size_t>(nread);
assert(nread_s <= swrite);
// 写数据计数,但不释放缓冲区
conn_raw_ptr->read_buffers.pop_back(nread_s, false);
}
// 如果在大内存块缓冲区,判定回调
conn_raw_ptr->read_buffers.front(data, sread, swrite);
if (nullptr != data && 0 == swrite) {
channel->error_code = 0;
data = ::atbus::detail::fn::buffer_prev(data, sread);
// 32位Hash校验和
uint32_t check_hash = atfw::util::hash::murmur_hash3_x86_32(reinterpret_cast<char *>(data) + sizeof(uint32_t),
static_cast<int>(sread - sizeof(uint32_t)), 0);
uint32_t expect_hash;
memcpy(&expect_hash, data, sizeof(uint32_t));
size_t msg_len = sread - sizeof(uint32_t); // - hash32 header
int errcode = EN_ATBUS_ERR_SUCCESS;
if (check_hash != expect_hash) {
errcode = EN_ATBUS_ERR_BAD_DATA;
++channel->read_check_hash_failed_count;
if (channel->read_check_hash_failed_count > channel->conf.max_read_check_hash_failed_count) {
is_free = true;
}
} else if (channel->conf.recv_buffer_limit_size > 0 && msg_len > channel->conf.recv_buffer_limit_size) {
errcode = EN_ATBUS_ERR_INVALID_SIZE;
++channel->read_check_block_size_failed_count;
if (channel->read_check_block_size_failed_count > channel->conf.max_read_check_block_size_failed_count) {
is_free = true;
}
}
io_stream_channel_callback(io_stream_callback_evt_t::EN_FN_RECVED, channel, conn_raw_ptr, 0, errcode,
reinterpret_cast<char *>(data) + sizeof(uint32_t), // + hash32 header
// 由于buffer_block内取出的数据已经保证了字节对齐,所以这里一定是4字节对齐
msg_len);
// 回调并释放缓冲区
conn_raw_ptr->read_buffers.pop_front(0, true);
}
if (is_free) {
if (conn_raw_ptr->read_head.len > 0) {
io_stream_channel_callback(io_stream_callback_evt_t::EN_FN_RECVED, channel, conn_raw_ptr, 0,
EN_ATBUS_ERR_INVALID_SIZE, conn_raw_ptr->read_head.buffer,
// 由于buffer_block内取出的数据已经保证了字节对齐,所以这里一定是4字节对齐
conn_raw_ptr->read_head.len);
}
// 强制中断
io_stream_disconnect(channel, conn_raw_ptr, nullptr);
}
}
static void io_stream_stream_init(io_stream_channel *channel, io_stream_connection *conn, adapter::stream_t *handle) {
if (nullptr == channel || nullptr == handle) {
return;
}
io_stream_handle_set_connection(handle, conn);
}
static void io_stream_tcp_init(io_stream_channel *channel, io_stream_connection *conn, adapter::tcp_t *handle) {
if (nullptr == channel || nullptr == handle) {
return;
}
io_stream_stream_init(channel, conn, reinterpret_cast<adapter::stream_t *>(handle));
}
static void io_stream_pipe_init(io_stream_channel *channel, io_stream_connection *conn, adapter::pipe_t *handle) {
if (nullptr == channel || nullptr == handle) {
return;
}
io_stream_stream_init(channel, conn, reinterpret_cast<adapter::stream_t *>(handle));
}
static void io_stream_stream_setup(io_stream_channel *channel, adapter::stream_t *handle) {
if (nullptr == channel || nullptr == handle) {
return;
}
uv_stream_set_blocking(handle, channel->conf.is_noblock ? 0 : 1);
}
static void io_stream_tcp_setup(io_stream_channel *channel, adapter::tcp_t *handle) {
if (nullptr == channel || nullptr == handle) {
return;
}
if (channel->conf.keepalive > 0) {
uv_tcp_keepalive(handle, 1, static_cast<unsigned int>(channel->conf.keepalive));
} else {
uv_tcp_keepalive(handle, 0, 0);
}
uv_tcp_nodelay(handle, channel->conf.is_nodelay ? 1 : 0);
#ifndef _WIN32
io_stream_stream_setup(channel, reinterpret_cast<adapter::stream_t *>(handle));
#endif
}
static void io_stream_pipe_setup(io_stream_channel *channel, adapter::pipe_t *handle) {
if (nullptr == channel || nullptr == handle) {
return;
}
io_stream_stream_setup(channel, reinterpret_cast<adapter::stream_t *>(handle));
}
static void io_stream_handle_on_close(uv_handle_t *handle) {
io_stream_connection *conn_raw_ptr = io_stream_handle_get_connection(handle);
// connect not completed, directly exit
if (nullptr == conn_raw_ptr) {
io_stream_handle_remove_private_data(handle);
return;
}
io_stream_channel *channel = conn_raw_ptr->channel;
assert(channel);
// 被动断开也会触发回调,这里的流程不计数active的req
if (nullptr == channel) {
io_stream_handle_remove_private_data(handle);
return;
}
io_stream_flag_guard flag_guard(channel->flags, io_stream_channel::EN_CF_IN_CALLBACK);
io_stream_channel::conn_gc_pool_t::iterator iter =
channel->conn_gc_pool.find(reinterpret_cast<uintptr_t>(conn_raw_ptr));
assert(iter != channel->conn_gc_pool.end());
iter->second->status = io_stream_connection::EN_ST_DISCONNECTED;
io_stream_channel_callback(io_stream_callback_evt_t::EN_FN_DISCONNECTED, channel, iter->second.get(), 0,
EN_ATBUS_ERR_SUCCESS, nullptr, 0);
if (nullptr != conn_raw_ptr->act_disc_cbk) {
conn_raw_ptr->act_disc_cbk(channel, conn_raw_ptr, EN_ATBUS_ERR_SUCCESS, nullptr, 0);
}
io_stream_handle_remove_private_data(handle);
channel->conn_gc_pool.erase(iter);
}
static void io_stream_handle_on_shutdown(uv_shutdown_t *req, int /*status*/) {
assert(req);
uv_close(reinterpret_cast<uv_handle_t *>(req->handle), io_stream_handle_on_close);
delete req;
}
// 删除函数,stream绑定在connection上
static int io_stream_shutdown_connection(io_stream_connection *conn) {
assert(conn && conn->handle);
assert(conn->channel);
// move to gc pool
if (conn && conn->channel) {
io_stream_channel::conn_pool_t::iterator iter = conn->channel->conn_pool.find(conn->fd);
assert(iter != conn->channel->conn_pool.end());
conn->channel->conn_gc_pool[reinterpret_cast<uintptr_t>(conn)] = iter->second;
conn->channel->conn_pool.erase(iter);
}
// ATBUS_CHANNEL_REQ_START(conn->channel);
// 被动断开也会触发回调,这里的流程不计数active的req
do {
if (0 == uv_is_writable(conn->handle.get())) {
break;
}
adapter::shutdown_t *shutdown_request = new adapter::shutdown_t();
if (nullptr == shutdown_request) {
break;
}
shutdown_request->data = nullptr;
if (0 != uv_shutdown(shutdown_request, conn->handle.get(), io_stream_handle_on_shutdown)) {
break;
}
return 0;
} while (false);
uv_close(reinterpret_cast<uv_handle_t *>(conn->handle.get()), io_stream_handle_on_close);
return 0;
}
// 删除函数,stream绑定在io_stream_connect_async_data上
static int io_stream_shutdown_async_data(io_stream_connect_async_data *async_data) {
assert(async_data && async_data->stream);
if (async_data && !async_data->stream) {
delete async_data;
return 0;
}
io_stream_handle_private_data *private_data = io_stream_handle_mutable_private_data(async_data->stream.get());
assert(private_data);
private_data->connect_async_lifetime.reset(async_data);
// 这里channel可能已经无效了
do {
if (0 == uv_is_writable(async_data->stream.get())) {
break;
}
adapter::shutdown_t *shutdown_request = new adapter::shutdown_t();
if (nullptr == shutdown_request) {
break;
}
shutdown_request->data = nullptr;
if (0 != uv_shutdown(shutdown_request, async_data->stream.get(), io_stream_handle_on_shutdown)) {
delete shutdown_request;
break;
}
return 0;
} while (false);
uv_close(reinterpret_cast<uv_handle_t *>(async_data->stream.get()), io_stream_handle_on_close);
return 0;
}
// 删除函数,stream绑定在shared_ptr上
static int io_stream_shutdown_ev_handle(std::shared_ptr<adapter::stream_t> &stream) {
io_stream_handle_private_data *private_data = io_stream_handle_mutable_private_data(stream.get());
assert(private_data);
private_data->stream_lifetime = stream;
do {
if (0 == uv_is_writable(stream.get())) {
break;
}
uv_shutdown_t *shutdown_request = new uv_shutdown_t();
if (nullptr == shutdown_request) {
break;
}
shutdown_request->data = nullptr;
if (0 != uv_shutdown(shutdown_request, stream.get(), io_stream_handle_on_shutdown)) {
delete shutdown_request;
break;
}
return 0;
} while (false);
// 这里channel可能已经无效了
uv_close(reinterpret_cast<uv_handle_t *>(stream.get()), io_stream_handle_on_close);
return 0;
}
static std::shared_ptr<io_stream_connection> io_stream_make_connection(io_stream_channel *channel,
std::shared_ptr<adapter::stream_t> handle) {
std::shared_ptr<io_stream_connection> ret;
if (nullptr == channel) {
return ret;
}
ret = std::make_shared<io_stream_connection>();
if (!ret) {
return ret;
}
if (0 != uv_fileno(reinterpret_cast<const uv_handle_t *>(handle.get()), &ret->fd)) {
ret.reset();
return ret;
}
ret->handle = handle;
ret->data = nullptr;
ATBUS_CHANNEL_IOS_CLEAR_FLAG(ret->flags);
io_stream_handle_set_connection(handle.get(), ret.get());
memset(ret->evt.callbacks, 0, sizeof(ret->evt.callbacks));
ret->act_disc_cbk = nullptr;
ret->status = io_stream_connection::EN_ST_CREATED;
ret->read_buffers.set_limit(channel->conf.recv_buffer_max_size, 0);
if (channel->conf.recv_buffer_max_size > 0 && channel->conf.recv_buffer_static > 0) {
ret->read_buffers.set_mode(channel->conf.recv_buffer_max_size, channel->conf.recv_buffer_static);
}
ret->read_head.len = 0;
ret->write_buffers.set_limit(channel->conf.send_buffer_max_size, 0);
if (channel->conf.send_buffer_max_size > 0 && channel->conf.send_buffer_static > 0) {
ret->write_buffers.set_mode(channel->conf.send_buffer_max_size, channel->conf.send_buffer_static);
}
channel->conn_pool[ret->fd] = ret;
ret->channel = channel;
// 监听关闭事件,用于释放资源
handle->close_cb = io_stream_handle_on_close;
// 监听可读事件
uv_read_start(handle.get(), io_stream_on_recv_alloc_fn, io_stream_on_recv_read_fn);
return ret;
}
// ============ C Style转C++ Style内存管理 ============
template <typename T>
static void io_stream_delete_stream_fn(adapter::stream_t *handle) {
T *real_conn = reinterpret_cast<T *>(handle);
// 到这里必须已经释放handle了,否则删除hanlde会导致数据异常。
assert(uv_is_closing(reinterpret_cast<adapter::handle_t *>(handle)));
// 保底再检查一次数据清理
io_stream_handle_remove_private_data(reinterpret_cast<adapter::handle_t *>(handle));
delete real_conn;
}
template <typename T>
static T *io_stream_make_stream_ptr(std::shared_ptr<adapter::stream_t> &res) {
T *real_conn = new T();
adapter::stream_t *stream_conn = reinterpret_cast<adapter::stream_t *>(real_conn);
res = std::shared_ptr<adapter::stream_t>(stream_conn, io_stream_delete_stream_fn<T>);
stream_conn->data = nullptr;
return real_conn;
}
// tcp 收到连接通用逻辑
static adapter::tcp_t *io_stream_tcp_connection_common(std::shared_ptr<io_stream_connection> &conn,
std::shared_ptr<adapter::stream_t> &recv_conn, uv_stream_t *req,
int &status) {
io_stream_connection *conn_raw_ptr = io_stream_handle_get_connection(req);
assert(conn_raw_ptr);
io_stream_channel *channel = conn_raw_ptr->channel;
assert(channel);
if (0 != status) {
return nullptr;
}
adapter::tcp_t *tcp_conn = io_stream_make_stream_ptr<adapter::tcp_t>(recv_conn);
if (nullptr == tcp_conn) {
return nullptr;
}
uv_tcp_init(req->loop, tcp_conn);
if (0 != (channel->error_code = uv_accept(req, recv_conn.get()))) {
status = channel->error_code;
return nullptr;
}
// 正在关闭,新连接直接断开,要在accept后执行,以保证连接会被正确断开
if (ATBUS_CHANNEL_IOS_CHECK_FLAG(channel->flags, io_stream_channel::EN_CF_CLOSING)) {
return nullptr;
}
conn = io_stream_make_connection(channel, recv_conn);
if (!conn) {
return nullptr;
}
// 后面不会再失败了
io_stream_tcp_setup(channel, tcp_conn);
io_stream_tcp_init(channel, conn.get(), tcp_conn);
return tcp_conn;
}
// tcp/ip 收到连接
static void io_stream_tcp_connection_cb(uv_stream_t *req, int status) {
io_stream_connection *conn_raw_ptr = io_stream_handle_get_connection(req);
assert(conn_raw_ptr);
io_stream_channel *channel = conn_raw_ptr->channel;
assert(channel);
io_stream_flag_guard flag_guard(channel->flags, io_stream_channel::EN_CF_IN_CALLBACK);
channel->error_code = status;
int res = EN_ATBUS_ERR_SUCCESS;