-
Notifications
You must be signed in to change notification settings - Fork 104
Expand file tree
/
Copy pathproxy_server.cpp
More file actions
2190 lines (1814 loc) · 55.5 KB
/
Copy pathproxy_server.cpp
File metadata and controls
2190 lines (1814 loc) · 55.5 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
//
// proxy_server.cpp
// ~~~~~~~~~~~~~~~~
//
// Copyright (c) 2019 Jack (jack dot wgm at gmail dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#include "proxy/proxy_server.hpp"
#include "proxy/proxy_util.hpp"
#include "proxy/strutil.hpp"
#include <boost/functional/hash.hpp>
namespace proxy {
//////////////////////////////////////////////////////////////////////////
proxy_server::proxy_server(net::any_io_executor executor, proxy_server_option opt)
: m_executor(executor)
, m_option(std::move(opt))
, m_timer(executor)
{
if (!m_option.stdio_target_.empty())
return;
m_certificates.store(&m_certificate_master);
init_ssl_context();
boost::system::error_code ec;
if (fs::exists(m_option.ipip_db_, ec))
{
try {
m_ipdb = std::make_unique<ip_ipdb>();
if (!m_ipdb->load(m_option.ipip_db_))
{
m_ipdb = std::make_unique<ip_datx>();
if (!m_ipdb->load(m_option.ipip_db_))
m_ipdb.reset();
}
} catch (const std::exception& e) {
XLOG_WARN << "ipip database " << m_option.ipip_db_ << ", load error: " << e.what();
}
}
init_acceptor();
}
std::shared_ptr<proxy_server>
proxy_server::make(net::any_io_executor executor, proxy_server_option opt)
{
return std::shared_ptr<proxy_server>(new
proxy_server(executor, opt));
}
bool proxy_server::rfc2818_verification_match_pattern(
const char* pattern, std::size_t pattern_length, const char* host)
{
const char* p = pattern;
const char* p_end = p + pattern_length;
const char* h = host;
while (p != p_end && *h)
{
if (*p == '*')
{
++p;
while (*h && *h != '.')
{
if (rfc2818_verification_match_pattern(p, p_end - p, h++))
return true;
}
}
else if (std::tolower(*p) == std::tolower(*h))
{
++p;
++h;
}
else
{
return false;
}
}
return p == p_end && !*h;
}
pem_file proxy_server::determine_pem_type(const fs::path& filepath) noexcept
{
pem_file result{ filepath, pem_type::none };
boost::system::error_code ec;
// 文件过大跳过, ssl 证书及密钥相关文件通常不可能超过1M大小.
auto filesize = fs::file_size(filepath, ec);
if (filesize > 1 * 1024 * 1024 || ec)
return result;
boost::nowide::fstream file(filepath, std::ios::in | std::ios::binary);
if (!file.is_open())
return result;
if (filepath.filename() == "password.txt" ||
filepath.filename() == "passwd.txt" ||
filepath.filename() == "passwd" ||
filepath.filename() == "password" ||
filepath.filename() == "passphrase" ||
filepath.filename() == "passphrase.txt")
{
result.type_ = pem_type::pwd;
return result;
}
proxy::pem_type type = pem_type::none;
std::string line;
boost::regex re(R"(-----BEGIN\s.*\s?PRIVATE\sKEY-----)");
boost::smatch what;
while (std::getline(file, line))
{
if (line.find("-----BEGIN CERTIFICATE-----") != std::string::npos)
{
type = pem_type::cert;
result.chains_++;
continue;
}
else if (line.find("DH PARAMETERS-----") != std::string::npos)
{
type = pem_type::dhparam;
break;
}
else if (boost::regex_search(line, what, re))
{
type = pem_type::key;
break;
}
}
result.type_ = type;
return result;
}
void proxy_server::walk_certificate(
const fs::path& directory, std::vector<certificate_file>& certificates) noexcept
{
if (!fs::exists(directory) || !fs::is_directory(directory))
{
XLOG_WARN << "Path is not a directory or doesn't exist: " << directory;
return;
}
certificate_file file;
for (const auto& entry : fs::directory_iterator(directory, fs::directory_options::skip_permission_denied))
{
if (entry.is_directory())
{
walk_certificate(entry.path(), certificates);
continue;
}
if (entry.is_regular_file())
{
// 读取文件, 并判断文件类型.
auto type = determine_pem_type(entry.path());
switch (type.type_)
{
case pem_type::cert:
if (type.chains_ > file.cert_.chains_)
file.cert_ = type;
break;
case pem_type::key:
file.key_ = type;
break;
case pem_type::dhparam:
file.dhparam_ = type;
break;
case pem_type::pwd:
file.pwd_ = type;
break;
default:
break;
}
}
}
// 如果找到了证书文件, 创建一个证书文件对象.
if (file.cert_.type_ != pem_type::none &&
file.key_.type_ != pem_type::none)
{
// 创建 ssl context 对象.
file.ssl_context_.emplace(net::ssl::context::sslv23);
auto& ssl_ctx = file.ssl_context_.value();
// 设置 ssl context 选项.
ssl_ctx.set_options(
net::ssl::context::default_workarounds
| net::ssl::context::no_sslv2
| net::ssl::context::no_sslv3
| net::ssl::context::no_tlsv1
| net::ssl::context::no_tlsv1_1
| net::ssl::context::single_dh_use
);
// 如果设置了 ssl_prefer_server_ciphers_ 则设置 SSL_OP_CIPHER_SERVER_PREFERENCE.
if (m_option.ssl_prefer_server_ciphers_)
ssl_ctx.set_options(SSL_OP_CIPHER_SERVER_PREFERENCE);
// 设置 ssl ciphers. (默认值已在 init_ssl_context 中设定)
SSL_CTX_set_cipher_list(ssl_ctx.native_handle(),
m_option.ssl_ciphers_.c_str());
// 设置 alpn 协议.
SSL_CTX_set_alpn_select_cb(ssl_ctx.native_handle(),
alpn_select_proto_cb, (void*)this);
// 设置证书文件.
boost::system::error_code ec;
ssl_ctx.use_certificate_chain_file(file.cert_.filepath_.string(), ec);
if (ec)
{
XLOG_WARN << "use_certificate_chain_file: "
<< file.cert_.filepath_
<< ", error: "
<< ec.message();
return;
}
// 设置 password 文件, 如果存在的话.
if (file.pwd_.type_ != pem_type::none && fs::exists(file.pwd_.filepath_))
{
auto pwd = file.pwd_.filepath_;
ssl_ctx.set_password_callback(
[pwd]([[maybe_unused]] auto... args) {
std::string password;
fileop::read(pwd, password);
return password;
}
);
}
// 设置私钥文件.
ssl_ctx.use_private_key_file(
file.key_.filepath_.string(),
net::ssl::context::pem, ec);
if (ec)
{
XLOG_WARN << "use_private_key_file: "
<< file.key_.filepath_
<< ", error: "
<< ec.message();
return;
}
// 设置 dhparam 文件, 如果存在的话.
if (file.dhparam_.type_ != pem_type::none && fs::exists(file.dhparam_.filepath_))
{
ssl_ctx.use_tmp_dh_file(file.dhparam_.filepath_.string(), ec);
if (ec)
{
XLOG_WARN << "use_tmp_dh_file: "
<< file.dhparam_.filepath_
<< ", error: "
<< ec.message();
return;
}
}
// 设置证书过期时间和域名.
X509* x509_cert = SSL_CTX_get0_certificate(ssl_ctx.native_handle());
const auto expire_date = X509_getm_notAfter(x509_cert);
#ifdef OPENSSL_IS_BORINGSSL
std::time_t expiration_time;
ASN1_TIME_to_time_t(expire_date, &expiration_time);
file.expire_date_ = boost::posix_time::from_time_t(expiration_time);
#else
std::tm expire_date_tm;
ASN1_TIME_to_tm(expire_date, &expire_date_tm);
file.expire_date_ = boost::posix_time::ptime_from_tm(expire_date_tm);
#endif
std::unique_ptr<GENERAL_NAMES, decltype(&GENERAL_NAMES_free)> general_names{
static_cast<GENERAL_NAMES*>(X509_get_ext_d2i(x509_cert, NID_subject_alt_name, 0, 0)),
&GENERAL_NAMES_free
};
if (general_names)
{
for (int i = 0; i < sk_GENERAL_NAME_num(general_names.get()); i++)
{
GENERAL_NAME* gen = sk_GENERAL_NAME_value(general_names.get(), i);
if (gen->type == GEN_DNS)
{
const ASN1_IA5STRING* domain = gen->d.dNSName;
auto* non_const_domain = const_cast<ASN1_STRING*>(domain);
if (ASN1_STRING_type(non_const_domain) == V_ASN1_IA5STRING &&
ASN1_STRING_get0_data(non_const_domain) &&
ASN1_STRING_length(non_const_domain))
{
file.subject_alt_name_.emplace_back(
(const char*)(ASN1_STRING_get0_data(non_const_domain)),
ASN1_STRING_length(non_const_domain)
);
}
}
}
}
else
{
XLOG_DBG << "No subject alternative name, will use Common Name as fallback.";
}
char cert_cname[256] = { 0 };
{
auto* x509_name = X509_get_subject_name(x509_cert);
int idx = X509_NAME_get_index_by_NID(x509_name, NID_commonName, -1);
if (idx >= 0)
{
auto* entry = X509_NAME_get_entry(x509_name, idx);
if (entry)
{
auto* data = X509_NAME_ENTRY_get_data(entry);
if (data && ASN1_STRING_length(data) > 0)
{
int copy_len = (std::min)(ASN1_STRING_length(data), (int)(sizeof(cert_cname) - 1));
memcpy(cert_cname, ASN1_STRING_get0_data(data), copy_len);
cert_cname[copy_len] = '\0';
}
}
}
}
file.domain_ = cert_cname;
// 保存到 certificates 中.
certificates.emplace_back(std::move(file));
}
}
void proxy_server::init_acceptor() noexcept
{
auto& endps = m_option.listens_;
for (const auto& [endp, v6only] : endps)
{
tcp_acceptor acceptor(m_executor);
boost::system::error_code ec;
acceptor.open(endp.protocol(), ec);
if (ec)
{
XLOG_WARN << "acceptor open: " << endp
<< ", error: " << ec.message();
continue;
}
acceptor.set_option(net::socket_base::reuse_address(true), ec);
if (ec)
{
XLOG_WARN << "acceptor set_option with reuse_address: "
<< ec.message();
}
if (m_option.reuse_port_)
{
#ifdef ENABLE_REUSEPORT
acceptor.set_option(reuse_port(true), ec);
if (ec)
{
XLOG_WARN << "acceptor set_option with SO_REUSEPORT: "
<< ec.message();
}
#endif
}
if (v6only)
{
acceptor.set_option(net::ip::v6_only(true), ec);
if (ec)
{
XLOG_ERR << "TCP server accept "
<< "set v6_only failed: " << ec.message();
continue;
}
}
acceptor.bind(endp, ec);
if (ec)
{
XLOG_ERR << "acceptor bind: " << endp
<< ", error: " << ec.message();
continue;
}
acceptor.listen(net::socket_base::max_listen_connections, ec);
if (ec)
{
XLOG_ERR << "acceptor listen: " << endp
<< ", error: " << ec.message();
continue;
}
m_tcp_acceptors.emplace_back(std::move(acceptor));
}
auto& uds_endps = m_option.uds_listens_;
for (const auto& endp : uds_endps)
{
try
{
m_unix_acceptors.emplace_back(m_executor, endp, false);
}
catch (const std::exception& e)
{
XLOG_ERR << "unix domain socket acceptor listen: " << endp.path()
<< ", error: " << e.what();
continue;
}
}
#if defined(__linux__) && defined(IP_TRANSPARENT)
// 创建 UDP TPROXY 透明代理 sockets,用于接收被重定向的 UDP 数据包.
if (m_option.proxy_pass_ && m_option.transparent_)
{
for (const auto& [tcp_endp, v6only] : m_option.listens_)
{
(void)v6only;
if (!m_option.proxy_pass_->scheme().starts_with("socks5") &&
!m_option.proxy_pass_->scheme().starts_with("http"))
continue;
net::ip::udp::socket udp_sock(m_executor);
boost::system::error_code ec;
// 从 TCP endpoint 构造对应的 UDP endpoint.
net::ip::udp::endpoint udp_endp(
tcp_endp.address(), tcp_endp.port());
udp_sock.open(udp_endp.protocol(), ec);
if (ec)
{
XLOG_WARN << "udp tproxy open: "
<< udp_endp << ", error: " << ec.message();
continue;
}
udp_sock.set_option(
net::socket_base::reuse_address(true), ec);
// 设置 IP_RECVORIGDSTADDR 以接收原始目标地址.
int opt = 1;
if (udp_endp.protocol() == net::ip::udp::v4())
{
udp_sock.set_option(transparent_opt(true), ec);
::setsockopt(udp_sock.native_handle(), IPPROTO_IP,
IP_RECVORIGDSTADDR, &opt, sizeof(opt));
}
else
{
udp_sock.set_option(transparent6_opt(true), ec);
::setsockopt(udp_sock.native_handle(), IPPROTO_IPV6,
IPV6_RECVORIGDSTADDR, &opt, sizeof(opt));
}
udp_sock.bind(udp_endp, ec);
if (ec)
{
XLOG_ERR << "udp tproxy bind: " << udp_endp
<< ", error: " << ec.message();
continue;
}
XLOG_DBG << "udp tproxy listen on: " << udp_endp;
m_udp_tproxy_listeners.push_back(std::move(udp_sock));
}
}
#endif // defined(__linux__) && defined(IP_TRANSPARENT)
}
void proxy_server::update_certificate(
const fs::path& directory, std::vector<certificate_file>& certificates) noexcept
{
// 清空现有证书.
certificates.clear();
// 扫描证书文件.
walk_certificate(directory, certificates);
// 按过期时间排序.
std::stable_sort(certificates.begin(), certificates.end(),
[](const certificate_file& a, const certificate_file& b) {
return a.expire_date_ < b.expire_date_;
});
auto print_path = [](const std::string& prefix, const fs::path path)
{
return path.empty() ? "" : prefix + path.string();
};
for (const auto& ctx : certificates)
{
XLOG_DBG << "domain: '" << ctx.domain_
<< "', expire: '" << ctx.expire_date_
<< print_path("', cert: '", ctx.cert_.filepath_)
<< print_path("', key: '", ctx.key_.filepath_)
<< print_path("', dhparam: '", ctx.dhparam_.filepath_)
<< print_path("', pwd: '", ctx.pwd_.filepath_);
}
}
void proxy_server::init_ssl_context() noexcept
{
// 如果没有设置证书文件, 则直接返回.
if (m_option.ssl_cert_path_.empty())
return;
// 默认的 ssl ciphers, 确保在 walk_certificate 之前赋值.
const std::string ssl_ciphers = "HIGH:!aNULL:!MD5:!3DES";
if (m_option.ssl_ciphers_.empty())
m_option.ssl_ciphers_ = ssl_ciphers;
// 读取并更新证书文件.
update_certificate(m_option.ssl_cert_path_, *m_certificates.load());
// 设置 SNI 回调函数.
SSL_CTX_set_tlsext_servername_callback(
m_ssl_srv_context.native_handle(), proxy_server::ssl_sni_callback);
SSL_CTX_set_tlsext_servername_arg(m_ssl_srv_context.native_handle(), this);
// 设置 ALPN 回调函数.
SSL_CTX_set_alpn_select_cb(m_ssl_srv_context.native_handle(),
alpn_select_proto_cb, (void*)this);
}
int proxy_server::alpn_select_proto_cb(SSL *ssl, const unsigned char **out,
unsigned char *outlen, const unsigned char *in,
unsigned int inlen, void *arg)
{
proxy_server* self = (proxy_server*)arg;
return self->alpn_select_proto(ssl, out, outlen, in, inlen);
}
int proxy_server::alpn_select_proto(SSL *ssl, const unsigned char **out,
unsigned char *outlen, const unsigned char *in,
unsigned int inlen) noexcept
{
(void)ssl;
int ret = SSL_select_next_proto((unsigned char **)out, outlen,
in, inlen,
(const unsigned char *)"\x8http/1.1", 9);
if (ret == OPENSSL_NPN_NEGOTIATED)
return SSL_TLSEXT_ERR_OK;
XLOG_DBG << "ALPN negotiation failed: "
<< inlen << " " << std::string((const char*)in, inlen);
return SSL_TLSEXT_ERR_ALERT_FATAL;
}
int proxy_server::ssl_sni_callback(SSL *ssl, int *ad, void *arg)
{
proxy_server* self = (proxy_server*)arg;
return self->sni_callback(ssl, ad);
}
int proxy_server::sni_callback(SSL *ssl, [[maybe_unused]] int *ad) noexcept
{
auto certificates_ptr = m_certificates.load();
if (!certificates_ptr)
return SSL_TLSEXT_ERR_OK;
auto& certificates = *certificates_ptr;
if (certificates.empty())
return SSL_TLSEXT_ERR_OK;
certificate_file* default_ctx = nullptr;
for (auto& c : certificates)
{
if (c.ssl_context_.has_value())
{
default_ctx = &c;
break;
}
}
if (!default_ctx)
return SSL_TLSEXT_ERR_OK;
const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
if (!servername)
{
SSL_set_SSL_CTX(ssl, default_ctx->ssl_context_->native_handle());
return SSL_TLSEXT_ERR_OK;
}
for (auto& ctx : certificates)
{
if (!ctx.ssl_context_.has_value())
continue;
if (!ctx.domain_.empty() &&
rfc2818_verification_match_pattern(ctx.domain_.c_str(), ctx.domain_.size(), servername))
{
SSL_set_SSL_CTX(ssl, ctx.ssl_context_->native_handle());
return SSL_TLSEXT_ERR_OK;
}
for (auto& alt_name : ctx.subject_alt_name_)
{
if (rfc2818_verification_match_pattern(alt_name.c_str(), alt_name.length(), servername))
{
SSL_set_SSL_CTX(ssl, ctx.ssl_context_->native_handle());
return SSL_TLSEXT_ERR_OK;
}
}
}
SSL_set_SSL_CTX(ssl, default_ctx->ssl_context_->native_handle());
return SSL_TLSEXT_ERR_OK;
}
net::awaitable<std::chrono::seconds> proxy_server::certificate_check()
{
boost::system::error_code ec;
// 找到下次需要检查证书的时间间隔, 如果有证书过期, 返回 0 表示应尽快检查.
// 如果所有证书都有效, 返回距最早过期的时间.
auto now = boost::posix_time::second_clock::local_time();
std::chrono::seconds earliest_expiry = std::chrono::hours(24) * 365;
auto certificates_ptr = m_certificates.load();
auto& certificates = *certificates_ptr;
for (const auto& ctx : certificates)
{
if (now > ctx.expire_date_)
{
XLOG_WARN << "domain: '" << ctx.domain_
<< "', cert: '" << ctx.cert_.filepath_.string()
<< "', key: '" << ctx.key_.filepath_.string()
<< "', dhparam: '" << ctx.dhparam_.filepath_.string()
<< "', pwd: '" << ctx.pwd_.filepath_.string()
<< "', expired: '" << ctx.expire_date_ << "'";
earliest_expiry = std::chrono::seconds::zero();
continue;
}
auto remaining = std::chrono::seconds((ctx.expire_date_ - now).total_seconds());
earliest_expiry = std::min(earliest_expiry, remaining);
}
if (earliest_expiry > std::chrono::seconds::zero())
co_return earliest_expiry;
// 热更新证书, 交替更新证书容器 master/slave.
if (certificates_ptr == &m_certificate_master)
{
update_certificate(m_option.ssl_cert_path_, m_certificate_slave);
m_certificates.store(&m_certificate_slave);
}
else
{
update_certificate(m_option.ssl_cert_path_, m_certificate_master);
m_certificates.store(&m_certificate_master);
}
co_return earliest_expiry;
}
net::awaitable<void> proxy_server::tick()
{
auto self = shared_from_this();
boost::system::error_code ec;
auto check_time_point = std::chrono::steady_clock::now();
while (!m_abort)
{
m_timer.expires_after(std::chrono::seconds(1));
co_await m_timer.async_wait(net_awaitable[ec]);
if (ec)
break;
auto now = std::chrono::steady_clock::now();
// 检查证书是否过期 (仅在配置了证书路径时).
if (!m_option.ssl_cert_path_.empty() && now > check_time_point)
{
// 返回过期间隔期.
auto duration = co_await certificate_check();
// 至少 5 分钟后再检查.
check_time_point = now + duration + std::chrono::minutes(5);
}
#if defined(__linux__)
if (m_option.transparent_)
{
// 检查 UDP TPROXY 流是否过期.
if (!m_udp_tproxy_flows.empty())
co_await udp_tproxy_check();
// 检查 UDP TPROXY socks5 连接是否需要重试.
if (m_retry_tproxy_socks5_connect)
{
net::co_spawn(m_executor,
udp_tproxy_socks5_connect(), net::detached);
}
}
#endif
}
co_return;
}
void proxy_server::start() noexcept
{
m_scheduler_locking = net::config(m_executor.context()).get("scheduler", "locking", true);
// 运行后端任务线程.
if (!m_scheduler_locking)
{
auto self = shared_from_this();
m_backend_thread = std::make_unique<std::thread>([this, self]() mutable
{
backend_thread_run();
});
}
// 如果是 stdio 模式, 则直接启动 stdio 监听协程.
if (!m_option.stdio_target_.empty())
{
auto self = shared_from_this();
net::co_spawn(m_executor, [this, self]() -> net::awaitable<void>
{
try
{
// 使用 stdio socket 初始化 proxy session.
#if defined(BOOST_ASIO_HAS_POSIX_STREAM_DESCRIPTOR)
net::posix::stream_descriptor stream_in(m_executor, ::dup(STDIN_FILENO));
stdio_stream stream(std::move(stream_in));
#else
std::shared_ptr<net::io_context> in_ctx = std::make_shared<net::io_context>(1);
std::thread([in_ctx]() mutable
{
auto work_guard = net::make_work_guard(*in_ctx);
try
{
in_ctx->run();
}
catch (const std::exception&)
{}
XLOG_DBG << "stdio input context thread exit";
}).detach();
stdio_stream stream(in_ctx->get_executor(), m_executor);
#endif
// 创建 proxy session 对象.
auto new_session =
std::make_shared<proxy_session>(
m_executor,
m_backend_context,
m_scheduler_locking,
m_dns_cache,
init_proxy_stream(std::move(stream)),
0,
self);
// 启动 proxy_session 对象.
new_session->start();
}
catch (const std::exception& e)
{
XLOG_ERR << "stdio proxy exception: " << e.what();
}
co_return;
}, net::detached);
return;
}
// 如果作为透明代理.
if (m_option.transparent_)
{
#if defined(__linux__)
# if defined (IP_TRANSPARENT) && defined (IPV6_TRANSPARENT)
for (auto& acceptor : m_tcp_acceptors)
{
boost::system::error_code error;
acceptor.set_option(transparent_opt(true), error);
acceptor.set_option(transparent6_opt(true), error);
}
# endif
#else
XLOG_WARN << "transparent proxy only support linux";
#endif
// 获取所有本机 ip 地址.
net::co_spawn(m_executor,
get_local_address(), net::detached);
}
// 同时启动32个连接协程为每个 acceptor 用于为 proxy client 提供服务.
for (auto& acceptor : m_tcp_acceptors)
{
for (int i = 0; i < 32; i++)
{
net::co_spawn(m_executor,
start_proxy_listen(acceptor), net::detached);
}
}
// 同时启动32个连接协程为每个 acceptor 用于为 proxy client 提供服务.
for (auto& acceptor : m_unix_acceptors)
{
for (int i = 0; i < 32; i++)
{
net::co_spawn(m_executor,
start_proxy_listen(acceptor), net::detached);
}
}
#if defined(__linux__)
if (m_option.transparent_)
{
net::co_spawn(m_executor,
start_udp_tproxy(), net::detached);
}
#endif // defined(__linux__)
// 启动定时器.
net::co_spawn(m_executor,
tick(), net::detached);
}
void proxy_server::close() noexcept
{
boost::system::error_code ignore_ec;
m_abort = true;
m_backend_context.stop();
if (m_backend_thread && m_backend_thread->joinable())
m_backend_thread->join();
m_timer.cancel();
for (auto& acceptor : m_tcp_acceptors)
acceptor.close(ignore_ec);
for (auto& acceptor : m_unix_acceptors)
acceptor.close(ignore_ec);
#if defined(__linux__)
// 关闭 UDP TPROXY 相关资源.
for (auto& [_, flow] : m_udp_tproxy_flows)
{
if (flow)
{
flow->backend_sock_.reset();
flow->relay_sock_.reset();
}
}
m_udp_tproxy_flows.clear();
for (auto& s : m_udp_tproxy_listeners)
s.close(ignore_ec);
#endif // defined(__linux__)
for (auto& [id, c] : m_clients)
{
if (auto client = c.lock())
client->close();
}
}
void proxy_server::remove_session(size_t id)
{
m_clients.erase(id);
}
size_t proxy_server::num_session()
{
return m_clients.size();
}
const proxy_server_option& proxy_server::option()
{
return m_option;
}
net::ssl::context& proxy_server::ssl_context()
{
return m_ssl_srv_context;
}
net::awaitable<std::optional<net::ip::tcp::endpoint>>
proxy_server::setup_tproxy(proxy_tcp_socket& socket, size_t connection_id) noexcept
{
#ifndef SO_ORIGINAL_DST
# define SO_ORIGINAL_DST 80
#endif
auto sockfd = socket.native_handle();
std::optional<net::ip::tcp::endpoint> remote_endp;
sockaddr_storage addr;
socklen_t addrlen = sizeof(addr);
if (::getsockopt(sockfd, IPPROTO_IP, SO_ORIGINAL_DST, (char*)&addr, &addrlen) < 0)
{
XLOG_WARN << "connection id: " << connection_id
<< ", getsockopt: " << (int)sockfd
<< ", SO_ORIGINAL_DST: " << strerror(errno);
co_return remote_endp;
}
{
auto ep = sockaddr_to_udp_endpoint(addr);
if (ep.address().is_unspecified())
{
XLOG_WARN << "connection id: " << connection_id
<< ", SO_ORIGINAL_DST unexpected family: " << addr.ss_family;
co_return remote_endp;
}
remote_endp.emplace(ep.address(), ep.port());
}
XLOG_DBG << "connection id: " << connection_id << ", tproxy, remote: " << *remote_endp;
// 请求的是本机的回环连接, 而不是 TPROXY 代理.
if (remote_endp->address().is_loopback())
{
remote_endp.reset();
co_return remote_endp;
}
// 如果 original dst 是本机地址 => 这不是 tproxy 转发目标
if (m_local_addrs.find(remote_endp->address()) != m_local_addrs.end())
remote_endp.reset();
co_return remote_endp;
}
// 切换到后端执行上下文(非锁定调度时).
// 当 m_scheduler_locking 为 false 时, 协程会切换到后端线程池执行, 适用于需要执行
// 同步操作(如 DNS 解析)的场景. 返回当前应使用的 executor.
net::awaitable<net::any_io_executor> proxy_server::switch_to_backend_executor()
{
if (!m_scheduler_locking)
{
co_await net::post(
net::bind_executor(m_backend_context.get_executor(), net::use_awaitable));
co_return m_backend_context.get_executor();
}
co_return m_executor;
}
// 从后端执行上下文切换回主执行上下文.
net::awaitable<void> proxy_server::switch_from_backend_executor()
{
if (!m_scheduler_locking)
co_await net::post(
net::bind_executor(m_executor, net::use_awaitable));
}
net::awaitable<void> proxy_server::get_local_address() noexcept
{
auto self = shared_from_this();
boost::system::error_code ec;
auto hostname = net::ip::host_name(ec);
if (ec)
{
XLOG_WARN
<< "get_local_address, host_name: "
<< ec.message();
co_return;
}
if (!is_hostname(hostname))